Trying to fill in a List of class - list

I'm really sorry I'm such a beginner...
At the end I just have a list of 8 TimeCardDayStrip with the same name/position when it'd supposed to be the 8 different names/roles.
I don't understand what I'm doing wrong here:
thank you very much
'''
class TimeCardDayStrip {
String name, position;
DateTime day;
#override
String toString(){
return '{ $this.name, $this.position }';
}
}
void main() {
var tcds = TimeCardDayStrip();
var listOfTcds = [];
List<String> names, roles;
names = ["Michael", "Gunnell", "Byrne", "Aspromonte", "Davis", "Adam Jordan", "Mirko"];
roles = ["Director", "Vice", "President", "1ST", "KEY 2ND", "2ND", "BASECAMP PA", "PA", " PA", "Add'l PA"];
for (int i = 0; i < names.length; i++) {
tcds.name = names[i];
tcds.position = roles[i];
listOfTcds.add(tcds);
// checking the list as it creates
print(listOfTcds[i].name+' is '+listOfTcds[i].position);
}
//print the list of card to check
print('print the list of time card to check');
for (int x = 0; x < listOfTcds.length; x++){
print (listOfTcds.elementAt(x).name);
}
}
'''

If you just want to print out each name:
Put this within the loop (you should create new object each loop instead of updating the same one)
for (int i = 0; i < names.length; i++) {
var tcds = TimeCardDayStrip();
tcds.name = names[i];
tcds.position = roles[i];
listOfTcds.add(tcds);
// checking the list as it creates
print('${listOfTcds[i].name} is ${listOfTcds[i].position}');
}
Then later
listOfTcds[x].name
If you want to display stuff:
#override
Widget build(BuildContext ctx) {
return ListView.builder(
itemCount: listOfTcds.length,
itemBuilder: (context, index) {
return CustomTile(item: listOfTcds[index]);
},
);
}

I believe you need to declare the tcds as Tcds = new TimecardDayStrip() and not just tcds = TimeCardDayStrip() or you are just changing the same object and not creating a new instance.

Related

How do I get an alert prompt when an "if" statement returns no 'finds' in Google Apps Script?

//Invoice find and transfer to Warehouse Sheet
function searchInvoiceWhSh() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var shUserForm = ss.getSheetByName("Warehouse Form")
var shSalesSheet = ss.getSheetByName("Sales")
var sValue = shUserForm.getRange("G5").getValue();
var sData = shSalesSheet.getDataRange().getValues();
var currentRow = 9
for (var i=0; i<sData.length; i++) {
var row = sData[i];
if (row[0] == sValue) { //do something}
currentRow += 2
}}
I've used this to search for an "Invoice number" from the "Sales" worksheet and when found to transfer the data back to the user form.
If, for example, the invoice number is typed incorrectly into the "sValue" cell, then no data will be transferred.
How do I code a prompt message to ask the user to check the invoice number as no records were found?
Try:
function searchInvoiceWhSh() {
const ss = SpreadsheetApp.getActiveSpreadsheet()
const shUserForm = ss.getSheetByName("Warehouse Form")
const shSalesSheet = ss.getSheetByName("Sales")
const sValue = shUserForm.getRange("G5").getValue()
const sData = shSalesSheet.getDataRange().getValues()
const targetData = sData.filter(row => row[0] === sValue)
if (targetData.length) {
// Value(s) found
targetData.forEach(row => {
Logger.log(row)
})
} else {
SpreadsheetApp.getUi().alert(`No match found.`)
}
}
This will search for the sValue provided as in your code, but will store the row in a variable once found. If it's not found, it will create an alert pop-up with your specified message.
Alternatively, you can check out UI Class for other pop-up options.
Try it like this:
function myfunk() {
var ss = SpreadsheetApp.getActive()
var fsh = ss.getSheetByName("Warehouse Form")
var ssh = ss.getSheetByName("Sales")
var fv = fsh.getRange("G5").getValue();
var svs = ssh.getDataRange().getValues();
let m = 0;
svs.forEach((r, i) => {
if (r[0] == fv) {
m++;
}
SpreadsheetApp.getUi().alert(`${m} matches found`)
});
}
Always provides a result

Add an another attribute to an existing List in Flutter

I have been trying many ways to add an isChecked: false attribute to every list inside the _filterOptions List in my Flutter Project. I couldn't find any solution to this. If there is any solution I am happy to see it.
List<dynamic> _filters = [];
List<List<dynamic>> _filterOptions =[];
var filters =
await json.decode(data)["getProductsByStore"]["aggregations"];
for(int i = 0; i < filters.length; i++){
_filters.add(filters[i]["label"]);
_filterOptions.add(filters[i]["options"]);
}
//print(filters[0]["options"]);
//print(_filters);
print(_filterOptions);
I am getting this kind of nested list when printed and I want to add the attribute to every list.
as an example:
[[{count: 3, label: 30-40, value: 30_40, isChecked:false}], [{count: 2, label: Bagged , value: 50, isChecked:false},{...},{...}...]]
Create Model class with your data and bool isChecked
class ModelClass{
String? label;
int? count;
List? options;
bool? isChecked;
ModelClass({this.label, this.count , this.options, this.isChecked = false});
ModelClass.fromJson(Map<String, dynamic> json){
label = json['label'];
count = json['count'];
options = json['options'];
}
}
then you can add data like below code
List<ModelClass> list = [];
void function()async{
List<dynamic> _filters = [];
List<List<dynamic>?> _filterOptions =[];
var filters =
await json.decode(data)["getProductsByStore"]["aggregations"];
for(int i = 0; i < filters.length; i++){
ModelClass modelClass = ModelClass.fromJson(filters[i]);
list.add(modelClass);
_filters.add(modelClass.label);
_filterOptions.add(modelClass.options);
}
print(list[0].options);
print(list[0].isChecked);
}
if you want to modify isChecked for some specific index
list[0].isChecked = false;
Just add these lines.
class YourWrapperClass {
YourWrapperClass({this.filterOptions = const [], this.isChecked = false});
List<List<dynamic>> filterOptions;
bool isChecked;
}
YourWrapperClass filterWrapper = YourWrapperClass(filterOptions: _filterOptions, isChecked: false);
And use this wrapper class object whenever ya need to access _filterOptions.
But, I would more rather recommend using the WrapperClass on the list elements, like so.
class YourWrapperClass {
YourWrapperClass({this.filterOption = const [], this.filter="", this.isChecked = false});
List<dynamic> filterOption;
dynamic filter;
bool isChecked;
}
List<YourWrapperClass> list = [];
var filters =
await json.decode(data)["getProductsByStore"]["aggregations"];
for(int i = 0; i < filters.length; i++){
list.add(YourWrapperClass(filterOption:filters[i]["options"], filter:filters[i]["label"], isChecked=false));
_filterOptions.add(filters[i]["options"]);
}

Xamarin Forms List Row Values not being updated when Re-LoadingData?

I am creating a list of scanned items. Whenever an item is scanned it checks if it already exists and if it does it increases the quantity, otherwise it will be added as a new item in the list.
When an item is added in the list the change is reflected correctly, however, when only the quantity is changed the value is not visually updated.
if(PurchaseUnloadData.scannedItems.Where(x => x.ItemID == item.ItemID).Count() > 0)
{
PurchaseUnloadData.scannedItems.FirstOrDefault(x => x.ItemID == item.ItemID).Quantity = PurchaseUnloadData.scannedItems.FirstOrDefault(x => x.ItemID == item.ItemID).Quantity + 1;
}
else
{
item.Quantity = 1;
PurchaseUnloadData.scannedItems.Add(item);
}
MessagingCenter.Send<ViewPurchaseUnloadingCart>(this, "ItemsChanged");
In addition when i scan an item twice, meaning the quantity gets to 2, if i add a new row the quantity value is updated! If there isn't a new row it just updates the data behind but not the list.
public class PurchaseUnloadingCartViewModel : ObservableObject
{
private NavigationCategoryData _category;
private PurchaseUnloadData.ScannedItemInfo _selectedItem;
public PurchaseUnloadingCartViewModel()
: base(listenCultureChanges: true)
{
LoadData();
ExportToExcelCommand = new Command(async () => await ExportDataToExcelAsync());
MessagingCenter.Subscribe<ViewPurchaseUnloadingCart>(this, "ItemsChanged", (sender) =>
{
LoadData();
});
}
public ObservableCollection<PurchaseUnloadData.ScannedItemInfo> Items { get; } = new ObservableCollection<PurchaseUnloadData.ScannedItemInfo>();
public NavigationCategoryData Category
{
get { return _category; }
set { SetProperty(ref _category, value); }
}
public PurchaseUnloadData.ScannedItemInfo SelectedItem
{
get { return _selectedItem; }
set
{
if (SetProperty(ref _selectedItem, value) && value != null)
{
Int64 itemID = Convert.ToInt64(value.ItemID);
Application.Current.MainPage.Navigation.PushAsync(new AddScannedItem("EDIT", itemID));
SetProperty(ref _selectedItem, null);
}
}
}
protected override void OnCultureChanged(CultureInfo culture)
{
LoadData();
}
private void LoadData()
{
Category = null;
Items.Clear();
int i = 0;
while (i < PurchaseUnloadData.scannedItems.Count)
{
Items.Add(PurchaseUnloadData.scannedItems[i]);
i++;
}
}
}
Implement INotifyPropertyChanged. Credits to Jason
https://learn.microsoft.com/en-us/dotnet/desktop/winforms/how-to-implement-the-inotifypropertychanged-interface?view=netframeworkdesktop-4.8

How to edit a list of object c# linq to xml

<Team Side="Home" TeamRef="ref123">
<Goal PlayerRef="p1111" Time="10" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
<Goal PlayerRef="p4444" Time="11" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
<Goal PlayerRef="p7777 Time="13" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
<Goal PlayerRef="p7777 Time="17" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
</Team>
public void GetScorer(string side, string OCompetition, string OSeason, string OGameId)
{
try
{
var xDoc = XDocument.Load(test);
var query = from q in xDoc.Descendants("Team")
where (string)q.Attribute("Side") == side
from d in q.Elements("Goal")
select new
{
TeamRef = q.Attribute("TeamRef").Value,
PlayerRef = d.Attribute("PlayerRef").Value,
Time = d.Attribute("Time").Value
};
var count = 0;
foreach (var qq in query)
{
if (side == "Home")
{
if (HomeSlateScorerList[count].PlayerRef != qq.PlayerRef)
{
HomeSlateScorerList.Add(new Scorer() { PlayerRef = qq.PlayerRef, Time = qq.Time, LastName = GetPlayerNameSlate(qq.PlayerRef, OSeason, OCompetition, OGameId) });
}
else
{
HomeSlateScorerList[count].Time = HomeSlateScorerList[count].Time + "' ";
}
}
if (side == "Away")
{
AwaySlateScorerList.Add(new Scorer() { PlayerRef = qq.PlayerRef, Time = qq.Time, LastName = GetPlayerNameSlate(qq.PlayerRef, OCompetition, OSeason, OGameId) });
}
count++;
}
}
catch (Exception)
{
// ignored
}
}
I would like to edit a player in a list of players
HomeSlateScorerList = new List<Scorer>();
AwaySlateScorerList = new List<Scorer>();
what I would like to achieve is for e.g. there are two players with the ref of "p7777" so in the list of object I would like to have one player with the playerref of "p7777" so if the player exist the format will be
playerref = "p7777"
Time = 13' 17'
or if one player its
Time = 13'
or if another goal is added to the xml its
Time = 13' 17' 25'
HomeSlateScorerList = HomeSlateScorerList
.GroupBy(s => s.PlayerRef)
.Select(g => new Scorer { PlayerRef = g.Key, Time = string.Join(", ", g.Select(v => v.Time)) })
.ToList();
Thanks to: #SergeyS SergeyS

Strange issue on reduce function

I always have reduce issue on practicing, like following map and reduce, if I add more document or add more field to emit in the map and reduce like following. it will return values as [], not sure what occur this?
problemNumber : doc.problemNumber,
UserId: idv,
event : doc.event
......
Map
function(doc) {
if(doc.event){
var idv = null;
for (var idu in doc.Data.users){
if (doc.eventData.users[idu].userTypeCode == "M"){
idv = doc.Data.users[idu].UserId;
}
}
var newDoc = {
problemNumber : doc.problemNumber,
UserId: idv,
event : doc.event
};
emit(null, newDoc);
}
}
Reduce
function(keys, values, rereduce) {
var result = [];
var closeMap = {};
for (var i=0; i<values.length; i++){
var doc = values[i];
if (doc.event=='CLOSE'){
closeMap[doc.problemNumber] = 1;
}
}
for (var i=0; i<values.length; i++){
var doc = values[i];
if (doc.event=='OPEN'){
if (closeMap[doc.problemNumber]){
doc.event = 'CLOSE';
}
result.push(doc);
}
}
return result;
}