问:
Regex - Select pattern within string
I'm new to Regex and facing a complicated !

I want to select ONLY the amount + the currency from the following list item.

Exemple: 150,00 Euro - 100,00 Libra ESTERLINA etc.

```<code>Monto: 150,00 EURO
Monto: 7.350,00 PESO URUGUAY | Pesos: 12.495,00 |Sucursal: 36|
Monto: 2.500,00 PESO URUGUAY
Monto: 200,00 U$S EEUU | Pesos: 12.550,00
Monto: 50,00 U$S EEUU
Monto: 700,00 REAL | Pesos: 10.500,00 | Sucursal: 101
Monto: 100,00 LIBRA ESTERLINA | Pesos: 8.500,00 | Sucursal: 12
Monto: 5.000,00 PESO CHILENO | Pesos: 400,00 | Sucursal: 101
</code>```

My regex test: https://regex101.com/r/R5Edrk/2

```<code>[0-9,.].+(Euro|URUGUAY|EEUU|CHILENO|ESTERLINA|REAL)
</code>```

I tried various combinations and formula but dont succeed to isolate amount + currency.
I also tried to select all the string untile the boundary "|" (the first vertical bar) but it didnt work...

Any help and explication is welcomed, thanks community ! :)

答:
Rather new to RegEx but what about something along these lines?

```<code>(?<=Monto:\s).*?(?=\s\||$)
</code>```

(?<=Monto:\s) - Negative LookBehind to set startposition after Monto:

.*? - any character as many times possible but lazy (stop when there is a match)

(?=\s\||$) - Positive LookAhead for any \s (space) followed by either a literal pipe symbol or end string.

Title: Regex - Select pattern within string

Body:
I'm new to Regex and facing a complicated !

I want to select ONLY the amount + the currency from the following list item.

Exemple: 150,00 Euro - 100,00 Libra ESTERLINA etc.

Monto: 150,00 EURO
Monto: 7.350,00 PESO URUGUAY | Pesos: 12.495,00 |Sucursal: 36|
Monto: 2.500,00 PESO URUGUAY
Monto: 200,00 U$S EEUU | Pesos: 12.550,00
Monto: 50,00 U$S EEUU
Monto: 700,00 REAL | Pesos: 10.500,00 | Sucursal: 101
Monto: 100,00 LIBRA ESTERLINA | Pesos: 8.500,00 | Sucursal: 12
Monto: 5.000,00 PESO CHILENO | Pesos: 400,00 | Sucursal: 101

My regex test: https://regex101.com/r/R5Edrk/2

[0-9,.].+(Euro|URUGUAY|EEUU|CHILENO|ESTERLINA|REAL)

I tried various combinations and formula but dont succeed to isolate amount + currency.
I also tried to select all the string untile the boundary "|" (the first vertical bar) but it didnt work...

Any help and explication is welcomed, thanks community ! :)

Body:
Rather new to RegEx but what about something along these lines?

(?<=Monto:\s).*?(?=\s\||$)

(?<=Monto:\s) - Negative LookBehind to set startposition after Monto:

.*? - any character as many times possible but lazy (stop when there is a match)

(?=\s\||$) - Positive LookAhead for any \s (space) followed by either a literal pipe symbol or end string.


来源: stackexchange

问:
Mobx Observer not working on a ObservableList item
I'm trying to check and uncheck the itens in my list, but i can't change the state of the checkbox, it's just change when i add another item in the list. if i add the setState method in CheckBox Onchanged method it works.

i tried some stuff but nothing changed

code to help:

Store:

```<code>import 'package:mobx/mobx.dart';
import 'package:mobxlearn/TodoApp/models/todo.model.dart';
part 'todo.store.g.dart';

class TodoStore = _TodoStoreBase with _$TodoStore;

abstract class _TodoStoreBase with Store {

  @observable
  var todoList = ObservableList<TodoItem>();

   @action
   void addTask(TodoItem task){
     todoList.add(task);
   }

}
</code>```

TodoItem:

```<code>import 'package:mobx/mobx.dart';
part 'todo.model.g.dart';

class TodoItem = _TodoItemBase with _$TodoItem;

abstract class _TodoItemBase with Store {

  @observable
  String title;

  @observable
  bool checked;

  @action
  void check(bool checkValue){
    print("item checkado - $checkValue");
    checked = checkValue;
  }

}
</code>```

View:

```<code>import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:mobxlearn/TodoApp/models/todo.model.dart';
import 'package:mobxlearn/TodoApp/stores/todo.store.dart';

class TodoHome extends StatelessWidget {
  final todo = TodoStore();

  final todoController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Column(
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            children: <Widget>[
              Expanded(
                child: TextField(
                  controller: todoController,
                  decoration: InputDecoration(
                    enabledBorder: OutlineInputBorder(),
                    focusedBorder: OutlineInputBorder(),
                    focusColor: Colors.purple,
                  ),
                  style: TextStyle(fontSize: 18, color: Colors.black),
                ),
              ),
              VerticalDivider(),
              MaterialButton(
                color: Colors.purple,
                child: Text(
                  "Add Task",
                  style: TextStyle(color: Colors.white),
                ),
                onPressed: () {
                  if (todoController.text.isNotEmpty) {
                    final todoItem = TodoItem();
                    todoItem.title = todoController.text;
                    todoItem.checked = true;
                    todo.addTask(todoItem);
                    todoController.text = "";
                    print(todo.todoList.toString());
                  }
                },
              )
            ],
          ),
        ),
        Divider(),
        Expanded(
          child: Observer(
            builder: (_) => ListView.builder(
                itemCount: todo.todoList.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    leading: Checkbox(
                        value: todo.todoList[index].checked,
                        onChanged: (boolean) {
                          print(boolean);
                          todo.todoList[index].check(boolean);
                        }),
                    title: Text(todo.todoList[index].title),
                    onTap: () {},
                  );
                }),
          ),
        )
      ],
    ));
  }
}
</code>```

thanks!!!!

答:
So after watching a video I got the solution when we use an Observablelist and we want to change the items state of this list, we can't just create an observer to the list, we need to create an observer for each Item and for the list too:

I needed to create a custom item and set an observer to this:

```<code>class CustomItem extends StatelessWidget {
  final TodoItem item;
  CustomItem({this.item});

  @override
  Widget build(BuildContext context) {
    return Observer(
      builder: (_) {
        return ListTile(
          leading: Checkbox(value: item.checked, onChanged: item.setCheck),
          title: Text(item.title),
        );
      },
    );
  }
}
</code>```

and in my view, I needed to set an observer to the list too:

```<code>Expanded(
          child: Observer(
          builder: (_) {
            return ListView.builder(
                itemCount: controller.list.length,
                itemBuilder: (context, index) {
                  var item = controller.list[index];
                  return CustomItem(item: item);
                });
          },
        ))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to check and uncheck the itens in my list, but i can't change the state of the checkbox, it's just change when i add another item in the list. if i add the setState method in CheckBox Onchanged method it works.

i tried some stuff but nothing changed

code to help:

Store:

import 'package:mobx/mobx.dart';
import 'package:mobxlearn/TodoApp/models/todo.model.dart';
part 'todo.store.g.dart';

class TodoStore = _TodoStoreBase with _$TodoStore;

abstract class _TodoStoreBase with Store {

  @observable
  var todoList = ObservableList<TodoItem>();

   @action
   void addTask(TodoItem task){
     todoList.add(task);
   }

}

TodoItem:

import 'package:mobx/mobx.dart';
part 'todo.model.g.dart';

class TodoItem = _TodoItemBase with _$TodoItem;

abstract class _TodoItemBase with Store {

  @observable
  String title;

  @observable
  bool checked;

  @action
  void check(bool checkValue){
    print("item checkado - $checkValue");
    checked = checkValue;
  }

}

View:

import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:mobxlearn/TodoApp/models/todo.model.dart';
import 'package:mobxlearn/TodoApp/stores/todo.store.dart';

class TodoHome extends StatelessWidget {
  final todo = TodoStore();

  final todoController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Column(
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            children: <Widget>[
              Expanded(
                child: TextField(
                  controller: todoController,
                  decoration: InputDecoration(
                    enabledBorder: OutlineInputBorder(),
                    focusedBorder: OutlineInputBorder(),
                    focusColor: Colors.purple,
                  ),
                  style: TextStyle(fontSize: 18, color: Colors.black),
                ),
              ),
              VerticalDivider(),
              MaterialButton(
                color: Colors.purple,
                child: Text(
                  "Add Task",
                  style: TextStyle(color: Colors.white),
                ),
                onPressed: () {
                  if (todoController.text.isNotEmpty) {
                    final todoItem = TodoItem();
                    todoItem.title = todoController.text;
                    todoItem.checked = true;
                    todo.addTask(todoItem);
                    todoController.text = "";
                    print(todo.todoList.toString());
                  }
                },
              )
            ],
          ),
        ),
        Divider(),
        Expanded(
          child: Observer(
            builder: (_) => ListView.builder(
                itemCount: todo.todoList.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    leading: Checkbox(
                        value: todo.todoList[index].checked,
                        onChanged: (boolean) {
                          print(boolean);
                          todo.todoList[index].check(boolean);
                        }),
                    title: Text(todo.todoList[index].title),
                    onTap: () {},
                  );
                }),
          ),
        )
      ],
    ));
  }
}

thanks!!!!

Body:
So after watching a video I got the solution when we use an Observablelist and we want to change the items state of this list, we can't just create an observer to the list, we need to create an observer for each Item and for the list too:

I needed to create a custom item and set an observer to this:

class CustomItem extends StatelessWidget {
  final TodoItem item;
  CustomItem({this.item});

  @override
  Widget build(BuildContext context) {
    return Observer(
      builder: (_) {
        return ListTile(
          leading: Checkbox(value: item.checked, onChanged: item.setCheck),
          title: Text(item.title),
        );
      },
    );
  }
}

and in my view, I needed to set an observer to the list too:

Expanded(
          child: Observer(
          builder: (_) {
            return ListView.builder(
                itemCount: controller.list.length,
                itemBuilder: (context, index) {
                  var item = controller.list[index];
                  return CustomItem(item: item);
                });
          },
        ))


问:
Migrate database oracle to postgresql : procedure
we are going to migrate our database from Oracle to PostgreSQL.

I am new in PostgreSQL. We have a procedure like this:

```<code>CREATE OR REPLACE PROCEDURE USPX_TEST (NAME IN VARCHAR2,cb_results_cursor OUT SYS_REFCURSOR) IS
BEGIN
 OPEN cb_results_cursor FOR
          SELECT * FROM EMPLOYEES WHERE EMP_NAME = NAME;
END USPX_TEST;
</code>```

Please provide me how to convert this same procedure in postgreSQL.

NOTE: we need to return the result in a cursor using out parameter

Thanks in advance...

答:
To return a result in Postgres, you use a function, not a procedure:

```<code>CREATE OR REPLACE function USPX_TEST (NAME IN VARCHAR2)
  returns setof employees
as
$$
  SELECT * FROM EMPLOYEES WHERE EMP_NAME = NAME;
$$
language sql;
</code>```

The use it like a table:

```<code>select *
from USPX_TEST('Zaphod');
</code>```

Body:
we are going to migrate our database from Oracle to PostgreSQL.

I am new in PostgreSQL. We have a procedure like this:

CREATE OR REPLACE PROCEDURE USPX_TEST (NAME IN VARCHAR2,cb_results_cursor OUT SYS_REFCURSOR) IS
BEGIN
 OPEN cb_results_cursor FOR
          SELECT * FROM EMPLOYEES WHERE EMP_NAME = NAME;
END USPX_TEST;

Please provide me how to convert this same procedure in postgreSQL.

NOTE: we need to return the result in a cursor using out parameter

Thanks in advance...

Body:
To return a result in Postgres, you use a function, not a procedure:

CREATE OR REPLACE function USPX_TEST (NAME IN VARCHAR2)
  returns setof employees
as
$$
  SELECT * FROM EMPLOYEES WHERE EMP_NAME = NAME;
$$
language sql;

The use it like a table:

select *
from USPX_TEST('Zaphod');


问:
Iterating over a custom collection of objects with yield and foreach without boxing/unboxing
I'm trying to take advantage of iterators in C# to clean up some spatial queries on objects in a game I'm making.

Here's what I'm doing currently:

```<code>    public struct ObjectInfo
    {
        public int x, y;
        public int Type;
        public int hp;
    }

    public static IEnumerable<ObjectInfo> NearbyObjects(int x, int y, int distance)
    {
        // Not actually what I'm doing, but for simplicity...
        for (int i = 0; i < 10; ++ i)
        {
            yield return new ObjectInfo();
        }
    }

    public static void Explode()
    {
        foreach (ObjectInfo o in NearbyObjects(0, 0, 1))
        {
            o.hp = 0;
        }
    }
</code>```

This works great except I think there is some boxing/unboxing going on. The CLRProfiler seems to verify this as I'm seeing allocations happening in my Explode method. I'd very much like to avoid any allocations after startup so I'm not triggering the garbage collector in the middle of a level or something. Is there some way I can keep this syntax while avoiding any allocation? Maybe by implementing my own iterators or something?

答:
The allocations in your Explode method are due to the internal workings of the iterator itself, not due to boxing.

Every iterator block is implemented by the compiler using a reference class to maintain the state which is used in the course of iterating over the IEnumerable, in your case with foreach.  Normally the allocation of this class is not noticed as a problem because the iterator iterates over a large collection or the client who is iterating is doing substantial work of their own or allocation that overwhelm the iterators allocation.

But if your collection is small (as yours is), and the foreach is very fast and has no allocations of its own, all that will be left is the allocation of the iterator state class.

To solve this performance problem you can simply reorganize your code to use for instead of foreach whereever the profiler tells you a lot of memory is being allocated in an iterator block.  It's usually a modest change and the performance boost if measurable is then worth it.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to take advantage of iterators in C# to clean up some spatial queries on objects in a game I'm making.

Here's what I'm doing currently:

    public struct ObjectInfo
    {
        public int x, y;
        public int Type;
        public int hp;
    }

    public static IEnumerable<ObjectInfo> NearbyObjects(int x, int y, int distance)
    {
        // Not actually what I'm doing, but for simplicity...
        for (int i = 0; i < 10; ++ i)
        {
            yield return new ObjectInfo();
        }
    }

    public static void Explode()
    {
        foreach (ObjectInfo o in NearbyObjects(0, 0, 1))
        {
            o.hp = 0;
        }
    }

This works great except I think there is some boxing/unboxing going on. The CLRProfiler seems to verify this as I'm seeing allocations happening in my Explode method. I'd very much like to avoid any allocations after startup so I'm not triggering the garbage collector in the middle of a level or something. Is there some way I can keep this syntax while avoiding any allocation? Maybe by implementing my own iterators or something?


问:
Redis Connection times out when trying to persist a comparatively bigger entity
I use azure redis with Spring-data and normally the entities saved onto it are in the ranges of 200KB- 1MB per request, but now when the entity is ~6MB, I get the exception:

```<code>org.springframework.data.redis.RedisConnectionFailureException: java.net.SocketTimeoutException: Read timed out; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketTimeoutException: Read timed out
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketTimeoutException: Read timed out
Caused by: java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method) ~[na:1.8.0_131]
at java.net.SocketInputStream.socketRead(SocketInputStream.java:116) ~[na:1.8.0_131]
at java.net.SocketInputStream.read(SocketInputStream.java:171) ~[na:1.8.0_131]
at java.net.SocketInputStream.read(SocketInputStream.java:141) ~[na:1.8.0_131]
at java.net.SocketInputStream.read(SocketInputStream.java:127) ~[na:1.8.0_131]
</code>```

Correct me if I'm wrong but 6MB shouldn't be a huge problem. I also tried bumping up the time-out overriding the JedisShardInfo, but the problem still persists. Any thoughts/help on this would be really appreciated, thanks in advance.

答: We applied a limit to the entity being persisted to redis to 4 MB and we haven't seen that issue any more.</p>

Body:
I use azure redis with Spring-data and normally the entities saved onto it are in the ranges of 200KB- 1MB per request, but now when the entity is ~6MB, I get the exception:

org.springframework.data.redis.RedisConnectionFailureException: java.net.SocketTimeoutException: Read timed out; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketTimeoutException: Read timed out
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketTimeoutException: Read timed out
Caused by: java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method) ~[na:1.8.0_131]
at java.net.SocketInputStream.socketRead(SocketInputStream.java:116) ~[na:1.8.0_131]
at java.net.SocketInputStream.read(SocketInputStream.java:171) ~[na:1.8.0_131]
at java.net.SocketInputStream.read(SocketInputStream.java:141) ~[na:1.8.0_131]
at java.net.SocketInputStream.read(SocketInputStream.java:127) ~[na:1.8.0_131]

Correct me if I'm wrong but 6MB shouldn't be a huge problem. I also tried bumping up the time-out overriding the JedisShardInfo, but the problem still persists. Any thoughts/help on this would be really appreciated, thanks in advance.


问:
How to create a Variable with scope global and but should not be a STATIC
Need a variable to hold a value which will be assigned once and will be used by every method of a class

if I specify it as non static variable it is not holding the value

```<code>Class Test{

private String test;

public void method1(){
     test = "String1";
}

public void method2(){
     System.out.println(test.length());
}

}
</code>```

Getting Null Pointer exception. the value of the test will be used in every method.

Could anyone help me, how to fix the issue.

答:
The NullPointerException will be thrown whenever the test variable is null and you try to invoke methods on that variable. In your case, when you invoke method2() before method1(). That has nothing to do with global, local or whatever, as Long Vu already mentioned.

So first you should make sure, you don't access an uninitialized variable. Then, if you need a class with a single instance, which should be accessible application wide, you can implement this using the singleton pattern. For more about it, have a look at this Wikipedia page: https://en.wikipedia.org/wiki/Singleton_pattern

Body:
Need a variable to hold a value which will be assigned once and will be used by every method of a class

if I specify it as non static variable it is not holding the value

Class Test{

private String test;

public void method1(){
     test = "String1";
}

public void method2(){
     System.out.println(test.length());
}

}

Getting Null Pointer exception. the value of the test will be used in every method.

Could anyone help me, how to fix the issue.


问:
Get the current commit id of specified submodule
I want get the current commit id of the specified submodule. I thought when I cd into submodule directory and run git rev-parse HEAD i get this after I noticed this is a superproject current id.
Tried git submodule status | grep <submodule_name> also but its to slow to me. Any idea how to get this information little bit faster?

答:
git submodule status | grep <submodule_name> also but its to slow to me

Starting with Git 2.16 (Q4 2017, two years after the OP's question), this should be faster (even though my previous answer remains a viable alternative).

See commit a9f8a37, commit 9f580a6 (06 Oct 2017), and commit 74a1064 (29 Sep 2017) by Prathamesh Chavan (pratham-pc).

(Merged by Junio C Hamano -- gitster -- in commit a1bf46e, 06 Nov 2017)

submodule: port submodule subcommand 'status' from shell to C

Mentored-by: Christian Couder

Mentored-by: Stefan Beller

Signed-off-by: Prathamesh Chavan

This aims to make git submodule 'status' a built-in. Hence, the function cmd_status() is ported from shell to C. This is done by introducing four functions: module_status(), submodule_status_cb(), submodule_status() and print_status().

The function module_status() acts as the front-end of the subcommand. It parses subcommand's options and then calls the function module_list_compute() for computing the list of submodules. Then this functions calls for_each_listed_submodule() looping through the list obtained.

Then for_each_listed_submodule() calls submodule_status_cb() for each of the submodule in its list. The function submodule_status_cb() calls submodule_status() after passing appropriate arguments to the funciton. Function submodule_status() is responsible for generating the status each submodule it is called for, and then calls print_status().

Finally, the function print_status() handles the printing of submodule's status.

Function set_name_rev() is also ported from git submodule to the submodule--helper builtin function compute_rev_name(), which now generates the value of the revision name as required.

But.. The way "git submodule status" reports an initialized but not yet populated submodule has not been reimplemented correctly when a part of the "git submodule" command was rewritten in C, which has been corrected with Git 2.26 (Q1 2020)

See commit f38c924 (02 Feb 2020), and commit 3b2885e, commit ace912b (24 Jan 2020) by Peter Kaestle (``).

(Merged by Junio C Hamano -- gitster -- in commit f2dcfcc, 14 Feb 2020)

submodule: fix status of initialized but not cloned submodules

Signed-off-by: Peter Kaestle

Original bash helper for "submodule status" was doing a check for initialized but not cloned submodules and prefixed the status with a minus sign in case no .git file or folder was found inside the submodule directory.

This check was missed when the original port of the functionality from bash to C was done.


问:
type 'List<dynamic>' is not a subtype of type 'String'
It contains lots of list and nested objects. I need to display all the DishName from the json file

Json URL adress :  Json address!! Check this out

i wanted to display the DishName in to my app in which there are lots of dishname in the json list.
i parsed the json file using instantly parse json website.
But now i dont know how to implent it on my app

code i wrote :

```<code>body: Container(
     child: Center(
      child: FutureBuilder(
        future:
            DefaultAssetBundle.of(context).loadString('jsons/data.json'),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return CircularProgressIndicator();
          }
          var myData = jsonDecode(snapshot.data);
          final welcome = welcomeFromJson(myData);

          print(myData.length);
          return ListView.builder(
            itemBuilder: (BuildContext context, int index) {
              return Card(
                  child: ListTile(
                title: Text(welcome[index]
                    .tableMenuList[index]
                    .categoryDishes[index]
                    .dishName),
              ));
            },
            itemCount: myData == null ? 0 : myData.length,
          );
        },
      ),
    ),
  ),
</code>```

i am getting error : type 'List' is not a subtype of type 'String'

this is the json class:-

```<code>// To parse this JSON data, do
//
//     final welcome = welcomeFromJson(jsonString);

import 'dart:convert';

List<Welcome> welcomeFromJson(String str) =>
    List<Welcome>.from(json.decode(str).map((x) => Welcome.fromJson(x)));

String welcomeToJson(List<Welcome> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Welcome {
  String restaurantId;
  String restaurantName;
  String restaurantImage;
  String tableId;
  String tableName;
  String branchName;
  String nexturl;
  List<TableMenuList> tableMenuList;

  Welcome({
    this.restaurantId,
    this.restaurantName,
    this.restaurantImage,
    this.tableId,
    this.tableName,
    this.branchName,
    this.nexturl,
    this.tableMenuList,
  });

  factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
        restaurantId: json["restaurant_id"],
        restaurantName: json["restaurant_name"],
        restaurantImage: json["restaurant_image"],
        tableId: json["table_id"],
        tableName: json["table_name"],
        branchName: json["branch_name"],
        nexturl: json["nexturl"],
        tableMenuList: List<TableMenuList>.from(
            json["table_menu_list"].map((x) => TableMenuList.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "restaurant_id": restaurantId,
        "restaurant_name": restaurantName,
        "restaurant_image": restaurantImage,
        "table_id": tableId,
        "table_name": tableName,
        "branch_name": branchName,
        "nexturl": nexturl,
        "table_menu_list":
            List<dynamic>.from(tableMenuList.map((x) => x.toJson())),
      };
}

class TableMenuList {
  String menuCategory;
  String menuCategoryId;
  String menuCategoryImage;
  String nexturl;
  List<CategoryDish> categoryDishes;

  TableMenuList({
    this.menuCategory,
    this.menuCategoryId,
    this.menuCategoryImage,
    this.nexturl,
    this.categoryDishes,
  });

  factory TableMenuList.fromJson(Map<String, dynamic> json) => TableMenuList(
        menuCategory: json["menu_category"],
        menuCategoryId: json["menu_category_id"],
        menuCategoryImage: json["menu_category_image"],
        nexturl: json["nexturl"],
        categoryDishes: List<CategoryDish>.from(
            json["category_dishes"].map((x) => CategoryDish.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "menu_category": menuCategory,
        "menu_category_id": menuCategoryId,
        "menu_category_image": menuCategoryImage,
        "nexturl": nexturl,
        "category_dishes":
            List<dynamic>.from(categoryDishes.map((x) => x.toJson())),
      };
}

class AddonCat {
  String addonCategory;
  String addonCategoryId;
  int addonSelection;
  String nexturl;
  List<CategoryDish> addons;

  AddonCat({
    this.addonCategory,
    this.addonCategoryId,
    this.addonSelection,
    this.nexturl,
    this.addons,
  });

  factory AddonCat.fromJson(Map<String, dynamic> json) => AddonCat(
        addonCategory: json["addon_category"],
        addonCategoryId: json["addon_category_id"],
        addonSelection: json["addon_selection"],
        nexturl: json["nexturl"],
        addons: List<CategoryDish>.from(
            json["addons"].map((x) => CategoryDish.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "addon_category": addonCategory,
        "addon_category_id": addonCategoryId,
        "addon_selection": addonSelection,
        "nexturl": nexturl,
        "addons": List<dynamic>.from(addons.map((x) => x.toJson())),
      };
}

class CategoryDish {
  String dishId;
  String dishName;
  double dishPrice;
  String dishImage;
  DishCurrency dishCurrency;
  int dishCalories;
  String dishDescription;
  bool dishAvailability;
  int dishType;
  String nexturl;
  List<AddonCat> addonCat;

  CategoryDish({
    this.dishId,
    this.dishName,
    this.dishPrice,
    this.dishImage,
    this.dishCurrency,
    this.dishCalories,
    this.dishDescription,
    this.dishAvailability,
    this.dishType,
    this.nexturl,
    this.addonCat,
  });

  factory CategoryDish.fromJson(Map<String, dynamic> json) => CategoryDish(
        dishId: json["dish_id"],
        dishName: json["dish_name"],
        dishPrice: json["dish_price"].toDouble(),
        dishImage: json["dish_image"],
        dishCurrency: dishCurrencyValues.map[json["dish_currency"]],
        dishCalories: json["dish_calories"],
        dishDescription: json["dish_description"],
        dishAvailability: json["dish_Availability"],
        dishType: json["dish_Type"],
        nexturl: json["nexturl"] == null ? null : json["nexturl"],
        addonCat: json["addonCat"] == null
            ? null
            : List<AddonCat>.from(
                json["addonCat"].map((x) => AddonCat.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "dish_id": dishId,
        "dish_name": dishName,
        "dish_price": dishPrice,
        "dish_image": dishImage,
        "dish_currency": dishCurrencyValues.reverse[dishCurrency],
        "dish_calories": dishCalories,
        "dish_description": dishDescription,
        "dish_Availability": dishAvailability,
        "dish_Type": dishType,
        "nexturl": nexturl == null ? null : nexturl,
        "addonCat": addonCat == null
            ? null
            : List<dynamic>.from(addonCat.map((x) => x.toJson())),
      };
}

enum DishCurrency { SAR }

final dishCurrencyValues = EnumValues({"SAR": DishCurrency.SAR});

class EnumValues<T> {
  Map<String, T> map;
  Map<T, String> reverseMap;

  EnumValues(this.map);

  Map<T, String> get reverse {
    if (reverseMap == null) {
      reverseMap = map.map((k, v) => new MapEntry(v, k));
    }
    return reverseMap;
  }
}
</code>```

答:
I personally use this one for generating dart classes from JSON https://javiercbk.github.io/json_to_dart/

From my experience most of these automatic class builders are flawed to some extent and it is good practice to go over the generated dart manually. Or try your luck and walk the stack trace to see where parsing failed (usually when handling int and double from what I've seen).

Anyhow back to your problem, from looking at your code I see you are misusing indexes and generally having problems with json data structure:

```<code>               title: Text(welcome[index]
                .tableMenuList[index]
                .categoryDishes[index]
                .dishName),
</code>```

The code above can easily throw "RangeError (index): Invalid value: Not in range..." (example if welcome[ 2 ] has only 1 tableMenuList). Even if all those arrays above are somehow the same length you would still not get the expected result.. The list would end up showing you 1st meal from the 1st menu list and 1st category dish, then next one would be 2nd meal from the 2nd menu and the 2nd restaurant.

Also because of the same reason as above the following code isn't enough:

```<code>itemCount: myData == null ? 0 : myData.length,
</code>```

You need to have an itemCount for each of those lists you are using.

I've modified your code to work with the given JSON and changed a few things, in the end it looks like this.

I'm posting my source bellow, hopefully it will make things clearer for you:

pubspec.yaml

```<code>dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.2
  http: any
</code>```

welcome_model.dart

```<code>class Welcome {
  String restaurantId;
  String restaurantName;
  String restaurantImage;
  String tableId;
  String tableName;
  String branchName;
  String nexturl;
  List<TableMenuList> tableMenuList;

  Welcome(
      {this.restaurantId,
        this.restaurantName,
        this.restaurantImage,
        this.tableId,
        this.tableName,
        this.branchName,
        this.nexturl,
        this.tableMenuList});

  Welcome.fromJson(Map<String, dynamic> json) {
    restaurantId = json['restaurant_id'];
    restaurantName = json['restaurant_name'];
    restaurantImage = json['restaurant_image'];
    tableId = json['table_id'];
    tableName = json['table_name'];
    branchName = json['branch_name'];
    nexturl = json['nexturl'];
    if (json['table_menu_list'] != null) {
      tableMenuList = new List<TableMenuList>();
      json['table_menu_list'].forEach((v) {
        tableMenuList.add(new TableMenuList.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['restaurant_id'] = this.restaurantId;
    data['restaurant_name'] = this.restaurantName;
    data['restaurant_image'] = this.restaurantImage;
    data['table_id'] = this.tableId;
    data['table_name'] = this.tableName;
    data['branch_name'] = this.branchName;
    data['nexturl'] = this.nexturl;
    if (this.tableMenuList != null) {
      data['table_menu_list'] =
          this.tableMenuList.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class TableMenuList {
  String menuCategory;
  String menuCategoryId;
  String menuCategoryImage;
  String nexturl;
  List<CategoryDishes> categoryDishes;

  TableMenuList(
      {this.menuCategory,
        this.menuCategoryId,
        this.menuCategoryImage,
        this.nexturl,
        this.categoryDishes});

  TableMenuList.fromJson(Map<String, dynamic> json) {
    menuCategory = json['menu_category'];
    menuCategoryId = json['menu_category_id'];
    menuCategoryImage = json['menu_category_image'];
    nexturl = json['nexturl'];
    if (json['category_dishes'] != null) {
      categoryDishes = new List<CategoryDishes>();
      json['category_dishes'].forEach((v) {
        categoryDishes.add(new CategoryDishes.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['menu_category'] = this.menuCategory;
    data['menu_category_id'] = this.menuCategoryId;
    data['menu_category_image'] = this.menuCategoryImage;
    data['nexturl'] = this.nexturl;
    if (this.categoryDishes != null) {
      data['category_dishes'] =
          this.categoryDishes.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class CategoryDishes {
  String dishId;
  String dishName;
  double dishPrice;
  String dishImage;
  String dishCurrency;
  double dishCalories;
  String dishDescription;
  bool dishAvailability;
  int dishType;
  String nexturl;
  List<AddonCat> addonCat;

  CategoryDishes(
      {this.dishId,
        this.dishName,
        this.dishPrice,
        this.dishImage,
        this.dishCurrency,
        this.dishCalories,
        this.dishDescription,
        this.dishAvailability,
        this.dishType,
        this.nexturl,
        this.addonCat});

  CategoryDishes.fromJson(Map<String, dynamic> json) {
    dishId = json['dish_id'];
    dishName = json['dish_name'];
    dishPrice = json['dish_price'];
    dishImage = json['dish_image'];
    dishCurrency = json['dish_currency'];
    dishCalories = json['dish_calories'];
    dishDescription = json['dish_description'];
    dishAvailability = json['dish_Availability'];
    dishType = json['dish_Type'];
    nexturl = json['nexturl'];
    if (json['addonCat'] != null) {
      addonCat = new List<AddonCat>();
      json['addonCat'].forEach((v) {
        addonCat.add(new AddonCat.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['dish_id'] = this.dishId;
    data['dish_name'] = this.dishName;
    data['dish_price'] = this.dishPrice;
    data['dish_image'] = this.dishImage;
    data['dish_currency'] = this.dishCurrency;
    data['dish_calories'] = this.dishCalories;
    data['dish_description'] = this.dishDescription;
    data['dish_Availability'] = this.dishAvailability;
    data['dish_Type'] = this.dishType;
    data['nexturl'] = this.nexturl;
    if (this.addonCat != null) {
      data['addonCat'] = this.addonCat.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class AddonCat {
  String addonCategory;
  String addonCategoryId;
  int addonSelection;
  String nexturl;
  List<Addons> addons;

  AddonCat(
      {this.addonCategory,
        this.addonCategoryId,
        this.addonSelection,
        this.nexturl,
        this.addons});

  AddonCat.fromJson(Map<String, dynamic> json) {
    addonCategory = json['addon_category'];
    addonCategoryId = json['addon_category_id'];
    addonSelection = json['addon_selection'];
    nexturl = json['nexturl'];
    if (json['addons'] != null) {
      addons = new List<Addons>();
      json['addons'].forEach((v) {
        addons.add(new Addons.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['addon_category'] = this.addonCategory;
    data['addon_category_id'] = this.addonCategoryId;
    data['addon_selection'] = this.addonSelection;
    data['nexturl'] = this.nexturl;
    if (this.addons != null) {
      data['addons'] = this.addons.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Addons {
  String dishId;
  String dishName;
  double dishPrice;
  String dishImage;
  String dishCurrency;
  double dishCalories;
  String dishDescription;
  bool dishAvailability;
  int dishType;

  Addons(
      {this.dishId,
        this.dishName,
        this.dishPrice,
        this.dishImage,
        this.dishCurrency,
        this.dishCalories,
        this.dishDescription,
        this.dishAvailability,
        this.dishType});

  Addons.fromJson(Map<String, dynamic> json) {
    dishId = json['dish_id'];
    dishName = json['dish_name'];
    dishPrice = json['dish_price'];
    dishImage = json['dish_image'];
    dishCurrency = json['dish_currency'];
    dishCalories = json['dish_calories'];
    dishDescription = json['dish_description'];
    dishAvailability = json['dish_Availability'];
    dishType = json['dish_Type'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['dish_id'] = this.dishId;
    data['dish_name'] = this.dishName;
    data['dish_price'] = this.dishPrice;
    data['dish_image'] = this.dishImage;
    data['dish_currency'] = this.dishCurrency;
    data['dish_calories'] = this.dishCalories;
    data['dish_description'] = this.dishDescription;
    data['dish_Availability'] = this.dishAvailability;
    data['dish_Type'] = this.dishType;
    return data;
  }
}
</code>```

welcome_page.dart

```<code>import 'package:flutter/material.dart';
import 'welcome_model.dart';
import 'dart:async';
import 'dart:io';
import 'dart:convert';
import 'package:http/http.dart' as http;

class WelcomePage extends StatefulWidget {
  @override
  _WelcomePageState createState() => new _WelcomePageState();

}

class _WelcomePageState extends State<WelcomePage> {
  List<Welcome> welcomeList;
  bool isLoading = true;
  int selectedRestaurantIndex = 0;
  String titleString = "Restaurant";

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  @override
  void setState(fn) {
    if(mounted){
      super.setState(fn);
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  _fetchData() async{
    setState(() {
      isLoading = true;
    });
    // String url = Uri.encodeFull("http://www.mocky.io/v2/5dfccffc310000efc8d2c1ad"); // original json has only one restaurant
    // the one bellow has 3 restaurants,
    // 1st one was left untouched,
    // 2nd one (Steak house) has only "From The Barnyard" and "Fast Food" menu types
    // 3rd one (Bistro cafe) has only "Fresh From The Sea" and "Fast Food" menu types
    String url = Uri.encodeFull("http://www.mocky.io/v2/5e4aa68c2f0000690097d3f6");
    var parsedJson;
    try {
      http.Response response = await http.get(url).
      timeout(Duration(seconds: 10));
      if (response.statusCode == 200) {
        if (response.bodyBytes != null) {
           parsedJson = json.decode(utf8.decode(response.bodyBytes));
        }
      } else {
        print('RESPONSE CODE != 200 !');
      }
    } on TimeoutException catch (e) {
      print('Error: $e');
    } on SocketException catch (e) {
      print('Error: $e');
    } on Error catch (e) {
      print('Error: $e');
    }

    if(parsedJson!=null){
        if(parsedJson.length>0){
          welcomeList = new List<Welcome>();
          for(int i=0; i<parsedJson.length; i++) {
            try {
              welcomeList.add(Welcome.fromJson(parsedJson[i]));
            } catch (e, s){
              print('Eroor parsing from JSON! For # $i');
              print('Error: $e');
              print('Stacktrace: $s');
            }
          }
          if(welcomeList[0]!=null && welcomeList[0].restaurantName!=null) {
             titleString = welcomeList[0].restaurantName;
          }
        }
    }

    setState(() {
      isLoading = false;
    });

  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          iconTheme: IconThemeData(
            color: Colors.white,
          ),
          title: Text(titleString),
          centerTitle: true,
        ),
        drawer: Drawer(
          child: ListView(
                padding: EdgeInsets.zero,
                children: <Widget>[
                  DrawerHeader(
                    child: Text("Select a restaurant", style: TextStyle(color: Colors.white, fontSize: 28),textAlign: TextAlign.center,
                    ),
                    decoration: BoxDecoration(
                      color: Theme.of(context).primaryColor,
                    ),
                  ),
                  (welcomeList!=null && welcomeList.length>0) ?
                  ListView.builder(
                      shrinkWrap: true,
                      physics: ClampingScrollPhysics(),
                      itemCount: welcomeList.length,
                      itemBuilder: (BuildContext context, int index) {
                        return Padding(
                            padding: EdgeInsets.all(8),
                            child: RaisedButton(
                              onPressed: () {
                                setState(() {
                                  selectedRestaurantIndex = index;
                                  titleString = welcomeList[index].restaurantName.toString();
                                });
                                Navigator.pop(context);
                              },
                              padding: EdgeInsets.all(12),
                              child: Text(welcomeList[index].restaurantName.toString()),
                          )
                        );
                        ;}
                  )
                  : Text("No restaurants loaded...")
                ]
            )
        ),
        body: (isLoading)
          ? Center(child: CircularProgressIndicator(),)
          : Container(
              child: Center(
                 child: ListView.builder(
                  itemBuilder: (BuildContext context, int index1) {
                    return Card(
                        child: ListTile(
                          subtitle: Text(welcomeList[selectedRestaurantIndex].tableMenuList[index1].menuCategory.toString()),
                          title: ListView.builder(
                            shrinkWrap: true,
                            physics: ClampingScrollPhysics(),
                            itemBuilder: (BuildContext context, int index2) {
                            return Card(
                                child: ListTile(
                                    title: Text(welcomeList[selectedRestaurantIndex].tableMenuList[index1].categoryDishes[index2].dishName.toString()),
                                ));
                          },
                          itemCount: (welcomeList[selectedRestaurantIndex].tableMenuList[index1] == null || welcomeList[selectedRestaurantIndex].tableMenuList[index1].categoryDishes == null) ? 0 : (welcomeList[selectedRestaurantIndex].tableMenuList[index1].categoryDishes.length) ,)
                        )
                    );
                  },
                  itemCount: (welcomeList == null || welcomeList[selectedRestaurantIndex] == null || welcomeList[selectedRestaurantIndex].tableMenuList == null) ? 0 : (welcomeList[selectedRestaurantIndex].tableMenuList.length) ,
                )
              ),
            ),
    );
  }
}
</code>```

JSON with 3 restaurants here or here.

Body:
It contains lots of list and nested objects. I need to display all the DishName from the json file

Json URL adress :  Json address!! Check this out

i wanted to display the DishName in to my app in which there are lots of dishname in the json list.
i parsed the json file using instantly parse json website.
But now i dont know how to implent it on my app

code i wrote :

body: Container(
     child: Center(
      child: FutureBuilder(
        future:
            DefaultAssetBundle.of(context).loadString('jsons/data.json'),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return CircularProgressIndicator();
          }
          var myData = jsonDecode(snapshot.data);
          final welcome = welcomeFromJson(myData);

          print(myData.length);
          return ListView.builder(
            itemBuilder: (BuildContext context, int index) {
              return Card(
                  child: ListTile(
                title: Text(welcome[index]
                    .tableMenuList[index]
                    .categoryDishes[index]
                    .dishName),
              ));
            },
            itemCount: myData == null ? 0 : myData.length,
          );
        },
      ),
    ),
  ),

i am getting error : type 'List' is not a subtype of type 'String'

this is the json class:-

// To parse this JSON data, do
//
//     final welcome = welcomeFromJson(jsonString);

import 'dart:convert';

List<Welcome> welcomeFromJson(String str) =>
    List<Welcome>.from(json.decode(str).map((x) => Welcome.fromJson(x)));

String welcomeToJson(List<Welcome> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Welcome {
  String restaurantId;
  String restaurantName;
  String restaurantImage;
  String tableId;
  String tableName;
  String branchName;
  String nexturl;
  List<TableMenuList> tableMenuList;

  Welcome({
    this.restaurantId,
    this.restaurantName,
    this.restaurantImage,
    this.tableId,
    this.tableName,
    this.branchName,
    this.nexturl,
    this.tableMenuList,
  });

  factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
        restaurantId: json["restaurant_id"],
        restaurantName: json["restaurant_name"],
        restaurantImage: json["restaurant_image"],
        tableId: json["table_id"],
        tableName: json["table_name"],
        branchName: json["branch_name"],
        nexturl: json["nexturl"],
        tableMenuList: List<TableMenuList>.from(
            json["table_menu_list"].map((x) => TableMenuList.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "restaurant_id": restaurantId,
        "restaurant_name": restaurantName,
        "restaurant_image": restaurantImage,
        "table_id": tableId,
        "table_name": tableName,
        "branch_name": branchName,
        "nexturl": nexturl,
        "table_menu_list":
            List<dynamic>.from(tableMenuList.map((x) => x.toJson())),
      };
}

class TableMenuList {
  String menuCategory;
  String menuCategoryId;
  String menuCategoryImage;
  String nexturl;
  List<CategoryDish> categoryDishes;

  TableMenuList({
    this.menuCategory,
    this.menuCategoryId,
    this.menuCategoryImage,
    this.nexturl,
    this.categoryDishes,
  });

  factory TableMenuList.fromJson(Map<String, dynamic> json) => TableMenuList(
        menuCategory: json["menu_category"],
        menuCategoryId: json["menu_category_id"],
        menuCategoryImage: json["menu_category_image"],
        nexturl: json["nexturl"],
        categoryDishes: List<CategoryDish>.from(
            json["category_dishes"].map((x) => CategoryDish.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "menu_category": menuCategory,
        "menu_category_id": menuCategoryId,
        "menu_category_image": menuCategoryImage,
        "nexturl": nexturl,
        "category_dishes":
            List<dynamic>.from(categoryDishes.map((x) => x.toJson())),
      };
}

class AddonCat {
  String addonCategory;
  String addonCategoryId;
  int addonSelection;
  String nexturl;
  List<CategoryDish> addons;

  AddonCat({
    this.addonCategory,
    this.addonCategoryId,
    this.addonSelection,
    this.nexturl,
    this.addons,
  });

  factory AddonCat.fromJson(Map<String, dynamic> json) => AddonCat(
        addonCategory: json["addon_category"],
        addonCategoryId: json["addon_category_id"],
        addonSelection: json["addon_selection"],
        nexturl: json["nexturl"],
        addons: List<CategoryDish>.from(
            json["addons"].map((x) => CategoryDish.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "addon_category": addonCategory,
        "addon_category_id": addonCategoryId,
        "addon_selection": addonSelection,
        "nexturl": nexturl,
        "addons": List<dynamic>.from(addons.map((x) => x.toJson())),
      };
}

class CategoryDish {
  String dishId;
  String dishName;
  double dishPrice;
  String dishImage;
  DishCurrency dishCurrency;
  int dishCalories;
  String dishDescription;
  bool dishAvailability;
  int dishType;
  String nexturl;
  List<AddonCat> addonCat;

  CategoryDish({
    this.dishId,
    this.dishName,
    this.dishPrice,
    this.dishImage,
    this.dishCurrency,
    this.dishCalories,
    this.dishDescription,
    this.dishAvailability,
    this.dishType,
    this.nexturl,
    this.addonCat,
  });

  factory CategoryDish.fromJson(Map<String, dynamic> json) => CategoryDish(
        dishId: json["dish_id"],
        dishName: json["dish_name"],
        dishPrice: json["dish_price"].toDouble(),
        dishImage: json["dish_image"],
        dishCurrency: dishCurrencyValues.map[json["dish_currency"]],
        dishCalories: json["dish_calories"],
        dishDescription: json["dish_description"],
        dishAvailability: json["dish_Availability"],
        dishType: json["dish_Type"],
        nexturl: json["nexturl"] == null ? null : json["nexturl"],
        addonCat: json["addonCat"] == null
            ? null
            : List<AddonCat>.from(
                json["addonCat"].map((x) => AddonCat.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "dish_id": dishId,
        "dish_name": dishName,
        "dish_price": dishPrice,
        "dish_image": dishImage,
        "dish_currency": dishCurrencyValues.reverse[dishCurrency],
        "dish_calories": dishCalories,
        "dish_description": dishDescription,
        "dish_Availability": dishAvailability,
        "dish_Type": dishType,
        "nexturl": nexturl == null ? null : nexturl,
        "addonCat": addonCat == null
            ? null
            : List<dynamic>.from(addonCat.map((x) => x.toJson())),
      };
}

enum DishCurrency { SAR }

final dishCurrencyValues = EnumValues({"SAR": DishCurrency.SAR});

class EnumValues<T> {
  Map<String, T> map;
  Map<T, String> reverseMap;

  EnumValues(this.map);

  Map<T, String> get reverse {
    if (reverseMap == null) {
      reverseMap = map.map((k, v) => new MapEntry(v, k));
    }
    return reverseMap;
  }
}

Body:
I personally use this one for generating dart classes from JSON https://javiercbk.github.io/json_to_dart/

From my experience most of these automatic class builders are flawed to some extent and it is good practice to go over the generated dart manually. Or try your luck and walk the stack trace to see where parsing failed (usually when handling int and double from what I've seen).

Anyhow back to your problem, from looking at your code I see you are misusing indexes and generally having problems with json data structure:

               title: Text(welcome[index]
                .tableMenuList[index]
                .categoryDishes[index]
                .dishName),

The code above can easily throw "RangeError (index): Invalid value: Not in range..." (example if welcome[ 2 ] has only 1 tableMenuList). Even if all those arrays above are somehow the same length you would still not get the expected result.. The list would end up showing you 1st meal from the 1st menu list and 1st category dish, then next one would be 2nd meal from the 2nd menu and the 2nd restaurant.

Also because of the same reason as above the following code isn't enough:

itemCount: myData == null ? 0 : myData.length,

You need to have an itemCount for each of those lists you are using.

I've modified your code to work with the given JSON and changed a few things, in the end it looks like this.

I'm posting my source bellow, hopefully it will make things clearer for you:

pubspec.yaml

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.2
  http: any

welcome_model.dart

class Welcome {
  String restaurantId;
  String restaurantName;
  String restaurantImage;
  String tableId;
  String tableName;
  String branchName;
  String nexturl;
  List<TableMenuList> tableMenuList;

  Welcome(
      {this.restaurantId,
        this.restaurantName,
        this.restaurantImage,
        this.tableId,
        this.tableName,
        this.branchName,
        this.nexturl,
        this.tableMenuList});

  Welcome.fromJson(Map<String, dynamic> json) {
    restaurantId = json['restaurant_id'];
    restaurantName = json['restaurant_name'];
    restaurantImage = json['restaurant_image'];
    tableId = json['table_id'];
    tableName = json['table_name'];
    branchName = json['branch_name'];
    nexturl = json['nexturl'];
    if (json['table_menu_list'] != null) {
      tableMenuList = new List<TableMenuList>();
      json['table_menu_list'].forEach((v) {
        tableMenuList.add(new TableMenuList.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['restaurant_id'] = this.restaurantId;
    data['restaurant_name'] = this.restaurantName;
    data['restaurant_image'] = this.restaurantImage;
    data['table_id'] = this.tableId;
    data['table_name'] = this.tableName;
    data['branch_name'] = this.branchName;
    data['nexturl'] = this.nexturl;
    if (this.tableMenuList != null) {
      data['table_menu_list'] =
          this.tableMenuList.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class TableMenuList {
  String menuCategory;
  String menuCategoryId;
  String menuCategoryImage;
  String nexturl;
  List<CategoryDishes> categoryDishes;

  TableMenuList(
      {this.menuCategory,
        this.menuCategoryId,
        this.menuCategoryImage,
        this.nexturl,
        this.categoryDishes});

  TableMenuList.fromJson(Map<String, dynamic> json) {
    menuCategory = json['menu_category'];
    menuCategoryId = json['menu_category_id'];
    menuCategoryImage = json['menu_category_image'];
    nexturl = json['nexturl'];
    if (json['category_dishes'] != null) {
      categoryDishes = new List<CategoryDishes>();
      json['category_dishes'].forEach((v) {
        categoryDishes.add(new CategoryDishes.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['menu_category'] = this.menuCategory;
    data['menu_category_id'] = this.menuCategoryId;
    data['menu_category_image'] = this.menuCategoryImage;
    data['nexturl'] = this.nexturl;
    if (this.categoryDishes != null) {
      data['category_dishes'] =
          this.categoryDishes.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class CategoryDishes {
  String dishId;
  String dishName;
  double dishPrice;
  String dishImage;
  String dishCurrency;
  double dishCalories;
  String dishDescription;
  bool dishAvailability;
  int dishType;
  String nexturl;
  List<AddonCat> addonCat;

  CategoryDishes(
      {this.dishId,
        this.dishName,
        this.dishPrice,
        this.dishImage,
        this.dishCurrency,
        this.dishCalories,
        this.dishDescription,
        this.dishAvailability,
        this.dishType,
        this.nexturl,
        this.addonCat});

  CategoryDishes.fromJson(Map<String, dynamic> json) {
    dishId = json['dish_id'];
    dishName = json['dish_name'];
    dishPrice = json['dish_price'];
    dishImage = json['dish_image'];
    dishCurrency = json['dish_currency'];
    dishCalories = json['dish_calories'];
    dishDescription = json['dish_description'];
    dishAvailability = json['dish_Availability'];
    dishType = json['dish_Type'];
    nexturl = json['nexturl'];
    if (json['addonCat'] != null) {
      addonCat = new List<AddonCat>();
      json['addonCat'].forEach((v) {
        addonCat.add(new AddonCat.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['dish_id'] = this.dishId;
    data['dish_name'] = this.dishName;
    data['dish_price'] = this.dishPrice;
    data['dish_image'] = this.dishImage;
    data['dish_currency'] = this.dishCurrency;
    data['dish_calories'] = this.dishCalories;
    data['dish_description'] = this.dishDescription;
    data['dish_Availability'] = this.dishAvailability;
    data['dish_Type'] = this.dishType;
    data['nexturl'] = this.nexturl;
    if (this.addonCat != null) {
      data['addonCat'] = this.addonCat.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class AddonCat {
  String addonCategory;
  String addonCategoryId;
  int addonSelection;
  String nexturl;
  List<Addons> addons;

  AddonCat(
      {this.addonCategory,
        this.addonCategoryId,
        this.addonSelection,
        this.nexturl,
        this.addons});

  AddonCat.fromJson(Map<String, dynamic> json) {
    addonCategory = json['addon_category'];
    addonCategoryId = json['addon_category_id'];
    addonSelection = json['addon_selection'];
    nexturl = json['nexturl'];
    if (json['addons'] != null) {
      addons = new List<Addons>();
      json['addons'].forEach((v) {
        addons.add(new Addons.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['addon_category'] = this.addonCategory;
    data['addon_category_id'] = this.addonCategoryId;
    data['addon_selection'] = this.addonSelection;
    data['nexturl'] = this.nexturl;
    if (this.addons != null) {
      data['addons'] = this.addons.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Addons {
  String dishId;
  String dishName;
  double dishPrice;
  String dishImage;
  String dishCurrency;
  double dishCalories;
  String dishDescription;
  bool dishAvailability;
  int dishType;

  Addons(
      {this.dishId,
        this.dishName,
        this.dishPrice,
        this.dishImage,
        this.dishCurrency,
        this.dishCalories,
        this.dishDescription,
        this.dishAvailability,
        this.dishType});

  Addons.fromJson(Map<String, dynamic> json) {
    dishId = json['dish_id'];
    dishName = json['dish_name'];
    dishPrice = json['dish_price'];
    dishImage = json['dish_image'];
    dishCurrency = json['dish_currency'];
    dishCalories = json['dish_calories'];
    dishDescription = json['dish_description'];
    dishAvailability = json['dish_Availability'];
    dishType = json['dish_Type'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['dish_id'] = this.dishId;
    data['dish_name'] = this.dishName;
    data['dish_price'] = this.dishPrice;
    data['dish_image'] = this.dishImage;
    data['dish_currency'] = this.dishCurrency;
    data['dish_calories'] = this.dishCalories;
    data['dish_description'] = this.dishDescription;
    data['dish_Availability'] = this.dishAvailability;
    data['dish_Type'] = this.dishType;
    return data;
  }
}

welcome_page.dart

import 'package:flutter/material.dart';
import 'welcome_model.dart';
import 'dart:async';
import 'dart:io';
import 'dart:convert';
import 'package:http/http.dart' as http;

class WelcomePage extends StatefulWidget {
  @override
  _WelcomePageState createState() => new _WelcomePageState();

}

class _WelcomePageState extends State<WelcomePage> {
  List<Welcome> welcomeList;
  bool isLoading = true;
  int selectedRestaurantIndex = 0;
  String titleString = "Restaurant";

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  @override
  void setState(fn) {
    if(mounted){
      super.setState(fn);
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  _fetchData() async{
    setState(() {
      isLoading = true;
    });
    // String url = Uri.encodeFull("http://www.mocky.io/v2/5dfccffc310000efc8d2c1ad"); // original json has only one restaurant
    // the one bellow has 3 restaurants,
    // 1st one was left untouched,
    // 2nd one (Steak house) has only "From The Barnyard" and "Fast Food" menu types
    // 3rd one (Bistro cafe) has only "Fresh From The Sea" and "Fast Food" menu types
    String url = Uri.encodeFull("http://www.mocky.io/v2/5e4aa68c2f0000690097d3f6");
    var parsedJson;
    try {
      http.Response response = await http.get(url).
      timeout(Duration(seconds: 10));
      if (response.statusCode == 200) {
        if (response.bodyBytes != null) {
           parsedJson = json.decode(utf8.decode(response.bodyBytes));
        }
      } else {
        print('RESPONSE CODE != 200 !');
      }
    } on TimeoutException catch (e) {
      print('Error: $e');
    } on SocketException catch (e) {
      print('Error: $e');
    } on Error catch (e) {
      print('Error: $e');
    }

    if(parsedJson!=null){
        if(parsedJson.length>0){
          welcomeList = new List<Welcome>();
          for(int i=0; i<parsedJson.length; i++) {
            try {
              welcomeList.add(Welcome.fromJson(parsedJson[i]));
            } catch (e, s){
              print('Eroor parsing from JSON! For # $i');
              print('Error: $e');
              print('Stacktrace: $s');
            }
          }
          if(welcomeList[0]!=null && welcomeList[0].restaurantName!=null) {
             titleString = welcomeList[0].restaurantName;
          }
        }
    }

    setState(() {
      isLoading = false;
    });

  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          iconTheme: IconThemeData(
            color: Colors.white,
          ),
          title: Text(titleString),
          centerTitle: true,
        ),
        drawer: Drawer(
          child: ListView(
                padding: EdgeInsets.zero,
                children: <Widget>[
                  DrawerHeader(
                    child: Text("Select a restaurant", style: TextStyle(color: Colors.white, fontSize: 28),textAlign: TextAlign.center,
                    ),
                    decoration: BoxDecoration(
                      color: Theme.of(context).primaryColor,
                    ),
                  ),
                  (welcomeList!=null && welcomeList.length>0) ?
                  ListView.builder(
                      shrinkWrap: true,
                      physics: ClampingScrollPhysics(),
                      itemCount: welcomeList.length,
                      itemBuilder: (BuildContext context, int index) {
                        return Padding(
                            padding: EdgeInsets.all(8),
                            child: RaisedButton(
                              onPressed: () {
                                setState(() {
                                  selectedRestaurantIndex = index;
                                  titleString = welcomeList[index].restaurantName.toString();
                                });
                                Navigator.pop(context);
                              },
                              padding: EdgeInsets.all(12),
                              child: Text(welcomeList[index].restaurantName.toString()),
                          )
                        );
                        ;}
                  )
                  : Text("No restaurants loaded...")
                ]
            )
        ),
        body: (isLoading)
          ? Center(child: CircularProgressIndicator(),)
          : Container(
              child: Center(
                 child: ListView.builder(
                  itemBuilder: (BuildContext context, int index1) {
                    return Card(
                        child: ListTile(
                          subtitle: Text(welcomeList[selectedRestaurantIndex].tableMenuList[index1].menuCategory.toString()),
                          title: ListView.builder(
                            shrinkWrap: true,
                            physics: ClampingScrollPhysics(),
                            itemBuilder: (BuildContext context, int index2) {
                            return Card(
                                child: ListTile(
                                    title: Text(welcomeList[selectedRestaurantIndex].tableMenuList[index1].categoryDishes[index2].dishName.toString()),
                                ));
                          },
                          itemCount: (welcomeList[selectedRestaurantIndex].tableMenuList[index1] == null || welcomeList[selectedRestaurantIndex].tableMenuList[index1].categoryDishes == null) ? 0 : (welcomeList[selectedRestaurantIndex].tableMenuList[index1].categoryDishes.length) ,)
                        )
                    );
                  },
                  itemCount: (welcomeList == null || welcomeList[selectedRestaurantIndex] == null || welcomeList[selectedRestaurantIndex].tableMenuList == null) ? 0 : (welcomeList[selectedRestaurantIndex].tableMenuList.length) ,
                )
              ),
            ),
    );
  }
}

JSON with 3 restaurants here or here.


问:
What is the differencce between MongoDB Atlas and MongoDB Atlas for AWS
During my investigation on compatible DBs for IoT data storing I looked into MongoDB and pricing is a little bit confusing.

Just wondering what is the difference between MongoDB Atlas and MongoDB Atlas for AWS as they both work on AWS?

And what is the right way to run MongoDB Atlas on AWS?

答:
As far as I can see, they both should mostly be similar :

MongoDB Atlas :

You can directly go to MongoDB-Atlas portal & create a MongoDB cluster(a cluster will usually be 3-shard/node replica set on which a DB is hosted) on either of the cloud providers (AWS/Google/Azure). This way all database updates/maintenance will usually be done by vendor. Quiet easy & simple - Which most people are opting for these days (SAAS/ db hosted on cloud). You can also opt for a free cluster which should be suitable for basic needs kind of learning MongoDB. While creating cluster you can check for pricing which is based on cluster level (M0 to M700), You can upgrade your cluster when ever you wish to, but when I was creating one I've noted that you would pay upfront for a certain amount of years likely 3 & whether you use the money or not you would not get anything back but it you've paid less then you might be charged over the time of usage. You'll pay bills thru MongoDB Atlas.

MongoDB Atlas for AWS :

From here aws-marketplace when you see the text marketplace (where multiple companies/people collaborate to sell products) it's basically these two companies have collaborated to provide MongoDB as SAAS. With this you can actually come from AWS rather than than Atlas from itself. When it comes to pricing AWS seems to provide some credits, It would be better if you can consult AWS & Atlas to check on their pricing & other terms if you really wanted to use it for enterprise purpose. You might end-up owing an AWS account to pay bills for this usage (Which hectic if you don't use AWS for other use-cases). Additionally if you check below on MongoDB Atlas for AWS page it seems like just a starting point is given at AWS side but entire setup would be done at Atlas.

You're charged for your purchase on your AWS bill. After you purchase
  a contract, you're directed to the vendor's site to complete setup and
  begin using this software.


问:
Using rdmsr/rdpmc for branch prediction accuracy
I am trying to understand how does a branch prediction unit work in a CPU.

I have used papi and also linux's perf-events but both of them do not give accurate results (for my case).

This is my code:

```<code>void func(int* arr, int sequence_len){
  for(int i = 0; i < sequence_len; i++){
      // region starts
      if(arr[i]){
          do_sth();
      }
      // region ends
  }
}
</code>```

My array consists of 0's and 1's. It has a pattern with a size of sequence_len. For example, if my size is 8, then it has a pattern of 0 1 0 1 0 0 1 1 or something like that.

Trial 1:

I am trying to understand how CPU predicts those branches. So, I have used papi and set up performance counter for branch predictions mispredicted (I know that it also counts indirect branches).

```<code>int func(){
  papi_read(r1);
  for(){
    //... same as above
  }
  papi_read(r2);
  return r2-r1;
}

int main(){
   init_papi();
   for(int i = 0; i < 10; i++)
     res[i] = func();

   print(res[i]);
}

</code>```

What I see as an output is that (for sequence length of 200)

100 #iter1
40  #iter2
10  #iter3
3
0
0
#...
```

<p>So, at first, the CPU blindly predicts the sequence, only success half of the time. In the next iterations, the CPU can predict better and better. After some amount of iterations, the CPU can guess that perfectly.</p>

<p><strong>Trial 2</strong></p>

<p>I would like to see, at which array index does the CPU misprediction.</p>

```int* func(){
  int* results;
  for(){
    papi_read(r1);
    if(arr[i])
        do_sth();
    papi_read(r2);
    res[i] = r2-r1;
  }
  return res;
}

int main(){
   init_papi();
   for(int i = 0; i < 10; i++)
     res[i] = func();

   print(res[i]);
}
```

<p>Expected result:</p>

<pre class="lang-sh prettyprint-override"><code>#1st iteration, 0 means no mispred, 1 means mispred
1 0 0 1 1 0 0 0 1 1 0... # total of 200 results
Mispred: 100/200
#2nd iteration
0 0 0 0 1 0 0 0 1 0 0... # total of 200 results
Mispred: 40/200 # it learned from previous iteration
#3rd iteration
0 0 0 0 0 0 0 0 1 0 0... # total of 200 results
Mispred: 10/200 # continues to learn
#...
</code>```

Received result:

#1st iteration
1 0 0 1 1 0 0 0 1 1 0... # total of 200 results
Mispred: 100/200
#2nd iteration
1 0 0 0 1 1 0 1 0 0 0... # total of 200 results
Mispred: 100/200 # it DID NOT learn from previous iteration
#3rd iteration
0 1 0 1 0 1 0 1 1 0 0... # total of 200 results
Mispred: 100/200 # NO LEARNING
#...
```

My observation

When I measure the misprediction outside of the for loop, I can see that CPU learns from its mispredictions. However, when I try to measure single branch instructions misprediction, then the CPU either cannot learn, or I am measuring it wrongly.

My explanation

I am giving 200 as a sequence length. The CPU has one small branch predictor, like 2-3 bit saturated counter in Intels, and one big global branch predictor. When I measure outside of the loop, I introduce less noise to the measurement. By less noise, I mean the papi calls.

Think about this: outside of the loop measurement

global history is: papi_start, branch_outcome1, branch_outcome2, branch_outcome3, ..., papi_end, papi_start (2nd loop of main iteration), branch_outcome1, ...

So, the branch predictor somehow finds the pattern in the same branch.

However, if I try to measure single branch instruction then the global history is:
papi_start, branchoutcome1, papiend, papistart, branchoutcome2, papiend...

So, I am introducing more and more branches to global history. I assume the global history cannot hold many branch entries and therefore, it cannot find any correlation/pattern in the desired if statement(branch).

As a result

I need to measure a single branch prediction outcome. I know that the CPU can learn the 200 pattern if I don't introduce papi too much. I have looked at the papi calls and I have seen lots of for loops, if conditions.

That is why I need better measurement. I have tried linux perf-event but it makes ioctl calls, which is a system call and I pollute the global history with system calls, and therefore, not a good measurement.

I have read that rdpmc and rdmsr instructions and I assume that since they are only instructions, I will not pollute the global history, and I can measure single branch instruction at a time.

However, I have no clue about how I can do that. I have AMD 3600 CPU. These are the links that I found online but I couldn't figure out how to do that. In addition to that, am I missing something?

Intel rdpmc

AMD Performance manual

答:
The perf_event_open() documentation describes how to correctly use rdpmc with events created via that interface. The approach described in @JohnDMcCalpin's answer also works, but it's based on programming the event control registers directly. Given a set of hardware events, figuring out how to schedule these events on the available hardware performance counters can be difficult. The perf_event subsystem handles this problem for you, which is a major advantage.

The perf_event subsystem supports rdpmc since Linux 3.4.

Starting with <linux/perf_event.h>, the following works:

do perf_event_open() to prepare to read counter of type = PERF_TYPE_HARDWARE config = PERF_COUNT_HW_BRANCH_MISSES

```<code>struct perf_event_attr attr ;
int fd ;

memset(&attr, 0, sizeof(attr)) ;

attr.type   = PERF_TYPE_HARDWARE ;
attr.config = PERF_COUNT_HW_BRANCH_MISSES;
attr.size = sizeof(attr) ;        // for completeness
attr.exclude_kernel = 1 ;         // count user-land events

perf_fd = (int)sys_perf_event_open(&attr, 0, -1, -1, PERF_FLAG_FD_CLOEXEC) ;
                                  // this pid, any cpu, no group_fd
</code>```

where:

```<code>static long
sys_perf_event_open(struct perf_event_attr* attr,
                              pid_t pid, int cpu, int group_fd, ulong flags)
{
  return syscall(__NR_perf_event_open, attr, pid, cpu, group_fd, flags) ;
}
</code>```

associate the perf_fd with a mmap page:

```<code>struct perf_event_mmap_page* perf_mm ;

perf_mm = mmap(NULL, page_size, PROT_READ, MAP_SHARED, perf_fd, 0) ;
</code>```

page_size can be 4096 for example. This buffer is used for storing samples. See the "Overflow handling" section of the documentation.

to read the counter need to combine some information in the perf_mm with what you read using RDPMC instruction, thus:

```<code>uint64_t  offset, count ;
uint32_t  lock, check, a, d, idx ;

lock = perf_mm->lock ;
do
  {
    check = lock ;
    __asm__ volatile("":::"memory") ;
    idx = perf_mm->index - 1 ;
    // Check that you're allowed to execute rdpmc. You can do this check once.
    // Check also that the event is currently active.
    // Starting with Linux 3.12, use cap_user_rdpmc.
    if (perf_mm->cap_user_rdpmc && idx) {
       // cap_user_rdpmc cannot change at this point because no code
       // that executes here that changes it. So it's safe.
       __asm__ volatile("\t rdpmc\n" : "=a" (a), "=d" (d) : "c" (idx)) ;
    }
    // In case of signed event counts, you have to use also pmc_width.
    // See the docs.
     offset = perf_mm->offset ;
    __asm__ volatile("":::"memory") ;
    lock = perf_mm->lock ;
  }
while (lock != check) ;

count = ((uint64_t)d << 32) + a ;
if (perf_mm->pmc_width != 64)
  {
    // need to sign extend the perf_mm->pmc_width bits of count.
  } ;
count += offset ;
</code>```

If the thread is not interrupted between the "start" and "end" reads, then I think we can assume that the perf_mm stuff will not change.  But if it is interrupted, then the kernel can update perf_mm stuff to account for any changes that affect this timing.

Note: The overhead around the RDPMC instructions is not huge, but I am experimenting with stripping all this back and seeing whether I can use the RDPMC results directly, provided that perf_mm->lock does not change.

Body:
I am trying to understand how does a branch prediction unit work in a CPU.

I have used papi and also linux's perf-events but both of them do not give accurate results (for my case).

This is my code:

void func(int* arr, int sequence_len){
  for(int i = 0; i < sequence_len; i++){
      // region starts
      if(arr[i]){
          do_sth();
      }
      // region ends
  }
}

My array consists of 0's and 1's. It has a pattern with a size of sequence_len. For example, if my size is 8, then it has a pattern of 0 1 0 1 0 0 1 1 or something like that.

Trial 1:

I am trying to understand how CPU predicts those branches. So, I have used papi and set up performance counter for branch predictions mispredicted (I know that it also counts indirect branches).

int func(){
  papi_read(r1);
  for(){
    //... same as above
  }
  papi_read(r2);
  return r2-r1;
}

int main(){
   init_papi();
   for(int i = 0; i < 10; i++)
     res[i] = func();

   print(res[i]);
}

What I see as an output is that (for sequence length of 200)

100 #iter1
40  #iter2
10  #iter3
3
0
0
#...

So, at first, the CPU blindly predicts the sequence, only success half of the time. In the next iterations, the CPU can predict better and better. After some amount of iterations, the CPU can guess that perfectly.

Trial 2

I would like to see, at which array index does the CPU misprediction.

int* func(){
  int* results;
  for(){
    papi_read(r1);
    if(arr[i])
        do_sth();
    papi_read(r2);
    res[i] = r2-r1;
  }
  return res;
}

int main(){
   init_papi();
   for(int i = 0; i < 10; i++)
     res[i] = func();

   print(res[i]);
}

Expected result:

#1st iteration, 0 means no mispred, 1 means mispred
1 0 0 1 1 0 0 0 1 1 0... # total of 200 results
Mispred: 100/200
#2nd iteration
0 0 0 0 1 0 0 0 1 0 0... # total of 200 results
Mispred: 40/200 # it learned from previous iteration
#3rd iteration
0 0 0 0 0 0 0 0 1 0 0... # total of 200 results
Mispred: 10/200 # continues to learn
#...

Received result:

#1st iteration
1 0 0 1 1 0 0 0 1 1 0... # total of 200 results
Mispred: 100/200
#2nd iteration
1 0 0 0 1 1 0 1 0 0 0... # total of 200 results
Mispred: 100/200 # it DID NOT learn from previous iteration
#3rd iteration
0 1 0 1 0 1 0 1 1 0 0... # total of 200 results
Mispred: 100/200 # NO LEARNING
#...

My observation

When I measure the misprediction outside of the for loop, I can see that CPU learns from its mispredictions. However, when I try to measure single branch instructions misprediction, then the CPU either cannot learn, or I am measuring it wrongly.

My explanation

I am giving 200 as a sequence length. The CPU has one small branch predictor, like 2-3 bit saturated counter in Intels, and one big global branch predictor. When I measure outside of the loop, I introduce less noise to the measurement. By less noise, I mean the papi calls.

Think about this: outside of the loop measurement

global history is: papi_start, branch_outcome1, branch_outcome2, branch_outcome3, ..., papi_end, papi_start (2nd loop of main iteration), branch_outcome1, ...

So, the branch predictor somehow finds the pattern in the same branch.

However, if I try to measure single branch instruction then the global history is:
papi_start, branchoutcome1, papiend, papistart, branchoutcome2, papiend...

So, I am introducing more and more branches to global history. I assume the global history cannot hold many branch entries and therefore, it cannot find any correlation/pattern in the desired if statement(branch).

As a result

I need to measure a single branch prediction outcome. I know that the CPU can learn the 200 pattern if I don't introduce papi too much. I have looked at the papi calls and I have seen lots of for loops, if conditions.

That is why I need better measurement. I have tried linux perf-event but it makes ioctl calls, which is a system call and I pollute the global history with system calls, and therefore, not a good measurement.

I have read that rdpmc and rdmsr instructions and I assume that since they are only instructions, I will not pollute the global history, and I can measure single branch instruction at a time.

However, I have no clue about how I can do that. I have AMD 3600 CPU. These are the links that I found online but I couldn't figure out how to do that. In addition to that, am I missing something?

Intel rdpmc

AMD Performance manual

Body:
The perf_event_open() documentation describes how to correctly use rdpmc with events created via that interface. The approach described in @JohnDMcCalpin's answer also works, but it's based on programming the event control registers directly. Given a set of hardware events, figuring out how to schedule these events on the available hardware performance counters can be difficult. The perf_event subsystem handles this problem for you, which is a major advantage.

The perf_event subsystem supports rdpmc since Linux 3.4.

Starting with <linux/perf_event.h>, the following works:

do perf_event_open() to prepare to read counter of type = PERF_TYPE_HARDWARE config = PERF_COUNT_HW_BRANCH_MISSES

struct perf_event_attr attr ;
int fd ;

memset(&attr, 0, sizeof(attr)) ;

attr.type   = PERF_TYPE_HARDWARE ;
attr.config = PERF_COUNT_HW_BRANCH_MISSES;
attr.size = sizeof(attr) ;        // for completeness
attr.exclude_kernel = 1 ;         // count user-land events

perf_fd = (int)sys_perf_event_open(&attr, 0, -1, -1, PERF_FLAG_FD_CLOEXEC) ;
                                  // this pid, any cpu, no group_fd

where:

static long
sys_perf_event_open(struct perf_event_attr* attr,
                              pid_t pid, int cpu, int group_fd, ulong flags)
{
  return syscall(__NR_perf_event_open, attr, pid, cpu, group_fd, flags) ;
}

associate the perf_fd with a mmap page:

struct perf_event_mmap_page* perf_mm ;

perf_mm = mmap(NULL, page_size, PROT_READ, MAP_SHARED, perf_fd, 0) ;

page_size can be 4096 for example. This buffer is used for storing samples. See the "Overflow handling" section of the documentation.

to read the counter need to combine some information in the perf_mm with what you read using RDPMC instruction, thus:

uint64_t  offset, count ;
uint32_t  lock, check, a, d, idx ;

lock = perf_mm->lock ;
do
  {
    check = lock ;
    __asm__ volatile("":::"memory") ;
    idx = perf_mm->index - 1 ;
    // Check that you're allowed to execute rdpmc. You can do this check once.
    // Check also that the event is currently active.
    // Starting with Linux 3.12, use cap_user_rdpmc.
    if (perf_mm->cap_user_rdpmc && idx) {
       // cap_user_rdpmc cannot change at this point because no code
       // that executes here that changes it. So it's safe.
       __asm__ volatile("\t rdpmc\n" : "=a" (a), "=d" (d) : "c" (idx)) ;
    }
    // In case of signed event counts, you have to use also pmc_width.
    // See the docs.
     offset = perf_mm->offset ;
    __asm__ volatile("":::"memory") ;
    lock = perf_mm->lock ;
  }
while (lock != check) ;

count = ((uint64_t)d << 32) + a ;
if (perf_mm->pmc_width != 64)
  {
    // need to sign extend the perf_mm->pmc_width bits of count.
  } ;
count += offset ;

If the thread is not interrupted between the "start" and "end" reads, then I think we can assume that the perf_mm stuff will not change.  But if it is interrupted, then the kernel can update perf_mm stuff to account for any changes that affect this timing.

Note: The overhead around the RDPMC instructions is not huge, but I am experimenting with stripping all this back and seeing whether I can use the RDPMC results directly, provided that perf_mm->lock does not change.


问:
Deserialize JSON to List in C# in a console application
Error

Cannot deserialize the current JSON object (e.g. {"name":"value"})
  into type 'System.Collections.Generic.List`1[ConsoleApp1.Menu]'
  because the type requires a JSON array (e.g. [1,2,3]) to deserialize
  correctly. To fix this error either change the JSON to a JSON array
  (e.g. [1,2,3]) or change the deserialized type so that it is a normal
  .NET type (e.g. not a primitive type like integer, not a collection
  type like an array or List) that can be deserialized from a JSON
  object. JsonObjectAttribute can also be added to the type to force it
  to deserialize from a JSON object. Path 'Test', line 3, position 9.

Question

Why do I get this error?

At the end I want to achieve to write every menu item in the console. For now I am stuck with this error. How do I achieve a result (Output) like this:

```<code>ID: 1 Name: Frosted Pumpkin Bread
ID: 2 Name: Ground to Go
...
</code>```

The Console application

```<code>using System;
using System.Collections.Generic;
using System.Net;
using Newtonsoft.Json;

namespace ConsoleApp1
{
    public class MenuItem
    {
        public string ID { get; set; }
        public string Description { get; set; }
        public string Summary { get; set; }
        public string Name { get; set; }
        public string ImageFile { get; set; }
    }

    public class Menu
    {
        public List<MenuItem> Test { get; set; }
    }

    class Program
    {

        static void Main(string[] args)
        {
          var webclient = new WebClient();
          var json = webclient.DownloadString(@"C:\Users\devuser\source\repos\ConsoleApp1\ConsoleApp1\data.json");
          var model = JsonConvert.DeserializeObject<List<Menu>>(json);

            foreach (var item in model)
            {
                Console.WriteLine();
            }
        }
    }
}
</code>```

My JSON-File looks like this

```<code>
{

  "Test": [

    {
      "ID": "1",
      "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.",
      "Summary": "A seasonal delight we offer every autumn.  Pumpking bread with just a bit of spice, cream cheese frosting with just a hint of home.",
      "Name": "Frosted Pumpkin Bread",
      "ImageFile": "pumpkinbread.png"
    },
    {
      "ID": "2",
      "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.",
      "Summary": "Love our coffee? Take it with you so you never have to be without!",
      "Name": "Ground to Go",
      "ImageFile": "granola.png"
    },
    {
      "ID": "3",
      "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.",
      "Summary": "Do you prefer to grind your own coffee? No problem, we'll give you the beans.",
      "Name": "Bean there, done that!",
      "ImageFile": "beans.jpg"
    },
    {
      "ID": "4",
      "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.",
      "Summary": "They're just as round as donuts, but far more healthy! Freshly made every morning before sunrise.",
      "Name": "Fresh Bagels",
      "ImageFile": "bagel.png"
    },
    {
      "ID": "5",
      "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.",
      "Summary": "We've got strawberries, blueberries, apples, bananas - we could list them all, but we'd prefer you come take a look!",
      "Name": "Fresh Fruit",
      "ImageFile": "strawberries.png"
    }
  ]
}
</code>```

答:
You're trying to deserialize the json as List<Menu>

```<code>JsonConvert.DeserializeObject<List<Menu>>(json);
</code>```

But the json does not contain a List of Menu, it only contains a single Menu object. You can see that the json starts with { }

```<code>{
    "Test": [...]
}
</code>```

{ } is a object, [ ] is an Array. So to be able to deserialize into a List of Menu your json should look like this:

```<code>[
    {
        "Test": [...]
    }
]
</code>```

so that you can have multiple Menu, like this:

```<code>[
    {
        "Test": [...]
    },
    {
        "Test": [...]
    },
    {
        "Test": [...]
    },
]
</code>```

I hope I was helpful

Body:
Error

Cannot deserialize the current JSON object (e.g. {"name":"value"})
  into type 'System.Collections.Generic.List`1[ConsoleApp1.Menu]'
  because the type requires a JSON array (e.g. [1,2,3]) to deserialize
  correctly. To fix this error either change the JSON to a JSON array
  (e.g. [1,2,3]) or change the deserialized type so that it is a normal
  .NET type (e.g. not a primitive type like integer, not a collection
  type like an array or List) that can be deserialized from a JSON
  object. JsonObjectAttribute can also be added to the type to force it
  to deserialize from a JSON object. Path 'Test', line 3, position 9.

Question

Why do I get this error?

At the end I want to achieve to write every menu item in the console. For now I am stuck with this error. How do I achieve a result (Output) like this:

ID: 1 Name: Frosted Pumpkin Bread
ID: 2 Name: Ground to Go
...

The Console application

using System;
using System.Collections.Generic;
using System.Net;
using Newtonsoft.Json;

namespace ConsoleApp1
{
    public class MenuItem
    {
        public string ID { get; set; }
        public string Description { get; set; }
        public string Summary { get; set; }
        public string Name { get; set; }
        public string ImageFile { get; set; }
    }

    public class Menu
    {
        public List<MenuItem> Test { get; set; }
    }

    class Program
    {

        static void Main(string[] args)
        {
          var webclient = new WebClient();
          var json = webclient.DownloadString(@"C:\Users\devuser\source\repos\ConsoleApp1\ConsoleApp1\data.json");
          var model = JsonConvert.DeserializeObject<List<Menu>>(json);

            foreach (var item in model)
            {
                Console.WriteLine();
            }
        }
    }
}

My JSON-File looks like this

{

  "Test": [

    {
      "ID": "1",
      "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.",
      "Summary": "A seasonal delight we offer every autumn.  Pumpking bread with just a bit of spice, cream cheese frosting with just a hint of home.",
      "Name": "Frosted Pumpkin Bread",
      "ImageFile": "pumpkinbread.png"
    },
    {
      "ID": "2",
      "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.",
      "Summary": "Love our coffee? Take it with you so you never have to be without!",
      "Name": "Ground to Go",
      "ImageFile": "granola.png"
    },
    {
      "ID": "3",
      "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.",
      "Summary": "Do you prefer to grind your own coffee? No problem, we'll give you the beans.",
      "Name": "Bean there, done that!",
      "ImageFile": "beans.jpg"
    },
    {
      "ID": "4",
      "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.",
      "Summary": "They're just as round as donuts, but far more healthy! Freshly made every morning before sunrise.",
      "Name": "Fresh Bagels",
      "ImageFile": "bagel.png"
    },
    {
      "ID": "5",
      "Description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus.",
      "Summary": "We've got strawberries, blueberries, apples, bananas - we could list them all, but we'd prefer you come take a look!",
      "Name": "Fresh Fruit",
      "ImageFile": "strawberries.png"
    }
  ]
}

Body:
You're trying to deserialize the json as List<Menu>

JsonConvert.DeserializeObject<List<Menu>>(json);

But the json does not contain a List of Menu, it only contains a single Menu object. You can see that the json starts with { }

{
    "Test": [...]
}

{ } is a object, [ ] is an Array. So to be able to deserialize into a List of Menu your json should look like this:

[
    {
        "Test": [...]
    }
]

so that you can have multiple Menu, like this:

[
    {
        "Test": [...]
    },
    {
        "Test": [...]
    },
    {
        "Test": [...]
    },
]

I hope I was helpful


问:
Regex to test if string begins with http:// or https://
I'm trying to set a regexp which will check the start of a string, and if it contains either http:// or https:// it should match it.

How can I do that? I'm trying the following which isn't working:

```<code>^[(http)(https)]://
</code>```

答:
Making this case insensitive wasn't working in asp.net so I just specified each of the letters.

Here's what I had to do to get it working in an asp.net RegularExpressionValidator:

```<code>[Hh][Tt][Tt][Pp][Ss]?://(.*)
</code>```

Notes:

(?i) and using /whatever/i didn't work probably because javascript hasn't brought in all case sensitive functionality

Originally had ^ at beginning but it didn't matter, but the (.*) did (Expression didn't work without (.*) but did work without ^)

Didn't need to escape the // though might be a good idea.

Here's the full RegularExpressionValidator if you need it:

```<code><asp:RegularExpressionValidator ID="revURLHeaderEdit" runat="server"
    ControlToValidate="txtURLHeaderEdit"
    ValidationExpression="[Hh][Tt][Tt][Pp][Ss]?://(.*)"
    ErrorMessage="URL should begin with http:// or https://" >
</asp:RegularExpressionValidator>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to set a regexp which will check the start of a string, and if it contains either http:// or https:// it should match it.

How can I do that? I'm trying the following which isn't working:

^[(http)(https)]://

Body:
Making this case insensitive wasn't working in asp.net so I just specified each of the letters.

Here's what I had to do to get it working in an asp.net RegularExpressionValidator:

[Hh][Tt][Tt][Pp][Ss]?://(.*)

Notes:

(?i) and using /whatever/i didn't work probably because javascript hasn't brought in all case sensitive functionality

Originally had ^ at beginning but it didn't matter, but the (.*) did (Expression didn't work without (.*) but did work without ^)

Didn't need to escape the // though might be a good idea.

Here's the full RegularExpressionValidator if you need it:

<asp:RegularExpressionValidator ID="revURLHeaderEdit" runat="server"
    ControlToValidate="txtURLHeaderEdit"
    ValidationExpression="[Hh][Tt][Tt][Pp][Ss]?://(.*)"
    ErrorMessage="URL should begin with http:// or https://" >
</asp:RegularExpressionValidator>