问:
Bootstrap 5.1 toggle not closing after opening(latest version)
I'm in the process of learning JS and have made a collapsable navbar. I got the menu to
open upon clicking the button, but it will not close. I've searched this site for
answers but anything I've found refers to Bootstrap. This is just pure JS. I've also
looked over my code for hours trying to spot a syntax error or anything that could be
going wrong. Any help would be greatly appreciated!
I am working on the latest version of bootstrap which 5.1 and facing this problem.

I am not able to resolve this. Navbar toggler is not closing after opening.
Here is my code:

<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <link rel="stylesheet" href="styles.css">

  <title>Hello, world!</title>

    tindog
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-label="Toggle navigation">

    </button>

          Contact

          Pricing

          Download

```

Help me regarding this issue.
I have included js bootstrap already.

答:
Solution -

comment out Separate Popper and Bootstrap JS

Navbar code structure modified as per bootstrap site

Ref URLs -

https://getbootstrap.com/docs/5.1/components/navbar/#external-content

https://getbootstrap.com/docs/5.1/getting-started/introduction/

<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <link rel="stylesheet" href="styles.css">

    <title>Hello, world!</title>

            tindog
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo01"
                aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">

            </button>

                Contact

                Pricing

                Download

```

Body:
I'm in the process of learning JS and have made a collapsable navbar. I got the menu to
open upon clicking the button, but it will not close. I've searched this site for
answers but anything I've found refers to Bootstrap. This is just pure JS. I've also
looked over my code for hours trying to spot a syntax error or anything that could be
going wrong. Any help would be greatly appreciated!
I am working on the latest version of bootstrap which 5.1 and facing this problem.

I am not able to resolve this. Navbar toggler is not closing after opening.
Here is my code:

<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <link rel="stylesheet" href="styles.css">

  <title>Hello, world!</title>

    tindog
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-label="Toggle navigation">

    </button>

          Contact

          Pricing

          Download

Help me regarding this issue.
I have included js bootstrap already.

Body:
Solution -

comment out Separate Popper and Bootstrap JS

Navbar code structure modified as per bootstrap site

Ref URLs -

https://getbootstrap.com/docs/5.1/components/navbar/#external-content

https://getbootstrap.com/docs/5.1/getting-started/introduction/

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <link rel="stylesheet" href="styles.css">

    <title>Hello, world!</title>
</head>

<body>
    <nav class="navbar navbar-dark bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">tindog</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo01"
                aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
        </div>
    </nav>
    <div class="collapse" id="navbarTogglerDemo01">
        <ul class="bg-dark p-4">
            <li class="nav-item">
                <a class="nav-link" href="#">Contact</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Pricing</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Download</a>
            </li>
        </ul>
    </div>

    <!-- Optional JavaScript; choose one of the two! -->

    <!-- Option 1: Bootstrap Bundle with Popper -->

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
        crossorigin="anonymous"></script>

    <!-- Option 2: Separate Popper and Bootstrap JS -->
    <!-- <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"
        integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB"
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js"
        integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13"
        crossorigin="anonymous"></script> -->

</body>
</html>


来源: stackexchange

问:
React array map inside map value not rendering
I have an object Array list and this array list includes duplicate values. So I need to render only unique values. But it's not working.</p>
```<code>{promotions.map((row) => (
  <div>
    <h1>{row.name}</h1>  //This is working
    {row.products.map(() => {
      const pp = row.products.filter( (ele, ind) => ind === row.products.findIndex( elem => elem.productId === ele.productId))

      pp.map((data)=>{
        return(
          <Chip
            key={`${row.productId}_${data.productId}`}
            classes={{ root: classes.productsChipRoot }}
            label={data.productName}
            style={{ margin: 3, backgroundColor: '#BBD7FB' }}
          />
        )
      })
    })}
  </div>
))}
</code>```

答:
You need to return your "pp" returned value correctly.

For example:

```<code>let firstArray = [{
  id: 1,
  name: "asd"
}, {
  id: 2,
  name: "fgh"
}];
let secondArray = [{
  id: 1,
  name: "hjk"
}, {
  id: 2,
  name: "zxc"
}];

firstArray.map(() => {
  const pp = firstArray.filter((ele, ind) => ind === firstArray.findIndex(elem => elem.id === 2))

  return pp.map((data) => {
    return (
      console.log(data)
    )
  })
})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an object Array list and this array list includes duplicate values. So I need to render only unique values. But it's not working.

{promotions.map((row) => (

{row.name}
  //This is working
    {row.products.map(() => {
      const pp = row.products.filter( (ele, ind) => ind === row.products.findIndex( elem => elem.productId === ele.productId))

      pp.map((data)=>{
        return(
          <Chip
            key={`${row.productId}_${data.productId}`}
            classes={{ root: classes.productsChipRoot }}
            label={data.productName}
            style={{ margin: 3, backgroundColor: '#BBD7FB' }}
          />
        )
      })
    })}

))}

Body:
You need to return your "pp" returned value correctly.

For example:

let firstArray = [{
  id: 1,
  name: "asd"
}, {
  id: 2,
  name: "fgh"
}];
let secondArray = [{
  id: 1,
  name: "hjk"
}, {
  id: 2,
  name: "zxc"
}];

firstArray.map(() => {
  const pp = firstArray.filter((ele, ind) => ind === firstArray.findIndex(elem => elem.id === 2))

  return pp.map((data) => {
    return (
      console.log(data)
    )
  })
})


问:
Count with MongoDB aggregate $group result
I have a database query with pymongo , like so

```<code>pipeline = [
    {"$group": {"_id": "$product", "count": {"$sum": 1}}},
]
rows = list(collection_name.aggregate(pipeline))
print(rows)
</code>```

The result like to

```<code>[
    {'_id': 'p1', 'count': 45},
    {'_id': 'p2', 'count': 4},
    {'_id': 'p3', 'count': 96},
    {'_id': 'p1', 'count': 23},
    {'_id': 'p4', 'count': 10}
]
</code>```

Objective:

On the basis of the above results, I want to conduct statistics between partitions. For example, To get the number of count times in the following intervals:

```<code>partition, count
(0, 10], 2
[11, 50), 2
[50, 100], 1
</code>```

Is there a way of doing this entirely using MongoDB aggregate framework?

Any comments would be very helpful. Thanks.

Answer by @Wernfried Domscheit

$bucket

```<code>pipeline = [
    {"$group": {"_id": "$product", "count": {"$sum": 1}}},
    {"$bucket": {
        "groupBy": "$count",
        "boundaries": [0, 11, 51, 100],
        "default": "Other",
        "output": {
            "count": {"$sum": 1},
        }
    }}
]
rows = list(tbl_athletes.aggregate(pipeline))
rows
</code>```

$bucketAuto

```<code>pipeline = [
    {"$group": {"_id": "$product", "count": {"$sum": 1}}},
    {"$bucketAuto": {
        "groupBy": "$count",
        "buckets": 5,
        "output": {
            "count": {"$sum": 1},
        }
    }}
]
rows = list(tbl_athletes.aggregate(pipeline))
rows
</code>```

NOTICE:

In $bucket，default must be there.

答:
Yes, you have the $bucket operator for that:

```<code>db.collection.aggregate([
   {
      $bucket: {
         groupBy: "$count",
         boundaries: [0, 11, 51, 100],
         output: {
            count: { $sum: 1 },
         }
      }
   }
])
</code>```

Or use $bucketAuto where the intervals are generated automatically.

Body:
I have a database query with pymongo , like so

pipeline = [
    {"$group": {"_id": "$product", "count": {"$sum": 1}}},
]
rows = list(collection_name.aggregate(pipeline))
print(rows)

The result like to

[
    {'_id': 'p1', 'count': 45},
    {'_id': 'p2', 'count': 4},
    {'_id': 'p3', 'count': 96},
    {'_id': 'p1', 'count': 23},
    {'_id': 'p4', 'count': 10}
]

Objective:

On the basis of the above results, I want to conduct statistics between partitions. For example, To get the number of count times in the following intervals:

partition, count
(0, 10], 2
[11, 50), 2
[50, 100], 1

Is there a way of doing this entirely using MongoDB aggregate framework?

Any comments would be very helpful. Thanks.

Answer by @Wernfried Domscheit

$bucket

pipeline = [
    {"$group": {"_id": "$product", "count": {"$sum": 1}}},
    {"$bucket": {
        "groupBy": "$count",
        "boundaries": [0, 11, 51, 100],
        "default": "Other",
        "output": {
            "count": {"$sum": 1},
        }
    }}
]
rows = list(tbl_athletes.aggregate(pipeline))
rows

$bucketAuto

pipeline = [
    {"$group": {"_id": "$product", "count": {"$sum": 1}}},
    {"$bucketAuto": {
        "groupBy": "$count",
        "buckets": 5,
        "output": {
            "count": {"$sum": 1},
        }
    }}
]
rows = list(tbl_athletes.aggregate(pipeline))
rows

NOTICE:

In $bucket，default must be there.

Body:
Yes, you have the $bucket operator for that:

db.collection.aggregate([
   {
      $bucket: {
         groupBy: "$count",
         boundaries: [0, 11, 51, 100],
         output: {
            count: { $sum: 1 },
         }
      }
   }
])

Or use $bucketAuto where the intervals are generated automatically.


问:
Why list of stories does not get initialized in this file once I run the code?
In this code, I cache data from Firebase realtime data base and then save it locally in Hive database. All this code used to work in another project that was null safe, but implementing this in an old project does not work. Where is the problem?
Here is the code:

```<code>class NewHomeScreen extends StatefulWidget {
  const NewHomeScreen({Key key}) : super(key: key);

  @override
  _NewHomeScreenState createState() => _NewHomeScreenState();
}

class _NewHomeScreenState extends State<NewHomeScreen> {
  List stories = [];
  Box<Story> storyBox;
  List<String> keys;
  @override
  void initState() {
    super.initState();
  }

  Future openBox() async {
    final document = await getApplicationDocumentsDirectory();
    Hive.init(document.path);
    Hive.registerAdapter<Story>(StoryAdapter());
    storyBox = await Hive.openBox<Story>('storyBoxName');
    print('Box Opened!');
  }

  Future<bool> getAllData() async {
    const url = 'https://shaparak-732ff.firebaseio.com/items.json';
    await openBox();
    try {
      final response = await http.get(Uri.parse(url));
      final extractedData = json.decode(response.body) as Map<String, dynamic>;
      await putData(extractedData);
    } catch (SocketException) {
      print('No Internet');
    }
    var mymap = storyBox.toMap().values.toList();
    if (mymap.isEmpty) {
      stories.add('empty');
    } else {
      stories = mymap;
    }
    return Future.value(true);
  }

  Future putData(Map<String, dynamic> data) async {
    await storyBox.clear();
    Story newStory;
    data.forEach((key, value) {
      newStory = Story(
        author: value['author'],
        category: value['category'],
        content: value['content'],
        id: key.toString(),
        title: value['title'],
      );
      storyBox.put(key, newStory);
    });
  }

  Future<void> updateData() async {
    const url = 'https://shaparak-732ff.firebaseio.com/items.json';
    try {
      final response = await http.get(Uri.parse(url));
      final extractedData = json.decode(response.body) as Map<String, dynamic>;
      await putData(extractedData);
      setState(() {});
    } catch (SocketException) {
      Fluttertoast.showToast(
          msg: "This is Center Short Toast",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0);
      print('No Internet');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFFDEBF7),
      appBar: AppBar(
        backgroundColor: Theme.of(context).primaryColor,
        title: Text("Shaparak"),
      ),
      body: Center(
        child: FutureBuilder(
          future: getAllData(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              if (stories.isEmpty) {
                return const Text(
                  'No Data',
                  style: TextStyle(
                    fontSize: 24.0,
                  ),
                );
              } else {
                return RefreshIndicator(
                  onRefresh: updateData,
                  child: ItemsGrid(storyBox.toMap().values.toList()),
                );
              }
            } else {
              return const CircularProgressIndicator();
            }
          },
        ),
      ),
    );
  }
}
</code>```

This used to work in a null safety migrated project, but implementing this in an old project which is not null safe, does not work. Can you please guide me how to solve it?

答: Hmm. May be it is the issue with the dart SDK version.</p>

Body:
In this code, I cache data from Firebase realtime data base and then save it locally in Hive database. All this code used to work in another project that was null safe, but implementing this in an old project does not work. Where is the problem?
Here is the code:

class NewHomeScreen extends StatefulWidget {
  const NewHomeScreen({Key key}) : super(key: key);

  @override
  _NewHomeScreenState createState() => _NewHomeScreenState();
}

class _NewHomeScreenState extends State<NewHomeScreen> {
  List stories = [];
  Box<Story> storyBox;
  List<String> keys;
  @override
  void initState() {
    super.initState();
  }

  Future openBox() async {
    final document = await getApplicationDocumentsDirectory();
    Hive.init(document.path);
    Hive.registerAdapter<Story>(StoryAdapter());
    storyBox = await Hive.openBox<Story>('storyBoxName');
    print('Box Opened!');
  }

  Future<bool> getAllData() async {
    const url = 'https://shaparak-732ff.firebaseio.com/items.json';
    await openBox();
    try {
      final response = await http.get(Uri.parse(url));
      final extractedData = json.decode(response.body) as Map<String, dynamic>;
      await putData(extractedData);
    } catch (SocketException) {
      print('No Internet');
    }
    var mymap = storyBox.toMap().values.toList();
    if (mymap.isEmpty) {
      stories.add('empty');
    } else {
      stories = mymap;
    }
    return Future.value(true);
  }

  Future putData(Map<String, dynamic> data) async {
    await storyBox.clear();
    Story newStory;
    data.forEach((key, value) {
      newStory = Story(
        author: value['author'],
        category: value['category'],
        content: value['content'],
        id: key.toString(),
        title: value['title'],
      );
      storyBox.put(key, newStory);
    });
  }

  Future<void> updateData() async {
    const url = 'https://shaparak-732ff.firebaseio.com/items.json';
    try {
      final response = await http.get(Uri.parse(url));
      final extractedData = json.decode(response.body) as Map<String, dynamic>;
      await putData(extractedData);
      setState(() {});
    } catch (SocketException) {
      Fluttertoast.showToast(
          msg: "This is Center Short Toast",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          fontSize: 16.0);
      print('No Internet');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFFDEBF7),
      appBar: AppBar(
        backgroundColor: Theme.of(context).primaryColor,
        title: Text("Shaparak"),
      ),
      body: Center(
        child: FutureBuilder(
          future: getAllData(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              if (stories.isEmpty) {
                return const Text(
                  'No Data',
                  style: TextStyle(
                    fontSize: 24.0,
                  ),
                );
              } else {
                return RefreshIndicator(
                  onRefresh: updateData,
                  child: ItemsGrid(storyBox.toMap().values.toList()),
                );
              }
            } else {
              return const CircularProgressIndicator();
            }
          },
        ),
      ),
    );
  }
}

This used to work in a null safety migrated project, but implementing this in an old project which is not null safe, does not work. Can you please guide me how to solve it?


问:
Cannot Resolve import android.support.multidex.MultiDex after change to newest Multidex
I want to use multidex in my application, At First I used depedencies :
'com.google.android:multidex:0.1', but after compile this error appeared :

Error:Execution failed for task ':packageAllDebugClassesForMultiDex'.

java.util.zip.ZipException: duplicate entry: android/support/multidex/BuildConfig.class

then I changed 'com.google.android:multidex:0.1' to 'com.android.support:multidex:1.0.1', but after that import android.support.multidex.MultiDex; in application class cannot be resolved, anybody can help ?

答:
Add following dependency in you app gradle</p>
```<code> implementation 'androidx.multidex:multidex:2.0.1'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Add following dependency in you app gradle

 implementation 'androidx.multidex:multidex:2.0.1'


答:
In Render, Map works for just outter map. So, the Inner map is not render. You should not use the inner map.

I recommend using filter method. Like this

```<code>row.products.filter(*condition*).map(()=>{
      return <div></div>
)
</code>```

Title: React array map inside map value not rendering

Body:
In Render, Map works for just outter map. So, the Inner map is not render. You should not use the inner map.

I recommend using filter method. Like this

row.products.filter(*condition*).map(()=>{
      return <div></div>
)


问:
Sum All Numbers in a Range
freecodecamp algorithm challenge. I can't determine at which point in my function I am returning more than one value. The correct return value should be 10. The console.log I print out in this function shows three values, with the one in the middle being the correct one. How do I target this specific value and ignore the other ones?
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-numbers-in-a-range</p>
```<code>function sumAll(arr) {
    for (let i = 0; i < arr.length; i++){
      if (arr[i] != arr[arr.length -1]){
        let num = arr[i] + 1;
        arr.splice(arr[i], 0, num);
          console.log(arr.reduce(function(sum, value) {
            return sum + value;
          }, 0));
      }
    }
}

sumAll([1, 4]);

</code>```

答:
Here is another way:</p>
```<code> const sumAll = (arr) => {
    arr.sort((a, b) => a - b)
    return ((arr[0]+arr[1])/2)*((arr[1]-arr[0])+1)
 }
</code>```

Title: Sum All Numbers in a Range

Body:
freecodecamp algorithm challenge. I can't determine at which point in my function I am returning more than one value. The correct return value should be 10. The console.log I print out in this function shows three values, with the one in the middle being the correct one. How do I target this specific value and ignore the other ones?
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-numbers-in-a-range

function sumAll(arr) {
    for (let i = 0; i < arr.length; i++){
      if (arr[i] != arr[arr.length -1]){
        let num = arr[i] + 1;
        arr.splice(arr[i], 0, num);
          console.log(arr.reduce(function(sum, value) {
            return sum + value;
          }, 0));
      }
    }
}

sumAll([1, 4]);

Body:
Here is another way:

 const sumAll = (arr) => {
    arr.sort((a, b) => a - b)
    return ((arr[0]+arr[1])/2)*((arr[1]-arr[0])+1)
 }


问:
Making an HTML table list monthly snapshots of a variable
The table below lists username by total descending.  How can I make each row list whoever had the highest total on the $date listed in the first column?

```<code>$query = "SELECT username, datesubmitted, COUNT(1) AS total
    FROM submission
    GROUP BY username

ORDER BY total DESC"

$result = mysql_query($query);

$date = strtotime("January 1, 2010");

$arr = array();

echo "<table>";
    while ($row = mysql_fetch_array($result)) {

    $date = strtotime("+1 month", $date);

            echo '<tr>';
            echo '<td >'.date("F j, Y", $date).'</td>';
            echo '<td >'.stripslashes($row["username"]).'</a></td>';
            echo '<td >'.number_format(($row["total"])).'</td>';
            echo '</tr>';
}

echo "</table>";
</code>```

答:
You can get the grouping in mysql as well, no need count in PHP:

```<code>SELECT count(*), username, datesubmitted
    FROM submission
    GROUP BY username, month(datesubmitted)
</code>```

Now you can just iterate over the result in display the table

Body:
The table below lists username by total descending.  How can I make each row list whoever had the highest total on the $date listed in the first column?

$query = "SELECT username, datesubmitted, COUNT(1) AS total
    FROM submission
    GROUP BY username

ORDER BY total DESC"

$result = mysql_query($query);

$date = strtotime("January 1, 2010");

$arr = array();

echo "
";
    while ($row = mysql_fetch_array($result)) {

    $date = strtotime("+1 month", $date);

            echo '
';
            echo ''.date("F j, Y", $date).'	';
            echo ''.stripslashes($row["username"]).'	';
            echo ''.number_format(($row["total"])).'	';
            echo '
';
}

echo "
";

Body:
You can get the grouping in mysql as well, no need count in PHP:

SELECT count(*), username, datesubmitted
    FROM submission
    GROUP BY username, month(datesubmitted)

Now you can just iterate over the result in display the table


问:
RecyclerView item height and width change dynamically Android
I am new to android development and I am developing an app where the app downloads pictures from server and show them in a gridView. But some extra spaces are coming up when the app is run on a bigger screen phone. Here are some screenshots. How do I solve this ? I have the model of each item with a fixed height and width of 110dp

My image model :

```<code><?xml version="1.0" encoding="utf-8"?>
<ImageView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="110dp"
    android:layout_height="110dp"
    app:srcCompat="@drawable/post2"
    android:id="@+id/imageView2"
    android:adjustViewBounds="true"
    android:scaleType="centerCrop"
    android:layout_margin="1.5dp" />
</code>```

My Recycler View :

```<code><android.support.v7.widget.RecyclerView
                android:id="@+id/gallerygrid"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="4dp"
                android:numColumns="auto_fit"
                android:stretchMode="columnWidth"
                android:visibility="visible"
                android:layout_gravity="center">

            </android.support.v7.widget.RecyclerView>
</code>```

答:
If you are using Constraint layout use constraint Dimens ratio as
mentioned above.

```<code><ImageView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 app:layout_constraintDimensionRatio="1:1"/>
</code>```

else if you are using linear or relative layout.

```<code><ImageView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:adjustViewBounds="true" />
</code>```

both will solve your problem but both of them are only recommend if you have small amount of data to populate, these tricks are not recommended for thousands of images, as this will calculate and set height of each item at run time which means this will run on main thread and for thousands of images this will create a laggy scrolling and may result in ANR on low end devices.

There is another work around to minimize this lag.

You can get the width of the imageView at runtime in onBindViewHolder and set the height equals to width or any multiple of width to attain your desired ratio.

```<code> CoroutineScope(Dispatchers.IO).launch {
      val width = holder.image.width

      withContext(Dispatchers.Main){
           holder.image.layoutParams.height = width
      }
  }
</code>```

Getting the width at background thread will take the load off of Main thread which ultimately results in smooth scrolling.

Body:
I am new to android development and I am developing an app where the app downloads pictures from server and show them in a gridView. But some extra spaces are coming up when the app is run on a bigger screen phone. Here are some screenshots. How do I solve this ? I have the model of each item with a fixed height and width of 110dp

My image model :

<?xml version="1.0" encoding="utf-8"?>
<ImageView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="110dp"
    android:layout_height="110dp"
    app:srcCompat="@drawable/post2"
    android:id="@+id/imageView2"
    android:adjustViewBounds="true"
    android:scaleType="centerCrop"
    android:layout_margin="1.5dp" />

My Recycler View :

<android.support.v7.widget.RecyclerView
                android:id="@+id/gallerygrid"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="4dp"
                android:numColumns="auto_fit"
                android:stretchMode="columnWidth"
                android:visibility="visible"
                android:layout_gravity="center">

            </android.support.v7.widget.RecyclerView>

Body:
If you are using Constraint layout use constraint Dimens ratio as
mentioned above.

<ImageView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 app:layout_constraintDimensionRatio="1:1"/>

else if you are using linear or relative layout.

<ImageView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:adjustViewBounds="true" />

both will solve your problem but both of them are only recommend if you have small amount of data to populate, these tricks are not recommended for thousands of images, as this will calculate and set height of each item at run time which means this will run on main thread and for thousands of images this will create a laggy scrolling and may result in ANR on low end devices.

There is another work around to minimize this lag.

You can get the width of the imageView at runtime in onBindViewHolder and set the height equals to width or any multiple of width to attain your desired ratio.

 CoroutineScope(Dispatchers.IO).launch {
      val width = holder.image.width

      withContext(Dispatchers.Main){
           holder.image.layoutParams.height = width
      }
  }

Getting the width at background thread will take the load off of Main thread which ultimately results in smooth scrolling.


答:
Alternative I: Will not catch the lone row 11, since it will try to pick the longest valid sequence from each starting point.

```<code>SELECT C.*
FROM (
    SELECT
        A.UID,
        A.TID AS TID1,
        MAX(B.TID) AS TID2
    FROM TblTask A
    INNER JOIN TblTask B
        ON B.UID = A.UID
        AND B.StartTime BETWEEN A.StartTime AND DATEADD(hour, 1, A.StartTime)
    GROUP BY A.TID, A.UID
    HAVING SUM(B.WId) >= 5 OR COUNT(*) >= 5
) Ranges
INNER JOIN TblTask C
    ON C.UID = Ranges.UID
    AND C.TID BETWEEN Ranges.TID1 AND Ranges.TID2
</code>```

Alternative II: Will report both (4..9) and (4..10), since those fall within the criteria.

```<code>SELECT D.*
FROM (
    SELECT
        A.Uid,
        A.TID AS TID1,
        B.TID AS TID2
    FROM TblTask A
    INNER JOIN TblTask B
        ON B.Uid = A.Uid
        AND B.StartTime BETWEEN A.StartTime AND DATEADD(hour, 1, A.StartTime)
    INNER JOIN TblTask C
        ON C.UID = A.UID
        AND C.TID BETWEEN A.TID AND B.TID
    GROUP BY A.TID, B.TID, A.Uid
    HAVING SUM(C.WId) >= 5  OR COUNT(*) >= 5
) Ranges
INNER JOIN TblTask D
    ON D.Uid = Ranges.Uid
    AND D.TID BETWEEN Ranges.TID1 AND Ranges.TID2;
</code>```

In either alternative, you could add columns from the Ranges table to distinguish between the concatenated sub-sequences.

Result of Alternative I:

```<code>TID   StartTime                 Uid   WId
  1   2011-06-06 09:30:00.000    10   1.5
  2   2011-06-06 09:40:00.000    10   3.5
  3   2011-06-06 09:50:00.000    10   1.0
  3   2011-06-06 09:50:00.000    10   1.0
  4   2011-06-06 10:45:00.000    10   2.5
  5   2011-06-06 10:50:00.000    10   1.5
  4   2011-06-06 10:45:00.000    10   2.5
  5   2011-06-06 10:50:00.000    10   1.5
  6   2011-06-06 10:55:00.000    10   0.0
  7   2011-06-06 11:30:00.000    10   0.0
  8   2011-06-06 11:35:00.000    10   0.0
  9   2011-06-06 11:40:00.000    10   0.0
 10   2011-06-06 11:43:00.000    10   0.0
  5   2011-06-06 10:50:00.000    10   1.5
  6   2011-06-06 10:55:00.000    10   0.0
  7   2011-06-06 11:30:00.000    10   0.0
  8   2011-06-06 11:35:00.000    10   0.0
  9   2011-06-06 11:40:00.000    10   0.0
 10   2011-06-06 11:43:00.000    10   0.0
  6   2011-06-06 10:55:00.000    10   0.0
  7   2011-06-06 11:30:00.000    10   0.0
  8   2011-06-06 11:35:00.000    10   0.0
  9   2011-06-06 11:40:00.000    10   0.0
 10   2011-06-06 11:43:00.000    10   0.0
 11   2011-06-06 11:20:00.000    11   7.0
 12   2011-06-06 11:30:00.000    11   1.0
</code>```

Result of Alternative II:

```<code>TID   StartTime                 Uid   WId
  1   2011-06-06 09:30:00.000    10   1.5
  2   2011-06-06 09:40:00.000    10   3.5
  1   2011-06-06 09:30:00.000    10   1.5
  2   2011-06-06 09:40:00.000    10   3.5
  3   2011-06-06 09:50:00.000    10   1.0
  3   2011-06-06 09:50:00.000    10   1.0
  4   2011-06-06 10:45:00.000    10   2.5
  5   2011-06-06 10:50:00.000    10   1.5
  4   2011-06-06 10:45:00.000    10   2.5
  5   2011-06-06 10:50:00.000    10   1.5
  6   2011-06-06 10:55:00.000    10   0.0
  7   2011-06-06 11:30:00.000    10   0.0
  8   2011-06-06 11:35:00.000    10   0.0
  4   2011-06-06 10:45:00.000    10   2.5
  5   2011-06-06 10:50:00.000    10   1.5
  6   2011-06-06 10:55:00.000    10   0.0
  7   2011-06-06 11:30:00.000    10   0.0
  8   2011-06-06 11:35:00.000    10   0.0
  9   2011-06-06 11:40:00.000    10   0.0
  4   2011-06-06 10:45:00.000    10   2.5
  5   2011-06-06 10:50:00.000    10   1.5
  6   2011-06-06 10:55:00.000    10   0.0
  7   2011-06-06 11:30:00.000    10   0.0
  8   2011-06-06 11:35:00.000    10   0.0
  9   2011-06-06 11:40:00.000    10   0.0
 10   2011-06-06 11:43:00.000    10   0.0
  5   2011-06-06 10:50:00.000    10   1.5
  6   2011-06-06 10:55:00.000    10   0.0
  7   2011-06-06 11:30:00.000    10   0.0
  8   2011-06-06 11:35:00.000    10   0.0
  9   2011-06-06 11:40:00.000    10   0.0
  5   2011-06-06 10:50:00.000    10   1.5
  6   2011-06-06 10:55:00.000    10   0.0
  7   2011-06-06 11:30:00.000    10   0.0
  8   2011-06-06 11:35:00.000    10   0.0
  9   2011-06-06 11:40:00.000    10   0.0
 10   2011-06-06 11:43:00.000    10   0.0
  6   2011-06-06 10:55:00.000    10   0.0
  7   2011-06-06 11:30:00.000    10   0.0
  8   2011-06-06 11:35:00.000    10   0.0
  9   2011-06-06 11:40:00.000    10   0.0
 10   2011-06-06 11:43:00.000    10   0.0
 11   2011-06-06 11:20:00.000    11   7.0
 11   2011-06-06 11:20:00.000    11   7.0
 12   2011-06-06 11:30:00.000    11   1.0
</code>```

Title: Need output Based on Count OR Weights based on TimeDifference

Body:
TID   StartTime                   Uid   WId
1     2011-06-06 09:30:00.000     10    1.5
2     2011-06-06 09:40:00.000     10    3.5
3     2011-06-06 09:50:00.000     10    1.0
4     2011-06-06 10:45:00.000     10    2.5
5     2011-06-06 10:50:00.000     10    1.5
6     2011-06-06 10:55:00.000     10    0
7     2011-06-06 11:30:00.000     10    0
8     2011-06-06 11:35:00.000     10    0
9     2011-06-06 11:40:00.000     10    0
10    2011-06-06 11:43:00.000     10    0
11    2011-06-06 11:20:00.000     11    7.0
12    2011-06-06 11:30:00.000     11    1.0

I have the data in Table TblTask , I need to write a query to calculate (sum(Wid) or Count(TID's)) based on time difference of each Starttime with another starttime having time difference 1 hour or close to 1 hr Group by UID.

For example take first start time(2011-06-06 09:30:00.000); the nearest start time having <=1 hr is (2011-06-06 10:30:00.000) (If the SUM(Wid) >=5.0 OR Count of Rows >=5). Here Weights are (1.5+3.5+1.0=6.0)
 First 3 rows TID's (1,2,3) as weight>=5 we need to show the records and
 TID's (3,4,5)  Here Weights are (1.0+2.5+1.5=5.0)
 For TID'd(4,5,6,7,8,9,10) Here Count (TID's is 7) So i want display all the records from 4 to 10

For TID's(5,6,7,8,9,10) as Count (TID's is > 5 ) i want display all the records from 5 to 10

For TID's(6,7,8,9,10) as Count (TID's is = 5 ) i want display all the records from 6 to 10

For TID 11 as WID > 5 i want to display record 11

For TID's (11,12) as WID >5 again i want to display record 11 and 12

Desired output will be:

TID    StartTime                 Uid
1     2011-06-06 09:30:00.000    10
2     2011-06-06 09:40:00.000    10
3     2011-06-06 09:50:00.000    10
3     2011-06-06 09:50:00.000    10
4     2011-06-06 10:45:00.000    10
5     2011-06-06 10:50:00.000    10
4     2011-06-06 10:45:00.000    10
5     2011-06-06 10:50:00.000    10
6     2011-06-06 10:55:00.000    10
7     2011-06-06 11:30:00.000    10
8     2011-06-06 11:35:00.000    10
9     2011-06-06 11:40:00.000    10
10    2011-06-06 11:43:00.000    10
5     2011-06-06 10:50:00.000    10
6     2011-06-06 10:55:00.000    10
7     2011-06-06 11:30:00.000    10
8     2011-06-06 11:35:00.000    10
9     2011-06-06 11:40:00.000    10
10    2011-06-06 11:43:00.000    10
6     2011-06-06 10:55:00.000    10
7     2011-06-06 11:30:00.000    10
8     2011-06-06 11:35:00.000    10
9     2011-06-06 11:40:00.000    10
10    2011-06-06 11:43:00.000    10
11    2011-06-06 11:20:00.000    11
11    2011-06-06 11:20:00.000    11
12    2011-06-06 11:30:00.000    11

Body:
Alternative I: Will not catch the lone row 11, since it will try to pick the longest valid sequence from each starting point.

SELECT C.*
FROM (
    SELECT
        A.UID,
        A.TID AS TID1,
        MAX(B.TID) AS TID2
    FROM TblTask A
    INNER JOIN TblTask B
        ON B.UID = A.UID
        AND B.StartTime BETWEEN A.StartTime AND DATEADD(hour, 1, A.StartTime)
    GROUP BY A.TID, A.UID
    HAVING SUM(B.WId) >= 5 OR COUNT(*) >= 5
) Ranges
INNER JOIN TblTask C
    ON C.UID = Ranges.UID
    AND C.TID BETWEEN Ranges.TID1 AND Ranges.TID2

Alternative II: Will report both (4..9) and (4..10), since those fall within the criteria.

SELECT D.*
FROM (
    SELECT
        A.Uid,
        A.TID AS TID1,
        B.TID AS TID2
    FROM TblTask A
    INNER JOIN TblTask B
        ON B.Uid = A.Uid
        AND B.StartTime BETWEEN A.StartTime AND DATEADD(hour, 1, A.StartTime)
    INNER JOIN TblTask C
        ON C.UID = A.UID
        AND C.TID BETWEEN A.TID AND B.TID
    GROUP BY A.TID, B.TID, A.Uid
    HAVING SUM(C.WId) >= 5  OR COUNT(*) >= 5
) Ranges
INNER JOIN TblTask D
    ON D.Uid = Ranges.Uid
    AND D.TID BETWEEN Ranges.TID1 AND Ranges.TID2;

In either alternative, you could add columns from the Ranges table to distinguish between the concatenated sub-sequences.

Result of Alternative I:

TID   StartTime                 Uid   WId
  1   2011-06-06 09:30:00.000    10   1.5
  2   2011-06-06 09:40:00.000    10   3.5
  3   2011-06-06 09:50:00.000    10   1.0
  3   2011-06-06 09:50:00.000    10   1.0
  4   2011-06-06 10:45:00.000    10   2.5
  5   2011-06-06 10:50:00.000    10   1.5
  4   2011-06-06 10:45:00.000    10   2.5
  5   2011-06-06 10:50:00.000    10   1.5
  6   2011-06-06 10:55:00.000    10   0.0
  7   2011-06-06 11:30:00.000    10   0.0
  8   2011-06-06 11:35:00.000    10   0.0
  9   2011-06-06 11:40:00.000    10   0.0
 10   2011-06-06 11:43:00.000    10   0.0
  5   2011-06-06 10:50:00.000    10   1.5
  6   2011-06-06 10:55:00.000    10   0.0
  7   2011-06-06 11:30:00.000    10   0.0
  8   2011-06-06 11:35:00.000    10   0.0
  9   2011-06-06 11:40:00.000    10   0.0
 10   2011-06-06 11:43:00.000    10   0.0
  6   2011-06-06 10:55:00.000    10   0.0
  7   2011-06-06 11:30:00.000    10   0.0
  8   2011-06-06 11:35:00.000    10   0.0
  9   2011-06-06 11:40:00.000    10   0.0
 10   2011-06-06 11:43:00.000    10   0.0
 11   2011-06-06 11:20:00.000    11   7.0
 12   2011-06-06 11:30:00.000    11   1.0

Result of Alternative II:

TID   StartTime                 Uid   WId
  1   2011-06-06 09:30:00.000    10   1.5
  2   2011-06-06 09:40:00.000    10   3.5
  1   2011-06-06 09:30:00.000    10   1.5
  2   2011-06-06 09:40:00.000    10   3.5
  3   2011-06-06 09:50:00.000    10   1.0
  3   2011-06-06 09:50:00.000    10   1.0
  4   2011-06-06 10:45:00.000    10   2.5
  5   2011-06-06 10:50:00.000    10   1.5
  4   2011-06-06 10:45:00.000    10   2.5
  5   2011-06-06 10:50:00.000    10   1.5
  6   2011-06-06 10:55:00.000    10   0.0
  7   2011-06-06 11:30:00.000    10   0.0
  8   2011-06-06 11:35:00.000    10   0.0
  4   2011-06-06 10:45:00.000    10   2.5
  5   2011-06-06 10:50:00.000    10   1.5
  6   2011-06-06 10:55:00.000    10   0.0
  7   2011-06-06 11:30:00.000    10   0.0
  8   2011-06-06 11:35:00.000    10   0.0
  9   2011-06-06 11:40:00.000    10   0.0
  4   2011-06-06 10:45:00.000    10   2.5
  5   2011-06-06 10:50:00.000    10   1.5
  6   2011-06-06 10:55:00.000    10   0.0
  7   2011-06-06 11:30:00.000    10   0.0
  8   2011-06-06 11:35:00.000    10   0.0
  9   2011-06-06 11:40:00.000    10   0.0
 10   2011-06-06 11:43:00.000    10   0.0
  5   2011-06-06 10:50:00.000    10   1.5
  6   2011-06-06 10:55:00.000    10   0.0
  7   2011-06-06 11:30:00.000    10   0.0
  8   2011-06-06 11:35:00.000    10   0.0
  9   2011-06-06 11:40:00.000    10   0.0
  5   2011-06-06 10:50:00.000    10   1.5
  6   2011-06-06 10:55:00.000    10   0.0
  7   2011-06-06 11:30:00.000    10   0.0
  8   2011-06-06 11:35:00.000    10   0.0
  9   2011-06-06 11:40:00.000    10   0.0
 10   2011-06-06 11:43:00.000    10   0.0
  6   2011-06-06 10:55:00.000    10   0.0
  7   2011-06-06 11:30:00.000    10   0.0
  8   2011-06-06 11:35:00.000    10   0.0
  9   2011-06-06 11:40:00.000    10   0.0
 10   2011-06-06 11:43:00.000    10   0.0
 11   2011-06-06 11:20:00.000    11   7.0
 11   2011-06-06 11:20:00.000    11   7.0
 12   2011-06-06 11:30:00.000    11   1.0


问:
How to write the if clause when iterating through a treeview?
I have a function that checks if a barcode is known to the warehouse. If so, the function grabs the row from the dataframe (occupied by an imported excel file) and will be inserted into a treeview with known items. If the barcode is unknown it will be inserted into a listbox.

The function works and does what it is supposed to do, but I want to expand it by updating the row in the treeview by increasing its quantity by 1 when adding the same barcode to the treeview. See the picture for the current behaviour. Known items treeview

```<code># Function to process new entered barcodes by filtering known and unknown items and adding them to treeview
def scan_check(event):
    scanned_item = scan_entry.get()
    for code in df.iloc[:, 1]:  # column with barcodes
        if code == scanned_item:
            for row in df.to_numpy().tolist():  # dataframe with item / barcode / item description / size / quantity
                if scanned_item in row:
                    quantity_count = 1
                    row.insert(4, quantity_count)
                    scanTree.insert(parent='', index='end', value=row)
                    for child in scanTree.get_children():
                        if scanTree.item(child, option='values'[3]) in scanTree.get_children():
                            quantity_count += 1
                            scanTree.set(child, 'Quantity', quantity_count)

            scan_entry.delete(0, tkinter.END)

            break   # to prevent adding item to unknown products listbox as well

    else:
        unknown_listbox.insert(tkinter.END, scanned_item)
        scan_entry.delete(0, tkinter.END)
</code>```

My question is: How would I write the if clause, after iterating throught the children, when I want to check if the added row from the dataframe is already in my treeview?

My attempts at the if clause did not work obviously. I was hoping anyone could help me with my problem. Thanks for reading.

答:
You can simplify the logic:

Search the treeview first for the barcode, if found, update the quantity

If not found, search the dataframe. If found, insert new record into treeview, otherwise insert the barcode to the unknown listbox

def scan_check(event):
    scanned_item = scan_entry.get().strip()
    if scanned_item == '':
        # do nothing if empty string is input
        return

    # search treeview
    for child in scanTree.get_children():
        row = scanTree.set(child)
        if row['Barcode'] == scanned_item:
            # update quantity
            scanTree.set(child, 'Quantity', int(row['Quantity'])+1)
            break # prevent executing else block
    else:
        # search dataframe
        result = df.loc[df['Barcode'].astype(str) == scanned_item]
        if result.empty:
            # should check whether barcode already exists?
            unknown_listbox.insert('end', scanned_item)
        else:
            scanTree.insert('', 'end', values=result.iloc[0].to_list()+[1])
    scan_entry.delete(0, 'end')
```

Body:
I have a function that checks if a barcode is known to the warehouse. If so, the function grabs the row from the dataframe (occupied by an imported excel file) and will be inserted into a treeview with known items. If the barcode is unknown it will be inserted into a listbox.

The function works and does what it is supposed to do, but I want to expand it by updating the row in the treeview by increasing its quantity by 1 when adding the same barcode to the treeview. See the picture for the current behaviour. Known items treeview

# Function to process new entered barcodes by filtering known and unknown items and adding them to treeview
def scan_check(event):
    scanned_item = scan_entry.get()
    for code in df.iloc[:, 1]:  # column with barcodes
        if code == scanned_item:
            for row in df.to_numpy().tolist():  # dataframe with item / barcode / item description / size / quantity
                if scanned_item in row:
                    quantity_count = 1
                    row.insert(4, quantity_count)
                    scanTree.insert(parent='', index='end', value=row)
                    for child in scanTree.get_children():
                        if scanTree.item(child, option='values'[3]) in scanTree.get_children():
                            quantity_count += 1
                            scanTree.set(child, 'Quantity', quantity_count)

            scan_entry.delete(0, tkinter.END)

            break   # to prevent adding item to unknown products listbox as well

    else:
        unknown_listbox.insert(tkinter.END, scanned_item)
        scan_entry.delete(0, tkinter.END)

My question is: How would I write the if clause, after iterating throught the children, when I want to check if the added row from the dataframe is already in my treeview?

My attempts at the if clause did not work obviously. I was hoping anyone could help me with my problem. Thanks for reading.


问:
How do I make Neo4J continue after conditional create
After having created a collection of nodes, some of the nodes should also have a relation attached based on a condition. In the example below the condition is simulated with WHERE n.number > 3 and the nodes are simple numbers:

```<code>WITH [2, 3, 4] as numbers
UNWIND numbers AS num
CREATE(n:Number {number: num})
WITH collect(n) AS nodes
UNWIND nodes AS n
WITH nodes, n WHERE n.number > 3
CREATE (n)-[:IM_SPECIAL]->(n)
RETURN nodes
</code>```

Which returns:

```<code>╒════════════════════════════════════════╕
│"nodes"                                 │
╞════════════════════════════════════════╡
│[{"number":2},{"number":3},{"number":4}]│
└────────────────────────────────────────┘
Added 3 labels, created 3 nodes, set 3 properties, created 1 relationship, started streaming 1 records in less than 1 ms and completed after 1 ms.
</code>```

My problem is that nothing is returned unless I have at least one of these "special" nodes that is caught by the filter. The problem can be simulated by changing the input numbers to [1, 2, 3] which returns an empty result (no nodes) even though the nodes are created (as they should):

```<code><empty result>
Added 3 labels, created 3 nodes, set 3 properties, completed after 2 ms.
</code>```

I might be approaching the problem totally wrong but I've exhausted my Google skills... what Neo4J Cypher magic am I missing?

答:
WITH nodes, n WHERE n.number > 3

Each clause of a Cypher query must yield a result for for the subsequent lines of the query to consume. The above line yields nothing if you start with [1,2,3].

For your purpose, this will work.

```<code>WITH [1,2,3,4] as numbers
UNWIND numbers AS num
CREATE(n:Number {number: num})
WITH n
CALL apoc.do.when(n.number>3,
  'CREATE (n)-[:IM_SPECIAL]->(n) RETURN n',
   'RETURN n',
  {n:n}
)
YIELD value as m
WITH collect(m) AS nodes

RETURN nodes
</code>```

Body:
After having created a collection of nodes, some of the nodes should also have a relation attached based on a condition. In the example below the condition is simulated with WHERE n.number > 3 and the nodes are simple numbers:

WITH [2, 3, 4] as numbers
UNWIND numbers AS num
CREATE(n:Number {number: num})
WITH collect(n) AS nodes
UNWIND nodes AS n
WITH nodes, n WHERE n.number > 3
CREATE (n)-[:IM_SPECIAL]->(n)
RETURN nodes

Which returns:

╒════════════════════════════════════════╕
│"nodes"                                 │
╞════════════════════════════════════════╡
│[{"number":2},{"number":3},{"number":4}]│
└────────────────────────────────────────┘
Added 3 labels, created 3 nodes, set 3 properties, created 1 relationship, started streaming 1 records in less than 1 ms and completed after 1 ms.

My problem is that nothing is returned unless I have at least one of these "special" nodes that is caught by the filter. The problem can be simulated by changing the input numbers to [1, 2, 3] which returns an empty result (no nodes) even though the nodes are created (as they should):

<empty result>
Added 3 labels, created 3 nodes, set 3 properties, completed after 2 ms.

I might be approaching the problem totally wrong but I've exhausted my Google skills... what Neo4J Cypher magic am I missing?

Body:
WITH nodes, n WHERE n.number > 3

Each clause of a Cypher query must yield a result for for the subsequent lines of the query to consume. The above line yields nothing if you start with [1,2,3].

For your purpose, this will work.

WITH [1,2,3,4] as numbers
UNWIND numbers AS num
CREATE(n:Number {number: num})
WITH n
CALL apoc.do.when(n.number>3,
  'CREATE (n)-[:IM_SPECIAL]->(n) RETURN n',
   'RETURN n',
  {n:n}
)
YIELD value as m
WITH collect(m) AS nodes

RETURN nodes


问:
Pass data to custom stateful widget and return validation staus form
I have created a custom stateful widget. I need to use this same widget multiple times in a form. The their are several different forms accessing the same widget. In order to avoid code duplication I extracted the widget

The only thing that changes in the widget is its label (e.g. Instrument Clean), the hint for the TextFormField (e.g. Instrument clean remark) and the TextEdittingController.

The TextFormField is only writable when Not Okay is selected.
Proper validation have been implemented for the same.

My question is how to send label text, hint text and TextEdittingController to this custom Widget and at the same time how to return validation return status to main form.

Code :

```<code>class ToogleRemarkWidget extends StatefulWidget {
  final TextEditingController textController;
  const ToogleRemarkWidget({required this.textController, Key? key})
      : super(key: key);
  @override
  State<ToogleRemarkWidget> createState() => _ToogleRemarkWidgetState();
}

class _ToogleRemarkWidgetState extends State<ToogleRemarkWidget> {
  final TextEditingController _textController = TextEditingController();
  int _toggleIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      mainAxisSize: MainAxisSize.max,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        const Expanded(
          flex: 2,
          child: Text('Instrument Clean : '),
        ),
        Expanded(
          flex: 3,
          child: Center(
            child: ToggleSwitch(
              totalSwitches: 2,
              initialLabelIndex: _toggleIndex,
              labels: const ['Okay', 'Not Okay'],
              //TODO Change Okay Icon
              activeBgColors: const [
                [Colors.green],
                [Colors.red]
              ],
              minWidth: 100.0,
              animate: true,
              onToggle: (index) {
                if (index == 0) {
                  _textController.clear();
                }
                setState(() {
                  _toggleIndex = index;
                });
              },
              cornerRadius: 20.0,
            ),
          ),
        ),
        Expanded(
          flex: 5,
          child: TextFormField(
            enabled: _toggleIndex == 0 ? false : true,
            controller: _textController,
            decoration: const InputDecoration(
              icon: Icon(Icons.note_add),
              label: Text('Instrument Clean Remark'),
              hintText: 'Enter Instrument Clean Remark',
              border: OutlineInputBorder(),
            ),
            validator: (value) {
              if (_toggleIndex == 1 && (value == null || value.isEmpty)) {
                return 'Please enter Instrument Cleaned By'; //Validation error
              }
              return null; //Validation Success
            },
          ),
        ),
      ],
    );
  }
}
</code>```

答:
I solved the problem defining all necessary fields in primary StatefulWidget class.

I accessed the necessary field from my primary StatefulWidget class in my build method using widget property.

```<code>class ToogleRemarkWidget extends StatefulWidget {
  final TextEditingController textController;
  final String label;
  const ToogleRemarkWidget({
    required this.textController,
    required this.label,
    Key? key,
  }) : super(key: key);

  @override
  State<ToogleRemarkWidget> createState() => _ToogleRemarkWidgetState();
}

class _ToogleRemarkWidgetState extends State<ToogleRemarkWidget> {
  //final TextEditingController _textController = TextEditingController();
  int _toggleIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      mainAxisSize: MainAxisSize.max,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Expanded(
          flex: kIsWeb ? 2 : 5,
          child: Text(widget.label),
        ),
        Expanded(
          flex: kIsWeb ? 2 : 5,
          child: Center(
            child: ToggleSwitch(
              totalSwitches: 2,
              initialLabelIndex: _toggleIndex,
              labels: const ['Okay', 'Not Okay'],
              //TODO Change Okay Icon
              activeBgColors: const [
                [Colors.green],
                [Colors.red]
              ],
              minWidth: 100.0,
              animate: true,
              onToggle: (index) {
                if (index == 0) {
                  widget.textController.clear();
                }
                setState(() {
                  _toggleIndex = index;
                });
              },
              cornerRadius: 20.0,
            ),
          ),
        ),
        Expanded(
          flex: 5,
          child: TextFormField(
            enabled: _toggleIndex == 0 ? false : true,
            controller: widget.textController,
            decoration: InputDecoration(
              icon: const Icon(Icons.note_add),
              label: Text(widget.label),
              hintText: 'Enter ${widget.label}',
              border: const OutlineInputBorder(),
            ),
            validator: (value) {
              if (_toggleIndex == 1 && (value == null || value.isEmpty)) {
                return 'Please enter ${widget.label} By'; //Validation error
              }
              return null; //Validation Success
            },
          ),
        ),
      ],
    );
  }
}
</code>```

Body:
I have created a custom stateful widget. I need to use this same widget multiple times in a form. The their are several different forms accessing the same widget. In order to avoid code duplication I extracted the widget

The only thing that changes in the widget is its label (e.g. Instrument Clean), the hint for the TextFormField (e.g. Instrument clean remark) and the TextEdittingController.

The TextFormField is only writable when Not Okay is selected.
Proper validation have been implemented for the same.

My question is how to send label text, hint text and TextEdittingController to this custom Widget and at the same time how to return validation return status to main form.

Code :

class ToogleRemarkWidget extends StatefulWidget {
  final TextEditingController textController;
  const ToogleRemarkWidget({required this.textController, Key? key})
      : super(key: key);
  @override
  State<ToogleRemarkWidget> createState() => _ToogleRemarkWidgetState();
}

class _ToogleRemarkWidgetState extends State<ToogleRemarkWidget> {
  final TextEditingController _textController = TextEditingController();
  int _toggleIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      mainAxisSize: MainAxisSize.max,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        const Expanded(
          flex: 2,
          child: Text('Instrument Clean : '),
        ),
        Expanded(
          flex: 3,
          child: Center(
            child: ToggleSwitch(
              totalSwitches: 2,
              initialLabelIndex: _toggleIndex,
              labels: const ['Okay', 'Not Okay'],
              //TODO Change Okay Icon
              activeBgColors: const [
                [Colors.green],
                [Colors.red]
              ],
              minWidth: 100.0,
              animate: true,
              onToggle: (index) {
                if (index == 0) {
                  _textController.clear();
                }
                setState(() {
                  _toggleIndex = index;
                });
              },
              cornerRadius: 20.0,
            ),
          ),
        ),
        Expanded(
          flex: 5,
          child: TextFormField(
            enabled: _toggleIndex == 0 ? false : true,
            controller: _textController,
            decoration: const InputDecoration(
              icon: Icon(Icons.note_add),
              label: Text('Instrument Clean Remark'),
              hintText: 'Enter Instrument Clean Remark',
              border: OutlineInputBorder(),
            ),
            validator: (value) {
              if (_toggleIndex == 1 && (value == null || value.isEmpty)) {
                return 'Please enter Instrument Cleaned By'; //Validation error
              }
              return null; //Validation Success
            },
          ),
        ),
      ],
    );
  }
}

Body:
I solved the problem defining all necessary fields in primary StatefulWidget class.

I accessed the necessary field from my primary StatefulWidget class in my build method using widget property.

class ToogleRemarkWidget extends StatefulWidget {
  final TextEditingController textController;
  final String label;
  const ToogleRemarkWidget({
    required this.textController,
    required this.label,
    Key? key,
  }) : super(key: key);

  @override
  State<ToogleRemarkWidget> createState() => _ToogleRemarkWidgetState();
}

class _ToogleRemarkWidgetState extends State<ToogleRemarkWidget> {
  //final TextEditingController _textController = TextEditingController();
  int _toggleIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      mainAxisSize: MainAxisSize.max,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Expanded(
          flex: kIsWeb ? 2 : 5,
          child: Text(widget.label),
        ),
        Expanded(
          flex: kIsWeb ? 2 : 5,
          child: Center(
            child: ToggleSwitch(
              totalSwitches: 2,
              initialLabelIndex: _toggleIndex,
              labels: const ['Okay', 'Not Okay'],
              //TODO Change Okay Icon
              activeBgColors: const [
                [Colors.green],
                [Colors.red]
              ],
              minWidth: 100.0,
              animate: true,
              onToggle: (index) {
                if (index == 0) {
                  widget.textController.clear();
                }
                setState(() {
                  _toggleIndex = index;
                });
              },
              cornerRadius: 20.0,
            ),
          ),
        ),
        Expanded(
          flex: 5,
          child: TextFormField(
            enabled: _toggleIndex == 0 ? false : true,
            controller: widget.textController,
            decoration: InputDecoration(
              icon: const Icon(Icons.note_add),
              label: Text(widget.label),
              hintText: 'Enter ${widget.label}',
              border: const OutlineInputBorder(),
            ),
            validator: (value) {
              if (_toggleIndex == 1 && (value == null || value.isEmpty)) {
                return 'Please enter ${widget.label} By'; //Validation error
              }
              return null; //Validation Success
            },
          ),
        ),
      ],
    );
  }
}


问:
save plotly plot to local file and insert into html
I am using python and plotly to product interactive html report. This post gives a nice framework.

If I produce the plot(via plotly) online, and insert the url into the html file, it works but refreshing the charts takes a long time. I wonder if I could produce the chart offline and have it embedded in the html report, so that loading speed is not a problem.

I find plot offline would generate a html for the chart, but I don't know how to embed it in another html. Anyone could help?

答:
to embed it in another page just use

```<code><iframe width="560" height="315" title="Plot1" src="./scatter1.html"></iframe>
</code>```

But why go with the trouble when you can not save it to a file and instead it, embed it directly

```<code>import plotly.offline as pyo
import plotly.graph_objs as go
import numpy as np

#generate the Plot
np.random.seed(42)
random_x = np.random.randint(1,101,100)
random_y = np.random.randint(1,101,100)

data = [go.Scatter(
    x = random_x,
    y = random_y,
    mode = 'markers',
)]

the_plot= pyo.plot(data, include_plotlyjs=False, output_type='div')
print(the_plot)
num=11

strTable = '<html><head><title>Plots and Reports</title><script src="https://cdn.plot.ly/plotly-latest.min.js"></script></head><body><table style="width:100%"><tr><th>Plot</th><th>Something else</th></tr>'

strRW = "<tr><td>"+the_plot+ "</td><td>"+str(num)+"</td></tr>"
strTable = strTable+strRW

strTable = strTable+"</table></body></html>"

hs = open("theReport.html", 'w')
hs.write(strTable)
</code>```

Body:
to embed it in another page just use

<iframe width="560" height="315" title="Plot1" src="./scatter1.html"></iframe>

But why go with the trouble when you can not save it to a file and instead it, embed it directly

import plotly.offline as pyo
import plotly.graph_objs as go
import numpy as np

#generate the Plot
np.random.seed(42)
random_x = np.random.randint(1,101,100)
random_y = np.random.randint(1,101,100)

data = [go.Scatter(
    x = random_x,
    y = random_y,
    mode = 'markers',
)]

the_plot= pyo.plot(data, include_plotlyjs=False, output_type='div')
print(the_plot)
num=11

strTable = '<html><head><title>Plots and Reports</title><script src="https://cdn.plot.ly/plotly-latest.min.js"></script></head><body><table style="width:100%"><tr><th>Plot</th><th>Something else</th></tr>'

strRW = "<tr><td>"+the_plot+ "</td><td>"+str(num)+"</td></tr>"
strTable = strTable+strRW

strTable = strTable+"</table></body></html>"

hs = open("theReport.html", 'w')
hs.write(strTable)


问:
Scala function fails when changing return type from Unit to String
I a teaching myself Scala, and have been dealing with the algorithmic problem of finding all balanced pairs of n parenthesis.

So, the following solution works:

```<code>object GetAllValidParenthesis extends App {
  def generateParenthesis(n: Int): Unit = {

    parenthesis("", 0, 0, n)

  }

  private def parenthesis(output: String, open: Int, close: Int, pairs: Int): Unit = {
    if ((open == pairs) && (close == pairs)) {
      println(output)
    }
    else {
      if (open < pairs) parenthesis(output + "(", open + 1, close, pairs)
      if (open > close) parenthesis(output + ")", open, close + 1, pairs)
    }
  }

  println(generateParenthesis(3))
}
</code>```

But, if I wanted to return a String instead of Unit (so as to later keep all strings in some data structure, like an array buffer), i.e., I did this:

```<code>private def parenthesis(output: String, open: Int, close: Int, pairs: Int): String = {
    if ((open == pairs) && (close == pairs)) {
      output
    }
    else {
      if (open < pairs) parenthesis(output + "(", open + 1, close, pairs)
      if (open > close) parenthesis(output + ")", open, close + 1, pairs)
    }
  }
</code>```

The compiler tells me:

```<code>type mismatch;
 found   : Unit
 required: String
      if (open > close) parenthesis(output + ")", open, close + 1, pairs)
</code>```

But it is impossible for the function to return anything but a String, since the only "return" is in the line that says "output", the rest are recursive calls.

Why does this happen? Is there any way in which I could fix this?

Thanks in advance for your help.

答:
In Scala, every expression has a value.

That's to say

// this is not a Boolean value
val exp = if (2 > 1) true

// in fact, is the same as following. The `Unit` and `Boolean`'s common type is `AnyVal`
val exp: AnyVal = if (2 > 1) true else {}

```
<p>In your problem, your function should generate a string of parenthesis and append it to result set rather than just return the value.</p>
<p>I have just write solution of this problem.</p>
<p>May be it's more appropriate like following</p>
<pre class="lang-scala prettyprint-override"><code>import scala.collection.mutable.ArrayBuffer

object GenerateParenthesis {

  def generateParenthesis(n: Int): List[String] = {

    val res = ArrayBuffer.empty[String]

    def travel(l: Int, r: Int, curString: String): Unit = {
      if (l == 0 && r == 0) res += curString
      if (l > 0) travel(l - 1, r, curString + "(")
      if (r > l) travel(l, r - 1, curString + ")")
    }

    travel(n, n, "")
    res.toList
  }
}
</code>```

The test code can be found here:

https://github.com/counter2015/LeetCodeScala/blob/6a3ff3d28a7b378490105684d080418c287680d8/src/test/scala/algorithms/medium/implementation/GenerateParenthesisTest.scala

Body:
I a teaching myself Scala, and have been dealing with the algorithmic problem of finding all balanced pairs of n parenthesis.

So, the following solution works:

object GetAllValidParenthesis extends App {
  def generateParenthesis(n: Int): Unit = {

    parenthesis("", 0, 0, n)

  }

  private def parenthesis(output: String, open: Int, close: Int, pairs: Int): Unit = {
    if ((open == pairs) && (close == pairs)) {
      println(output)
    }
    else {
      if (open < pairs) parenthesis(output + "(", open + 1, close, pairs)
      if (open > close) parenthesis(output + ")", open, close + 1, pairs)
    }
  }

  println(generateParenthesis(3))
}

But, if I wanted to return a String instead of Unit (so as to later keep all strings in some data structure, like an array buffer), i.e., I did this:

private def parenthesis(output: String, open: Int, close: Int, pairs: Int): String = {
    if ((open == pairs) && (close == pairs)) {
      output
    }
    else {
      if (open < pairs) parenthesis(output + "(", open + 1, close, pairs)
      if (open > close) parenthesis(output + ")", open, close + 1, pairs)
    }
  }

The compiler tells me:

type mismatch;
 found   : Unit
 required: String
      if (open > close) parenthesis(output + ")", open, close + 1, pairs)

But it is impossible for the function to return anything but a String, since the only "return" is in the line that says "output", the rest are recursive calls.

Why does this happen? Is there any way in which I could fix this?

Thanks in advance for your help.

Body:
In Scala, every expression has a value.

That's to say

// this is not a Boolean value
val exp = if (2 > 1) true

// in fact, is the same as following. The `Unit` and `Boolean`'s common type is `AnyVal`
val exp: AnyVal = if (2 > 1) true else {}

In your problem, your function should generate a string of parenthesis and append it to result set rather than just return the value.

I have just write solution of this problem.

May be it's more appropriate like following

import scala.collection.mutable.ArrayBuffer

object GenerateParenthesis {

  def generateParenthesis(n: Int): List[String] = {

    val res = ArrayBuffer.empty[String]

    def travel(l: Int, r: Int, curString: String): Unit = {
      if (l == 0 && r == 0) res += curString
      if (l > 0) travel(l - 1, r, curString + "(")
      if (r > l) travel(l, r - 1, curString + ")")
    }

    travel(n, n, "")
    res.toList
  }
}

The test code can be found here:

https://github.com/counter2015/LeetCodeScala/blob/6a3ff3d28a7b378490105684d080418c287680d8/src/test/scala/algorithms/medium/implementation/GenerateParenthesisTest.scala


问:
how to apply images to selected items  combobox in extjs 4.0
I want to add images in front of the text in an ExtJS combobox. I have the following code in listConfig...

```<code>  listConfig: {
       getInnerTpl: function(displayField) {
          var tpl = '<div>' +'my img path is here' +   '{name}</div>';
          return tpl;
       }
  },
</code>```

And my store is like this

```<code>Ext.define('state', {
    extend: 'Ext.data.Model',
    fields: [{ name: 'stateCode', type: 'int' }, { name: 'name', type: "string"}]
});
</code>```

My JSON response from the server...

```<code>[{"stateCode":"0","name":"--Select--"},{"stateCode":"1","name":"ABC"},{"stateCode":"2","name":"XYZ"},{"stateCode":"3","name":"OPQ"},{"stateCode":"188587","name":"LMN"}]
</code>```

Here i get the image infront of all items in combobox, but I only want the image infront of items with stateCode 1.

Please help

答:
```<code>var tpl = '<div><img src='img/path/image.jpg' class="state-{state}" />{name}</div>';
</code>```

then uses css clasess to do something with your image (like hide or show)

Body:
I want to add images in front of the text in an ExtJS combobox. I have the following code in listConfig...

  listConfig: {
       getInnerTpl: function(displayField) {
          var tpl = '
' +'my img path is here' +   '{name}
';
          return tpl;
       }
  },

And my store is like this

Ext.define('state', {
    extend: 'Ext.data.Model',
    fields: [{ name: 'stateCode', type: 'int' }, { name: 'name', type: "string"}]
});

My JSON response from the server...

[{"stateCode":"0","name":"--Select--"},{"stateCode":"1","name":"ABC"},{"stateCode":"2","name":"XYZ"},{"stateCode":"3","name":"OPQ"},{"stateCode":"188587","name":"LMN"}]

Here i get the image infront of all items in combobox, but I only want the image infront of items with stateCode 1.

Please help

Body:
var tpl = '<div><img src='img/path/image.jpg' class="state-{state}" />{name}</div>';

then uses css clasess to do something with your image (like hide or show)


问:
How to encrypt a password field in django
I have a model with name, code and password. I need to encrypt the password. Also I should'nt show a plain text in the password field.
I referred to this link

Password field in Django model

But the answer is old and need to know what the present approach is.

My model is as below

```<code>class Crew(models.Model):
    crew_id = models.AutoField(primary_key=True)
    crew_code = models.CharField(max_length=200, null=False, unique=True)
    crew_name = models.CharField(max_length=200, null=False)
    crew_password = models.CharField(max_length=200, null=False)
</code>```

答:
I've tried this method of making.

Add this is your model

from django.contrib.auth.hashers import make_password

```<code>  class Crew(models.Model):

        crew_id = models.AutoField(primary_key=True)
        crew_code = models.CharField(max_length=200, null=False, unique=True)
        crew_name = models.CharField(max_length=200, null=False)
        crew_password = models.CharField(max_length=200, null=False)

    def save(self, *args, **kwargs):
        self.password = make_password(self.password)
        super(Crew, self).save(*args, **kwargs)
</code>```

This working for me .

Thanks

Body:
I have a model with name, code and password. I need to encrypt the password. Also I should'nt show a plain text in the password field.
I referred to this link

Password field in Django model

But the answer is old and need to know what the present approach is.

My model is as below

class Crew(models.Model):
    crew_id = models.AutoField(primary_key=True)
    crew_code = models.CharField(max_length=200, null=False, unique=True)
    crew_name = models.CharField(max_length=200, null=False)
    crew_password = models.CharField(max_length=200, null=False)

Body:
I've tried this method of making.

Add this is your model

from django.contrib.auth.hashers import make_password

  class Crew(models.Model):

        crew_id = models.AutoField(primary_key=True)
        crew_code = models.CharField(max_length=200, null=False, unique=True)
        crew_name = models.CharField(max_length=200, null=False)
        crew_password = models.CharField(max_length=200, null=False)

    def save(self, *args, **kwargs):
        self.password = make_password(self.password)
        super(Crew, self).save(*args, **kwargs)

This working for me .

Thanks


问:
how to add data to json file flutter?
i have a data.json file like this in which i am getting a list of data i want to add  another parameter{p_quantity} to this json file .
Or i can the parameter by default as empty then how i can i update that value .

```<code>[
  {
    "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.qEvRk2ip9vubQ-_xnfTj1AHaFj%26pid%3DApi&f=1",
    "p_name":"Apple",
    "p_id":1,
    "p_cost":30,
    "p_availability":1,
    "p_details":"Imported from Swiss",
    "p_category":"Premium"
  },
  {
    "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse3.mm.bing.net%2Fth%3Fid%3DOIP.l5ZNKHxygp8AHCJbVwlUaAHaE8%26pid%3DApi&f=1",
    "p_name":"Mango",
    "p_id":2,
    "p_cost":50,
    "p_availability":1,
    "p_details":"Farmed at Selam",
    "p_category":"Tamilnadu"
  },
  {
    "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse2.mm.bing.net%2Fth%3Fid%3DOIP.hRWr-pLb_cF-gOn31CCSJgHaHa%26pid%3DApi&f=1",
    "p_name":"Bananna",
    "p_id":3,
    "p_cost":5,
    "p_availability":0
  },
  {
    "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse2.mm.bing.net%2Fth%3Fid%3DOIP.FFvWgkIBYYekEc8BVt_wHgHaFW%26pid%3DApi&f=1",
    "p_name":"Orange",
    "p_id":4,
    "p_cost":25,
    "p_availability":1,
    "p_details":"from Nagpur",
    "p_category":"Premium"
  }
]
</code>```

in which i want to add another parameter "p_quantity" . how can i do that ?
I am getting the data via this function

```<code>Future<List<Products>> readJsonData() async {
  //read json file
  final jsondata = await rootBundle.rootBundle.loadString('assets/data.json');
  //decode json data as list
  final list = json.decode(jsondata) as List<dynamic>;
  //map json and initialize using DataModel
  return list.map((e) => Products.fromJson(e)).toList();
}
</code>```

and here is the product class

```<code>class  Products {
String? pImage;
String? pName;
int? pId;
int? pCost;
int? pAvailability;
String? pDetails;
String? pCategory;

Products(
{this.pImage,
this.pName,
this.pId,
this.pCost,
this.pAvailability,
this.pDetails,
this.pCategory});

Products.fromJson(Map<String, dynamic> json) {
pImage = json['p_image'];
pName = json['p_name'];
pId = json['p_id'];
pCost = json['p_cost'];
pAvailability = json['p_availability'];
pDetails = json['p_details'];
pCategory = json['p_category'];
}

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['p_image'] = pImage;
data['p_name'] = pName;
data['p_id'] = pId;
data['p_cost'] = pCost;
data['p_availability'] = pAvailability;
data['p_details'] = pDetails;
data['p_category'] = pCategory;
return data;
}
}
</code>```

答:
You need to create a Map. After that, you can add variables to that Map using this command:

```<code>exampleMap["p_data"] = "somedata";
</code>```

This should work.

Title: how to add data to json file flutter?

Body:
i have a data.json file like this in which i am getting a list of data i want to add  another parameter{p_quantity} to this json file .
Or i can the parameter by default as empty then how i can i update that value .

[
  {
    "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.qEvRk2ip9vubQ-_xnfTj1AHaFj%26pid%3DApi&f=1",
    "p_name":"Apple",
    "p_id":1,
    "p_cost":30,
    "p_availability":1,
    "p_details":"Imported from Swiss",
    "p_category":"Premium"
  },
  {
    "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse3.mm.bing.net%2Fth%3Fid%3DOIP.l5ZNKHxygp8AHCJbVwlUaAHaE8%26pid%3DApi&f=1",
    "p_name":"Mango",
    "p_id":2,
    "p_cost":50,
    "p_availability":1,
    "p_details":"Farmed at Selam",
    "p_category":"Tamilnadu"
  },
  {
    "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse2.mm.bing.net%2Fth%3Fid%3DOIP.hRWr-pLb_cF-gOn31CCSJgHaHa%26pid%3DApi&f=1",
    "p_name":"Bananna",
    "p_id":3,
    "p_cost":5,
    "p_availability":0
  },
  {
    "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse2.mm.bing.net%2Fth%3Fid%3DOIP.FFvWgkIBYYekEc8BVt_wHgHaFW%26pid%3DApi&f=1",
    "p_name":"Orange",
    "p_id":4,
    "p_cost":25,
    "p_availability":1,
    "p_details":"from Nagpur",
    "p_category":"Premium"
  }
]

in which i want to add another parameter "p_quantity" . how can i do that ?
I am getting the data via this function

Future<List<Products>> readJsonData() async {
  //read json file
  final jsondata = await rootBundle.rootBundle.loadString('assets/data.json');
  //decode json data as list
  final list = json.decode(jsondata) as List<dynamic>;
  //map json and initialize using DataModel
  return list.map((e) => Products.fromJson(e)).toList();
}

and here is the product class

class  Products {
String? pImage;
String? pName;
int? pId;
int? pCost;
int? pAvailability;
String? pDetails;
String? pCategory;

Products(
{this.pImage,
this.pName,
this.pId,
this.pCost,
this.pAvailability,
this.pDetails,
this.pCategory});

Products.fromJson(Map<String, dynamic> json) {
pImage = json['p_image'];
pName = json['p_name'];
pId = json['p_id'];
pCost = json['p_cost'];
pAvailability = json['p_availability'];
pDetails = json['p_details'];
pCategory = json['p_category'];
}

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['p_image'] = pImage;
data['p_name'] = pName;
data['p_id'] = pId;
data['p_cost'] = pCost;
data['p_availability'] = pAvailability;
data['p_details'] = pDetails;
data['p_category'] = pCategory;
return data;
}
}

Body:
You need to create a Map. After that, you can add variables to that Map using this command:

exampleMap["p_data"] = "somedata";

This should work.


问:
Error with Ops Agent GCE metadata unauthenticated
Trying to get Ops Agent working and used the following command to install it:

```<code>curl -sSO https://dl.google.com/cloudagents/add-google-cloud-ops-agent-repo.sh
sudo bash add-google-cloud-ops-agent-repo.sh --also-install
</code>```

I see the following error in the logs of journalctl -u google-cloud-ops-agent-opentelemetry-collector -xn

```<code>otelopscol[2706]: 2022-02-06T21:50:36.140Z        info        exporterhelper/queued_retry.go:215        Exporting failed. Will retry the request after interval.        {"kind": "exporter", "name": "googlecloud", "error": "[rpc error: code = Unauthenticated desc = transport: per-RPC creds failed due to error: metadata: GCE metadata \"instance/service-accounts/default/token?scopes=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fmonitoring%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fmonitoring.read%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fmonitoring.write\" not defined; rpc error: code = Unauthenticated desc = transport: per-RPC creds failed due to error: metadata: GCE metadata \"instance/service-accounts/default/token?scopes=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fmonitoring%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fmonitoring.read%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fmonitoring.write\" not defined; rpc error: code = Unauthenticated desc = transport: per-RPC creds failed due to error: metadata: GCE metadata \"instance/service-accounts/default/token?scopes=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fmonitoring%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fmonitoring.read%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fmonitoring.write\" not defined]", "interval": "14.115202828s"}
</code>```

The services otherwise look good and are running but the UI reports that Ops Agent wasn't actually running which I suspect is due to no data being sent back.

Here is the status of running agents:

```<code>google-cloud-ops-agent-opentelemetry-collector.service - Google Cloud Ops Agent - Metrics Agent
     Loaded: loaded (/lib/systemd/system/google-cloud-ops-agent-opentelemetry-collector.service; static; vendor preset: enabled)
     Active: active (running) since Sat 2022-02-05 04:38:41 UTC; 1 day 17h ago
    Process: 2690 ExecStartPre=/opt/google-cloud-ops-agent/libexec/google_cloud_ops_agent_engine -service=otel -in /etc/google-clou>
   Main PID: 2706 (otelopscol)
      Tasks: 9 (limit: 2369)
     Memory: 193.6M
     CGroup: /system.slice/google-cloud-ops-agent-opentelemetry-collector.service
             └─2706 /opt/google-cloud-ops-agent/subagents/opentelemetry-collector/otelopscol --config=/run/google-cloud-ops-agent-o>

Feb 06 21:55:53 mongo-1 otelopscol[2706]:         /root/go/pkg/mod/go.opentelemetry.io/collector@v0.42.0/exporter/exporterhelper/qu>
Feb 06 21:55:53 mongo-1 otelopscol[2706]: go.opentelemetry.io/collector/exporter/exporterhelper.(*metricsSenderWithObservability).s>
Feb 06 21:55:53 mongo-1 otelopscol[2706]:         /root/go/pkg/mod/go.opentelemetry.io/collector@v0.42.0/exporter/exporterhelper/me>
Feb 06 21:55:53 mongo-1 otelopscol[2706]: go.opentelemetry.io/collector/exporter/exporterhelper.(*queuedRetrySender).start.func1
Feb 06 21:55:53 mongo-1 otelopscol[2706]:         /root/go/pkg/mod/go.opentelemetry.io/collector@v0.42.0/exporter/exporterhelper/qu>
Feb 06 21:55:53 mongo-1 otelopscol[2706]: go.opentelemetry.io/collector/exporter/exporterhelper/internal.consumerFunc.consume
Feb 06 21:55:53 mongo-1 otelopscol[2706]:         /root/go/pkg/mod/go.opentelemetry.io/collector@v0.42.0/exporter/exporterhelper/in>
Feb 06 21:55:53 mongo-1 otelopscol[2706]: go.opentelemetry.io/collector/exporter/exporterhelper/internal.(*boundedMemoryQueue).Star>
Feb 06 21:55:53 mongo-1 otelopscol[2706]:         /root/go/pkg/mod/go.opentelemetry.io/collector@v0.42.0/exporter/exporterhelper/in>
Feb 06 21:55:53 mongo-1 otelopscol[2706]: 2022-02-06T21:55:53.145Z        info        exporterhelper/queued_retry.go:215        Exp>

● google-cloud-ops-agent.service - Google Cloud Ops Agent
     Loaded: loaded (/lib/systemd/system/google-cloud-ops-agent.service; enabled; vendor preset: enabled)
     Active: active (exited) since Sat 2022-02-05 04:38:41 UTC; 1 day 17h ago
    Process: 2691 ExecStartPre=/opt/google-cloud-ops-agent/libexec/google_cloud_ops_agent_engine -in /etc/google-cloud-ops-agent/co>
    Process: 2704 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
   Main PID: 2704 (code=exited, status=0/SUCCESS)

Feb 05 04:38:41 mongo-1 systemd[1]: Starting Google Cloud Ops Agent...
Feb 05 04:38:41 mongo-1 systemd[1]: Finished Google Cloud Ops Agent.
● google-cloud-ops-agent-fluent-bit.service - Google Cloud Ops Agent - Logging Agent
     Loaded: loaded (/lib/systemd/system/google-cloud-ops-agent-fluent-bit.service; static; vendor preset: enabled)
     Active: active (running) since Sun 2022-02-06 15:05:35 UTC; 6h ago
    Process: 22138 ExecStartPre=/opt/google-cloud-ops-agent/libexec/google_cloud_ops_agent_engine -service=fluentbit -in /etc/googl>
   Main PID: 22144 (fluent-bit)
      Tasks: 22 (limit: 2369)
     Memory: 29.0M
     CGroup: /system.slice/google-cloud-ops-agent-fluent-bit.service
             └─22144 /opt/google-cloud-ops-agent/subagents/fluent-bit/bin/fluent-bit --config /run/google-cloud-ops-agent-fluent-bi>

Feb 06 15:05:35 mongo-1 systemd[1]: google-cloud-ops-agent-fluent-bit.service: Scheduled restart job, restart counter is at 7.
Feb 06 15:05:35 mongo-1 systemd[1]: Stopped Google Cloud Ops Agent - Logging Agent.
Feb 06 15:05:35 mongo-1 systemd[1]: Starting Google Cloud Ops Agent - Logging Agent...
Feb 06 15:05:35 mongo-1 systemd[1]: Started Google Cloud Ops Agent - Logging Agent.
Feb 06 15:05:35 mongo-1 fluent-bit[22144]: Fluent Bit v1.8.12
Feb 06 15:05:35 mongo-1 fluent-bit[22144]: * Copyright (C) 2019-2021 The Fluent Bit Authors
Feb 06 15:05:35 mongo-1 fluent-bit[22144]: * Copyright (C) 2015-2018 Treasure Data
Feb 06 15:05:35 mongo-1 fluent-bit[22144]: * Fluent Bit is a CNCF sub-project under the umbrella of Fluentd
Feb 06 15:05:35 mongo-1 fluent-bit[22144]: * https://fluentbit.io
</code>```

答:
The issue was due to the VM not having a service account. The solution was to do the following:

create a service account

assign the service account Logs Writer and Monitoring Metric Writer roles

Stop the VM, Edit the VM, set the newly created service account, start the VM

Note that by default a VM has a default service account. In my case I created the VM and explicitely didn't enable any service account hence the issue.

Body:
Trying to get Ops Agent working and used the following command to install it:

curl -sSO https://dl.google.com/cloudagents/add-google-cloud-ops-agent-repo.sh
sudo bash add-google-cloud-ops-agent-repo.sh --also-install

I see the following error in the logs of journalctl -u google-cloud-ops-agent-opentelemetry-collector -xn

otelopscol[2706]: 2022-02-06T21:50:36.140Z        info        exporterhelper/queued_retry.go:215        Exporting failed. Will retry the request after interval.        {"kind": "exporter", "name": "googlecloud", "error": "[rpc error: code = Unauthenticated desc = transport: per-RPC creds failed due to error: metadata: GCE metadata \"instance/service-accounts/default/token?scopes=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fmonitoring%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fmonitoring.read%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fmonitoring.write\" not defined; rpc error: code = Unauthenticated desc = transport: per-RPC creds failed due to error: metadata: GCE metadata \"instance/service-accounts/default/token?scopes=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fmonitoring%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fmonitoring.read%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fmonitoring.write\" not defined; rpc error: code = Unauthenticated desc = transport: per-RPC creds failed due to error: metadata: GCE metadata \"instance/service-accounts/default/token?scopes=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fmonitoring%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fmonitoring.read%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fmonitoring.write\" not defined]", "interval": "14.115202828s"}

The services otherwise look good and are running but the UI reports that Ops Agent wasn't actually running which I suspect is due to no data being sent back.

Here is the status of running agents:

google-cloud-ops-agent-opentelemetry-collector.service - Google Cloud Ops Agent - Metrics Agent
     Loaded: loaded (/lib/systemd/system/google-cloud-ops-agent-opentelemetry-collector.service; static; vendor preset: enabled)
     Active: active (running) since Sat 2022-02-05 04:38:41 UTC; 1 day 17h ago
    Process: 2690 ExecStartPre=/opt/google-cloud-ops-agent/libexec/google_cloud_ops_agent_engine -service=otel -in /etc/google-clou>
   Main PID: 2706 (otelopscol)
      Tasks: 9 (limit: 2369)
     Memory: 193.6M
     CGroup: /system.slice/google-cloud-ops-agent-opentelemetry-collector.service
             └─2706 /opt/google-cloud-ops-agent/subagents/opentelemetry-collector/otelopscol --config=/run/google-cloud-ops-agent-o>

Feb 06 21:55:53 mongo-1 otelopscol[2706]:         /root/go/pkg/mod/go.opentelemetry.io/collector@v0.42.0/exporter/exporterhelper/qu>
Feb 06 21:55:53 mongo-1 otelopscol[2706]: go.opentelemetry.io/collector/exporter/exporterhelper.(*metricsSenderWithObservability).s>
Feb 06 21:55:53 mongo-1 otelopscol[2706]:         /root/go/pkg/mod/go.opentelemetry.io/collector@v0.42.0/exporter/exporterhelper/me>
Feb 06 21:55:53 mongo-1 otelopscol[2706]: go.opentelemetry.io/collector/exporter/exporterhelper.(*queuedRetrySender).start.func1
Feb 06 21:55:53 mongo-1 otelopscol[2706]:         /root/go/pkg/mod/go.opentelemetry.io/collector@v0.42.0/exporter/exporterhelper/qu>
Feb 06 21:55:53 mongo-1 otelopscol[2706]: go.opentelemetry.io/collector/exporter/exporterhelper/internal.consumerFunc.consume
Feb 06 21:55:53 mongo-1 otelopscol[2706]:         /root/go/pkg/mod/go.opentelemetry.io/collector@v0.42.0/exporter/exporterhelper/in>
Feb 06 21:55:53 mongo-1 otelopscol[2706]: go.opentelemetry.io/collector/exporter/exporterhelper/internal.(*boundedMemoryQueue).Star>
Feb 06 21:55:53 mongo-1 otelopscol[2706]:         /root/go/pkg/mod/go.opentelemetry.io/collector@v0.42.0/exporter/exporterhelper/in>
Feb 06 21:55:53 mongo-1 otelopscol[2706]: 2022-02-06T21:55:53.145Z        info        exporterhelper/queued_retry.go:215        Exp>

● google-cloud-ops-agent.service - Google Cloud Ops Agent
     Loaded: loaded (/lib/systemd/system/google-cloud-ops-agent.service; enabled; vendor preset: enabled)
     Active: active (exited) since Sat 2022-02-05 04:38:41 UTC; 1 day 17h ago
    Process: 2691 ExecStartPre=/opt/google-cloud-ops-agent/libexec/google_cloud_ops_agent_engine -in /etc/google-cloud-ops-agent/co>
    Process: 2704 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
   Main PID: 2704 (code=exited, status=0/SUCCESS)

Feb 05 04:38:41 mongo-1 systemd[1]: Starting Google Cloud Ops Agent...
Feb 05 04:38:41 mongo-1 systemd[1]: Finished Google Cloud Ops Agent.
● google-cloud-ops-agent-fluent-bit.service - Google Cloud Ops Agent - Logging Agent
     Loaded: loaded (/lib/systemd/system/google-cloud-ops-agent-fluent-bit.service; static; vendor preset: enabled)
     Active: active (running) since Sun 2022-02-06 15:05:35 UTC; 6h ago
    Process: 22138 ExecStartPre=/opt/google-cloud-ops-agent/libexec/google_cloud_ops_agent_engine -service=fluentbit -in /etc/googl>
   Main PID: 22144 (fluent-bit)
      Tasks: 22 (limit: 2369)
     Memory: 29.0M
     CGroup: /system.slice/google-cloud-ops-agent-fluent-bit.service
             └─22144 /opt/google-cloud-ops-agent/subagents/fluent-bit/bin/fluent-bit --config /run/google-cloud-ops-agent-fluent-bi>

Feb 06 15:05:35 mongo-1 systemd[1]: google-cloud-ops-agent-fluent-bit.service: Scheduled restart job, restart counter is at 7.
Feb 06 15:05:35 mongo-1 systemd[1]: Stopped Google Cloud Ops Agent - Logging Agent.
Feb 06 15:05:35 mongo-1 systemd[1]: Starting Google Cloud Ops Agent - Logging Agent...
Feb 06 15:05:35 mongo-1 systemd[1]: Started Google Cloud Ops Agent - Logging Agent.
Feb 06 15:05:35 mongo-1 fluent-bit[22144]: Fluent Bit v1.8.12
Feb 06 15:05:35 mongo-1 fluent-bit[22144]: * Copyright (C) 2019-2021 The Fluent Bit Authors
Feb 06 15:05:35 mongo-1 fluent-bit[22144]: * Copyright (C) 2015-2018 Treasure Data
Feb 06 15:05:35 mongo-1 fluent-bit[22144]: * Fluent Bit is a CNCF sub-project under the umbrella of Fluentd
Feb 06 15:05:35 mongo-1 fluent-bit[22144]: * https://fluentbit.io


问:
Using curl to send xml data
I'm trying to do a propfind with curl.  I can get it to work provided I type all of my data on the same line (no newlines) and escape () any quotation marks. What I would like to do is specify my data to send in a text file or something so I can type it out in some legible way and then have curl use it.

I know curl can read from a file like this:

```<code>curl --user username:password --header "Content-Type: text/xml" --request PROPFIND https://whatevermyurlis.com --data-urlencode @blah.txt
</code>```

but I keep getting Bad Request back.  Document is empty, line 1, column 1

答: Apparently it doesn't like text files...I changed it to .xml and it worked fine.</p>

Title: Using curl to send xml data

Body:
I'm trying to do a propfind with curl.  I can get it to work provided I type all of my data on the same line (no newlines) and escape () any quotation marks. What I would like to do is specify my data to send in a text file or something so I can type it out in some legible way and then have curl use it.

I know curl can read from a file like this:

curl --user username:password --header "Content-Type: text/xml" --request PROPFIND https://whatevermyurlis.com --data-urlencode @blah.txt

but I keep getting Bad Request back.  Document is empty, line 1, column 1


问:
partial search and lowercase search in nodejs
I'm trying to implement multiple search functionality such as userName and userId with separate input for userName and userId. If I give userName as "Dave Steve" or "dave steve" or "Dave" or "steve" or "dav" and click on the search button I should get the result But When I give "Dave steve" it working fine but not with other case How do I implement it ?

Json data:

```<code>let logData={
"dataLog":
[
    {
        "userId":"1",
        "userName":"Dave Steve",
    },
    {
        "userId":"2",
        "userName":"John Doe",
    }
],
}
</code>```

Here is my code

```<code>app.get('/getData', (req, res) => {
  let accessData= logData.dataLog;
  let userName = req.query.userName;
  let userId = req.query.userId;
    console.log(userName, userId)
    let filterData = accessData.filter((data) => {
      return (userId === undefined || data.userId === userId) &&
        (userName === undefined || userName === userNameData)
    })
    console.log(filterData)
    const response = {
      header: getSuccessHeader,
      body: filterData
    };
    res.status(200);
    res.send(response);
});
</code>```

答:
Here is an implemented stackblitz link for you, go through it.

The comparison need to happen with both cases with an or statement :

```<code>userName.toLowerCase() === data.userName.toLowerCase() ||
userName.toLowerCase().indexOf(data.userName.toLowerCase()) === -1
</code>```

Body:
I'm trying to implement multiple search functionality such as userName and userId with separate input for userName and userId. If I give userName as "Dave Steve" or "dave steve" or "Dave" or "steve" or "dav" and click on the search button I should get the result But When I give "Dave steve" it working fine but not with other case How do I implement it ?

Json data:

let logData={
"dataLog":
[
    {
        "userId":"1",
        "userName":"Dave Steve",
    },
    {
        "userId":"2",
        "userName":"John Doe",
    }
],
}

Here is my code

app.get('/getData', (req, res) => {
  let accessData= logData.dataLog;
  let userName = req.query.userName;
  let userId = req.query.userId;
    console.log(userName, userId)
    let filterData = accessData.filter((data) => {
      return (userId === undefined || data.userId === userId) &&
        (userName === undefined || userName === userNameData)
    })
    console.log(filterData)
    const response = {
      header: getSuccessHeader,
      body: filterData
    };
    res.status(200);
    res.send(response);
});

Body:
Here is an implemented stackblitz link for you, go through it.

The comparison need to happen with both cases with an or statement :

userName.toLowerCase() === data.userName.toLowerCase() ||
userName.toLowerCase().indexOf(data.userName.toLowerCase()) === -1


问:
React app stuck on "Starting the development server"
I have a react app created by create-react-app. After running npm start (the start script is present in package.json as "start": "react-scripts start") the console says Starting the development server as usual and fires up the browser. But after this both the console and the browser do absolutely nothing indefinitely. No error or output. It simply does nothing.</p>

答:
Here are tow points checked:

Remove package.lock and node_modules, re-install: npm i.

Check the node version. Maybe you currently use version is 12.0.0, but this project limited 14.0.0.


问:
How To Get Last Inserted Row From Table Using LINQ?
Employee

Empid | EmployeeName

1-------------Ron

2------------John

Department

Depid | DepartmentName | Status| Empid

1---------------Account--------- 1---------1

2---------------HR----------------1---------1

3---------------Finance----------1---------2

4---------------Design-----------1---------2

Here I have two table Employee and Department. One employee can be in different department such as empid = 1 in two department i.e account and hr similarly empid = 2 in two department i.e finance and design .
 Now, for example since empid = 1 is inserted in depid = 1 and depid = 2 but I am tryingto get depid = 2 which is last inserted row for empid = 2.Similarly, for empid = 2 last row of department which is depid = 4.

Now, the problem is that my LINQ join doesnot give the required output.

Since i am very much new to Linq, help will be highly appreciated.Thank you

Below is my LINQ Join

```<code> var empDepList = (from D in db.Department.Where(x => x.Status == 1)
                   join E in db.Employee on D.Empid equals E.Empid
                   select new
                   {
                     D.DepartmentName, E.EmployeeName
                   }).ToList();
</code>```

答:
```<code>context.MyTable.Find(context.MyTable.Max(p => p.Id));
</code>```

Body:
Employee

Empid | EmployeeName

1-------------Ron

2------------John

Department

Depid | DepartmentName | Status| Empid

1---------------Account--------- 1---------1

2---------------HR----------------1---------1

3---------------Finance----------1---------2

4---------------Design-----------1---------2

Here I have two table Employee and Department. One employee can be in different department such as empid = 1 in two department i.e account and hr similarly empid = 2 in two department i.e finance and design .
 Now, for example since empid = 1 is inserted in depid = 1 and depid = 2 but I am tryingto get depid = 2 which is last inserted row for empid = 2.Similarly, for empid = 2 last row of department which is depid = 4.

Now, the problem is that my LINQ join doesnot give the required output.

Since i am very much new to Linq, help will be highly appreciated.Thank you

Below is my LINQ Join

 var empDepList = (from D in db.Department.Where(x => x.Status == 1)
                   join E in db.Employee on D.Empid equals E.Empid
                   select new
                   {
                     D.DepartmentName, E.EmployeeName
                   }).ToList();