How to use TBodies method of html Package

Best K6 code snippet using html.TBodies

console-js.go

Source:console-js.go Github

copy

Full Screen

1package mapreduce2const js = `3<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>4<script type="text/javascript" id="js">5var license = "Minified tablesorter (http://tablesorter.com/docs/) Copyright (c) 2014 Christian Bach, used under MIT license";6/* The MIT License (MIT)7Copyright (c) 2014 Christian Bach8Permission is hereby granted, free of charge, to any person obtaining a copy9of this software and associated documentation files (the "Software"), to deal10in the Software without restriction, including without limitation the rights11to use, copy, modify, merge, publish, distribute, sublicense, and/or sell12copies of the Software, and to permit persons to whom the Software is13furnished to do so, subject to the following conditions:14The above copyright notice and this permission notice shall be included in all15copies or substantial portions of the Software.16THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR17IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,18FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE19AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER20LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,21OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE22SOFTWARE. */23(function($){$.extend({tablesorter:new24function(){var parsers=[],widgets=[];this.defaults={cssHeader:"header",cssAsc:"headerSortUp",cssDesc:"headerSortDown",cssChildRow:"expand-child",sortInitialOrder:"asc",sortMultiSortKey:"shiftKey",sortForce:null,sortAppend:null,sortLocaleCompare:true,textExtraction:"simple",parsers:{},widgets:[],widgetZebra:{css:["even","odd"]},headers:{},widthFixed:false,cancelSelection:true,sortList:[],headerList:[],dateFormat:"us",decimal:'/\.|\,/g',onRenderHeader:null,selectorHeaders:'thead th',debug:false};function benchmark(s,d){log(s+","+(new Date().getTime()-d.getTime())+"ms");}this.benchmark=benchmark;function log(s){if(typeof console!="undefined"&&typeof console.debug!="undefined"){console.log(s);}else{alert(s);}}function buildParserCache(table,$headers){if(table.config.debug){var parsersDebug="";}if(table.tBodies.length==0)return;var rows=table.tBodies[0].rows;if(rows[0]){var list=[],cells=rows[0].cells,l=cells.length;for(var i=0;i<l;i++){var p=false;if($.metadata&&($($headers[i]).metadata()&&$($headers[i]).metadata().sorter)){p=getParserById($($headers[i]).metadata().sorter);}else if((table.config.headers[i]&&table.config.headers[i].sorter)){p=getParserById(table.config.headers[i].sorter);}if(!p){p=detectParserForColumn(table,rows,-1,i);}if(table.config.debug){parsersDebug+="column:"+i+" parser:"+p.id+"\n";}list.push(p);}}if(table.config.debug){log(parsersDebug);}return list;};function detectParserForColumn(table,rows,rowIndex,cellIndex){var l=parsers.length,node=false,nodeValue=false,keepLooking=true;while(nodeValue==''&&keepLooking){rowIndex++;if(rows[rowIndex]){node=getNodeFromRowAndCellIndex(rows,rowIndex,cellIndex);nodeValue=trimAndGetNodeText(table.config,node);if(table.config.debug){log('Checking if value was empty on row:'+rowIndex);}}else{keepLooking=false;}}for(var i=1;i<l;i++){if(parsers[i].is(nodeValue,table,node)){return parsers[i];}}return parsers[0];}function getNodeFromRowAndCellIndex(rows,rowIndex,cellIndex){return rows[rowIndex].cells[cellIndex];}function trimAndGetNodeText(config,node){return $.trim(getElementText(config,node));}function getParserById(name){var l=parsers.length;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==name.toLowerCase()){return parsers[i];}}return false;}function buildCache(table){if(table.config.debug){var cacheTime=new Date();}var totalRows=(table.tBodies[0]&&table.tBodies[0].rows.length)||0,totalCells=(table.tBodies[0].rows[0]&&table.tBodies[0].rows[0].cells.length)||0,parsers=table.config.parsers,cache={row:[],normalized:[]};for(var i=0;i<totalRows;++i){var c=$(table.tBodies[0].rows[i]),cols=[];if(c.hasClass(table.config.cssChildRow)){cache.row[cache.row.length-1]=cache.row[cache.row.length-1].add(c);continue;}cache.row.push(c);for(var j=0;j<totalCells;++j){cols.push(parsers[j].format(getElementText(table.config,c[0].cells[j]),table,c[0].cells[j]));}cols.push(cache.normalized.length);cache.normalized.push(cols);cols=null;};if(table.config.debug){benchmark("Building cache for "+totalRows+" rows:",cacheTime);}return cache;};function getElementText(config,node){var text="";if(!node)return"";if(!config.supportsTextContent)config.supportsTextContent=node.textContent||false;if(config.textExtraction=="simple"){if(config.supportsTextContent){text=node.textContent;}else{if(node.childNodes[0]&&node.childNodes[0].hasChildNodes()){text=node.childNodes[0].innerHTML;}else{text=node.innerHTML;}}}else{if(typeof(config.textExtraction)=="function"){text=config.textExtraction(node);}else{text=$(node).text();}}return text;}function appendToTable(table,cache){if(table.config.debug){var appendTime=new Date()}var c=cache,r=c.row,n=c.normalized,totalRows=n.length,checkCell=(n[0].length-1),tableBody=$(table.tBodies[0]),rows=[];for(var i=0;i<totalRows;i++){var pos=n[i][checkCell];rows.push(r[pos]);if(!table.config.appender){var l=r[pos].length;for(var j=0;j<l;j++){tableBody[0].appendChild(r[pos][j]);}}}if(table.config.appender){table.config.appender(table,rows);}rows=null;if(table.config.debug){benchmark("Rebuilt table:",appendTime);}applyWidget(table);setTimeout(function(){$(table).trigger("sortEnd");},0);};function buildHeaders(table){if(table.config.debug){var time=new Date();}var meta=($.metadata)?true:false;var header_index=computeTableHeaderCellIndexes(table);$tableHeaders=$(table.config.selectorHeaders,table).each(function(index){this.column=header_index[this.parentNode.rowIndex+"-"+this.cellIndex];this.order=formatSortingOrder(table.config.sortInitialOrder);this.count=this.order;if(checkHeaderMetadata(this)||checkHeaderOptions(table,index))this.sortDisabled=true;if(checkHeaderOptionsSortingLocked(table,index))this.order=this.lockedOrder=checkHeaderOptionsSortingLocked(table,index);if(!this.sortDisabled){var $th=$(this).addClass(table.config.cssHeader);if(table.config.onRenderHeader)table.config.onRenderHeader.apply($th);}table.config.headerList[index]=this;});if(table.config.debug){benchmark("Built headers:",time);log($tableHeaders);}return $tableHeaders;};function computeTableHeaderCellIndexes(t){var matrix=[];var lookup={};var thead=t.getElementsByTagName('THEAD')[0];var trs=thead.getElementsByTagName('TR');for(var i=0;i<trs.length;i++){var cells=trs[i].cells;for(var j=0;j<cells.length;j++){var c=cells[j];var rowIndex=c.parentNode.rowIndex;var cellId=rowIndex+"-"+c.cellIndex;var rowSpan=c.rowSpan||1;var colSpan=c.colSpan||125var firstAvailCol;if(typeof(matrix[rowIndex])=="undefined"){matrix[rowIndex]=[];}for(var k=0;k<matrix[rowIndex].length+1;k++){if(typeof(matrix[rowIndex][k])=="undefined"){firstAvailCol=k;break;}}lookup[cellId]=firstAvailCol;for(var k=rowIndex;k<rowIndex+rowSpan;k++){if(typeof(matrix[k])=="undefined"){matrix[k]=[];}var matrixrow=matrix[k];for(var l=firstAvailCol;l<firstAvailCol+colSpan;l++){matrixrow[l]="x";}}}}return lookup;}function checkCellColSpan(table,rows,row){var arr=[],r=table.tHead.rows,c=r[row].cells;for(var i=0;i<c.length;i++){var cell=c[i];if(cell.colSpan>1){arr=arr.concat(checkCellColSpan(table,headerArr,row++));}else{if(table.tHead.length==1||(cell.rowSpan>1||!r[row+1])){arr.push(cell);}}}return arr;};function checkHeaderMetadata(cell){if(($.metadata)&&($(cell).metadata().sorter===false)){return true;};return false;}function checkHeaderOptions(table,i){if((table.config.headers[i])&&(table.config.headers[i].sorter===false)){return true;};return false;}function checkHeaderOptionsSortingLocked(table,i){if((table.config.headers[i])&&(table.config.headers[i].lockedOrder))return table.config.headers[i].lockedOrder;return false;}function applyWidget(table){var c=table.config.widgets;var l=c.length;for(var i=0;i<l;i++){getWidgetById(c[i]).format(table);}}function getWidgetById(name){var l=widgets.length;for(var i=0;i<l;i++){if(widgets[i].id.toLowerCase()==name.toLowerCase()){return widgets[i];}}};function formatSortingOrder(v){if(typeof(v)!="Number"){return(v.toLowerCase()=="desc")?1:0;}else{return(v==1)?1:0;}}function isValueInArray(v,a){var l=a.length;for(var i=0;i<l;i++){if(a[i][0]==v){return true;}}return false;}function setHeadersCss(table,$headers,list,css){$headers.removeClass(css[0]).removeClass(css[1]);var h=[];$headers.each(function(offset){if(!this.sortDisabled){h[this.column]=$(this);}});var l=list.length;for(var i=0;i<l;i++){h[list[i][0]].addClass(css[list[i][1]]);}}function fixColumnWidth(table,$headers){var c=table.config;if(c.widthFixed){var colgroup=$('<colgroup>');$("tr:first td",table.tBodies[0]).each(function(){colgroup.append($('<col>').css('width',$(this).width()));});$(table).prepend(colgroup);};}function updateHeaderSortCount(table,sortList){var c=table.config,l=sortList.length;for(var i=0;i<l;i++){var s=sortList[i],o=c.headerList[s[0]];o.count=s[1];o.count++;}}function multisort(table,sortList,cache){if(table.config.debug){var sortTime=new Date();}var dynamicExp="var sortWrapper = function(a,b) {",l=sortList.length;for(var i=0;i<l;i++){var c=sortList[i][0];var order=sortList[i][1];var s=(table.config.parsers[c].type=="text")?((order==0)?makeSortFunction("text","asc",c):makeSortFunction("text","desc",c)):((order==0)?makeSortFunction("numeric","asc",c):makeSortFunction("numeric","desc",c));var e="e"+i;dynamicExp+="var "+e+" = "+s;dynamicExp+="if("+e+") { return "+e+"; } ";dynamicExp+="else { ";}var orgOrderCol=cache.normalized[0].length-1;dynamicExp+="return a["+orgOrderCol+"]-b["+orgOrderCol+"];";for(var i=0;i<l;i++){dynamicExp+="}; ";}dynamicExp+="return 0; ";dynamicExp+="}; ";if(table.config.debug){benchmark("Evaling expression:"+dynamicExp,new Date());}eval(dynamicExp);cache.normalized.sort(sortWrapper);if(table.config.debug){benchmark("Sorting on "+sortList.toString()+" and dir "+order+" time:",sortTime);}return cache;};function makeSortFunction(type,direction,index){var a="a["+index+"]",b="b["+index+"]";if(type=='text'&&direction=='asc'){return"("+a+" == "+b+" ? 0 : ("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : ("+a+" < "+b+") ? -1 : 1 )));";}else if(type=='text'&&direction=='desc'){return"("+a+" == "+b+" ? 0 : ("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : ("+b+" < "+a+") ? -1 : 1 )));";}else if(type=='numeric'&&direction=='asc'){return"("+a+" === null && "+b+" === null) ? 0 :("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : "+a+" - "+b+"));";}else if(type=='numeric'&&direction=='desc'){return"("+a+" === null && "+b+" === null) ? 0 :("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : "+b+" - "+a+"));";}};function makeSortText(i){return"((a["+i+"] < b["+i+"]) ? -1 : ((a["+i+"] > b["+i+"]) ? 1 : 0));";};function makeSortTextDesc(i){return"((b["+i+"] < a["+i+"]) ? -1 : ((b["+i+"] > a["+i+"]) ? 1 : 0));";};function makeSortNumeric(i){return"a["+i+"]-b["+i+"];";};function makeSortNumericDesc(i){return"b["+i+"]-a["+i+"];";};function sortText(a,b){if(table.config.sortLocaleCompare)return a.localeCompare(b);return((a<b)?-1:((a>b)?1:0));};function sortTextDesc(a,b){if(table.config.sortLocaleCompare)return b.localeCompare(a);return((b<a)?-1:((b>a)?1:0));};function sortNumeric(a,b){return a-b;};function sortNumericDesc(a,b){return b-a;};function getCachedSortType(parsers,i){return parsers[i].type;};this.construct=function(settings){return this.each(function(){if(!this.tHead||!this.tBodies)return;var $this,$document,$headers,cache,config,shiftDown=0,sortOrder;this.config={};config=$.extend(this.config,$.tablesorter.defaults,settings);$this=$(this);$.data(this,"tablesorter",config);$headers=buildHeaders(this);this.config.parsers=buildParserCache(this,$headers);cache=buildCache(this);var sortCSS=[config.cssDesc,config.cssAsc];fixColumnWidth(this);$headers.click(function(e){var totalRows=($this[0].tBodies[0]&&$this[0].tBodies[0].rows.length)||0;if(!this.sortDisabled&&totalRows>0){$this.trigger("sortStart");var $cell=$(this);var i=this.column;this.order=this.count++%2;if(this.lockedOrder)this.order=this.lockedOrder;if(!e[config.sortMultiSortKey]){config.sortList=[];if(config.sortForce!=null){var a=config.sortForce;for(var j=0;j<a.length;j++){if(a[j][0]!=i){config.sortList.push(a[j]);}}}config.sortList.push([i,this.order]);}else{if(isValueInArray(i,config.sortList)){for(var j=0;j<config.sortList.length;j++){var s=config.sortList[j],o=config.headerList[s[0]];if(s[0]==i){o.count=s[1];o.count++;s[1]=o.count%2;}}}else{config.sortList.push([i,this.order]);}};setTimeout(function(){setHeadersCss($this[0],$headers,config.sortList,sortCSS);appendToTable($this[0],multisort($this[0],config.sortList,cache));},1);return false;}}).mousedown(function(){if(config.cancelSelection){this.onselectstart=function(){return false};return false;}});$this.bind("update",function(){var me=this;setTimeout(function(){me.config.parsers=buildParserCache(me,$headers);cache=buildCache(me);},1);}).bind("updateCell",function(e,cell){var config=this.config;var pos=[(cell.parentNode.rowIndex-1),cell.cellIndex];cache.normalized[pos[0]][pos[1]]=config.parsers[pos[1]].format(getElementText(config,cell),cell);}).bind("sorton",function(e,list){$(this).trigger("sortStart");config.sortList=list;var sortList=config.sortList;updateHeaderSortCount(this,sortList);setHeadersCss(this,$headers,sortList,sortCSS);appendToTable(this,multisort(this,sortList,cache));}).bind("appendCache",function(){appendToTable(this,cache);}).bind("applyWidgetId",function(e,id){getWidgetById(id).format(this);}).bind("applyWidgets",function(){applyWidget(this);});if($.metadata&&($(this).metadata()&&$(this).metadata().sortlist)){config.sortList=$(this).metadata().sortlist;}if(config.sortList.length>0){$this.trigger("sorton",[config.sortList]);}applyWidget(this);});};this.addParser=function(parser){var l=parsers.length,a=true;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==parser.id.toLowerCase()){a=false;}}if(a){parsers.push(parser);};};this.addWidget=function(widget){widgets.push(widget);};this.formatFloat=function(s){var i=parseFloat(s);return(isNaN(i))?0:i;};this.formatInt=function(s){var i=parseInt(s);return(isNaN(i))?0:i;};this.isDigit=function(s,config){return/^[-+]?\d*$/.test($.trim(s.replace(/[,.']/g,'')));};this.clearTableBody=function(table){if($.browser.msie){function empty(){while(this.firstChild)this.removeChild(this.firstChild);}empty.apply(table.tBodies[0]);}else{table.tBodies[0].innerHTML="";}};}});$.fn.extend({tablesorter:$.tablesorter.construct});var ts=$.tablesorter;ts.addParser({id:"text",is:function(s){return true;},format:function(s){return $.trim(s.toLocaleLowerCase());},type:"text"});ts.addParser({id:"digit",is:function(s,table){var c=table.config;return $.tablesorter.isDigit(s,c);},format:function(s){return $.tablesorter.formatFloat(s);},type:"numeric"});ts.addParser({id:"currency",is:function(s){return/^[£$€?.]/.test(s);},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/[£$€]/g),""));},type:"numeric"});ts.addParser({id:"ipAddress",is:function(s){return/^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);},format:function(s){var a=s.split("."),r="",l=a.length;for(var i=0;i<l;i++){var item=a[i];if(item.length==2){r+="0"+item;}else{r+=item;}}return $.tablesorter.formatFloat(r);},type:"numeric"});ts.addParser({id:"url",is:function(s){return/^(https?|ftp|file):\/\/$/.test(s);},format:function(s){return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//),''));},type:"text"});ts.addParser({id:"isoDate",is:function(s){return/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s);},format:function(s){return $.tablesorter.formatFloat((s!="")?new Date(s.replace(new RegExp(/-/g),"/")).getTime():"0");},type:"numeric"});ts.addParser({id:"percent",is:function(s){return/\%$/.test($.trim(s));},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g),""));},type:"numeric"});ts.addParser({id:"usLongDate",is:function(s){return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/));},format:function(s){return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"shortDate",is:function(s){return/\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);},format:function(s,table){var c=table.config;s=s.replace(/\-/g,"/");if(c.dateFormat=="us"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$1/$2");}else if (c.dateFormat == "pt") {s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$2/$1");} else if(c.dateFormat=="uk"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$2/$1");}else if(c.dateFormat=="dd/mm/yy"||c.dateFormat=="dd-mm-yy"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/,"$1/$2/$3");}return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"time",is:function(s){return/^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);},format:function(s){return $.tablesorter.formatFloat(new Date("2000/01/01 "+s).getTime());},type:"numeric"});ts.addParser({id:"metadata",is:function(s){return false;},format:function(s,table,cell){var c=table.config,p=(!c.parserMetadataName)?'sortValue':c.parserMetadataName;return $(cell).metadata()[p];},type:"numeric"});ts.addWidget({id:"zebra",format:function(table){if(table.config.debug){var time=new Date();}var $tr,row=-1,odd;$("tr:visible",table.tBodies[0]).each(function(i){$tr=$(this);if(!$tr.hasClass(table.config.cssChildRow))row++;odd=(row%2==0);$tr.removeClass(table.config.widgetZebra.css[odd?0:1]).addClass(table.config.widgetZebra.css[odd?1:0])});if(table.config.debug){$.tablesorter.benchmark("Applying Zebra widget",time);}}});})(jQuery);26// Extending tablesorter for mapreduce console27$.tablesorter.addParser({28 id: 'isoDatetime',29 is: function(s) { return false; },30 format: function(s) {31 s = s.replace(/^([0-9-]+)\s+([0-9:.]+).*$/, "$1T$2Z");32 return $.tablesorter.formatFloat(new Date(s).getTime());33 },34 type: 'numeric'35});36$.tablesorter.addParser({37 id: 'duration',38 is: function(s) { return false; },39 format: function(s) {40 s = s.replace(/(?:-.+|(\d*?)h?(\d*?)m?([0-9.]+).?)s$/, function(match, p1, p2, p3) {41 t = 0;42 if (p1) { t = t + 3600 * parseInt(p1) }43 if (p2) { t = t + 60 * parseInt(p2) }44 if (p3) { t = t + parseFloat(p3) }45 return t;46 });47 return $.tablesorter.formatFloat(s);48 },49 type: 'numeric'50});51$.tablesorter.addWidget({52 id: 'filter',53 format: function(table) {54 $("thead th", table).each(function(index) {55 $("select", this).each(function() {56 var values = $("option",this).toArray();57 if(values.length == 0) {58 var options = {}59 $("tbody tr td:nth-child(" + (index + 1) + ")", table).each(function(){60 t = $(this).text();61 if(options[t]) { options[t]++ }62 else { options[t] = 1}63 });64 for (o in options) {65 $(this).append("<option selected value='" + o + "'>" + o + ": " + options[o] + "</option>");66 values.length = values.length + 1;67 }68 $(this).attr("size", values.length);69 }70 });71 $(":input", this).each(function() {72 var find = $(this).val();73 if(! Array.isArray(find)){ find = [ find ] }74 $("tbody tr td:nth-child(" + (index + 1) + ")", table).each(function() {75 var text = $(this).text()76 for(let f of find.values()) {77 if(text.includes(f)) {78 $(this).attr("filtered", false);79 break;80 } else {81 $(this).attr("filtered", true);82 }83 }84 });85 });86 });87 $("tbody tr").show();88 $("tbody tr td[filtered=true]").parent().hide();89 },90});91`...

Full Screen

Full Screen

webpages.go

Source:webpages.go Github

copy

Full Screen

1package main2var indexPage = `3<!DOCTYPE html>4<html>5 <head>6 <title>Tanglebeat dashboard</title>7 <meta charset="UTF-8">8 <meta name="description" content="Page displays state of the Tanglebeat instance">9 <meta name="keywords" content="IOTA, Tangle, Tanglebeat, crypto, token, metrics">10 <meta name="author" content="lunfardo">11 </head>12 <style>13 table {14 border-collapse: collapse;15 }16 th, td, #runningOnly {17 font-family: "Liberation Mono", monospace;18 font-size: 12px;19 text-align: left;20 padding: 3px;21 vertical-align: top;22 }23 tr:nth-child(even){background-color: #f2f2f2}24 </style>25 <script type="text/javascript" src="/loadjs">26 </script>27 <body onload=main()>28 <h3> IRI msg inputs (Zero MQ)</h3>29 <input type="checkbox" id="runningOnly" onclick="clickRunningOnly()">Show running only</input>30 <table id="maintable" border="1">31 <tr> 32 <td>ZMQ host</td> 33 <td>avgBehindSNSec</td> 34 <td>leaderTXPerc</td>35 <td>leaderSNPerc</td>36 <td>lastTXMsecAgo</td>37 <td>lastSNMsecAgo</td>38 <td>runningAlreadyMin</td> 39 </tr>40 </table>41 <table border="0">42 <tr>43 <td><b>Compound IRI msg output (Nanomsg)</b></td>44 <td><b>Buffers</b></td>45 <td><b>Go runtime</b></td>46 </tr>47 <tr>48 <td>49 <table id="outputtable" border="1">50 <tr></tr>51 </table>52 </td>53 <td>54 <table id="rtt1" border="1">55 <tr></tr>56 </table>57 </td>58 <td>59 <table id="rtt2" border="1">60 <tr></tr>61 </table>62 <td>63 </td>64 </tr>65 </table>66 <h3>Senders</h3>67 <table id="sendertable" border="0">68 <tr></tr>69 </table>70 </body>71</html>72`73var loadjs = `74 var runningOnly = false;75 function clickRunningOnly(){76 var checkBox = document.getElementById("runningOnly");77 runningOnly = checkBox.checked;78 }79 function ts2Time(ts, ago) {80 var d=new Date(); 81 var nowTs = d.getTime(); 82 var seconds = Math.floor((nowTs-ts)/1000);83 days = Math.floor(seconds / (24 * 3600));84 days_rem = seconds - days * 24 * 3600;85 hours = Math.floor(days_rem/3600) 86 hours_rem = days_rem - hours * 360087 minutes = Math.floor(hours_rem/60)88 seconds = hours_rem - minutes * 6089 ret = ""90 if (days > 0) ret = days + " days ";91 if (hours > 0) ret = ret + hours + " h ";92 if (minutes > 0) ret = ret + minutes + " min "93 ret = ret + seconds +" sec";94 if (ago){95 ret = ret + " ago";96 }97 return ret98 }99 function refresh(fun, millis){100 fun();101 setInterval(fun, millis);102 }103 function deleteChildren(obj){104 while( obj.hasChildNodes() ){105 obj.removeChild(obj.lastChild);106 }107 }108 function populateRow(row, data, heading){109 if (heading){110 for (key in data){111 if (key != "lastErr"){112 el = document.createElement('td');113 el.innerHTML = "<b>" + key + "</b>";114 row.appendChild(el);115 }116 }117 return true;118 } 119 if (data.running){120 for (key in data){121 if (key != "lastErr"){122 el = document.createElement('td');123 if (key == "runningSince" || key == "lastHeartbeat"){124 el.innerHTML = ts2Time(data[key], true);125 } else {126 el.innerHTML = data[key];127 }128 row.appendChild(el);129 }130 }131 return true;132 }133 if (runningOnly){134 return false;135 }136 el = document.createElement('td');137 el.innerHTML = data["uri"];138 row.appendChild(el);139 140 el = document.createElement('td');141 el.innerHTML = data["running"];142 row.appendChild(el);143 el = document.createElement('td');144 el.setAttribute("colspan", Object.keys(data).length - 2)145 el.innerHTML = data["lastErr"];146 row.appendChild(el);147 return true;148 }149 function populateRoutineStats(resp){150 tb = document.getElementById("maintable").tBodies[0];151 deleteChildren(tb);152 first = true153 for (idx in resp){154 if (first){155 row = document.createElement('tr');156 populateRow(row, resp[idx], true)157 tb.appendChild(row);158 first = false159 }160 row = document.createElement('tr');161 if (populateRow(row, resp[idx], false)){162 tb.appendChild(row);163 }164 }165 }166 function populate(tbname, datalist){167 tb = document.getElementById(tbname).tBodies[0];168 deleteChildren(tb);169 for (key in datalist[0]){170 row = document.createElement('tr');171 cell = document.createElement('td');172 cell.innerHTML = key;173 row.appendChild(cell);174 for (idx in datalist){175 cell = document.createElement('td');176 cell.innerHTML = datalist[idx][key];177 row.appendChild(cell);178 }179 tb.appendChild(row);180 }181 }182 function refreshStats(){183 var xhttp = new XMLHttpRequest();184 xhttp.onreadystatechange = function() {185 var resp;186 if (this.readyState == 4){187 if (this.status == 200) {188 resp = JSON.parse(this.response);189 populateRoutineStats(resp.zmqInputStats);190 populate("outputtable", [resp.zmqOutputStats, resp.zmqOutputStats10min]);191 populate("rtt1", [resp.zmqRuntimeStats]);192 populate("rtt2", [resp.goRuntimeStats]);193 }194 }195 };196 req = "/api1/internal_stats/displayall";197 xhttp.open("GET", req, true);198 xhttp.send();199 }200 var colNames = ["Seq", "Addr idx", "Balance", "Bundle", "Duration", "State", "(Re)attach/<br>Promote", "Last heartbeat"];201 function bundleLink(bundle){202 d = 'https://thetangle.org/bundle/' + bundle;203 s = bundle.substring(0, 12) + "..";204 return '<a href="' + d + '" target="_blank">' + s + '</a>';205 }206 function populateSenderStates(resp){207 tb = document.getElementById("sendertable").tBodies[0];208 deleteChildren(tb);209 firstRow = true;210 for (r in resp){211 if (firstRow){212 row = document.createElement('tr');213 for (i in colNames){214 cell = document.createElement('td');215 cell.innerHTML = '<b>'+colNames[i]+'</b>';216 row.appendChild(cell);217 } 218 firstRow = false;219 tb.appendChild(row);220 }221 row = document.createElement('tr');222 cell = document.createElement('td');223 cell.innerHTML = resp[r].seqName;224 row.appendChild(cell);225 cell = document.createElement('td');226 cell.innerHTML = resp[r].index;227 row.appendChild(cell);228 cell = document.createElement('td');229 cell.innerHTML = resp[r].balance;230 row.appendChild(cell);231 cell = document.createElement('td');232 cell.innerHTML = bundleLink(resp[r].bundle);233 row.appendChild(cell);234 cell = document.createElement('td');235 cell.innerHTML = ts2Time(resp[r].startedTs, false);236 row.appendChild(cell);237 cell = document.createElement('td');238 cell.innerHTML = resp[r].state;239 row.appendChild(cell);240 cell = document.createElement('td');241 cell.innerHTML = resp[r].numAttach + "/" + resp[r].numPromo;242 row.appendChild(cell);243 cell = document.createElement('td');244 cell.innerHTML = ts2Time(resp[r].lastHeartbeat, true)245 row.appendChild(cell);246 tb.appendChild(row);247 }248 }249 function refreshSenderStates(){250 var xhttp = new XMLHttpRequest();251 xhttp.onreadystatechange = function() {252 var resp;253 if (this.readyState == 4){254 if (this.status == 200) {255 resp = JSON.parse(this.response);256 populateSenderStates(resp);257 }258 }259 };260 req = "/api1/senders";261 xhttp.open("GET", req, true);262 xhttp.send();263 }264 function main(){265 refresh(refreshStats, 3000);266 refresh(refreshSenderStates, 3000);267 }268`269var loadJsSenderState = `270 271`...

Full Screen

Full Screen

htmltable.go

Source:htmltable.go Github

copy

Full Screen

1// Package htmltable implements a HTML table parser2package htmltable3import (4 "bytes"5 "fmt"6 "io"7 "golang.org/x/net/html"8)9// Table represents a HTML table10type Table struct {11 Headers [][]string12 Rows [][]string13}14// Parse parses HTML from r15func Parse(r io.Reader) (page []Table, err error) {16 n, err := html.Parse(r)17 if err != nil {18 return nil, fmt.Errorf("failed to parse HTML: %s", err)19 }20 tables := getElementsByName(n, "table")21 for _, t := range tables {22 table := parseTable(t)23 page = append(page, table)24 }25 return26}27func parseTable(n *html.Node) (table Table) {28 theads := getElementsByName(n, "thead")29 if len(theads) > 0 {30 table.Headers = parseRows(theads[0])31 }32 tbodies := getElementsByName(n, "tbody")33 if len(tbodies) > 0 {34 table.Rows = parseRows(tbodies[0])35 }36 return37}38func parseRows(n *html.Node) (rows [][]string) {39 for _, tr := range getElementsByName(n, "tr") {40 elems := []string{}41 for _, td := range getElementsByName(tr, "td") {42 elems = append(elems, getTextContent(td))43 }44 rows = append(rows, elems)45 }46 return47}48func getElementsByName(n *html.Node, name string) (elements []*html.Node) {49 for c := n.FirstChild; c != nil; c = c.NextSibling {50 if c.Data == name {51 elements = append(elements, c)52 }53 for _, el := range getElementsByName(c, name) {54 // buf := new(bytes.Buffer)55 // html.Render(buf, c)56 // fmt.Printf("name=%s, c=%s\n", name, buf)57 elements = append(elements, el)58 }59 }60 return61}62func getTextContent(n *html.Node) string {63 buf := new(bytes.Buffer)64 for c := n.FirstChild; c != nil; c = c.NextSibling {65 if c.Type == html.TextNode {66 fmt.Fprintf(buf, c.Data)67 }68 fmt.Fprintf(buf, getTextContent(c))69 }70 return buf.String()71}...

Full Screen

Full Screen

TBodies

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 for _, url := range os.Args[1:] {4 resp, err := http.Get(url)5 if err != nil {6 log.Fatal(err)7 }8 defer resp.Body.Close()9 doc, err := html.Parse(resp.Body)10 if err != nil {11 log.Fatal(err)12 }13 for _, node := range TBodies(doc) {14 fmt.Printf("%+v15 }16 }17}18func TBodies(doc *html.Node) []*html.Node {19 var f func(*html.Node)20 f = func(n *html.Node) {21 if n.Type == html.ElementNode && n.Data == "tbody" {22 nodes = append(nodes, n)23 }24 for c := n.FirstChild; c != nil; c = c.NextSibling {25 f(c)26 }27 }28 f(doc)29}30import (31func main() {32 for _, url := range os.Args[1:] {33 resp, err := http.Get(url)34 if err != nil {35 log.Fatal(err)36 }37 defer resp.Body.Close()38 doc, err := html.Parse(resp.Body)39 if err != nil {40 log.Fatal(err)41 }42 for _, node := range TBodies(doc) {43 fmt.Printf("%+v44 }45 }46}47func TBodies(doc *html.Node) []*html.Node {48 var f func(*html.Node)49 f = func(n *html.Node) {50 if n.Type == html.ElementNode && n.Data == "tbody" {51 nodes = append(nodes, n)52 }53 for c := n.FirstChild; c != nil; c = c.NextSibling {54 f(c)55 }56 }57 f(doc)

Full Screen

Full Screen

TBodies

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 doc.Find("tbody").Each(func(i int, s *goquery.Selection) {7 fmt.Println(s.Text())8 })9}

Full Screen

Full Screen

TBodies

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 log.Fatal(err)5 }6 doc.Find("tbody").Each(func(i int, s *goquery.Selection) {7 band := s.Find("a").Text()8 title := s.Find("b").Text()9 fmt.Printf("Review %d: %s - %s10 })11}

Full Screen

Full Screen

TBodies

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 log.Fatal(err)5 }6 doc.Find("body").Each(func(i int, s *goquery.Selection) {7 fmt.Println(s.Html())8 })9}10< body class="vasq" jsaction="rcuQ6b:npT2md" style="margin: 0px;">< div id="viewport">< div id="viewport-wrapper">< div id="content">< div id="main">< div id="cnt">< div id="center_col">< form action="/search" id="tsf" method="GET" name="f" onsubmit="return q.value || (q.value = 'Search Google');">< table cellpadding="0" cellspacing="0" id="gb" style="width:100%">< tbody>< tr>< td class="gbh" colspan="4" style="height:32px"></td></tr>< tr>< td class="gbf" colspan="4" style="height:0px"></td></tr>< tr>< td class="gbg" style="width:4px;height:32px"></td>< td class="gbg" style="width:4px;height:32px"></td>< td class="gbg" style="height:32px"></td>< td class="gbg" style="width:4px;height:32px"></td></tr>< tr>< td class="gbg" style="width:4px"></td>< td class="gbg" style="width:4px"></td>< td class="gbh" style="height:32px"></td>< td class="gbg" style="width:4px"></td></tr>< tr>< td class="gbg" style="width:4px;height:32px"></td>< td class="gbg" style="width:4px;height:32px"></td>< td class="gbg" style="height:32px"></td>< td class="gbg" style="width:4px;height:32px"></td></tr></tbody></table>< table cellpadding="0" cellspacing="0" id="gb" style="width:100%">< tbody>< tr>< td

Full Screen

Full Screen

TBodies

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 panic(err)5 }6 defer res.Body.Close()7 doc, err := html.Parse(res.Body)8 if err != nil {9 panic(err)10 }11 fmt.Println("Number of TBodies:", len(TBodies(doc)))12}13func TBodies(doc *html.Node) []*html.Node {14 var f func(*html.Node)15 f = func(n *html.Node) {16 if n.Type == html.ElementNode && n.Data == "tbody" {17 tbodies = append(tbodies, n)18 }19 for c := n.FirstChild; c != nil; c = c.NextSibling {20 f(c)21 }22 }23 f(doc)24}

Full Screen

Full Screen

TBodies

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println("error")5 }6 defer resp.Body.Close()7 doc, err := goquery.NewDocumentFromResponse(resp)8 if err != nil {9 fmt.Println("error")10 }11 doc.Find("body").Each(func(i int, s *goquery.Selection) {12 fmt.Println(s.Text())13 })14}

Full Screen

Full Screen

TBodies

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 log.Fatal(err)5 }6 defer resp.Body.Close()7 if resp.StatusCode != 200 {8 log.Fatalf("status code error: %d %s", resp.StatusCode, resp.Status)9 }10 doc, err := goquery.NewDocumentFromReader(resp.Body)11 if err != nil {12 log.Fatal(err)13 }14 doc.Find("tbody").Each(func(i int, s *goquery.Selection) {15 band := s.Find("tr").Text()16 title := s.Find("td").Text()17 fmt.Printf("Review %d: %s - %s18 })19}

Full Screen

Full Screen

TBodies

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 log.Fatal(err)5 }6 doc.Find("tbody").Each(func(i int, s *goquery.Selection) {7 band := s.Find("tbody").Text()8 title := s.Find("tbody").Text()9 fmt.Printf("Review %d: %s - %s10 })11}12import (13func main() {14 if err != nil {15 log.Fatal(err)16 }17 doc.Find("thead").Each(func(i int, s *goquery.Selection) {18 band := s.Find("thead").Text()19 title := s.Find("thead").Text()20 fmt.Printf("Review %d: %s - %s21 })22}23import (24func main() {25 if err != nil {26 log.Fatal(err)27 }28 doc.Find("tfoot").Each(func(i int, s *goquery.Selection) {

Full Screen

Full Screen

TBodies

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 defer resp.Body.Close()7 body, err := ioutil.ReadAll(resp.Body)8 if err != nil {9 fmt.Println(err)10 }11 s := string(body)12 fmt.Println(html.UnescapeString(s))13}

Full Screen

Full Screen

TBodies

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 file, err := os.Open("test.html")4 if err != nil {5 fmt.Println(err)6 }7 defer file.Close()8 doc, err := html.Parse(file)9 if err != nil {10 fmt.Println(err)11 }12 TBodies := html.TBodies(doc)13 for _, tbody := range TBodies {14 fmt.Println(tbody)15 }16}

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run K6 automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful