Best JavaScript code snippet using best
select-logic.js
Source:select-logic.js
1/*2_________________Created by emyers 10/2016_____________3*/4$(".selectpicker").selectpicker();5//Change Displayed Metric select options6function populateMetricOptions(selectedIndex) {7 var metricOptions;8 //var keepMetricIndex = selectedIndex;9 if ($("#displayedMetricSelect")[0].selectedOptions.length > 0) {10 var previousFieldLabel = $("#displayedMetricSelect")[0].selectedOptions[0].label;11 var test = $("#displayedMetricSelect option:selected");12 }13 if ($(".radio input[type='radio']:checked")[0].id == "radio1") {14 switch (selectedIndex) {15 case 0:16 if ($("#st-select")[0].selectedIndex > 0) {17 metricOptions = Catchments_st; //UPDATE TODO if catchments are split, update to the appropriate object.18 } else {19 metricOptions = Catchments;20 }21 break;22 case 1:23 if ($("#st-select")[0].selectedIndex > 0) {24 metricOptions = Group3_st;25 } else {26 metricOptions = Group3;27 }28 break;29 case 2:30 if ($("#st-select")[0].selectedIndex > 0) {31 metricOptions = Group2_st;32 } else {33 metricOptions = Group2;34 }35 break;36 case 3:37 if ($("#st-select")[0].selectedIndex > 0) {38 metricOptions = Group1_st;39 } else {40 metricOptions = Group1;41 }42 break;43 case 4:44 if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp2-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {45 metricOptions = Group3_st;46 }47 else if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {48 metricOptions = Group3_st;49 }50 else if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp2-select")[0].selectedIndex > 0) {51 metricOptions = Group3_st;52 }53 else if ($("#grp2-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {54 metricOptions = Group2_st;55 }56 else if ($("#grp3-select")[0].selectedIndex > 0) {57 metricOptions = Group3_st;58 }59 else if ($("#grp2-select")[0].selectedIndex > 0) {60 metricOptions = Group2_st;61 }62 else if ($("#grp1-select")[0].selectedIndex > 0) {63 metricOptions = Group1_st;64 } else {65 metricOptions = ST;66 }67 break;68 }69 } if ($(".radio input[type='radio']:checked")[0].id == "radio2") {70 switch (selectedIndex) {71 case 0:72 if ($("#st-select")[0].selectedIndex > 0) {73 metricOptions = Catchments_st_tn; //UPDATE TODO if catchments are split, update to the appropriate object.74 } else {75 metricOptions = Catchments_tn;76 }77 break;78 case 1:79 if ($("#st-select")[0].selectedIndex > 0) {80 metricOptions = Group3_st_tn;81 } else {82 metricOptions = Group3_tn;83 }84 break;85 case 2:86 if ($("#st-select")[0].selectedIndex > 0) {87 metricOptions = Group2_st_tn;88 } else {89 metricOptions = Group2_tn;90 }91 break;92 case 3:93 if ($("#st-select")[0].selectedIndex > 0) {94 metricOptions = Group1_st_tn;95 } else {96 metricOptions = Group1_tn;97 }98 break;99 case 4:100 if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp2-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {101 metricOptions = Group3_st_tn;102 }103 else if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {104 metricOptions = Group3_st_tn;105 }106 else if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp2-select")[0].selectedIndex > 0) {107 metricOptions = Group3_st_tn;108 }109 else if ($("#grp2-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {110 metricOptions = Group2_st_tn;111 }112 else if ($("#grp3-select")[0].selectedIndex > 0) {113 metricOptions = Group3_st_tn;114 }115 else if ($("#grp2-select")[0].selectedIndex > 0) {116 metricOptions = Group2_st_tn;117 }118 else if ($("#grp1-select")[0].selectedIndex > 0) {119 metricOptions = Group1_st_tn;120 } else {121 metricOptions = ST_tn;122 }123 break;124 }125 } if ($(".radio input[type='radio']:checked")[0].id == "radio3"){126 switch (selectedIndex) {127 case 0:128 if ($("#st-select")[0].selectedIndex > 0) {129 metricOptions = Catchments_st_q; //UPDATE TODO if catchments are split, update to the appropriate object.130 } else {131 metricOptions = Catchments_q;132 }133 break;134 case 1:135 if ($("#st-select")[0].selectedIndex > 0) {136 metricOptions = Group3_st_q;137 } else {138 metricOptions = Group3_q;139 }140 break;141 case 2:142 if ($("#st-select")[0].selectedIndex > 0) {143 metricOptions = Group2_st_q;144 } else {145 metricOptions = Group2_q;146 }147 break;148 case 3:149 if ($("#st-select")[0].selectedIndex > 0) {150 metricOptions = Group1_st_q;151 } else {152 metricOptions = Group1_q;153 }154 break;155 case 4:156 if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp2-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {157 metricOptions = Group3_st_q;158 }159 else if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {160 metricOptions = Group3_st_q;161 }162 else if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp2-select")[0].selectedIndex > 0) {163 metricOptions = Group3_st_q;164 }165 else if ($("#grp2-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {166 metricOptions = Group2_st_q;167 }168 else if ($("#grp3-select")[0].selectedIndex > 0) {169 metricOptions = Group3_st_q;170 }171 else if ($("#grp2-select")[0].selectedIndex > 0) {172 metricOptions = Group2_st_q;173 }174 else if ($("#grp1-select")[0].selectedIndex > 0) {175 metricOptions = Group1_st_q;176 } else {177 metricOptions = ST_q;178 }179 break;180 }181 } if ($(".radio input[type='radio']:checked")[0].id == "radio4"){182 switch (selectedIndex) {183 case 0:184 if ($("#st-select")[0].selectedIndex > 0) {185 metricOptions = Catchments_st_ss; //UPDATE TODO if catchments are split, update to the appropriate object.186 } else {187 metricOptions = Catchments_ss;188 }189 break;190 case 1:191 if ($("#st-select")[0].selectedIndex > 0) {192 metricOptions = Group3_st_ss;193 } else {194 metricOptions = Group3_ss;195 }196 break;197 case 2:198 if ($("#st-select")[0].selectedIndex > 0) {199 metricOptions = Group2_st_ss;200 } else {201 metricOptions = Group2_ss;202 }203 break;204 case 3:205 if ($("#st-select")[0].selectedIndex > 0) {206 metricOptions = Group1_st_ss;207 } else {208 metricOptions = Group1_ss;209 }210 break;211 case 4:212 if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp2-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {213 metricOptions = Group3_st_ss;214 }215 else if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {216 metricOptions = Group3_st_ss;217 }218 else if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp2-select")[0].selectedIndex > 0) {219 metricOptions = Group3_st_ss;220 }221 else if ($("#grp2-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {222 metricOptions = Group2_st_ss;223 }224 else if ($("#grp3-select")[0].selectedIndex > 0) {225 metricOptions = Group3_st_ss;226 }227 else if ($("#grp2-select")[0].selectedIndex > 0) {228 metricOptions = Group2_st_ss;229 }230 else if ($("#grp1-select")[0].selectedIndex > 0) {231 metricOptions = Group1_st_ss;232 } else {233 metricOptions = ST_ss;234 }235 break;236 }237 }238 //remove old and set new metric options, refresh select picker239 $("#displayedMetricSelect")240 .find("option")241 .remove();242 $.each(metricOptions, function(index, value) {243 $("#displayedMetricSelect").append(new Option(value.name, value.field));244 });245 $("#displayedMetricSelect").selectpicker("refresh");246 //find previously Selected metric value247 var selectedMetric = function(previousFieldLabel, metricOptions) {248 for (var i = 0, len = metricOptions.length; i < len; i++) {249 if (previousFieldLabel === metricOptions[i].name) {250 return metricOptions[i];251 }252 }253 return null;254 };255 //set the selected metric dropdown here256 if (previousFieldLabel) {257 if (selectedMetric(previousFieldLabel, metricOptions) != null) {258 //set dropdown to previously selected value259 $("#displayedMetricSelect").selectpicker("val", selectedMetric(previousFieldLabel, metricOptions).field); //use field value, not name260 } else {261 //set default to the first new metric option because the previously selected value isn't in the new list.262 $("#displayedMetricSelect").selectpicker("val", metricOptions[0].field);263 }264 } else {265 $("#displayedMetricSelect").selectpicker("val", metricOptions[0].field);266 }267} // END populateMetricOptions268function updateSourceOptions() {269 delete app.chosenSource;270 //remove old source data options, add new and refresh271 $("#displayedSourceSelect")272 .find("option")273 .remove();274 $("#displayedSourceSelect").append(new Option('All Sources', 'All Sources'));275 var sourceOptions = getChartOutfields(app.map.getLayer("SparrowRanking").visibleLayers[0]);276 $.each(sourceOptions, function(index, value) {277 if (value.attribute.indexOf('_') > -1) {278 var shortName = value.label.split(") ")[1]279 $("#displayedSourceSelect").append(new Option(shortName, value.attribute));280 }281 });282 $("#displayedSourceSelect").selectpicker("refresh");283 $("#displayedSourceSelect").selectpicker("val", "All Sources");284}285//used when clearing the AOI286function returnDefaultLayer(sparrowId) {287 switch (sparrowId) {288 case 5:289 return 0;290 case 6:291 return 1;292 case 7:293 return 2;294 case 8:295 return 3;296 case 14:297 return 9;298 case 15:299 return 10;300 case 16:301 return 11;302 case 17:303 return 12;304 case 23:305 return 18;306 case 24:307 return 19;308 case 25:309 return 20;310 case 26:311 return 21;312 case 32:313 return 27;314 case 33:315 return 28;316 case 34:317 return 29;318 case 35:319 return 30;320 }321}322//used when clearing AOI to revert any selections back to the full state laeyer323function returnToStateLayer(sparrowId){324 switch(sparrowId){325 case 8:326 return 4;327 case 7:328 return 4;329 case 6:330 return 4;331 case 5:332 return 4;333 case 17:334 return 13;335 case 16:336 return 13;337 case 15: 338 return 13;339 case 14:340 return 13;341 case 26:342 return 22;343 case 25:344 return 22;345 case 24:346 return 22;347 case 23:348 return 22;349 case 35:350 return 31;351 case 34:352 return 31;353 case 33:354 return 31;355 case 32:356 return 31;357 }358}359//uses the #groupResultsSelect selected value and Selected radio to define the SparrowRanking display layer.360function setAggregateGroup(groupBySelectedIndex, selectedRadio) {361 if (selectedRadio == "radio1") {362 var layerArrayValue;363 switch (groupBySelectedIndex) {364 case 0:365 if ($("#st-select")[0].selectedIndex > 0) {366 layerArrayValue = 5; //TODO UPDATE AddCatchments with splits if they become available?367 } else {368 layerArrayValue = 0;369 }370 break;371 case 1:372 if ($("#st-select")[0].selectedIndex > 0) {373 layerArrayValue = 6; //sg3374 } else {375 layerArrayValue = 1;376 }377 break;378 case 2:379 if ($("#st-select")[0].selectedIndex > 0) {380 layerArrayValue = 7; //sg2381 } else {382 layerArrayValue = 2;383 }384 break;385 case 3:386 if ($("#st-select")[0].selectedIndex > 0) {387 layerArrayValue = 8; //sg1388 } else {389 layerArrayValue = 3;390 }391 break;392 case 4:393 if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp2-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {394 layerArrayValue = 6; //sg3395 }396 else if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {397 layerArrayValue = 6; //sg3398 }399 else if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp2-select")[0].selectedIndex > 0) {400 layerArrayValue = 6; //sg3401 }402 else if ($("#grp2-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {403 layerArrayValue = 7; //sg2404 }405 else if ($("#grp3-select")[0].selectedIndex > 0) {406 layerArrayValue = 6; //sg3407 }408 else if ($("#grp2-select")[0].selectedIndex > 0) {409 layerArrayValue = 7; //sg2410 }411 else if ($("#grp1-select")[0].selectedIndex > 0) {412 layerArrayValue = 8; //sg1413 } else {414 layerArrayValue = 4; //ST415 }416 break;417 }418 } if (selectedRadio == "radio2") {419 //UPDATE TODO impoartant! verify layerIDs here when Nitrogen Layers become available!!!!!420 var layerArrayValue;421 switch (groupBySelectedIndex) {422 case 0:423 if ($("#st-select")[0].selectedIndex > 0) {424 layerArrayValue = 14; //TODO UPDATE AddCatchments with splits if they become available?425 } else {426 layerArrayValue = 9;427 }428 break;429 case 1:430 if ($("#st-select")[0].selectedIndex > 0) {431 layerArrayValue = 15; //grp3 w/ state splits432 } else {433 layerArrayValue = 10;434 }435 break;436 case 2:437 if ($("#st-select")[0].selectedIndex > 0) {438 layerArrayValue = 16; //grp2 w/ state splits439 } else {440 layerArrayValue = 11;441 }442 break;443 case 3:444 if ($("#st-select")[0].selectedIndex > 0) {445 layerArrayValue = 17; //grp1 w/ state splits446 } else {447 layerArrayValue = 12;448 }449 break;450 case 4:451 if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp2-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {452 layerArrayValue = 15; //sg3453 }454 else if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {455 layerArrayValue = 15; //sg3456 }457 else if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp2-select")[0].selectedIndex > 0) {458 layerArrayValue = 15; //sg3459 }460 else if ($("#grp2-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {461 layerArrayValue = 16; //sg2462 }463 else if ($("#grp3-select")[0].selectedIndex > 0) {464 layerArrayValue = 15; //sg3465 }466 else if ($("#grp2-select")[0].selectedIndex > 0) {467 layerArrayValue = 16; //sg2468 }469 else if ($("#grp1-select")[0].selectedIndex > 0) {470 layerArrayValue = 17; //sg1471 } else {472 layerArrayValue = 13; //ST473 }474 break;475 } 476 } if (selectedRadio == "radio3"){477 //UPDATE TODO impoartant! verify layerIDs here when Nitrogen Layers become available!!!!!478 var layerArrayValue;479 switch (groupBySelectedIndex) {480 case 0:481 if ($("#st-select")[0].selectedIndex > 0) {482 layerArrayValue = 23; //TODO UPDATE AddCatchments with splits if they become available?483 } else {484 layerArrayValue = 18;485 }486 break;487 case 1:488 if ($("#st-select")[0].selectedIndex > 0) {489 layerArrayValue = 24; //grp3 w/ state splits490 } else {491 layerArrayValue = 19;492 }493 break;494 case 2:495 if ($("#st-select")[0].selectedIndex > 0) {496 layerArrayValue = 25; //grp2 w/ state splits497 } else {498 layerArrayValue = 20;499 }500 break;501 case 3:502 if ($("#st-select")[0].selectedIndex > 0) {503 layerArrayValue = 26; //grp1 w/ state splits504 } else {505 layerArrayValue = 21;506 }507 break;508 case 4:509 if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp2-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {510 layerArrayValue = 24; //sg3511 }512 else if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {513 layerArrayValue = 24; //sg3514 }515 else if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp2-select")[0].selectedIndex > 0) {516 layerArrayValue = 24; //sg3517 }518 else if ($("#grp2-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {519 layerArrayValue = 25; //sg2520 }521 else if ($("#grp3-select")[0].selectedIndex > 0) {522 layerArrayValue = 24; //sg3523 }524 else if ($("#grp2-select")[0].selectedIndex > 0) {525 layerArrayValue = 25; //sg2526 }527 else if ($("#grp1-select")[0].selectedIndex > 0) {528 layerArrayValue = 26; //sg1529 } else {530 layerArrayValue = 22; //ST531 }532 break;533 }534 } if (selectedRadio == "radio4") {535 //UPDATE TODO impoartant! verify layerIDs here when Nitrogen Layers become available!!!!!536 var layerArrayValue;537 switch (groupBySelectedIndex) {538 case 0:539 if ($("#st-select")[0].selectedIndex > 0) {540 layerArrayValue = 32; //TODO UPDATE AddCatchments with splits if they become available?541 } else {542 layerArrayValue = 27;543 }544 break;545 case 1:546 if ($("#st-select")[0].selectedIndex > 0) {547 layerArrayValue = 33; //grp3 w/ state splits548 } else {549 layerArrayValue = 28;550 }551 break;552 case 2:553 if ($("#st-select")[0].selectedIndex > 0) {554 layerArrayValue = 34; //grp2 w/ state splits555 } else {556 layerArrayValue = 29;557 }558 break;559 case 3:560 if ($("#st-select")[0].selectedIndex > 0) {561 layerArrayValue = 35; //grp1 w/ state splits562 } else {563 layerArrayValue = 30;564 }565 break;566 case 4:567 if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp2-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {568 layerArrayValue = 33; //sg3569 }570 else if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {571 layerArrayValue = 33; //sg3572 }573 else if ($("#grp3-select")[0].selectedIndex > 0 && $("#grp2-select")[0].selectedIndex > 0) {574 layerArrayValue = 33; //sg3575 }576 else if ($("#grp2-select")[0].selectedIndex > 0 && $("#grp1-select")[0].selectedIndex > 0) {577 layerArrayValue = 34; //sg2578 }579 else if ($("#grp3-select")[0].selectedIndex > 0) {580 layerArrayValue = 33; //sg3581 }582 else if ($("#grp2-select")[0].selectedIndex > 0) {583 layerArrayValue = 34; //sg2584 }585 else if ($("#grp1-select")[0].selectedIndex > 0) {586 layerArrayValue = 35; //sg1587 } else {588 layerArrayValue = 31; //ST589 }590 break;591 }592 }593 var visibleLayerIds = [layerArrayValue];594 var sparrowRanking = app.map.getLayer("SparrowRanking");595 sparrowRanking.setVisibleLayers(visibleLayerIds);596} //END setAggregateGroup()597function AOIChange(e) {598 $("#page-loader").fadeIn();599 var selectId = e.currentTarget.id;600 var selectValue = e.currentTarget.value;601 var groupResultsIndex = $("#groupResultsSelect")[0].selectedIndex;602 //call to check if user has selected a value in the AOI603 var AOIhasValue = function() {604 if ($("#grp1-select")[0].value !== ""){605 return true;606 }607 //if GRP2 is selected return false and keep GRP3 disabled608 /* else if ($("#grp2-select")[0].value !== "" ){609 return true;610 } */611 else if ($("#grp3-select")[0].value !== "" ){612 return true;613 }614 else if ($("#st-select")[0].value !== "" ){615 return true616 }617 else{618 return false;619 }620 }621 if ($("#groupResultsSelect")[0].selectedIndex == 1 || $("#groupResultsSelect")[0].selectedIndex == 0) {622 //ENABLE huc8 dropdown623 $("#grp3-select").removeClass("disabled"); //huc8624 $("#grp3-select").removeAttr("disabled");625 } else if ($("#groupResultsSelect")[0].selectedIndex == 4){626 if( AOIhasValue() === true ){627 $("#grp3-select").removeClass("disabled"); //huc8628 $("#grp3-select").removeAttr("disabled");629 }630 }631 var newObj = {632 selectedId: selectId,633 selectedValue: selectValue634 };635 //TODO ? if groupResultsIndex == 4 set aggregate group636 //if (selectId == "st-select" && groupResultsIndex != 4) {637 //if not already on a state split layer, set one now.638 //TODO: figure out how you can access the current layers to see if you're on a split layer.639 //if(app.map.getLayer('SparrowRanking').visibleLayers[0]){640 populateMetricOptions($("#groupResultsSelect")[0].selectedIndex);641 setAggregateGroup(groupResultsIndex, $(".radio input[type='radio']:checked")[0].id);642 updateSourceOptions();643 //}644 //only update if there's a value to update to (clearing selected values depending on Group Results by selections)645 if (newObj.selectedValue != "") {646 app.setLayerDefObj(newObj);647 }648 setLayerDefs();649 generateRenderer();650 if ($("#chartWindowDiv").css("visibility") == "visible") {651 $("#toast_title").html("Loading...");652 $("#toast_body").html("Chart updating");653 $("#toast-fixed").fadeIn();654 app.map.graphics.clear();655 app.createChartQuery();656 }657} //END AOIChange()658function setLayerDefs() {659 var definitionString = "";660 var layerDefObj = app.getLayerDefObj();661 if (layerDefObj.AOIST) {662 if (definitionString != "") {663 definitionString += " AND ST = " + "'" + layerDefObj.AOIST + "'";664 } else {665 definitionString += "ST = " + "'" + layerDefObj.AOIST + "'";666 }667 }668 if (layerDefObj.AOI1) {669 if (definitionString != "") {670 definitionString += " AND GP1 = " + "'" + layerDefObj.AOI1 + "'";671 } else {672 definitionString += "GP1 = " + "'" + layerDefObj.AOI1 + "'";673 }674 }675 if (layerDefObj.AOI2) {676 if (definitionString != "") {677 definitionString += " AND GP2 = " + "'" + layerDefObj.AOI2 + "'";678 } else {679 definitionString += "GP2 = " + "'" + layerDefObj.AOI2 + "'";680 }681 }682 /***TODO UPDATE IMPORTANT -- ADDED BUT NOT ***/683 if (layerDefObj.AOI3) {684 if (definitionString != "") {685 definitionString += " AND GP3 = " + "'" + layerDefObj.AOI3 + "'";686 } else {687 definitionString += "GP3 = " + "'" + layerDefObj.AOI3 + "'";688 }689 }690 var layerDefs = [];691 //LayerDefs on ALL Layers692 /***TODO UPDATE IMPORTANT -- note that not all of these layer combinations are going to work with the attributes we have currently. Some layer defs will not set because the fields don't exist***/693 layerDefs[0] = definitionString;694 layerDefs[1] = definitionString;695 layerDefs[2] = definitionString;696 layerDefs[3] = definitionString;697 layerDefs[4] = definitionString;698 layerDefs[5] = definitionString;699 layerDefs[6] = definitionString;700 layerDefs[7] = definitionString;701 layerDefs[8] = definitionString;702 layerDefs[9] = definitionString;703 layerDefs[10] = definitionString;704 layerDefs[11] = definitionString;705 layerDefs[12] = definitionString;706 layerDefs[13] = definitionString;707 layerDefs[14] = definitionString;708 layerDefs[15] = definitionString;709 layerDefs[16] = definitionString;710 layerDefs[17] = definitionString;711 layerDefs[18] = definitionString;712 layerDefs[19] = definitionString;713 layerDefs[20] = definitionString;714 layerDefs[21] = definitionString;715 layerDefs[22] = definitionString;716 layerDefs[23] = definitionString;717 layerDefs[24] = definitionString;718 layerDefs[25] = definitionString;719 layerDefs[26] = definitionString;720 layerDefs[27] = definitionString;721 layerDefs[28] = definitionString;722 layerDefs[29] = definitionString;723 layerDefs[30] = definitionString;724 layerDefs[31] = definitionString;725 layerDefs[32] = definitionString;726 layerDefs[33] = definitionString;727 layerDefs[34] = definitionString;728 layerDefs[35] = definitionString;729 app.map.getLayer("SparrowRanking").setLayerDefinitions(layerDefs);730} // END setLayerDefs()731function getTableFields(headerKeysArr, sparrowLayerId) {732 var label = "";733 var flatArr = [];734 var htmlHeaderArr = [];735 var configArr = [];736 var removeField = "";737 switch (sparrowLayerId) {738 case 0:739 configArr = Group3;740 removeField = "GP3";741 $.each(tableOutFields, function(i, object) {742 flatArr.push(object);743 });744 break;745 case 4:746 configArr = Group3_st;747 removeField = "SG3";748 $.each(stateTableOutFields, function(i, object) {749 flatArr.push(object);750 });751 break;752 case 7:753 configArr = Group3_tn;754 removeField = "GP3";755 $.each(tableOutFields, function(i, object) {756 flatArr.push(object);757 });758 break;759 case 11:760 configArr = Group3_st_tn;761 removeField = "SG3";762 $.each(stateTableOutFields, function(i, object) {763 flatArr.push(object);764 });765 break;766 }767 $.each(configArr, function(index, item) {768 flatArr.push({ field: item.field, name: item.name });769 $.each(item.chartOutfields, function(i, fields) {770 if (771 fields.attribute == removeField &&772 flatArr773 .map(function(f) {774 return f.field;775 })776 .indexOf(removeField) < 0777 ) {778 flatArr.push({ field: fields.attribute, name: fields.label });779 } else if (fields.attribute != removeField) {780 flatArr.push({ field: fields.attribute, name: fields.label });781 }782 });783 });784 htmlHeaderArr.push("<tr>");785 $.each(headerKeysArr, function(index, key) {786 //console.log(key);787 $.each(flatArr, function(index, obj) {788 if (key == obj.field) {789 //console.log(obj.field);790 htmlHeaderArr.push("<th>" + obj.name + "</th>");791 return false; //escape the each loop?792 }793 });794 });795 htmlHeaderArr.push("</tr>");796 return htmlHeaderArr.join("");797}798function getLegendLabels(sparrowLayerId) {799 var label = "";800 var configObject = app.getLayerConfigObject(sparrowLayerId);801 var setModel = function (sparrowLayerId) {802 if (sparrowLayerId <= 8) {803 return "Total Phosphorus";804 }805 if (sparrowLayerId >= 9 && sparrowLayerId <= 17) {806 return "Total Nitrogen";807 }808 if (sparrowLayerId >= 18 && sparrowLayerId <= 26) {809 return "Streamflow";810 }811 if (sparrowLayerId > 26) {812 return "Suspended Sediment";813 }814 }815 var nutrientModel = setModel(sparrowLayerId);816 $.each(configObject, function(index, item) {817 if ($("#displayedMetricSelect").val() == item.field) {818 label = item.name;819 }820 });821 if (app.chosenSource) {label += ' from ' + app.chosenSource.label}822 return nutrientModel + ", " + label;823} //END getLegendLabels()824function getChartOutfields(sparrowLayerId) {825 var chartFieldsArr = [];826 //console.log("in GetChartOutfields()")827 var configObject = app.getLayerConfigObject(sparrowLayerId);828 $.each(configObject, function(index, item) {829 if ($("#displayedMetricSelect").val() == item.field) {830 $.each(item.chartOutfields, function(i, fields) {831 chartFieldsArr.push(fields);832 });833 }834 });835 return chartFieldsArr;836} //END getLegendLabels()837function getExtraOutfields(outfieldsArr, sparrowLayerId) {838 var finalChartArr = outfieldsArr;839 //UPDATE IMPORTANT! check additional area field names840 switch (sparrowLayerId) {841 case 0:842 case 9:843 case 18:844 case 27:845 //CATCHMENTS846 //finalChartArr.push("PNAME");847 finalChartArr.push("INCAREAKM2");848 finalChartArr.push("CUMAREAKM2"); 849 finalChartArr.push("COMID");850 break;851 case 1:852 case 10:853 case 19:854 case 28:855 //HUC8856 finalChartArr.push("GP3_AREA");857 break;858 case 2:859 case 11:860 case 20:861 case 29:862 //Tributarys863 finalChartArr.push("GP2_AREA");864 break;865 case 3:866 case 12:867 case 21:868 case 30:869 //Independent Watershed870 finalChartArr.push("GP1_AREA");871 break;872 case 4:873 case 13:874 case 22:875 case 31:876 //State877 finalChartArr.push("ST_AREA");878 break;879 case 5:880 case 14:881 case 23:882 case 32:883 //Catchments w/ state divisions884 finalChartArr.push("INCAREAKM2");885 finalChartArr.push("CUMAREAKM2");886 finalChartArr.push("ST_COMID");887 break;888 case 6:889 case 15:890 case 24:891 case 33:892 //grp3 w/ state divisions893 finalChartArr.push("SG3_AREA");894 break;895 case 7:896 case 16:897 case 25:898 case 34:899 //grp 2 w/ state divisions900 finalChartArr.push("SG2_AREA");901 break;902 case 8:903 case 17:904 case 26:905 case 35:906 //grp1 w/ state divisions907 finalChartArr.push("SG1_AREA");908 break;909 }910 return finalChartArr;911}912function generateRenderer() {913 require([914 "esri/map",915 "esri/Color",916 "esri/dijit/Legend",917 "esri/layers/LayerDrawingOptions",918 "esri/symbols/SimpleLineSymbol",919 "esri/symbols/SimpleFillSymbol",920 "esri/tasks/ClassBreaksDefinition",921 "esri/tasks/AlgorithmicColorRamp",922 "esri/tasks/GenerateRendererParameters",923 "esri/tasks/GenerateRendererTask",924 "esri/tasks/query",925 "esri/tasks/QueryTask",926 "dojo/dom",927 "dojo/dom-class",928 "dojo/on",929 "dojo/domReady!"930 ], function(931 Map,932 Color,933 Legend,934 LayerDrawingOptions,935 SimpleLineSymbol,936 SimpleFillSymbol,937 ClassBreaksDefinition,938 AlgorithmicColorRamp,939 GenerateRendererParameters,940 GenerateRendererTask,941 Query,942 QueryTask,943 dom,944 domClass,945 on946 ) {947 var sparrowId = app.map.getLayer("SparrowRanking").visibleLayers[0];948 //apply layer defs to renderer if they exist949 if (app.map.getLayer("SparrowRanking").layerDefinitions) {950 var dynamicLayerDefs = app.map.getLayer("SparrowRanking").layerDefinitions[sparrowId];951 app.layerDef = dynamicLayerDefs;952 } else {953 app.map.getLayer("SparrowRanking").setDefaultLayerDefinitions(); //is this necessary?954 app.layerDef = "1=1";955 }956 //UPDATE important! url must match serviceBaseURL in config957 app.Url = serviceBaseURL + sparrowId;958 // get polygon count for global storage959 var query = new Query();960 var queryTask = new QueryTask(app.Url);961 query.where = app.layerDef;962 query.maxAllowableOffset = 750;963 queryTask.executeForCount(964 query,965 function(count) {966 app.polygonResponseCount = count;967 if (app.polygonResponseCount > 2500 && $("#chartButton").prop("disabled", false)) {968 $("#chartButton")969 .prop("disabled", true)970 .css("pointer-events", "none");971 $("#chartButtonWrapper").css("cursor", "not-allowed");972 //note: popup chart button done @ end of chart function since it's not built yet973 $("#fromMapTab").prop("disabled", true);974 } else {975 $("#chartButton")976 .prop("disabled", false)977 .css("pointer-events", "auto");978 $("#chartButtonWrapper").css("cursor", "pointer");979 //note: popup chart button done @ end of chart function since it's not built yet980 $("#fromMapTab").prop("disabled", false);981 }982 if ($("#chartWindowDiv").css("visibility") == "visible") {983 if (app.polygonResponseCount > 2500) {984 $("#toast_title").html("Warning");985 $("#toast_body").html(986 "Cannot show chart for " +987 app.polygonResponseCount +988 " features. Please narrow Area of Interest or Group Results and try again."989 );990 $("#toast-fixed").fadeIn();991 setTimeout(function() {992 $("#toast-fixed").fadeOut();993 }, 5000);994 app.map.graphics.clear();995 $("#chartButton").html("Show Chart");996 app.formattedHighlightString = "";997 $("#chartWindowDiv").css("visibility", "hidden");998 $("#chartWindowContainer").empty();999 $("#chartWindowPanelTitle").empty();1000 } else {1001 app.createChartQuery();1002 }1003 }1004 },1005 function(error) {1006 console.log(error);1007 }1008 );1009 var selectedMetric = $("#displayedMetricSelect")[0].value;1010 app.outFields = [selectedMetric];1011 app.currentAttribute = selectedMetric;1012 var classDef = new ClassBreaksDefinition();1013 if (app.chosenSource) {1014 classDef.classificationField = app.chosenSource.attribute;1015 } else {1016 classDef.classificationField = app.currentAttribute;1017 }1018 classDef.classificationMethod = "quantile";1019 classDef.breakCount = 5;1020 var scale = app.map.getScale();1021 var zoom = app.map.getZoom();1022 //check for dynamic border criteria and set symbols1023 if (dynamicBorderLayers.includes($("#groupResultsSelect")[0].value)) {1024 if (app.map.getZoom() > borderThreshold) {1025 classDef.baseSymbol = new SimpleFillSymbol(1026 SimpleFillSymbol.STYLE_SOLID,1027 new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([168, 168, 168]), 0.1)1028 );1029 } else {1030 //symbol WITHOUT borders1031 classDef.baseSymbol = new SimpleFillSymbol("solid", null, null);1032 }1033 } else {1034 //symbol WITH borders1035 classDef.baseSymbol = new SimpleFillSymbol(1036 SimpleFillSymbol.STYLE_SOLID,1037 new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([168, 168, 168]), 0.1)1038 );1039 }1040 var colorRamp = new AlgorithmicColorRamp();1041 //different ramps for phos/nitro1042 if ($(".radio input[type='radio']:checked")[0].id == "radio1") {1043 //phos brown schema1044 //colorRamp.fromColor = new Color.fromHex((!isNaN(colorIndex) ? phosToColors[colorIndex] : "#FFF1DC")); //original light1045 colorRamp.fromColor = new Color.fromHex((app.chosenSource != undefined) ? fromSourceColor : "#FFF6E8"); //lighter, increases contrast1046 //colorRamp.toColor = new Color.fromHex((!isNaN(colorIndex) ? phosColors[colorIndex] : "#632E0E")); //original dark1047 colorRamp.toColor = new Color.fromHex((app.chosenSource != undefined) ? toSourceColor : "#3F1700"); //darker, increases contrast1048 }1049 if ($(".radio input[type='radio']:checked")[0].id == "radio2") {1050 //nitro green schema1051 colorRamp.fromColor = new Color.fromHex((app.chosenSource != undefined) ? fromSourceColor : "#F5EBB8");1052 //colorRamp.toColor = new Color.fromHex((!isNaN(colorIndex) ? nitroColors[colorIndex] : "#004120")); //original dark1053 colorRamp.toColor = new Color.fromHex((app.chosenSource != undefined) ? toSourceColor : "#003419"); //darker1054 }1055 if ($(".radio input[type='radio']:checked")[0].id == "radio3") {1056 //streamflow blue schema1057 colorRamp.fromColor = new Color.fromHex((app.chosenSource != undefined) ? fromSourceColor : "#cef3f5");//new light1058 colorRamp.toColor = new Color.fromHex((app.chosenSource != undefined) ? toSourceColor : "#00305");1059 }1060 if ($(".radio input[type='radio']:checked")[0].id == "radio4") {1061 //sediment color ramp1062 //colorRamp.fromColor = new Color.fromHex((!isNaN(colorIndex) ? sedimentToColors[colorIndex] : "#FFF4e0"));//original light1063 colorRamp.fromColor = new Color.fromHex((app.chosenSource != undefined) ? fromSourceColor : "#FFF6CF");//more saturated yellow1064 //colorRamp.toColor = new Color.fromHex((!isNaN(colorIndex) ? sedimentColors[colorIndex] : "#B24903"));//original dark1065 colorRamp.toColor = new Color.fromHex((app.chosenSource != undefined) ? toSourceColor : "#A04100");1066 }1067 colorRamp.algorithm = "hsv"; // options are: "cie-lab", "hsv", "lab-lch"1068 classDef.colorRamp = colorRamp;1069 var params = new GenerateRendererParameters();1070 params.classificationDefinition = classDef;1071 // limit the renderer to data being shown by the current layer1072 params.formatLabel = false; //formatLabel = false otherwise expect some bad behavior from the renderer!1073 params.where = app.layerDef;1074 var generateRenderer = new GenerateRendererTask(app.Url);1075 generateRenderer.execute(params, processValues, errorHandler);1076 function processValues(renderer) {1077 //calculate legend values to 3 significant figures1078 function sigFigures(n) {1079 if (n > 0) {1080 //return values as 3 significant figures with comma separated thousands1081 return parseFloat(n.toPrecision(3)).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");1082 } else {1083 return n.toString();1084 }1085 }1086 $.each(renderer.infos, function (index, info) {1087 //calculate sig figures; sigFigures returns string1088 var minVal = sigFigures(info.minValue);1089 var maxVal = sigFigures(info.maxValue);1090 //set new 1091 if (index == 4) {1092 //handle greater than for last label maxValue1093 var newLabel = "> " + minVal;1094 } else if (index == 0) {1095 //no greater than for 1st legend itm1096 var newLabel = minVal + " - " + maxVal;1097 } else {1098 var newLabel = "> " + minVal + " - " + maxVal;1099 }1100 renderer.infos[index].label = newLabel;1101 });1102 applyRenderer(renderer);1103 }1104 function applyRenderer(renderer) {1105 var sparrowId = app.map.getLayer("SparrowRanking").visibleLayers[0];1106 var layer = app.map.getLayer("SparrowRanking");1107 // dynamic layer stuff1108 var optionsArray = [];1109 var drawingOptions = new LayerDrawingOptions();1110 drawingOptions.renderer = renderer;1111 // set the drawing options for the relevant layer1112 // optionsArray index corresponds to layer index in the map service1113 optionsArray[sparrowId] = drawingOptions;1114 layer.setLayerDrawingOptions(optionsArray);1115 if (!app.hasOwnProperty("legend")) {1116 createLegend();1117 } else {1118 var legendInfo = app.legend.layerInfos;1119 //get rid of sparrow ranking while saving other legend elements1120 var updatedLegendInfos = $.grep(legendInfo, function (value) {1121 return value.layer.id !== "SparrowRanking";1122 });1123 var newSparrowRanking = {1124 layer: app.map.getLayer("SparrowRanking"),1125 title: getLegendLabels(app.map.getLayer("SparrowRanking").visibleLayers[0])1126 }1127 updatedLegendInfos.unshift(newSparrowRanking); //put sparrowRanking @ front of array to maintain legend layer order1128 app.legend.refresh(updatedLegendInfos);1129 }1130 if (layer.visible == false) {1131 layer.show();1132 }1133 }1134 function errorHandler(err) {1135 console.log("generateRenderer Err ", err);1136 $("#page-loader").fadeOut();1137 }1138 function createLegend() {1139 app.legend = new Legend(1140 {1141 map: app.map,1142 layerInfos: [1143 {1144 layer: app.map.getLayer("SparrowRanking"),1145 title: getLegendLabels(app.map.getLayer("SparrowRanking").visibleLayers[0])1146 }1147 ]1148 },1149 dom.byId("legendDiv")1150 );1151 app.legend.startup();1152 }1153 //$("#page-loader").fadeOut();1154 }); // END Dojo...
telemetry.ts
Source:telemetry.ts
1import assert from 'assert'2import * as api from '@opentelemetry/api'3import { Meter } from '@opentelemetry/metrics'4import { PrometheusExporter } from '@opentelemetry/exporter-prometheus'5import { MeterProvider } from '@opentelemetry/metrics'6import * as is from '@carv/is'7import { noop, set } from '@carv/stdlib'8import { Avvio } from './avvio'9import Batcher from './batcher'10import * as boundaries from './boundaries'11import * as facades from './facades'12import { makeName, validateName } from './names'13export interface TelemetryOptions {14 name?: string15 /**16 * App prefix for metrics, if needed17 *18 * @default ''19 * */20 prefix?: string21 labels?: api.Labels22 interval?: number23 logger?: api.Logger24}25export interface MetricOptions {26 prefix?: string27 name: string28 description?: string29 unit?: string30 labels?: api.Labels | undefined31}32export interface ValueMetricOptions extends MetricOptions {33 boundaries?: boundaries.Boundaries | boundaries.BoundariesConfig | undefined34}35export interface BatchMetricOptions extends MetricOptions {36 /**37 * Indicates how long the batch metric should wait to update before cancel38 */39 timeout?: number40}41export type MaybePromiseLike<T = unknown> = T | PromiseLike<T>42export type ValueObserverCallback<T extends facades.BaseValueObserver> = (43 observer: T,44) => MaybePromiseLike<number | unknown>45export type BatchObserverCallback = (46 observer: facades.BatchObserver,47) => MaybePromiseLike<api.Observation[] | unknown>48const kMeter = Symbol('kMeter')49const kLabels = Symbol('kLabels')50const kMetrics = Symbol('kMetrics')51export class Telemetry extends Avvio {52 private readonly [kMeter]: Meter53 private readonly [kLabels]: api.Labels | undefined54 private readonly [kMetrics]: Map<string, facades.Metric>55 log: api.Logger56 exportMetrics: () => string57 constructor({58 name = 'telemetry',59 prefix,60 labels,61 interval = 60000,62 logger,63 }: TelemetryOptions = {}) {64 super()65 const exporter = new PrometheusExporter({ prefix, logger, preventServerStart: true })66 this.exportMetrics = () =>67 (exporter as any)._batcher.hasMetric68 ? (exporter as any)._serializer.serialize((exporter as any)._batcher.checkPointSet())69 : '# no registered metrics'70 const meterProvider = new MeterProvider({71 batcher: new Batcher(),72 exporter,73 interval,74 // gracefulShutdown: true,75 logger,76 logLevel: 3, // Debug; get all logs and let the logger decide which to discard77 })78 this.log = meterProvider.logger79 this[kMeter] = meterProvider.getMeter(name)80 this[kLabels] = labels81 this[kMetrics] = new Map()82 // Mixin the avvio methods83 this.onClose((_instance, done) => {84 meterProvider.shutdown().finally(() => done())85 })86 }87 async collect(): Promise<string> {88 await (this[kMeter] as any)._controller._collect()89 return this.exportMetrics()90 }91 linearBoundaries(start: number, count: number, width?: number): boundaries.Boundaries {92 return boundaries.linear(start, count, width)93 }94 exponentialBoundaries(start: number, count: number, factor?: number): boundaries.Boundaries {95 return boundaries.exponential(start, count, factor)96 }97 getBoundaries(config?: boundaries.BoundariesConfig): boundaries.Boundaries | undefined {98 return boundaries.create(config)99 }100 getLabels(labels?: api.Labels | undefined): api.Labels {101 return { ...this[kLabels], ...labels }102 }103 validateName(name: string): string {104 validateName(name)105 assert(106 !this.has(name),107 `A metric with the name ${JSON.stringify(name)} has already been registered.`,108 )109 return name110 }111 makeName(...parts: (string | undefined | null | false)[]): string {112 return makeName(...parts)113 }114 has(name: string): boolean {115 return this[kMetrics].has(name)116 }117 get<T extends facades.Metric>(name: string): T | undefined118 get<T extends facades.Metric>(name: string, factory: (telemetry: Telemetry, name: string) => T): T119 get<T extends facades.Metric>(120 name: string,121 factory?: (telemetry: Telemetry, name: string) => T,122 ): T | undefined {123 return (this[kMetrics].get(name) ||124 (factory && setMetric(this[kMetrics], factory(this, name)))) as T | undefined125 }126 /**127 * Choose this kind of metric when the value is a quantity, the sum is of primary interest,128 * and the event count and value distribution are not of primary interest.129 * It is restricted to non-negative increments.130 *131 * Example uses for Counter:132 *133 * - count the number of bytes received134 * - count the number of requests completed135 * - count the number of accounts created136 * - count the number of checkpoints run137 * - count the number of 5xx errors.138 */139 createCounter(options: MetricOptions): facades.CounterMetric {140 const { name, labels, metricOptions } = getOptions(this, options)141 return setMetric(142 this[kMetrics],143 new facades.CounterMetric(name, this[kMeter].createCounter(name, metricOptions), labels),144 )145 }146 /**147 * Counters go up, and reset when the process restarts.148 *149 * UpDownCounter is similar to Counter except that it supports negative increments.150 * It is generally useful for capturing changes in an amount of resources used,151 * or any quantity that rises and falls during a request.152 *153 * Example uses for UpDownCounter:154 *155 * - count the number of active requests156 * - count memory in use by instrumenting new and delete157 * - count queue size by instrumenting enqueue and dequeue158 * - count semaphore up and down operations159 */160 createUpDownCounter(options: MetricOptions): facades.UpDownCounterMetric {161 const { name, labels, metricOptions } = getOptions(this, options)162 return setMetric(163 this[kMetrics],164 new facades.UpDownCounterMetric(165 name,166 this[kMeter].createUpDownCounter(name, metricOptions),167 labels,168 ),169 )170 }171 /**172 * ValueRecorder is a non-additive synchronous instrument useful for recording any non-additive number,173 * positive or negative.174 *175 * Values captured by ValueRecorder.record(value) are treated as individual events belonging to a distribution176 * that is being summarized. ValueRecorder should be chosen either when capturing measurements that do not177 * contribute meaningfully to a sum, or when capturing numbers that are additive in nature, but where the178 * distribution of individual increments is considered interesting.179 */180 createValueRecorder(options: ValueMetricOptions): facades.ValueRecorderMetric {181 const { name, labels, metricOptions } = getValueOptions(this, options)182 return setMetric(183 this[kMetrics],184 new facades.ValueRecorderMetric(185 name,186 this[kMeter].createValueRecorder(name, metricOptions),187 labels,188 ),189 )190 }191 /**192 * Choose this kind of metric when only last value is important without worry about aggregation.193 *194 * The callback can be sync or async.195 */196 createValueObserver(197 options: ValueMetricOptions,198 callback: ValueObserverCallback<facades.ValueObserver> = noop,199 ): facades.ValueObserverMetric {200 assert(is.function(callback), 'Callback must be a function')201 const { name, labels, metricOptions } = getValueOptions(this, options)202 return setMetric(203 this[kMetrics],204 new facades.ValueObserverMetric(205 name,206 this[kMeter].createValueObserver(name, metricOptions, observer =>207 invoke(callback, new facades.ValueObserver(observer, labels), reportValue),208 ),209 labels,210 ),211 )212 }213 /**214 * Choose this kind of metric when sum is important and you want to capture any value that starts215 * at zero and rises or falls throughout the process lifetime.216 *217 * The callback can be sync or async.218 */219 createUpDownSumObserver(220 options: MetricOptions,221 callback: ValueObserverCallback<facades.UpDownSumObserver> = noop,222 ): facades.UpDownSumObserverMetric {223 assert(is.function(callback), 'Callback must be a function')224 const { name, labels, metricOptions } = getOptions(this, options)225 return setMetric(226 this[kMetrics],227 new facades.UpDownSumObserverMetric(228 name,229 this[kMeter].createUpDownSumObserver(name, metricOptions, observer =>230 invoke(callback, new facades.UpDownSumObserver(observer, labels), reportValue),231 ),232 labels,233 ),234 )235 }236 /**237 * Choose this kind of metric when collecting a sum that never decreases.238 *239 * The callback can be sync or async.240 */241 createSumObserver(242 options: MetricOptions,243 callback: ValueObserverCallback<facades.SumObserver> = noop,244 ): facades.SumObserverMetric {245 assert(is.function(callback), 'Callback must be a function')246 const { name, labels, metricOptions } = getOptions(this, options)247 return setMetric(248 this[kMetrics],249 new facades.SumObserverMetric(250 name,251 this[kMeter].createSumObserver(name, metricOptions, observer =>252 invoke(callback, new facades.SumObserver(observer, labels), reportValue),253 ),254 labels,255 ),256 )257 }258 /**259 * Choose this kind of metric when you need to update multiple observers with the results of a single async calculation.260 */261 createBatchObserver(262 options: BatchMetricOptions,263 callback: BatchObserverCallback,264 ): facades.BatchObserverMetric {265 assert(is.function(callback), 'Callback must be a function')266 const { name, labels, metricOptions } = getBatchOptions(this, options)267 return setMetric(268 this[kMetrics],269 new facades.BatchObserverMetric(270 name,271 this[kMeter].createBatchObserver(272 name,273 observer =>274 invoke(callback, new facades.BatchObserver(observer, labels), reportObservations),275 metricOptions,276 ),277 labels,278 ),279 )280 }281}282function setMetric<T extends facades.Metric>(metrics: Map<string, facades.Metric>, metric: T): T {283 return set(metrics, metric.name, metric)284}285function getOptions<T extends MetricOptions>(286 telemetry: Telemetry,287 { prefix, name, labels, unit, description = unit && `in ${unit}`, ...metricOptions }: T,288) {289 return {290 name: telemetry.validateName(telemetry.makeName(prefix, name)),291 labels: telemetry.getLabels(labels),292 metricOptions: { ...metricOptions, unit, description },293 }294}295function getValueOptions<T extends ValueMetricOptions>(296 telemetry: Telemetry,297 { boundaries: boundariesConfig, ...options }: T,298) {299 const parsedOptions = getOptions(telemetry, options)300 return {301 ...parsedOptions,302 metricOptions: {303 ...parsedOptions.metricOptions,304 boundaries: telemetry.getBoundaries(boundariesConfig),305 },306 }307}308function getBatchOptions<T extends BatchMetricOptions>(309 telemetry: Telemetry,310 { timeout: maxTimeoutUpdateMS, ...options }: T,311) {312 const parsedOptions = getOptions(telemetry, options)313 return {314 ...parsedOptions,315 metricOptions: { maxTimeoutUpdateMS, ...parsedOptions.metricOptions },316 }317}318function invoke<O, R>(319 callback: (observer: O) => MaybePromiseLike<R>,320 observer: O,321 report: (value: R, observer: O) => void,322): void | PromiseLike<void> {323 const value = callback(observer)324 if (is.promiseLike(value)) {325 return wrapThenable(value, observer, report)326 }327 report(value, observer)328}329async function wrapThenable<O, R>(330 thenable: PromiseLike<R>,331 observer: O,332 report: (value: R, observer: O) => void,333) {334 const value = await thenable335 report(value, observer)336}337function reportValue(value: unknown, observer: facades.BaseValueObserver) {338 if (is.number(value)) {339 observer.observe(value)340 }341}342function reportObservations(value: unknown, observer: facades.BatchObserver) {343 // Ensure observe is called atleast once344 observer.observe(is.array(value) ? value : [])...
demo.component.data.ts
Source:demo.component.data.ts
1export let DefaultInputData = {2 text: 'RAGE aims to develop, transform and enrich advanced technologies from the leisure games industry ' +3 'into self-contained gaming assets (i.e. solutions showing economic value potential) that support game ' +4 'studios at developing applied games easier, faster and more cost-effectively. These assets will be ' +5 'available along with a large volume of high-quality knowledge resources through a self-sustainable ' +6 'Ecosystem, which is a social space that connects research, gaming industries, intermediaries, ' +7 'education providers, policy makers and end-users. RAGE â Realising an Applied Gaming Eco-system, is a ' +8 '48-months Technology and Know-How driven Research and Innovation project co-funded by EU Framework ' +9 'Programme for Research and Innovation, Horizon 2020.' +10 String.fromCharCode(10) +11 'The EU based industry for non-leisure games â Applied Games â is an emerging business with ' +12 'multiple uses in industry, education, health and the public administration sectors. As such, it is ' +13 'still fragmented and needs critical mass to compete globally. Nevertheless its growth potential is ' +14 'widely recognised and even suggested to exceed the growth potential of the leisure games market.' +15 String.fromCharCode(10) +16 'The gaming technology assets gathered along the project lifecycle will be tested and evaluated by ' +17 'gaming companies integrated in the RAGE consortium. These companies will be creating games that will ' +18 'be empirically validated in real world pilots in different application scenarios representing ' +19 'different markets and target groups for the Applied Games industry.',20 semanticSimilarityThreshold: 0.3,21 languages: [22 {23 id: '1',24 name: 'English',25 value: 'en'26 },27 {28 id: '2',29 name: 'French',30 value: 'fr'31 },32 {33 id: '3',34 name: 'Romanian',35 value: 'ro'36 },37 {38 id: '4',39 name: 'Dutch',40 value: 'nl'41 },42 {43 id: '5',44 name: 'Spanish',45 value: 'es'46 },47 {48 id: '6',49 name: 'Russian',50 value: 'ru'51 }52 ],53 defaultLanguage: function () {54 return DefaultInputData.languages[0];55 },56 posTaggingOptions: [57 true,58 false59 ],60 defaultPosTaggingOption: function () {61 return DefaultInputData.posTaggingOptions[0];62 },63 dialogismOptions: [64 true,65 false66 ],67 defaultDialogismOption: function () {68 return DefaultInputData.dialogismOptions[1];69 },70 defaultBigrams: false,71 metricOptions: {72 lsa: {73 'de': [{74 id: '1',75 name: 'None',76 value: ''77 }],78 'en': [{79 id: '1',80 name: 'TASA',81 value: 'TASA'82 },83 {84 id: '2',85 name: 'None',86 value: ''87 }],88 'es': [{89 id: '1',90 name: 'Jose Antonio',91 value: 'Jose_Antonio'92 },93 {94 id: '2',95 name: 'None',96 value: ''97 }],98 'fr': [{99 id: '1',100 name: 'Le Monde',101 value: 'le_monde'102 },103 {104 id: '2',105 name: 'None',106 value: ''107 }],108 'it': [{109 id: '1',110 name: 'None',111 value: ''112 }],113 'la': [{114 id: '1',115 name: 'Latin Letters',116 value: 'Letters'117 },118 {119 id: '2',120 name: 'None',121 value: ''122 }],123 'nl': [{124 id: '1',125 name: 'None',126 value: ''127 }],128 'ro': [{129 id: '1',130 name: 'Read me',131 value: 'readme'132 },133 {134 id: '2',135 name: 'None',136 value: ''137 }],138 'ru': [{139 id: '2',140 name: 'None',141 value: ''142 }]143 },144 lda: {145 'de': [{146 id: '1',147 name: 'None',148 value: ''149 }],150 'en': [{151 id: '1',152 name: 'TASA',153 value: 'TASA'154 },155 {156 id: '2',157 name: 'None',158 value: ''159 }],160 'es': [{161 id: '1',162 name: 'Jose Antonio',163 value: 'Jose_Antonio'164 },165 {166 id: '2',167 name: 'None',168 value: ''169 }],170 'fr': [{171 id: '1',172 name: 'Le Monde',173 value: 'le_monde'174 },175 {176 id: '2',177 name: 'None',178 value: ''179 }],180 'it': [{181 id: '1',182 name: 'None',183 value: ''184 }],185 'la': [{186 id: '1',187 name: 'None',188 value: ''189 }],190 'nl': [{191 id: '1',192 name: 'None',193 value: ''194 }195 ],196 'ro': [{197 id: '1',198 name: 'None',199 value: ''200 }],201 'ru': [{202 id: '2',203 name: 'None',204 value: ''205 }]206 },207 word2vec: {208 'de': [{209 id: '1',210 name: 'None',211 value: ''212 }],213 'en': [{214 id: '1',215 name: 'TASA',216 value: 'TASA'217 },218 {219 id: '2',220 name: 'None',221 value: ''222 }],223 'es': [{224 id: '1',225 name: 'Jose Antonio',226 value: 'Jose_Antonio'227 },228 {229 id: '2',230 name: 'None',231 value: ''232 }],233 'fr': [{234 id: '1',235 name: 'Le Monde',236 value: 'le_monde'237 },238 {239 id: '2',240 name: 'None',241 value: ''242 }],243 'it': [{244 id: '1',245 name: 'None',246 value: ''247 }],248 'la': [{249 id: '1',250 name: 'None',251 value: ''252 }],253 'nl': [{254 id: '1',255 name: 'INL',256 value: 'INL'257 },258 {259 id: '2',260 name: 'None',261 value: ''262 }],263 'ro': [{264 id: '1',265 name: 'Read me',266 value: 'readme'267 },268 {269 id: '2',270 name: 'None',271 value: ''272 }],273 'ru': [{274 id: '1',275 name: 'RNC Wikipedia',276 value: 'RNC_Wikipedia'277 },278 {279 id: '2',280 name: 'None',281 value: ''282 }]283 }284 },285 defaultMetricOptions: {286 lsa: {287 'de': function () {288 return DefaultInputData.metricOptions.lsa.de[0];289 },290 'en': function () {291 return DefaultInputData.metricOptions.lsa.en[0];292 },293 'es': function () {294 return DefaultInputData.metricOptions.lsa.es[0];295 },296 'fr': function () {297 return DefaultInputData.metricOptions.lsa.fr[0];298 },299 'it': function () {300 return DefaultInputData.metricOptions.lsa.it[0];301 },302 'la': function () {303 return DefaultInputData.metricOptions.lsa.la[0];304 },305 'nl': function () {306 return DefaultInputData.metricOptions.lsa.nl[0];307 },308 'ro': function () {309 return DefaultInputData.metricOptions.lsa.ro[0];310 },311 'ru': function () {312 return DefaultInputData.metricOptions.lsa.ru[0];313 }314 },315 lda: {316 'de': function () {317 return DefaultInputData.metricOptions.lda.de[0];318 },319 'en': function () {320 return DefaultInputData.metricOptions.lda.en[0];321 },322 'es': function () {323 return DefaultInputData.metricOptions.lda.es[0];324 },325 'fr': function () {326 return DefaultInputData.metricOptions.lda.fr[1];327 },328 'it': function () {329 return DefaultInputData.metricOptions.lda.it[0];330 },331 'la': function () {332 return DefaultInputData.metricOptions.lda.la[0];333 },334 'nl': function () {335 return DefaultInputData.metricOptions.lda.nl[0];336 },337 'ro': function () {338 return DefaultInputData.metricOptions.lda.ro[0];339 },340 'ru': function () {341 return DefaultInputData.metricOptions.lda.ru[0];342 }343 },344 word2vec: {345 'de': function () {346 return DefaultInputData.metricOptions.word2vec.de[0];347 },348 'en': function () {349 return DefaultInputData.metricOptions.word2vec.en[0];350 },351 'es': function () {352 return DefaultInputData.metricOptions.word2vec.es[0];353 },354 'fr': function () {355 return DefaultInputData.metricOptions.word2vec.fr[0];356 },357 'it': function () {358 return DefaultInputData.metricOptions.word2vec.it[0];359 },360 'la': function () {361 return DefaultInputData.metricOptions.word2vec.la[0];362 },363 'nl': function () {364 return DefaultInputData.metricOptions.word2vec.nl[0];365 },366 'ro': function () {367 return DefaultInputData.metricOptions.word2vec.ro[0];368 },369 'ru': function () {370 return DefaultInputData.metricOptions.word2vec.ru[0];371 }372 }373 },374 number_of_docs: [375 {376 id: '1',377 name: '4',378 value: '4'379 },380 {381 id: '2',382 name: '5',383 value: '5'384 },385 {386 id: '3',387 name: '6',388 value: '6'389 },390 {391 id: '4',392 name: '7',393 value: '7'394 },395 {396 id: '5',397 name: '8',398 value: '8'399 }400 ]...
Using AI Code Generation
1var bby = require('bestbuy')('u4wz5r5r5rjz5d8g5p7z3x9g');2var options = {3};4bby.products('(categoryPath.id=abcat0502000&salePrice<500)', options, function(err, data) {5 if (err) {6 console.log(err);7 } else {8 console.log(data.products);9 }10});
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!!