I'm trying to get several values from a list of maps but whenever I alter the new List values, it also alters the same values in the original list of maps.
How can I clone the list properly so this doesn't happen?
final List<Map> entries = [
{'date': '2019-7-29', 'data': 85.0},
{'date': '2019-8-2', 'data': 85.0},
{'date': '2019-8-3', 'data': 85.0},
];
List<Map> getSelected() {
List<Map> obj = [];
for (var i = 0; i < 2; i++) {
obj.add(entries[i]);
obj[i]['data'] = obj[i]['data'] * 2;
}
return obj;
}
selected = getSelected();
EDIT: This was suggested but doesn't appear to fix things. I guess because objects are passed by reference.
List<Map> getSelected(List<Map> arr) {
List<Map> obj = [];
for (var i = 0; i < 2; i++) {
obj.add(arr[i]);
obj[i]['data'] = obj[i]['data'] * 2;
}
return obj;
}
selected = getSelected(entries);
final List<Map> entries = [
{'date': '2019-7-29', 'data': 85.0},
{'date': '2019-8-2', 'data': 85.0},
{'date': '2019-8-3', 'data': 85.0},
];
List<Map> selected = new List<Map>();
entries.forEach((map) => { selected.add(new Map.from(map)) });
selected.forEach((map) => map["data"] = map["data"] * 2 );
would solve your issue.
Related
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]);
}
I'm using Datatables to display tables in Django on the server side. After searching for a phrase, I have a button ready to save the current table after filtering to Excel. I would like the second button to create a new table in the database and save the same table to it as for Excel.
I don't know how I can send AJAX data to Django and read it in views in such a way that I can query the database.
javascript:
$(document).ready(function () {
function newexportaction(e, dt, button, config) {
var self = this;
var oldStart = dt.settings()[0]._iDisplayStart;
dt.one('preXhr', function (e, s, data) {
data.start = 0;
data.length = 2147483647;
dt.one('preDraw', function (e, settings) {
// Call the original action function
if (button[0].className.indexOf('buttons-excel') >= 0) {
$.fn.dataTable.ext.buttons.excelHtml5.available(dt, config) ?
$.fn.dataTable.ext.buttons.excelHtml5.action.call(self, e, dt, button, config) :
$.fn.dataTable.ext.buttons.excelFlash.action.call(self, e, dt, button, config);
}
dt.one('preXhr', function (e, s, data) {
settings._iDisplayStart = oldStart;
data.start = oldStart;
});
});
});
dt.ajax.reload();
}
$("#tb").DataTable({
"lengthChange": true,
"paging": true,
"searching": true,
"oLanguage": {
"sSearch": "Szukaj:",
},
"language": {
"processing": "Przetwarzanie",
"lengthMenu": "Pokaż _MENU_ elementów",
"info": "Wyświetlono od _START_ do _END_ z _TOTAL_ elementów",
"zeroRecords": "Nie znaleziono pasujących elementów",
"paginate": {
"first": "Pierwsza",
"last": "Ostatnia",
"next": "Kolejna",
"previous": "Poprzednia"
},
"emptyTable": "Brak danych do wyświetlenia",
},
"processing": true,
"serverSide": true,
buttons: [
{
extend: 'excel',
titleAttr: 'Excel',
title: '',
action: newexportaction
},
],
dom: 'B<"clear">lfrtip',
// "destroy": true,
"pageLength": 15,
"ordering": false,
"ajax": {
"url": "paging2/",
"type": "get"
},
});
});
views.py:
def paging2(request):
draw = int (request.GET.get ('draw')) # record the number of operations
start = int (request.GET.get ('start')) # start position
length = int (request.GET.get ('length')) # length of each page
search_key = request.GET.get ('search[value]') # search keyword
order_column = request.GET.get ('order [0] [column]') # sort field index
order_column = request.GET.get ('order [0] [dir]') #Ordering rule: ase / desc
# sql query all data, then do paging, the speed is slow
# if search_key:
# result = query(search_key)
# else:
# result = select_all()
# data = result[start:start+length]
# count = len(result)
# sql for paging, fast
if search_key:
sql_search = "SELECT NAZWA,TEL,NIP,Adres,WWW, EMAIL, Branza, NAZWA_SCRAPERA FROM gus_all t1 WHERE NOT EXISTS (SELECT * FROM matka_new t2 WHERE t2.NIP = t1.NIP) AND LENGTH(TEL) = 9 AND `STATUS` = 'AKTYWNY' AND NAZWA_SCRAPERA is NOT NULL AND Branza like '%%%s%%'" % search_key
sql_search_len = "SELECT COUNT(*) FROM gus_all t1 WHERE NOT EXISTS (SELECT * FROM matka_new t2 WHERE t2.NIP = t1.NIP) AND LENGTH(TEL) = 9 AND `STATUS` = 'AKTYWNY' AND NAZWA_SCRAPERA is NOT NULL AND Branza like '%%%s%%'"% search_key
result, count = query(sql_search, sql_search_len)
data = result[start:start + length]
else:
sql = """
SELECT NAZWA,TEL,NIP,Adres,WWW, EMAIL, Branza, NAZWA_SCRAPERA FROM gus_all t1 WHERE NOT EXISTS (SELECT * FROM matka_new t2 WHERE t2.NIP = t1.NIP) AND LENGTH(TEL) = 9 AND `STATUS` = 'AKTYWNY' AND NAZWA_SCRAPERA is NOT NULL
LIMIT %s OFFSET %s
"""
data = select_by_page(length, start, sql)
# data = select_by_page(start, start + length)
sql_len = "SELECT COUNT(*) FROM gus_all t1 WHERE NOT EXISTS (SELECT * FROM matka_new t2 WHERE t2.NIP = t1.NIP) AND LENGTH(TEL) = 9 AND `STATUS` = 'AKTYWNY' AND NAZWA_SCRAPERA is NOT NULL"
count = all_count(sql_len)
dic = {
'draw': draw,
'recordsTotal': count,
'recordsFiltered': count,
'data': data,
}
return HttpResponse(json.dumps(dic), content_type='application/json')
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']);
}
i am developing a webpage in DJANGO which contains a bootstrap tree view. Now if i click o a particular node i need to display the children in a bootstrap list.
Here is my view
def get_context_data(self, **kwargs):
context = dict()
organization = Organization.objects.all()
orglocations = Orglocations.objects.all()
locationprocessarea = Locationprocessarea.objects.all()
processareaasset = Processareaasset.objects.all()
processtaglink = Processareaassettaglink.objects.all()
context["TreeStructure"] = [
{
'text': organizations.name,
'nodes': [
{
'text': orglocationss.name,
'nodes': [
{
'text': processarea.name,
'nodes': [
{
'text': processasset.name,
'nodes':[{
'text':processareafilter.name,
'nodes':[{
'text':taglink.name
}for taglink in processtaglink.filter(areaassetid=processareafilter.id)]
}for processareafilter in processareaasset.filter(parentassetid=processasset.id)]
} for processasset in processareaasset.filter(processareaid=processarea.id).filter(parentassetid__isnull=True)]
} for processarea in locationprocessarea.filter(locationid=orglocationss.id)]
} for orglocationss in orglocations.filter(organizationid_id=organizations.id)]
} for organizations in organization.filter(id=1)]
return {
"tree_view": context
}
thanks in advanceenter code here
jsondata = f.read()
dataList = json.loads(jsondata)
projectName = dataList['query']['project']
reportStartTime = dataList['query']['startTime']
reportEndTime = dataList['query']['endTime']
allEventList = dataList['sessionEvents']
'''We need a Type for each data so it will be
like startTime:endTime'''
flag = False
count = 0
esbulkData = []
for event in allEventList:
ls = event["l"]
del event["l"]
for l in ls:
llist = []
eventList = []
llist.append(l)
event["l"] = llist
eventList.append(event)
flurryData = { "project": projectName, "startTime": reportStartTime, "endTime": reportEndTime, "sessionEvents": eventList }
#{
# "_index": "tickets-index",
# "_type": "tickets",
# "_id": j,
# "_source": {
# "any":"data" + str(j),
# "timestamp": datetime.now()}
# }
esData = {"_index": "fl_ios_prod_feb_bulk", "_type": "flurryRawSchema", "_id": count, "_source": flurryData}
esbulkData.append(esData)
es = Elasticsearch([ES_URL])
res = helpers.bulk(es, esbulkData)
if (res):
print("Passed")
else:
print("Failed")
In above code, everything works just fine but doc_count don't go more than 500 while checking on "Sense". It seems to have deleted some docs.
Please help. I am having those nights
Okay So I forget to increase the count and that what was issue.