Convert CSV to List<List<dynamic>> with rows and columns - list

I want to convert csv to List<List> my code bellow is working and get the file and convert it like this:
[[item 1;1200;1300],[item 2;1200;1300]].
It's handle [item 1;1200;1300] as a single element I can't reach item 1 or 1200 or 1300 as alone.
I want to handle it like this List[0][0] the result will be item 1.
TextButton(
onPressed: () async {
result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['csv'],
dialogTitle: 'Choose Your File',
);
if (result != null) {
PlatformFile file = result!.files.first;
filePath = file.path!;
prvdr.openFile(filePath);
} else {}
},
child: const Text('Press Here'),
),
The Fuction
void openFile(filePath) async {
File itemsFile = File(filePath);
print('CSV to List');
final input = itemsFile.openRead();
final fields = await input.transform(utf8.decoder).transform(const CsvToListConverter()).toList();
print(fields);
for(var i = 0; i < fields.length; i++){
print(fields[i][0]);
print(fields[i][1]);
print(fields[i][2]);
}
}
My csv is like this
item 1;1200;1300
item 2;1200;1300
item 3;1200;1300
item 4;1200;1300

You should do a for loop that loops on the list and splits every element by ;
Example:
final fields = await input.transform(utf8.decoder).transform(const CsvToListConverter()).toList();
List<List<String>> finalList = [];
for(var i = 0; i < fields.length; i++){
finalList.add(fields[i].split(";"));
}
// Now you cand access finalList
for(var i = 0; i < finalFields.length; i++){
print(finalFields[i][0]);
print(finalFields[i][1]);
print(finalFields[i][2]);
}

Related

How to enable tooltip for line segment in Line Chart with Chart.js

I am able to configure the line chart tooltip when I hover over the datapoint. However, I would also like to show some data if hover is over the line segment between two data points.
Code I am using is as follows :
callbacks: {
label: function (context) {
var value = labels[context.dataIndex];
for (var i = 0; i < flares.length; i++) {
// console.log(labels[ctx.p0DataIndex], flares[i]);
if (
value >= flares[i].Starttime &&
value <= flares[i].Endtime
) {
return "Peak-Score : " + flares[i].PeakScore;
}
}
return "No flares";
},
},
'''

how to save a list of data to a variable in flutter dart

var users = [
{id :3,name : adel,description: agent},{ id :4,name : anu,description: Manager,},
{id:5,name:arun,description:poen}
]
here i want to save each json object save in separate variable ,so i can acess it easily, how to do that
for (int i =0; i<users.length;i++)
{
var descrip = users[i]['description'];
}
when i using this above loop method ,the variable saves only the last data in the list , im new to flutter , anyone know how to save this data to variable ,please help me
final List<String> description = new [];
for(int i = 1;i < users.length; i++){
description.add(users[i]['description']);
}
As Belle Zaid said you declared your variable descrip inside your loop and overwrite it on each step. That's the reason why you only get your last value. First you need to declare a List outside of the for loop and inside the loop you add each value to the list.
final List<String> descrip = [];
for(int i = 0;i < users.length; i++){
descrip.add(users[i]['description']);
}
Try this
List<Map<String, dynamic>> usersJson = [
{'id': 3, 'name': 'adel', 'description': 'agent'},
{ 'id': 4, 'name': 'anu', 'description': 'Manager',},
{'id': 5, 'name': 'arun', 'description': 'poen'}
];
List<String> descriptions = [];
for (int i =0; i<users.length;i++)
{
descriptions.add(users[i]['description']);
}

Regular expression to extract Words inside nested parentheses

im looking for the regexp that make able to do this tasks
message Body Input: Test1 (Test2) (test3) (ti,ab(text(text here(possible text)text(possible text(more text))))) end (text)
the result that i want Result: (text(text here(possible text)text(possible text(more text))))
I want to collect everything that is inside ti,ab(................)
var messageBody = message.getPlainBody()
var ssFile = DriveApp.getFileById(id);
DriveApp.getFolderById(folder.getId()).addFile(ssFile);
var ss = SpreadsheetApp.open(ssFile);
var sheet = ss.getSheets()[0];
sheet.insertColumnAfter(sheet.getLastColumn());
SpreadsheetApp.flush();
var sheet = ss.getSheets()[0];
var range = sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn() + 1)
var values = range.getValues();
values[0][sheet.getLastColumn()] = "Search Strategy";
for (var i = 1; i < values.length; i++) {
//here my Regexp
var y = messageBody.match(/\((ti,ab.*)\)/ig);
if (y);
values[i][values[i].length - 1] = y.toString();
range.setValues(values);
The only solution you may use here is to extract all substrings inside parentheses and then filter them to get all those that start with ti,ab:
var a = [], r = [], result;
var txt = "Test1 (Test2) (test3) (ti,ab(text(text here(possible text)text(possible text(more text))))) end (text)";
for(var i=0; i < txt.length; i++){
if(txt.charAt(i) == '(') {
a.push(i);
}
if(txt.charAt(i) == ')') {
r.push(txt.substring(a.pop()+1,i));
}
}
result = r.filter(function(x) { return /^ti,ab\(/.test(x); })
.map(function(y) {return y.substring(6,y.length-1);})
console.log(result);
The nested parentheses function is borrowed from Nested parentheses get string one by one. The /^ti,ab\(/ regex matches ti,ab( at the start of the string.
The above solution allows extracting nested parentheses inside nested parentheses. If you do not need it, use
var txt = "Test1 (Test2) ((ti,ab(text(text here))) AND ab(test3) Near Ti(test4) NOT ti,ab,su(test5) NOT su(Test6))";
var start=0, r = [], level=0;
for (var j = 0; j < txt.length; j++) {
if (txt.charAt(j) == '(') {
if (level === 0) start=j;
++level;
}
if (txt.charAt(j) == ')') {
if (level > 0) {
--level;
}
if (level === 0) {
r.push(txt.substring(start, j+1));
}
}
}
console.log("r: ", r);
var rx = "\\b(?:ti|ab|su)(?:,(ti|ab|su))*\\(";
var result = r.filter(function(y) { return new RegExp(rx, "i").test(y); })
.map(function(x) {
return x.replace(new RegExp(rx, "ig"), '(')
});
console.log("Result:",result);
The pattern used to filter and remove the unnecessary words
\b(?:ti|ab|su)(?:,(ti|ab|su))*\(
Details
\b - a word boundary
(?:ti|ab|su) - 1 of the alternatives,
(?:,(ti|ab|su))* - 0 or more repetitions of , followed with 1 of the 3 alternatives
\( - a (.
The match is replaced with ( to restore it in the match.

Google Table Chart: Date Format

I am returning data to the chart using JSON.
I've managed to format the date for the x-axiz of the Line Chart, using;
var options = {
hAxis: {
format: ' dd MMM yy'
},
}
But I need help doing the same for a Table Chart where one of the columns should be of date format.
At the moment it is displaying "/Date(1372761341103)/"
How do I format this option?
As I understand it, the "options" variable setting is not available for the Table Chart.
Also, when I add my columns, setting my 'Date' column's data type to 'date' doesn't work...no chart is returned.
This is my code currently:
function drawChart3() {
$.get('/MyMall/GetAdRunData', {},
function (data) {
/* Add data */
var tdata = new google.visualization.DataTable()
tdata.addColumn('number', 'Id');
tdata.addColumn('string','Date');
tdata.addColumn('number', 'Opens');
for (var i = 0; i < data.length; i++) {
tdata.addRow([data[i].Id, data[i].Date, data[i].Opens]);
}
/* Draw chart */
var chart = new google.visualization.Table(document.getElementById('chart_adRun'));
//var formatter = new google.visualization.ColorFormat();
//var monthYearFormatter = new google.visualization.DateFormat({ pattern: "MMM yyyy" });
monthYearFormatter.format(tdata, 0);
formatter.addRange(-1, 1, 'white', 'orange');
formatter.addRange(0, 2, 'red', '#33ff33');
formatter.addRange(1, 10, 'red', 'pink');
formatter.format(tdata, 1); // Apply formatter to second column
chart.draw(tdata, { allowHtml: true, showRowNumber: false });
}
)
}
I solved it this way...
for (var i = 0; i < data.length; i++) {
var date = new Date(parseInt(data[i].Date.substr(6)));
tdata.addRow([data[i].Id, date, data[i].Opens]);
}

How to interact with a table in a dashboard drawn by using google graphs api?

I have a dashboard containing a table and a string filtering box. I would like to interact with the table to be able to select rows and retrieve respective data from it.
after slight changes I got the getSelection() method working but there appeared another problem.. With the code below I try to filter the table and then select and get row data.. It all seems okay but when I do so the filtered table row numbers and the row numbers in the actual data does not match. that is I end up alerting the row data with reference to the pre-filtered table... Again any suggestion is highly valued.. thanks..
var dashboard, table, data;
function drawVisualization() {
var array = new Array(['ticker','time','bid','open','high','low','volume']);
var ticker, time, bid, open, high, low, volume;
$.get('php/getdata.php', {input: 'stocklist'}, function(data1){
$.each(data1, function(index, value){
ticker = value.ticker;
time = value.time;
bid = parseFloat(value.bid);
open = parseFloat(value.open);
high = parseFloat(value.high);
low = parseFloat(value.low);
volume = parseFloat(value.volume);
array.push([ticker, time, bid, open, high, low, volume]);
});
data = google.visualization.arrayToDataTable(array);
var stringFilter = new google.visualization.ControlWrapper({
'controlType': 'StringFilter',
'containerId': 'control1',
'options': {
'filterColumnLabel': 'ticker'
}
});
table = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'chart1',
'options': {'showRowNumber': false, 'height': '130px', 'width': '1000px'}
});
dashboard = new google.visualization.Dashboard(document.getElementById('dashboard'))
dashboard.bind(stringFilter, table);
dashboard.draw(data);
google.visualization.events.addListener(table, 'select', selectHandler);
}, "json");
}
function selectHandler() {
var selection = table.getChart().getSelection();
for (var i = 0; i < selection.length; i++) {
var item = selection[i];
if (item.row != null && item.column != null) {
} else if (item.row != null) {
stockID = data.getFormattedValue(item.row, 0);
} else if (item.column != null) {
stockID = data.getFormattedValue(0, item.column);
}
}
if (stockID == '') {
return;
}
alert(stockID);
}
google.setOnLoadCallback(drawVisualization);
I've had a similar problem.
You have to get the new DataTable after applying the filter. Try changing
stockID = data.getFormattedValue(item.row, 0);
to
stockID = table.getDataTable().getFormattedValue(item.row, 0);
and the same for the other case.
cheers