Best JavaScript code snippet using qawolf
vaccination.js
Source:vaccination.js
1// get files from OWID github repository2var file_update_time = "https://covid.ourworldindata.org/data/owid-covid-data-last-updated-timestamp.txt";3var file_vaccinations = "https://covid.ourworldindata.org/data/vaccinations/vaccinations.csv";4var file_locations = "https://covid.ourworldindata.org/data/vaccinations/locations.csv";5var file_population = "https://raw.githubusercontent.com/owid/COVID-19-data/master/scripts/input/un/population_2020.csv";6// to do: use stable url instead7// https://covid.ourworldindata.org/data/vaccinations/vaccinations.csv8// get files from my github repository9var file_vaccine_group = "vaccine_groups.csv";10// define color variables11const clrBlue = 'rgba(49,130,189,.5)';12const clrRed = 'rgba(215,25,28,.5)';13const clrPink = 'rgba(233,163,201,.5)'14const clrGreen = 'rgba(26,150,65, .5)';15const clrGray = 'rgba(204,204,204,.9)';16const clrBlack = 'rgba(0,0,0,.9)';17const clrWhiteTransparent = 'rgba(255,255,255,0)';18// define isotope grid19var $grid = '';20// get data (with filters, if any)21getData();22function getData(){ 23 // promise data from sources24 Promise.all([25 d3.csv(file_vaccinations),26 d3.csv(file_locations),27 d3.csv(file_population),28 d3.csv(file_update_time),29 ]).then(function(data) {30 // get data from promise31 var arrVaccinations = data[0];32 var arrLocations = data[1];33 var arrPopulation = data[2];34 var updateTime = data[3].columns[0];35 const lastUpdated = changeTimezone(updateTime);36 document.getElementById('last_update').innerHTML += ' <small class="text-muted">Data updated: ' + lastUpdated + '</small>';37 // exclude dupe locations from arrVaccinations38 const arrVacDetail = arrVaccinations.filter(function(d) { 39 return d.location != "England" && d.location != "European Union" && d.location != "Northern Ireland" && d.location != "Scotland" && d.location != "Wales" && d.location != "World" && d.location != "Africa" && d.location != "Asia" && d.location != "Europe" && d.location != "North America" && d.location != "South America" && d.location != "Oceania" && d.location != "High income" && d.location != "Low income" && d.location != "Lower middle income" && d.location != "Upper middle income";40 });41 // create new elements in arrVacDetail42 arrVacDetail.forEach(function(d) {43 d.daily_vaccinations_per_hundred = (d.daily_vaccinations_per_million / 10000).toFixed(3);44 d.date_sort = reformatDate(d.date);45 d.concatLocDate = d.location + d.date;46 });47 // sort arrVacDetail to ensure desired to prepare for fill up next step48 arrVacDetail.sort((a, b) => a.location.localeCompare(b.location) || a.date_sort - b.date_sort);49 // create new fill up arrays50 arrVacPer100Filled = getFilledUpArray(arrVacDetail.map(function(i){return i.total_vaccinations_per_hundred;}));51 arrTotalVaccinationsFilled = getFilledUpArray(arrVacDetail.map(function(i){return i.total_vaccinations;}));52 arrDailyVaccinationsFilled = getFilledUpArray(arrVacDetail.map(function(i){return i.daily_vaccinations_per_hundred;}));53 // write new fill up arrays back to arrVacDetail54 var i = 0;55 arrVacDetail.forEach(function(d) {56 d.total_vaccinations_per_hundred_filled = arrVacPer100Filled[i];57 d.total_vaccinations_filled = arrTotalVaccinationsFilled[i];58 d.daily_vaccinations_per_hundred_filled = arrDailyVaccinationsFilled[i];59 i++;60 });61 // group by location and get max date eg last_observation_date62 var arrLastObservationDate = d3.nest()63 .key(function(d) { 64 return d.location; 65 })66 .rollup(function(v) { 67 return {68 last_observation_date: d3.max(v, function(d) { return d.date; }),69 };70 })71 .entries(arrVacDetail)72 .map(function(group) {73 return {74 location: group.key,75 last_observation_date: group.value.last_observation_date76 }77 });78 // left join arrLastObservationDate to arrPopulation79 const arrLocationPop = equijoinWithDefault(80 arrLastObservationDate, arrPopulation, 81 "location", "entity", 82 ({location, last_observation_date}, {population}, ) => 83 ({location, last_observation_date, population}), 84 {population: null});85 // left join arrLastObservationDate to arrPopulation86 const arrLocationPopVac = equijoinWithDefault(87 arrLocationPop, arrLocations, 88 "location", "location", 89 ({location, last_observation_date, population}, {vaccines}, ) => 90 ({location, last_observation_date, population, vaccines}), 91 {population: null});92 93 // left join arrLocationPop to arrVacDetail94 const arrVacDetailLoc = equijoinWithDefault(95 arrVacDetail, arrLocationPopVac, 96 "location", "location", 97 ({concatLocDate, location, iso_code, date, date_sort, total_vaccinations, total_vaccinations_filled, people_vaccinated, people_fully_vaccinated, daily_vaccinations_raw, daily_vaccinations, total_vaccinations_per_hundred, total_vaccinations_per_hundred_filled, people_vaccinated_per_hundred, people_fully_vaccinated_per_hundred, daily_vaccinations_per_million, daily_vaccinations_per_hundred, daily_vaccinations_per_hundred_filled}, {last_observation_date, population, vaccines}, ) => 98 ({concatLocDate, location, iso_code, date, date_sort, total_vaccinations, total_vaccinations_filled, people_vaccinated, people_fully_vaccinated, daily_vaccinations_raw, daily_vaccinations, total_vaccinations_per_hundred, total_vaccinations_per_hundred_filled, people_vaccinated_per_hundred, people_fully_vaccinated_per_hundred, daily_vaccinations_per_million, daily_vaccinations_per_hundred, daily_vaccinations_per_hundred_filled, last_observation_date, population, vaccines}), 99 {population: null});100 // create new element in arrVacDetailLoc101 arrVacDetailLoc.forEach(function(d) {102 if (d.date === d.last_observation_date) {d.current_date = 'current_date'} else { d.current_date = ''};103 });104 // filter vaccinations dataset by location max date to get current records only105 const arrVacDetailLocCurrent = arrVacDetailLoc.filter(function(d) {106 return d.current_date == 'current_date';107 });108 // order vaccinationMaxDate desc by total_vaccinations_per_hundred109 arrVacDetailLocCurrent.sort((a, b) => {110 return b.total_vaccinations_per_hundred_filled - a.total_vaccinations_per_hundred_filled;111 });112 113 // create country count114 var countryCount = arrVacDetailLocCurrent.length;115 116 // CREATE CHART117 function createGlobalTotal100RankChart() {118 // create divs, para for chart119 document.getElementById('div_global_rank').innerHTML = '';120 var divTitle = document.createElement("h4");121 var divDesc= document.createElement("p");122 //var divLegend = document.createElement("ul");123 var divChart = document.createElement("div");124 divChart.id = 'div_global_rank_chart';125 var chartTitle = 'Total Doses Per 100 People - Rank By Country';126 var chartDesc = 'Shows vaccine doses administered per 100 people for all ' + countryCount + ' countries currently in OWID dataset.';127 /*128 var chartLegend = 129 '<li class="list-inline-item">Change from previous day:</li>' + 130 '<li class="list-inline-item">Increase</li>' + 131 '<li class="list-inline-item legend_box_green"> </li>' + 132 '<li class="list-inline-item">Decrease</li>' + 133 '<li class="list-inline-item legend_box_red"> </li>' + 134 '<li class="list-inline-item">Unchanged</li>' + 135 '<li class="list-inline-item legend_box_gray"> </li>';136 */137 divTitle.innerHTML = chartTitle;138 divDesc.innerHTML = chartDesc;139 //divLegend.innerHTML = chartLegend;140 //divLegend.className = 'list-inline small';141 document.getElementById('div_global_rank').append(divTitle);142 document.getElementById('div_global_rank').append(divDesc);143 //document.getElementById('div_global_rank').append(divLegend);144 document.getElementById('div_global_rank').append(divChart);145 146 // define x and y axis arrays147 var x = [];148 var yPer100 = [];149 var yper100Prev = [];150 var yper100Change = [];151 152 // create axes x and y arrays153 for (var i=0; i<arrVacDetailLocCurrent.length; i++) {154 var row = arrVacDetailLocCurrent[i];155 x.push(row['location']);156 yPer100.push(row['total_vaccinations_per_hundred_filled']);157 yper100Prev.push(row['total_vaccinations_per_hundred_filled_prev']);158 if (row['total_vaccinations_per_hundred_filled'] > row['total_vaccinations_per_hundred_filled_prev']) {159 yper100Change.push('increase');160 } else if (row['total_vaccinations_per_hundred_filled'] < row['total_vaccinations_per_hundred_filled_prev']) {161 yper100Change.push('decrease');162 } else {163 yper100Change.push('unchanged');164 }165 }166 // create chart trace167 var trPer100 = {168 name: 'Doses Per 100',169 hoverlabel: {170 namelength :-1171 },172 x: x,173 y: yPer100,174 showgrid: false,175 fill: 'tozeroy',176 type: 'bar',177 marker:{178 color: clrGray, // fillColor(yPer100, yper100Prev) // red, green, gray based on change from prev179 },180 };181 // create chart layout182 var layout = {183 title: {184 text: '',185 font: {186 size: 14187 },188 },189 autosize: true,190 autoscale: false,191 //width: 200,192 height: 300,193 margin: {194 l: 40,195 r: 40,196 b: 120,197 t: 10,198 pad: 2199 },200 xaxis: { 201 tickfont: {202 size: 8203 },204 showgrid: false,205 tickmode: 'linear',206 },207 yaxis: { 208 tickfont: {209 size: 11210 },211 showgrid: false212 }213 }214 // create plotly data, config, chart215 var data = [trPer100];216 var config = {responsive: true}217 Plotly.newPlot('div_global_rank_chart', data, layout, config);218 }219 // CREATE CHART220 function createAllCountryRankSubPlots() {221 // create arrVacDates array with unique dates to loop through 222 var arrVacDates = [...new Set(arrVacDetailLoc.map(item => item.date))];223 // create max and min dates224 var minVacDate = d3.min(arrVacDates.map(d=>d));225 var maxVacDate = d3.max(arrVacDates.map(d=>d));226 // sort arrVacDates array desc order on date modified to integer227 // to loop through them desc below228 arrVacDates.sort(function(a,b) {229 a = a.split('-').join('');230 b = b.split('-').join('');231 //return a > b ? 1 : a < b ? -1 : 0; // asc232 return a < b ? 1 : a > b ? -1 : 0; // desc233 });234 // define country rank array235 var arrCountryRank = [];236 // create arrCountryRank237 // loop through arrVacDates desc, get max date per country, that is less than loop date238 // assign that max date as country's last report date 239 for (var i=0; i<arrVacDates.length; i++) {240 var loopDate = arrVacDates[i];241 // filter arrVacDetailLoc to dates less than loop date242 var arrVacLoopDate = arrVacDetailLoc.filter(function(d) { 243 return d.date <= loopDate;244 });245 // summarize location by country's last report date246 var arrVacLoopDateMax = d3.nest()247 .key(function(d) { 248 return d.location; 249 })250 .rollup(function(v) { 251 return {252 max_loop_date: d3.max(v, function(d) { return d.date; }),253 max_loop_date_sort: d3.max(v, function(d) { return d.date_sort; })254 };255 })256 .entries(arrVacLoopDate)257 .map(function(group) {258 return {259 location: group.key,260 max_loop_date: group.value.max_loop_date,261 max_loop_date_sort: group.value.max_loop_date_sort262 }263 });264 // create arrVacLoopDateMax concat location and date to join arrays265 arrVacLoopDateMax.forEach(function(d) {266 d.concatLocDate = d.location + d.max_loop_date;267 });268 // join arrVacLoopDateMax to arrVacLoopDate to get all data back269 const arrVacLoopDateMaxFull = equijoinWithDefault(270 arrVacLoopDateMax, arrVacLoopDate, 271 "concatLocDate", "concatLocDate", 272 ({max_loop_date}, {concatLocDate, daily_vaccinations, daily_vaccinations_per_hundred, daily_vaccinations_per_million, daily_vaccinations_raw, date, date_sort, iso_code, last_observation_date, location, people_fully_vaccinated, people_fully_vaccinated_per_hundred, people_vaccinated, people_vaccinated_per_hundred, population, total_vaccinations, total_vaccinations_filled, total_vaccinations_per_hundred, total_vaccinations_per_hundred_filled, vaccines}, ) => 273 ({max_loop_date, concatLocDate, daily_vaccinations, daily_vaccinations_per_hundred, daily_vaccinations_per_million, daily_vaccinations_raw, date, date_sort, iso_code, last_observation_date, location, people_fully_vaccinated, people_fully_vaccinated_per_hundred, people_vaccinated, people_vaccinated_per_hundred, population, total_vaccinations, total_vaccinations_filled, total_vaccinations_per_hundred, total_vaccinations_per_hundred_filled, vaccines}), 274 {population: null});275 276 // order arrVacLoopDateMaxFull desc by total_vaccinations_per_hundred to get rank277 arrVacLoopDateMaxFull.sort((a, b) => {278 return b.total_vaccinations_per_hundred_filled - a.total_vaccinations_per_hundred_filled;279 });280 // define loop country count281 vCountryCount = arrVacLoopDateMaxFull.length;282 283 // create arrCountryRank284 for (var j=0; j < arrVacLoopDateMaxFull.length; j++) {285 row = arrVacLoopDateMaxFull[j];286 // push elements to arrCountryRank287 arrCountryRank.push({288 date: loopDate, 289 date_sort: row.max_loop_date_sort, 290 location: row.location, 291 total_vaccinations: parseInt(row.total_vaccinations_filled).toLocaleString(),292 total_vaccinations_per100: parseFloat(row.total_vaccinations_per_hundred_filled).toFixed(2), 293 rank: (parseInt(j) + 1),294 rank_percentile: getRankPctile((parseInt(j) + 1), vCountryCount),295 vaccines: row.vaccines296 });297 }298 }299 // create divs, para for section300 document.getElementById('div_sub_plot_rank').innerHTML = '';301 var divTitle = document.createElement("h4");302 var divDesc= document.createElement("p");303 var divChart = document.createElement("div");304 var divButtons = document.createElement("div");305 divChart.id = 'div_sub_plots';306 divChart.className = 'grid';307 var chartTitle = 'Total Doses Per 100 People - Global Rank Percentile By Country';308 var chartDesc = 'Visualizations show vaccine dose administration per 100 people as a daily global rank percentile (blue line) for all countries in OWID dataset. Includes trendline (red dashed line).';309 var chartButtons = 310 '<span><strong>Sort:</strong> </span><div class="btn-group flex-wrap" role="group" aria-label="Basic example">' +311 '<button type="button" class="btn btn-light sort-btn" value="asc" data-sort-by="location">Country</button>' +312 '<button type="button" class="btn btn-light sort-btn" value="asc" data-sort-by="rank">Rank</button>' +313 '<button type="button" class="btn btn-light sort-btn" value="asc" data-sort-by="slope">Trend</button>' +314 '<button type="button" class="btn btn-light sort-btn" value="asc" data-sort-by="min_date">Date</button>' +315 '<button type="button" class="btn btn-light sort-btn" value="asc" data-sort-by="total_vaccinations">Doses</button>' +316 '<button type="button" class="btn btn-light sort-btn" value="asc" data-sort-by="population">Population</button>' +317 '</div>';318 divTitle.innerHTML = chartTitle;319 divDesc.innerHTML = chartDesc;320 divButtons.innerHTML = chartButtons;321 document.getElementById('div_sub_plot_rank').append(divTitle);322 document.getElementById('div_sub_plot_rank').append(divDesc);323 document.getElementById('div_sub_plot_rank').append(divButtons);324 document.getElementById('div_sub_plot_rank').append(divChart);325 // create unique location array to loop through326 var arrRanklocations = [...new Set(arrCountryRank.map(item => item.location))];327 arrRanklocations.sort((a, b) => a.localeCompare(b));328 // loop to create each location chart329 for (var i=0; i < arrRanklocations.length; i++) {330 var xDate = [];331 var xDateSort = [];332 var xDateDays = [];333 var yRankPctile = [];334 // filter to current loop country335 var locationData = arrCountryRank.filter(function(d) { 336 return d.location === arrRanklocations[i];337 });338 339 var currentRank = arrVacDetailLocCurrent.findIndex(x => x.location === arrRanklocations[i]) + 1;340 var currentTotalVax = arrVacDetailLocCurrent.find(x => x.location === arrRanklocations[i]).total_vaccinations_filled;341 var currentPer100 = arrVacDetailLocCurrent.find(x => x.location === arrRanklocations[i]).total_vaccinations_per_hundred_filled;342 var locPopulation = arrVacDetailLocCurrent.find(x => x.location === arrRanklocations[i]).population;343 var locVaccines = arrVacDetailLocCurrent.find(x => x.location === arrRanklocations[i]).vaccines;344 345 // create location chart x y arrays346 for (var j=0; j < locationData.length; j++) {347 xDate.push(locationData[j].date);348 xDateSort.push(parseInt(locationData[j].date_sort));349 xDateDays.push(dateDiffInDays(new Date("2020-12-13"), new Date(locationData[j].date)));350 yRankPctile.push(locationData[j].rank_percentile);351 }352 var xDateMin = d3.min(xDate.map(d=>d));353 var xDateDaysMin = d3.min(xDateDays.map(d=>d));354 var xDateDaysMax = d3.max(xDateDays.map(d=>d));355 var lr = linearRegression(yRankPctile, xDateDays);356 357 var trRankPctile = {358 name: '',359 hoverlabel: {360 namelength :-1361 },362 yaxis: 'y',363 x: xDate,364 y: yRankPctile,365 //type: 'line',366 mode: 'lines',367 line: {368 dash: 'solid',369 width: 2370 },371 marker:{372 color: clrBlue373 },374 };375 var trTrendline = {376 name: '',377 hoverinfo:'skip',378 yaxis: 'y',379 x: [getDiffDate(xDateDaysMin), getDiffDate(xDateDaysMax)],380 y: [xDateDaysMin * lr.slope + lr.intercept, xDateDaysMax * lr.slope + lr.intercept],381 type: 'scatter',382 mode: 'lines',383 line: {384 dash: 'dot',385 width: 2386 },387 marker:{388 color: clrRed389 }390 };391 // create chart layout392 var layout = {393 title: {394 text: '<span style="font-weight: bold;">' + arrRanklocations[i] + '</span>',395 font: {396 size: 14397 },398 },399 autosize: true,400 autoscale: false,401 width: 200,402 height: 175,403 margin: {404 l: 28,405 r: 10,406 b: 25,407 t: 50408 },409 showlegend: false,410 xaxis: { 411 tickmode: 'linear',412 tick0: minVacDate,413 dtick: 30 * 24 * 60 * 60 * 1000, // milliseconds414 tickformat: '%b',415 range: [minVacDate, maxVacDate],416 tickfont: {417 size: 9418 },419 showgrid: false,420 },421 yaxis: { 422 title: {423 text: '',424 },425 tickfont: {426 size: 9427 },428 tickvals: [50,100],429 ticktext: ['50%','100%'],430 range: [0, 100],431 showgrid: false432 }433 }434 // create location div elements435 var div_sub_plot = document.createElement("div");436 var div_span_location = document.createElement("span");437 var div_span_rank = document.createElement("span");438 var div_span_slope = document.createElement("span");439 var div_span_min_date = document.createElement("span");440 var div_span_total_vaccinations = document.createElement("span");441 var div_span_population = document.createElement("span");442 // create element id and classnames443 div_sub_plot.id = 'div_sub_plot_' + i;444 div_sub_plot.className = 'div_sub_plot';445 div_span_location.className = 'location';446 div_span_rank.className = 'rank';447 div_span_slope.className = 'slope';448 div_span_min_date.className = 'min_date';449 div_span_total_vaccinations.className = 'total_vaccinations';450 div_span_population.className = 'population';451 // append location div to the parent div_sub_plots (isotope 'grid')452 document.getElementById('div_sub_plots').append(div_sub_plot);453 // add hidden spans to location div for isotope454 div_sub_plot.innerHTML += '<span class="location span_hide" >'+ arrRanklocations[i] +'</span>';455 div_sub_plot.innerHTML += '<span class="rank span_hide">'+ currentRank + '</span>';456 div_sub_plot.innerHTML += '<span class="min_date span_hide">' + xDateDaysMin + '</span>';457 div_sub_plot.innerHTML += '<span class="slope span_hide">'+ lr.slope + '</span>';458 div_sub_plot.innerHTML += '<span class="total_vaccinations span_hide">' + currentTotalVax + '</span>';459 div_sub_plot.innerHTML += '<span class="population span_hide">' + locPopulation + '</span>';460 // add visible content below chart in location div461 div_sub_plot.innerHTML += '<p class="span_show">Current Rank: ' + currentRank + '<br>Doses per 100: '+ parseFloat(currentPer100).toFixed(2) + '<br>Doses: ' + parseInt(currentTotalVax).toLocaleString() + ' <br>Start: '+ xDateMin + '<br>Pop: ' + parseInt(locPopulation).toLocaleString() + '<br>' + locVaccines + '</p>';462 // create plotly data, config, chart463 var data = [trRankPctile, trTrendline];464 var config = {responsive: true}465 Plotly.newPlot('div_sub_plot_' + i, data, layout, config);466 }467 468 }469 // create charts when page loads470 createGlobalTotal100RankChart();471 createAllCountryRankSubPlots();472 473 // initiate isotope474 var $grid = $('.grid').isotope({475 itemSelector: '.div_sub_plot',476 layoutMode: 'fitRows',477 getSortData: {478 location: '.location',479 rank: '.rank parseInt',480 slope: '.slope parseFloat',481 min_date: '.min_date parseInt',482 total_vaccinations: '.total_vaccinations parseInt',483 population: '.population parseInt'484 }485 });486 // isotope button clicks487 $('.sort-btn').on( 'click', function() {488 var sortByValue = $(this).attr('data-sort-by');489 if ($(this).val() == "asc") {490 $(this).val("desc");491 varSortOrder = true;492 } else {493 $(this).val("asc");494 varSortOrder = false;495 }496 $grid.isotope({ 497 sortBy: sortByValue,498 sortAscending: varSortOrder499 });500 });501 // isotope filter502 $('#filter-value').on('input', function() {503 var filterValue = $('#filter-value').val();504 var filterDirection = $('#filter-direction').val();505 $grid.isotope({ filter: function() {506 var locationPop = $(this).find('.population').text();507 //if (filterDirection == 'grtrThan') {508 // return parseInt(filterValue) > filterValue;509 // } else {510 return parseInt(locationPop, 10) > parseInt(filterValue);511 //}512 513 } })514 });515 });516}517// FUNCTIONS518function getDiffDate(days) {519 var date = new Date("2020-12-13");520 return date.setDate(date.getDate() + days)521}522// a and b are javascript Date objects523function dateDiffInDays(a, b) {524 const _MS_PER_DAY = 1000 * 60 * 60 * 24;525 // Discard the time and time-zone information.526 const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());527 const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());528 529 return Math.floor((utc2 - utc1) / _MS_PER_DAY);530 }531// fill 'up' array - if value missing get prev values532 function getFilledUpArray(array) {533 let lastDefinedElement;534 return array.map(element => {535 if (element === "") {536 element = lastDefinedElement;537 }538 lastDefinedElement = element;539 return element;540 });541}542// create trendline543function linearRegression(y, x){544 var lr = {};545 var n = y.length;546 var sum_x = 0;547 var sum_y = 0;548 var sum_xy = 0;549 var sum_xx = 0;550 var sum_yy = 0;551 for (var i = 0; i < y.length; i++) {552 sum_x += parseInt(x[i]);553 sum_y += y[i];554 sum_xy += (parseInt(x[i]) * y[i]);555 sum_xx += (parseInt(x[i]) * parseInt(x[i]));556 sum_yy += (y[i] * y[i]);557 } 558 lr['slope'] = (n * sum_xy - sum_x * sum_y) / (n * sum_xx - sum_x * sum_x);559 lr['intercept'] = (sum_y - lr.slope * sum_x)/n;560 lr['r2'] = Math.pow((n * sum_xy - sum_x * sum_y)/Math.sqrt((n * sum_xx - sum_x * sum_x) * (n * sum_yy - sum_y * sum_y)), 2);561 return lr;562};563// not used yet but hide show date, country table564function toggleTable(tableId) {565 if (document.getElementById(tableId).style.display == "table" ) {566 document.getElementById(tableId).style.display="none";567 } else {568 document.getElementById(tableId).style.display="table";569 }570}571// get rank percentile for single rank / country count572function getRankPctile(rank, ctryCount) {573 return parseInt((ctryCount - rank + 1) / ctryCount * 100);574}575// get rank percentile for array of ranks / country counts576function getPercentile(arrRank, arrCtryCount) {577 results = [];578 for (var i=0; i<arrRank.length; i++) {579 if (arrRank[i] > 0) {580 results.push(parseInt((arrCtryCount[i] - arrRank[i] + 1) / arrCtryCount[i] * 100));581 }582 }583 return results584}585// used to round up y axis range max value586function roundUp10(x) {587 return Math.ceil(x / 10) * 10;588}589// left join function used to join datasets590function equijoinWithDefault(xs, ys, primary, foreign, sel, def) {591 const iy = ys.reduce((iy, row) => iy.set(row[foreign], row), new Map);592 return xs.map(row => typeof iy.get(row[primary]) !== 'undefined' ? sel(row, iy.get(row[primary])): sel(row, def));593}594// remove date hyphens to create integer to sort with595function reformatDate(d) {596 // "2021-03-13" is owid date format 597 var newDate = d.replace(/-/g, '');598 return newDate599}600function changeTimezone(d) {601 var date = new Date(d);602 var dateEST = new Date(date.setHours(date.getHours() - 5));603 return new Date(dateEST.getTime() - (dateEST.getTimezoneOffset() * 60000)).toISOString().replace('T', ' ').slice(0, -8) + ' EST';604}605// assign bar color based on current and prev per 100 values606function fillColor(yper100, yper100Prev) {607 colors = [];608 for (var i = 0; i < yper100.length; i++) {609 if (yper100[i] > yper100Prev[i]) {610 colors.push(clrGreen);611 } else if (yper100[i] < yper100Prev[i]) {612 colors.push(clrRed);613 } else {614 colors.push(clrGray);615 }616 }617 return colors618}619// hide show additional notes hidden div by clicking read more link620function hideShowDiv(id) {621 var e = document.getElementById(id);622 if(e.style.display == 'block')623 e.style.display = 'none';624 else625 e.style.display = 'block';...
ssearchbar.js
Source:ssearchbar.js
...185 var li_list = getLiList();186 // handle different verbs different-like187 li_list = getItemList().searchLocations(value);188 // Rank search results189 //li_locations = rankLocations(li_locations);190 // Fill up Ul191 fillUl(varUl, li_list.slice(0,4), searchOne, clik1);192 boldifyMatch(varUl, value);193 // displayUl194 showUl(varUl);195 }196 // submit search for create s-ble197 submtBtn.onclick = function(e) {198 199 /*200 var tableDiv = getTableDiv();201 // prevent default event behavior.202 e.preventDefault();203 // what did you 204 // think it was gonna do? Cure cancer?205 //206 var formData = {207 op : 'searchSearchables',208 table : tables,209 query : searchOne.value210 };211 var template = document.getElementById('disp-searchable-tmpl').innerHTML;212 var searchSbmt = new Ajax({213 requestType: 'POST',214 requestUrl: 'admin/admin_ops.php',215 requestParameters: ' ',216 data: formData,217 dataType : 'JSON',218 sendNow: true219 }, function(data) { 220 // should return with a handsome table221 var result = JSON.parse(data);222 // set tableDiv to display the thing223 tableDiv.innerHTML = Mustache.render(template, 224 { 'columns': result.cols});225 // remove buttons for important fields226 $('.edit-toggle.imp').remove();227 // remove buttons for nonfk posers228 // YOU KNOW WHO YOU ARE!229 $('.db_find.bleh').remove();230 $('.db_find.imp_fk').remove();231 // hide inputs232 $('.edit-input').hide();233 // remove edit toggle for important things234 $('.edit-toggle.imp_fk').remove();235 });236 $('.edit-toggle').on('click', editValue);237 // find buttons need call search bar function238 $( '.find' ).on('click', function(e) {239 var col = $( e.target ).parents('td.db_find').siblings('td.db_col').text();240 col = stringParse(col);241 callSearchBar(col);242 });243 */244 }245 // position uls246 oneX = searchOne.offsetLeft;247 oneY = searchOne.offsetTop + searchOne.offsetHeight;248 //queryX = oneX;249 //queryUl.style.display = "block";250 //varX = oneX + queryUl.offsetWidth;251 //queryUl.style.display = "none";252 // set varX to searchbar offset253 varX = oneX;254 //queryUl.style.left = queryX.toString() + "px";255 varUl.style.left = varX.toString() + "px";256 //queryUl.style.top = oneY.toString() + "px";257 varUl.style.top = oneY.toString() + "px";258 /** takes an unordered list and fills them259 * @param - ul, unordered list dom element260 * - data, a list of text261 * - clickTarg, to receive click value262 **/263 function fillUl(ul, data, clickTarg, clickTrk) {264 var name = null; 265 for (var i = 0; i < data.length; i++) {266 // check for duplicate names267 // if they're in there, forget em268 if (name == data[i].name) 269 {continue;}270 else 271 {name = data[i].name;}272 273 var item = document.createElement("LI");274 var itemText = document.createTextNode(data[i].name);275 item.appendChild(itemText);276 ul.appendChild(item);277 // add onclick function to278 // add value to element279 item.onclick = function(e) {280 e.stopPropagation();281 // get element282 var elem = e.target;283 //alert (e.target.tagName);284 // check if we've got a bold tag by accident285 // if so, get the parent (li) 286 if (elem.tagName == 'B')287 elem = elem.parentNode;288 // remove tags289 var value = elem.innerHTML.replace(/(<([^>]+)>)/ig,"");290 // change value of target291 clickTarg.value = value;292 // change value of track293 clickTrk.value = 1;294 // mark down topic if we're varUl295 if (e.target.parentNode.id == 's-var') {296 // get type from parallel list297 var children = e.target.parentNode.childNodes;298 var i = 0;299 for (; i < children.length; i++) 300 if (e.target == children[i]) 301 break;302 // set type303 topic.value = data[i].type;304 }305 // disappear parent306 ul.style.display = 'none';307 // clear ul308 clearUl(ul);309 }310 }311 }312 function clearUl(ul) {313 while (ul.firstChild)314 ul.removeChild(ul.firstChild);315 }316 function hideUl(ul) {317 ul.style.display = 'none';318 }319 function showUl(ul) {320 ul.style.display = 'block';321 }322 function updateValue(e, box) {323 // get pressed key324 var keyCode = ('which' in e) ? e.which : e.keyCode;325 // if it's a smelly shift, 326 // don't care327 if (keyCode === 16)328 return box.value;329 // if backspace, return string330 // minus 1331 if (keyCode === 8)332 return box.value.substring(0, box.value.length-1);333 // otherwise add to value334 keyCode = String.fromCharCode(keyCode).toLowerCase();335 return box.value + keyCode;336 }337 function searchList(term, src) {338 var list = [];339 for (var i = 0; i < src.length; i++)340 {341 var lower_src = src[i].name.toLowerCase();342 match = lower_src.indexOf(term.toLowerCase());343 // if it's a hit,344 // prioritize matches at beginning345 if (match >= 0)346 if (match == 0)347 list.unshift(src[i]);348 else349 list.push(src[i]);350 }351 return list;352 }353 function boldifyMatch(ul, term)354 {355 var sub;356 // for each term in the list357 for (var i = 0; i < ul.children.length; i++) {358 sub = term.toLowerCase();359 // get start and endpoints360 // of term, and li string361 var tStart = ul.children[i].innerHTML.toLowerCase().indexOf(sub);362 var tEnd = tStart + term.length;363 var iEnd = ul.children[i].innerHTML.length;364 var t1 = ul.children[i].innerHTML.substr(0,tStart);365 var t2 = ul.children[i].innerHTML.substr(tStart, term.length);366 var t3 = ul.children[i].innerHTML.substr(tEnd,iEnd);367 // if match starts @ beginning...368 if (tStart == 0)369 ul.children[i].innerHTML = '<b>' + t2 + '</b>' + t3;370 else371 ul.children[i].innerHTML = t1 + '<b>' + t2 + '</b>' + t3;372 }373 }374 function rankLocations(list) {375 // want to push items with United States376 // to the top377 var rankedList = [];378 379 // if list is short enough, return380 if (list.length <= LIST_SIZE)381 return list;382 var unshiftCount = 0;383 for (var i = 0; i < list.length; i++)384 {385 /*386 // break if you've got387 // four priority things388 if (unshiftCount >= 4)...
searchbar (copy).js
Source:searchbar (copy).js
...241 switch (selector.selectedIndex) {242 case 0:243 li_locations = locations.searchLocations(value);244 // Rank search results245 //li_locations = rankLocations(li_locations);246 // Fill up Ul247 fillUl(varUl, li_locations.slice(0,4), searchOne, clik1);248 boldifyMatch(varUl, value);249 break;250 case 1:251 // search for language252 li_languages = languages.search(value);253 // fill ul254 fillUl(varUl, li_languages.slice(0,4), searchOne, clik1);255 boldifyMatch(varUl, value);256 break;257 }258 // displayUl259 showUl(varUl);260 }261 // update list262 searchTwo.onkeydown = function(e) {263 // clear ul264 clearUl(locUl);265 // get new value266 var value = updateValue(e, searchTwo);267 // if value changes, unclick268 if (value != searchTwo.value)269 clik2.value = 0;270 if (value == '')271 return;272 // get locations273 li_locations = locations.searchLocations(value);274 // Rank search results275 //li_locations = rankLocations(li_locations);276 // Fill up Ul277 fillUl(locUl, li_locations.slice(0,4), searchTwo, clik2);278 boldifyMatch(locUl, value);279 }280 selector.onchange = function() {281 topic.value = '';282 }283 // position uls284 oneX = searchOne.offsetLeft;285 oneY = searchOne.offsetTop + searchOne.offsetHeight;286 twoX = searchTwo.offsetLeft;287 //queryX = oneX;288 //queryUl.style.display = "block";289 //varX = oneX + queryUl.offsetWidth;290 //queryUl.style.display = "none";291 // set varX to searchbar offset292 varX = oneX;293 //queryUl.style.left = queryX.toString() + "px";294 varUl.style.left = varX.toString() + "px";295 locUl.style.left = twoX.toString() + "px";296 //queryUl.style.top = oneY.toString() + "px";297 varUl.style.top = oneY.toString() + "px";298 locUl.style.top = oneY.toString() + "px";299 }300 /** takes an unordered list and fills them301 * @param - ul, unordered list dom element302 * - data, a list of text303 * - clickTarg, to receive click value304 **/305 function fillUl(ul, data, clickTarg, clickTrk) {306 var name = null; 307 for (var i = 0; i < data.length; i++) {308 // check for duplicate names309 // if they're in there, forget em310 if (name == data[i].name) 311 {continue;}312 else 313 {name = data[i].name;}314 315 var item = document.createElement("LI");316 var itemText = document.createTextNode(data[i].name);317 item.appendChild(itemText);318 ul.appendChild(item);319 // add onclick function to320 // add value to element321 item.onclick = function(e) {322 e.stopPropagation();323 // get element324 var elem = e.target;325 //alert (e.target.tagName);326 // check if we've got a bold tag by accident327 // if so, get the parent (li) 328 if (elem.tagName == 'B')329 elem = elem.parentNode;330 // remove tags331 var value = elem.innerHTML.replace(/(<([^>]+)>)/ig,"");332 // change value of target333 clickTarg.value = value;334 // change value of track335 clickTrk.value = 1;336 // mark down topic if we're varUl337 if (e.target.parentNode.id == 's-var') {338 // get type from parallel list339 var children = e.target.parentNode.childNodes;340 var i = 0;341 for (; i < children.length; i++) 342 if (e.target == children[i]) 343 break;344 // set type345 topic.value = data[i].type;346 }347 // disappear parent348 ul.style.display = 'none';349 // clear ul350 clearUl(ul);351 }352 }353 }354 function clearUl(ul) {355 while (ul.firstChild)356 ul.removeChild(ul.firstChild);357 }358 function hideUl(ul) {359 ul.style.display = 'none';360 }361 function showUl(ul) {362 ul.style.display = 'block';363 }364 function updateValue(e, box) {365 // get pressed key366 var keyCode = ('which' in e) ? e.which : e.keyCode;367 // if it's a smelly shift, 368 // don't care369 if (keyCode === 16)370 return box.value;371 // if backspace, return string372 // minus 1373 if (keyCode === 8)374 return box.value.substring(0, box.value.length-1);375 // otherwise add to value376 keyCode = String.fromCharCode(keyCode).toLowerCase();377 return box.value + keyCode;378 }379 function searchList(term, src) {380 var list = [];381 for (var i = 0; i < src.length; i++)382 {383 var lower_src = src[i].name.toLowerCase();384 match = lower_src.indexOf(term.toLowerCase());385 // if it's a hit,386 // prioritize matches at beginning387 if (match >= 0)388 if (match == 0)389 list.unshift(src[i]);390 else391 list.push(src[i]);392 }393 return list;394 }395 function boldifyMatch(ul, term)396 {397 var sub;398 // for each term in the list399 for (var i = 0; i < ul.children.length; i++) {400 sub = term.toLowerCase();401 // get start and endpoints402 // of term, and li string403 var tStart = ul.children[i].innerHTML.toLowerCase().indexOf(sub);404 var tEnd = tStart + term.length;405 var iEnd = ul.children[i].innerHTML.length;406 var t1 = ul.children[i].innerHTML.substr(0,tStart);407 var t2 = ul.children[i].innerHTML.substr(tStart, term.length);408 var t3 = ul.children[i].innerHTML.substr(tEnd,iEnd);409 // if match starts @ beginning...410 if (tStart == 0)411 ul.children[i].innerHTML = '<b>' + t2 + '</b>' + t3;412 else413 ul.children[i].innerHTML = t1 + '<b>' + t2 + '</b>' + t3;414 }415 }416 function rankLocations(list) {417 // in this rudimentary list, we just418 // want to push items with United States419 // to the top420 var rankedList = [];421 422 // if list is short enough, return423 if (list.length <= LIST_SIZE)424 return list;425 var unshiftCount = 0;426 for (var i = 0; i < list.length; i++)427 {428 /*429 // break if you've got430 // four priority things...
gatsby-node.ts
Source:gatsby-node.ts
...134 const populationData = preparePopulationData(populations);135 const historyData = prepareHistoryData(coronavirusData);136 const summaryData = prepareSummaryData(historyData);137 [...locations]138 .sort(rankLocations(summaryData, populationData))139 .reduce<{ readonly [areaType: string]: number }>(140 (141 accumulator,142 [areaCode, areaName, areaType]: readonly [string, string, string],143 index: number144 ) => {145 // Combine calculated data146 const location = {147 areaCode,148 areaName,149 areaType,150 slug: `/${areaType}/${String(paramCase(areaName))}`,151 population: populationData[areaCode],152 rank: index + 1,...
location.ts
Source:location.ts
...80 });81 describe.skip('rankLocations', () => {82 it('returns a number to sort by', () => {83 // To be implemented84 rankLocations({}, {});85 });86 });87 describe('formatAreaType', () => {88 it('Makes the area type pretty', () => {89 const areaType = 'nation';90 const result = formatAreaType(areaType);91 expect(typeof result).toStrictEqual('string');92 expect(result).not.toStrictEqual(areaType);93 });94 it('Returns "All Locations" when null is provided', () => {95 const areaType = null;96 const result = formatAreaType(areaType);97 expect(result).toMatch(/^all locations$/i);98 });...
Using AI Code Generation
1const { rankLocations } = require("qawolf");2 { x: 1, y: 1 },3 { x: 2, y: 2 },4 { x: 3, y: 3 }5];6console.log(rankLocations(locations));7const { create } = require("qawolf");8const browser = await create();9await browser.close();10const { create } = require("qawolf");11const browser = await create();12await browser.close();13const { create } = require("qawolf");14const browser = await create();15await browser.close();16const { create } = require("qawolf");17const browser = await create();18await browser.close();19const { create } = require("qawolf");20const browser = await create();21await browser.close();22const { create } = require("qawolf");23const browser = await create();24await browser.close();25const { create } = require("qawolf");26const browser = await create();27await browser.close();28const { create } = require("qawolf");29const browser = await create();30await browser.close();31const { create } = require("qawolf");32const browser = await create();33await browser.close();34const { create } = require("qawolf");35const browser = await create();36await browser.close();37const { create } = require("qawolf");38const browser = await create();39await browser.close();40const { create } =
Using AI Code Generation
1const { rankLocations } = require("qawolf");2 {3 },4 {5 },6 {7 },8 {9 },10];11const rankedLocations = rankLocations(locations);12console.log(rankedLocations);13const { rankLocations } = require("qawolf");14 {15 },16 {17 },18 {19 },20 {21 },22];23const rankedLocations = rankLocations(locations);24console.log(rankedLocations);
Using AI Code Generation
1const { rankLocations } = require('qawolf');2const locations = require('./locations.json');3const rankedLocations = rankLocations(locations);4console.log(rankedLocations);5const { generateLocations } = require('qawolf');6const locations = generateLocations();7console.log(locations);
Using AI Code Generation
1const qawolf = require("qawolf");2qawolf.rankLocations([{x: 10, y: 10}, {x: 10, y: 10}])3 .then(console.log);4 .then(console.log);5 .then(console.log);6 .then(console.log);7 .then(console.log);8 .then(console.log);9 .then(console.log);10 .then(console.log);11 .then(console.log);12 .then(console.log);13 .then(console.log);14 .then(console.log);15 .then(console.log);16 .then(console.log);
Using AI Code Generation
1const { rankLocations } = require("@qawolf/rank-locations");2const { launch } = require("@qawolf/browser");3const { create } = require("@qawolf/web");4const { get } = require("http");5async function test() {6 const browser = await launch();7 const context = await browser.newContext();8 const page = await context.newPage();9 const searchInput = await page.$("input[name='q']");10 await searchInput.type("qawolf");11 await searchInput.press("Enter");
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!