Optimize tableView insertion in CoronaSDK - lua

This code takes two seconds to process.
print("before loop scholarships:"..system.getTimer())
for i = 1, scholarshipTableSize do
-- Insert the row into the tableView
tableView:insertRow
{
isCategory = false,
rowHeight = 75,
rowColor =
{
default = { 255, 232, 4 },
over = { 0, 158, 255 },
},
lineColor = { 0, 0, 0 },
}
end
scholarshipTableSize is somewhere around 1200. How can I optimize this insertion so that it performs faster?

After I updated to the latest corona build, the time was much better. around 2 ms.
Now I am using build 2013.1137

Related

How do I find an error in the while loop?

I need help. I wrote the code and checked it a hundred times. But I can't find the error. All code before the while loop works without errors. Error in the loop itself. When you run it, you get an infinite loop.
I would be grateful if you could tell me where I made the mistake and why it turns out to be an infinite loop.
class Semis {
int i;
double k;
Semis(this.i, this.k);
}
void main() {
var p = [
0, 1, 5, 8, 9, 10, 17, 17, 20, 24, // 0X's
30, 32, 35, 39, 43, 43, 45, 49, 50, 54, // 1X's
57, 60, 65, 68, 70, 74, 80, 81, 84, 85, // 2X's
87, 91, 95, 99, 101, 104, 107, 112, 115, 116, // 3X's
119, 121, 125, 129, 131, 134, 135, 140, 143, 145, // 4X's
151
];
Function cutLog = (List p, int n) {
// Some array to store calculated values
num sum = 0;
int iter = 0;
int stock = n;
List<Semis> pL = [];
var map = Map.fromIterable(p,
key: (index) => p.indexOf(index),
value: (item) => item / (p.indexOf(item) > 0 ? p.indexOf(item) : 1));
var sortedMap = Map.fromEntries(
map.entries.toList()..sort((e1, e2) => e2.value.compareTo(e1.value)));
sortedMap.forEach(
(i, k) => pL.isEmpty || pL.last.i > i ? pL.add(Semis(i, k)) : null);
while (stock > 0) {
if ((stock - pL[iter].i) > 0) {
sum = sum + p[pL[iter].i];
stock = stock - pL[iter].i;
} else
iter++;
}
return sum; // Good luck intern!
};
print(cutLog(p, 5));
}
You get an infinite loop because the condition of the loop never fails.
The condition is that stock > 0. However, what you do in the loop is:
If stock minus some value is >0, you decrement stock. Therefore stock remains higher than 0
Else you increment the iterator.
You never actually allow stock to be decremented enough so that it becomes 0. I think your if comparison should be made using >= 0, if that seems logical for your algorithm. If not, then you probably need to rework it more.
If you look at the list of Semis you create, its last element is Semis(0, 0.0).
That means that your loop, will eventually reach this, and then
if ((stock - pL[iter].i) > 0) {
sum = sum + p[pL[iter].i];
stock = stock - pL[iter].i;
will do nothing because pL[iter].i is zero.
You probably need to bail out of the loop at this point.
Your loop will, as Lyubomir Vasilev says, never have a false condition because stock never reaches zero. Your iter is increment, and if it hadn't been for the Semis(0, _) entry, you would eventually have run past the end of the pL array and gotten an index-out-of-range error. With that zero-value in the loop, you will run forever.

How to calculate cpu utilization of container in docker using http api

I know that the CPU utilization of the container can be obtained by docker stats:
#docker stats
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
05076af468cd mystifying_kepler 0.02% 10.5MiB / 5.712GiB 0.18% 656B / 0B 0B / 0B 1
And I want to get this data through the HTTP api:http api.
Data i get from this http api is :
{
"read": "2019-11-26T22:18:33.027963669Z",
"preread": "2019-11-26T22:18:32.013978454Z",
"pids_stats": {
"current": 1
},
"blkio_stats": {
"io_service_bytes_recursive": [],
"io_serviced_recursive": [],
"io_queue_recursive": [],
"io_service_time_recursive": [],
"io_wait_time_recursive": [],
"io_merged_recursive": [],
"io_time_recursive": [],
"sectors_recursive": []
},
"num_procs": 0,
"storage_stats": {},
"cpu_stats": {
"cpu_usage": {
"total_usage": 361652820,
"percpu_usage": [361652820],
"usage_in_kernelmode": 50000000,
"usage_in_usermode": 100000000
},
"system_cpu_usage": 144599100000000,
"online_cpus": 1,
"throttling_data": {
"periods": 0,
"throttled_periods": 0,
"throttled_time": 0
}
},
"precpu_stats": {
"cpu_usage": {
"total_usage": 361488978,
"percpu_usage": [361488978],
"usage_in_kernelmode": 50000000,
"usage_in_usermode": 100000000
},
"system_cpu_usage": 144598090000000,
"online_cpus": 1,
"throttling_data": {
"periods": 0,
"throttled_periods": 0,
"throttled_time": 0
}
},
"memory_stats": {
"usage": 11005952,
"max_usage": 11108352,
"stats": {
"active_anon": 11005952,
"active_file": 0,
"cache": 0,
"dirty": 0,
"hierarchical_memory_limit": 9223372036854771712,
"hierarchical_memsw_limit": 9223372036854771712,
"inactive_anon": 0,
"inactive_file": 0,
"mapped_file": 0,
"pgfault": 8151,
"pgmajfault": 0,
"pgpgin": 4137,
"pgpgout": 1450,
"rss": 11005952,
"rss_huge": 0,
"total_active_anon": 11005952,
"total_active_file": 0,
"total_cache": 0,
"total_dirty": 0,
"total_inactive_anon": 0,
"total_inactive_file": 0,
"total_mapped_file": 0,
"total_pgfault": 8151,
"total_pgmajfault": 0,
"total_pgpgin": 4137,
"total_pgpgout": 1450,
"total_rss": 11005952,
"total_rss_huge": 0,
"total_unevictable": 0,
"total_writeback": 0,
"unevictable": 0,
"writeback": 0
},
"limit": 6133108736
},
"name": "/mystifying_kepler",
"id": "05076af468cdeb3d15d147a25e8ccee5f4d029ffcba1d60f14f84e2c9e25d6a9",
"networks": {
"eth0": {
"rx_bytes": 656,
"rx_packets": 8,
"rx_errors": 0,
"rx_dropped": 0,
"tx_bytes": 0,
"tx_packets": 0,
"tx_errors": 0,
"tx_dropped": 0
}
}
}
I was able to calculate the utilization of memory from the data, but I didn't find a way to get the CPU utilization .
And ideas?
You've probably solved this by now, but for the next person... This example is in Python, but the data fields and math are the same if you're making API calls.
The API returns cumulative values, so you need more than one sample - do the math using the difference between samples to get the utilization for that period. This example uses the streaming mode, which pushes an update every second.
# These initial values will seed the "last" cycle's saved values
containerCPU = 0
systemCPU = 0
container = client.containers.get(containerID)
#This function is blocking; the loop will proceed when there's a new update to iterate
for stats in container.stats(decode=True):
#Save the values from the last sample
lastContainerCPU = containerCPU
lastSystemCPU = systemCPU
#Get the container's usage, the total system capacity, and the number of CPUs
#The math returns a Linux-style %util, where 100.0 = 1 CPU core fully used
containerCPU = stats.get('cpu_stats',{}).get('cpu_usage',{}).get('total_usage')
systemCPU = stats.get('cpu_stats',{}).get('system_cpu_usage')
numCPU = len(stats.get('cpu_stats',{}).get('cpu_usage',{}).get('percpu_usage',0))
# Skip the first sample (result will be wrong because the saved values are 0)
if lastContainerCPU and lastSystemCPU:
cpuUtil = (containerCPU - lastContainerCPU) / (systemCPU - lastSystemCPU)
cpuUtil = cpuUtil * numCPU * 100
print(cpuUtil)

Highcharts: Stacked bar chart display categories data, not series

I have two JS associative arrays that look like this:
var distroDates = [
{
name: 'exDate',
data: [
'06/25/2013',
'12/17/2012',
'06/20/2012',
'12/19/2011',
'06/21/2011',
'12/20/2010',
'06/21/2010',
'12/21/2009',
'06/22/2009',
'12/22/2008',
'06/23/2008',
'12/24/2007',
'12/21/2006',
'12/23/2005',
'12/23/2004',
'12/22/2003',
'12/23/2002'
]
},
{
name: 'Record Date',
data: [
'06/27/2013',
'12/19/2012',
'06/22/2012',
'12/21/2011',
'06/23/2011',
'12/22/2010',
'06/23/2010',
'12/23/2009',
'06/24/2009',
'12/24/2008',
'06/25/2008',
'12/27/2007',
'12/26/2006',
'12/28/2005',
'12/28/2004',
'12/24/2003',
'12/26/2002'
]
},
{
name: 'Payable Date',
data: [
'07/02/2013',
'12/24/2012',
'06/27/2012',
'12/29/2011',
'06/27/2011',
'12/30/2010',
'06/25/2010',
'12/31/2009',
'06/26/2009',
'12/31/2008',
'06/27/2008',
'01/04/2008',
'12/28/2006',
'12/30/2005',
'12/30/2004',
'01/02/2004',
'01/02/2003'
]
}
]
var distroData = [
{
name: 'Income',
data: [
0.3908,
0.4948,
0.2311,
0.3342,
0.245,
0.2213,
0.19,
0.1404,
0.2014,
0.2266,
0.2131,
0.2328,
0.1288,
0.0044,
0.6248,
0,
0
]
},
{
name: 'S.T. Capital Gains',
data: [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
name: 'L.T. Capital Gains',
data: [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
name: 'Return on Capital',
data: [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0.0202,
0,
0,
0
]
}
]
The distroData array is used for the series. The distroDates is used for the categories. I want the categories to display in the tooltip (rather than the usual series data) and I want the tooltip to update with the category values as I hover over each bar along the x-axis.
The following code accomplished this using Highcharts v2.1.4/Highstock v1.2.5 (both are loaded):
tooltip: {
formatter: function() {
var s = '<table class="tooltip distro"><tbody>';
var chart = this.points[0].series.chart; //get the chart object
var categories = chart.xAxis[0].categories; //get the categories array
var index = 0;
var distroDataPoint;
while(this.x !== categories[index]){index++;} //compute the index of corr y value in each data arrays
$.each(distroDates, function(i, categories) { //loop through categories array
s += '<tr><td>'+ categories.name +':</td><td>' + categories.data[index] + '</td></tr>'; //use index to peg categories and distro data to series
distroDataPoint = '<tr><td>Distribution:</td><td>$' + distroData[0].data[index] + '</td></tr>';
});
s += distroDataPoint + '</tbody></table>'
return s;
},
shared: true
},
However, when I upgraded to Highstock 1.3.4 (which includes Highcharts) the while statement locked my browser (FF and Chrome). The browser gave the familiar "Script is non-responsive" alert I assume because it was caught in an expensive loop.
Any ideas how I can rewrite or substitute the while so that performance is acceptable?
Why don't you just use shared tooltip? Just set tooltip.shared = true and everything will work fine. See example how to format shared tooltip here.

Mismatch when duplicating lua table

I'm writing a game using Lua and Love2d but I've hit a snag when dealing with nested tables.
I have a function that runs through a table containing numbers corresponding to walls, buttons, etc. and prints colored blocks based on the keys. An example of one of these tables would look like this:
map = {
{ 1, 1, 1, 1, 1, 1, 1, 1, 1 }
{ 1, 0, 0, 0, 0, 0, 0, 0, 1 }
{ 1, 0, 1, 1, 2, 0, 0, 0, 1 }
{ 1, 0, 0, 0, 0, 0, 0, 0, 1 }
{ 1, 1, 1, 1, 1, 1, 1, 1, 1 }
}
This works fine when rendered. However when I attempt to create this same table using a function that reads this data from a text file looking like this:
111111111
100000001
101120001
100000001
111111111
It creates a table that seems identical but it simply doesn't work when I try to render it.
So I tried debugging using a bit of code that prints out table contents and though the contents are the same, the bit of hex describing the nested tables are different. Example:
Reading the first nested table of the map file:
1 table: 0x106c5a720
1 1
2 1
3 1
4 1
5 1
6 1
7 1
8 1
9 1
Reading the first nested table of the manually created table:
1 table: 0x106c64120
1 1
2 1
3 1
4 1
5 1
6 1
7 1
8 1
9 1
What's going on here? The values are all identical but something strange is happening.
edit: Here's the bit of code that renders the map for reference:
for y=1, #map do
for x=1, #map[y] do
if map[y][x] == 1 then
print("found a wall")
love.graphics.rectangle("fill", x * 30, y * 30, 30, 30)
elseif map[y][x] == 2 then
print("found a button")
love.graphics.setColor(255, 0, 0)
love.graphics.rectangle("fill", x * 30, y * 30, 30, 30)
love.graphics.setColor(0, 0, 255)
end
end
end
When reading data from a text file, you are getting strings.
In your original map table you have numbers.
Numbers are not equal to strings.
assert(1 ~= '1')

Highchart update categories when adding points

Background
I was trying to show the average traffic with respect to the hours DYNAMICALLY using highchart. That is to say I want it show the traffic repeatedly like this, when the time comes to 23:00 next I want it back to 0:00.
I am doing this by setting 24 categories ['0:00', '1:00'...,'23:00'], and adding points when the data is updated by ajax, say every 1 second.
var chart = new Highcharts.Chart({
...//some options
xAxis: {
categories:['0:00','1:00','2:00',...,'23:00']
},
load: function() {setInterval(updateData,1000)}
series: [] //empty series here, adding dynamically by ajax
})
the updateData is defined as a function
function updateData(){
var data = $.ajax(...)// get the data
var series = chart.series[0];
if(series.data.length < 24){ //when data.length is < 24 add directly
chart.series[0].addPoint(data,true,false);
}else{
chart.series[0].addPoint(data,true,true);//set the 3rd option to true to remove the first data point, actually here this data is equal to the first one since this is a circle, when it comes to 24:00 it is actually 0:00, and I should update the xAxis.
//code updating the axis categories to [1:00, 2:00...23:00,0:00]
xAxis.setCategories(categories);
}
}
the x-axis turns out to be [2:00, 3:00, ...23:00, 0:00, 24], That is to say the point that I add this time does NOT correspond to the categories[24]:0:00, It is actually corresponding to the categories[25] which is not exist, so it is set to 24 in default.
A solution (quick and dirty)
do not ring shift the categories but push a new circle to it,like:
categories.push("time");//time is 0:00-23:00
xAxis.setCategories(categories);
but this will make the categories larger and larger..which is bad.
How can I fix this.
Another solution(also with some problems)
By using datetime as the type of x-axis, there is another problem. My data format is as follws
time count
8:00 23
9:00 56
... ...
and I can construct Points like [time, count], the question is I have time only. Even if I construct data by manually adding a date like
time = (new Date("2012-11-17 "+time)).getTime()
seems feasible. But when it got through 24 hours, the spline comes back to the left of the chart since the x-axis value here is equal to the first one.
BTW: how can I make the x-axis show only the time, the image above showed date at the left side, and the time interval is automatically display how to make it display all?
Thank You for your attention!!!
I followed your advice #Ruchit Rami and revised my code:
/*update part*/
var time = series.points.length > 0 ? series.points[series.points.length-1].category+3600 : 0;
//from 1970-1-1 0:00 And **add 1 hour everytime**
if (series.data.length < 24) {
series.addPoint([time, sum],true,false);
} else {
series.addPoint([time, sum],true,true);
}
/*chart part*/
xAxis: {
type: 'datetime',
dateTimeLabelFormat: {
second: '%H:%M',
minute: '%H:%M',
hour: '%H:%M',
day: '%H:%M',
week: '%H:%M',
month: '%H:%M',
year: '%H:%M'
}
tickInterval: 3600
}
The result
The date label format seems not affected though I specify it
And the time is not correct. Why? Thanks!
still didnt displayed right
To display only time on the X-axis you can use dateTimeLabelFormats property of xaxis and you can use tickInterval for setting tick interval on xaxis.
//Sets tickInterval to 24 * 3600 * 1000 if display is by day
tickInterval : 24 * 3600 * 1000,
dateTimeLabelFormats : {
hour : '%H:%M',
day : "%H:%M"
}
Now, for the issue of chart redraw from the first point, you will need to increase the date of the xaxis point. I am unable to come up with any elegant solution but you can check for time "0:00" while adding new points dynamically and before adding that point increase its date part by one compared to last point in the series.You can find the last point of the series by series.points[series.points.length-1]. Hope i haven't missed anything.
Now, this may not be what you are looking for but I am making some assumptions about what you want to show:
Data by hour for one "day" 0000-2300
Do not care to show the date just the time
Data fluctuates across "days" for a given time
I have created an example here of the chart iterating through 4 "days" of data. I did this by creating an empty data series first to draw the chart, then on load of the chart I iterate through an array of data sets every 1.5 seconds. It then loops back over to the beginning. I have it updating a DIV with what the "day" is. Please let me know if I have missed some condition you need.
Here is the looping code:
var data1 = [5, 8, 2, 5, 7, 4, 1, 2, 30, 20, 50, 30, 150, 130, 70, 50, 20, 47, 32, 18, 20, 15, 16, 8];
var data2 = [9, 15, 3, 4, 1, 1, 0, 0, 60, 75, 112, 190, 267, 365, 258, 164, 168, 190, 47, 16, 20, 18, 5, 8];
var data3 = [15, 18, 12, 5, 7, 4, 1, 2, 130, 20, 150, 130, 150, 130, 70, 50, 20, 47, 32, 18, 20, 15, 16, 8];
var data4 = [19, 15, 13, 4, 11, 11, 0, 0, 60, 175, 112, 190, 267, 365, 258, 164, 168, 190, 47, 16, 20, 18, 15, 18];
var dataSet = [data1, data2, data3, data4];
var dataIter = 0;
$(function() {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
events: {
load: function() {
var series = this.series[0];
setInterval(function() {
if (dataIter >= dataSet.length) dataIter = 0;
series.setData(dataSet[dataIter], true);
$("#dayLabel").text("Day - " +dataIter.toString());
dataIter += 1;
}, 1500);
}
}
},
xAxis: {
categories: ['0000', '0100', '0200', '0300', '0400', '0500', '0600', '0700', '0800', '0900', '1000', '1100', '1200', '1300', '1400', '1500', '1600', '1700', '1800', '1900', '2000', '2100', '2200', '2300'],
labels: {
rotation: 90
}
},
yAxis: {
min: 0,
max: 500
},
series: [{
data: []}]
});
});

Resources