问:
React & Axios api call not updating hooks before rendering
I'm newer to React and Axios, but I'm currently working on a personal project where I use a stock market API to get the current price of a stock after hitting submit on the form. When I make an api call, both of my hooks price and total do not get updated prior to rendering the data on the page. I'm unsure why this is happening because inside of my callback function in the .then block I update both the price and total hooks based off of the responses from the API.

Ultimately when I try to add another stock to my table, it uses the previous price and total that should have been calculated for the stock prior. I appreciate any help or explanation on why this happens.

```<code>import React, { Component, useState, useEffect } from 'react';
import axios from 'axios';

function StockData(props) {
  const [ticker, setTicker] = useState();
  const [quantity, setQuantity] = useState(0);
  const [price, setPrice] = useState(0);
  const [total, setTotal] = useState(0);
  const [data, updateData] = useState([]);

  // handles form on click function to add another stock to the portfolio
  const HandleSubmit = (e) => {
    e.preventDefault();

    const stockData =
      'https://api.polygon.io/v2/aggs/ticker/' +
      ticker +
      '/prev?adjusted=true&apiKey=SuaIlAqCImCfcixB2Qn3FBuZP1mkqkfl';

    // makes get request call to polygon.io api to get stock data
    // console.log('axios request');
    axios
      .get(stockData)
      .then((response) => {
        // represents the stock ticker
        console.log(response.data.results[0]['T']);

        // this represents the stock closing price
        setPrice(response.data.results[0]['c']);

        // calculate the total of purchasing price*quantity
        let currTotal = price * quantity;
        setTotal(currTotal);

        let stock = [ticker, quantity, price, total];
        updateData([...data, stock]);
        // console.log(ticker, quantity, price, total);
      })
      .catch((error) => {
        console.log(error);
      });
    console.log(data);
  };

 return (
    <div>
      <form>
        <label>Add a Stock: </label>
        <input
          type='text'
          placeholder='Enter a Stock Ticker'
          name='ticker'
          value={ticker}
          onChange={(e) => setTicker(e.target.value.toUpperCase())}
        />
        <input
          type='number'
          placeholder='Quantity'
          name='quantity'
          value={quantity}
          onChange={(e) => setQuantity(e.target.value)}
        />
        <input type='submit' onClick={HandleSubmit}></input>
      </form>
      <div className='stock-list'>
        <table>
          <thead>
            <tr>
              <th>Ticker</th>
              <th>Quantity</th>
              <th>Price</th>
              <th>Total</th>
            </tr>
          </thead>
          <tbody>
            {data.map((stock) => (
              <tr>
                <td>{stock[0]}</td>
                <td>{stock[1]}</td>
                <td>{stock[2]}</td>
                <td>{stock[3]}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
export default StockData;

</code>```

答:
I can't comment, I just arrive on StackO, so I use response to talk with you about your trouble.
Do you try to put every setState on chaining.then like that :

```<code>.then(res => setState(res))
.then(res => setState2(res))
...
</code>```

Say me

Body:
I'm newer to React and Axios, but I'm currently working on a personal project where I use a stock market API to get the current price of a stock after hitting submit on the form. When I make an api call, both of my hooks price and total do not get updated prior to rendering the data on the page. I'm unsure why this is happening because inside of my callback function in the .then block I update both the price and total hooks based off of the responses from the API.

Ultimately when I try to add another stock to my table, it uses the previous price and total that should have been calculated for the stock prior. I appreciate any help or explanation on why this happens.

import React, { Component, useState, useEffect } from 'react';
import axios from 'axios';

function StockData(props) {
  const [ticker, setTicker] = useState();
  const [quantity, setQuantity] = useState(0);
  const [price, setPrice] = useState(0);
  const [total, setTotal] = useState(0);
  const [data, updateData] = useState([]);

  // handles form on click function to add another stock to the portfolio
  const HandleSubmit = (e) => {
    e.preventDefault();

    const stockData =
      'https://api.polygon.io/v2/aggs/ticker/' +
      ticker +
      '/prev?adjusted=true&apiKey=SuaIlAqCImCfcixB2Qn3FBuZP1mkqkfl';

    // makes get request call to polygon.io api to get stock data
    // console.log('axios request');
    axios
      .get(stockData)
      .then((response) => {
        // represents the stock ticker
        console.log(response.data.results[0]['T']);

        // this represents the stock closing price
        setPrice(response.data.results[0]['c']);

        // calculate the total of purchasing price*quantity
        let currTotal = price * quantity;
        setTotal(currTotal);

        let stock = [ticker, quantity, price, total];
        updateData([...data, stock]);
        // console.log(ticker, quantity, price, total);
      })
      .catch((error) => {
        console.log(error);
      });
    console.log(data);
  };

 return (

      <form>
        Add a Stock:
        <input
          type='text'
          placeholder='Enter a Stock Ticker'
          name='ticker'
          value={ticker}
          onChange={(e) => setTicker(e.target.value.toUpperCase())}
        />
        <input
          type='number'
          placeholder='Quantity'
          name='quantity'
          value={quantity}
          onChange={(e) => setQuantity(e.target.value)}
        />
        <input type='submit' onClick={HandleSubmit}></input>
      </form>

              Ticker
              Quantity
              Price
              Total

            {data.map((stock) => (

                {stock[0]}
                {stock[1]}
                {stock[2]}
                {stock[3]}

            ))}

  );
}
export default StockData;

Body:
I can't comment, I just arrive on StackO, so I use response to talk with you about your trouble.
Do you try to put every setState on chaining.then like that :

.then(res => setState(res))
.then(res => setState2(res))
...

Say me


来源: stackexchange

问:
How do I decrease the height of mat-select in angular material, not the options inside it?
Have tried a solution I saw on Stack Overflow but it only decreased the height of the options inside the mat-select.

Thank you in advance.

```<code><mat-form-field *ngIf="!isLoading" appearance="fill">
    <mat-label>Sort by Type</mat-label>
    <mat-select
        panelClass="sel"
        name="selected"
        [(ngModel)]="selected"
        (selectionChange)="onChangeSelect()"
    >
        <mat-option value="">All</mat-option>
        <mat-option value="Db">Debit</mat-option>
        <mat-option value="Cr">Credit</mat-option>
    </mat-select>
</mat-form-field>
</code>```

答:
Late reply for future users

You should add the following code in your div

```<code>style="font-size: 10px"
</code>```

click this link to view the differences
Link to stackblitz

Result image

ContentLicense: CC BY-SA 4.0

Body:
Have tried a solution I saw on Stack Overflow but it only decreased the height of the options inside the mat-select.

Thank you in advance.

<mat-form-field *ngIf="!isLoading" appearance="fill">
    <mat-label>Sort by Type</mat-label>
    <mat-select
        panelClass="sel"
        name="selected"
        [(ngModel)]="selected"
        (selectionChange)="onChangeSelect()"
    >
        <mat-option value="">All</mat-option>
        <mat-option value="Db">Debit</mat-option>
        <mat-option value="Cr">Credit</mat-option>
    </mat-select>
</mat-form-field>

Body:
Late reply for future users

You should add the following code in your div

style="font-size: 10px"

click this link to view the differences
Link to stackblitz

Result image


问:
How do I check if a variable has gone up?
here is some code. I want to make an if statement but only when a variable has increased</p>
```<code>while True:
    a += 1

    if a ????
        print('a has changed')

</code>```

答:
A more clever way using the python Observer pattern.

```<code>class observe_value_change():
   def __init__(self):
      self._initial = 1

   @property
   def position(self):
      return self._initial

   @position.setter
   def position(self, new_value):
      self._initial = new_value
      print("execute more code here!")
      print(self._initial)
</code>```

To test

```<code>p = observe_value_change()
print(p.position)
p.position = 4
</code>```

Explanation:
When the value of position changes, it will call the position setter method otherwise it will not be called.
So, the if block can be written inside the position setter method.

Body:
here is some code. I want to make an if statement but only when a variable has increased

while True:
    a += 1

    if a ????
        print('a has changed')

Body:
A more clever way using the python Observer pattern.

class observe_value_change():
   def __init__(self):
      self._initial = 1

   @property
   def position(self):
      return self._initial

   @position.setter
   def position(self, new_value):
      self._initial = new_value
      print("execute more code here!")
      print(self._initial)

To test

p = observe_value_change()
print(p.position)
p.position = 4

Explanation:
When the value of position changes, it will call the position setter method otherwise it will not be called.
So, the if block can be written inside the position setter method.


问:
How can I push values into nested array with JavaScript?
I have the following code and I'm attempting to push randomly generated numbers into the data array. I'm just not quite sure on how to access the array. I know my code is probably very sloppy and inefficient, but I'm trying my best to learn and got stuck on this. I'd really appreciate any help.</p>
```<code><script>
  var balance = 0;

  function nextDay() {
    var dayCount = 0;
    if (dayCount < 5) {
      randNum = Math.random() * (max - min) + min;
      console.log(randNum);
      max = randNum + 50;
      min = randNum - 50;
      dayCount++;
    }
  }

  function sell() {
    balance = balance + randNum;
    console.log("current balance:" + balance);
    randNum = 0;
    max = randNum + 50;
    min = randNum - 50;
  }

  const startingValues = [];
  function getStartingValues() {
    var max = 100;
    var min = -100;
    for (let startingCount = 0; startingCount < 8; startingCount++) {
      var randNum = Math.random() * (max - min) + min;
      max = randNum + 500;
      min = randNum - 100;
      data.datasets[3].data.push(randNum);
      console.log(startingValues[startingCount]);
    }
  }
  getStartingValues();

  const labels = ["Week 1", "Week 2", "Week 3", "Week 4", "Week 5", "Week 6"];

  const data = {
    labels: labels,
    datasets: [
      {
        label: "graph",
        backgroundColor: "rgb(255, 99, 132)",
        borderColor: "rgb(255, 99, 132)",
        data: [],
      },
    ],
  };

  const config = {
    type: "line",
    data: data,
    options: {},
  };
</script>
</code>```

答:
Using the Array constructor you can create nested arrays (There are other ways as well).

  const data = [];
  const startingValues = [];

function getStartingValues() {
    var max = 100
    var min = -100
    for (let i = 0; i <= 7; i++) {

        data[i] = Math.random() * (max - min) + min;
    }
    //Add data as nested arrray to startingValues
    startingValues[0] = new Array(data);
}

getStartingValues();
console.log(startingValues); //Starting values is a 1x8 nested array```


问:
How do I add a pre tag inside a code tag with jQuery?
I'm trying to use jQuery to format code blocks, specifically to add a ```</code> tag inside the <code><code></code> tag:</p>

```$(document).ready(function() {
   $("code").wrapInner("``````");
});
```

<p>Firefox applies the formatting correctly, but IE puts the entire code block on one line. If I add an alert  </p>

```alert($("code").html());
```

<p>I see that IE has inserted some additional text into the pre tag:</p>

```

```

<p>If I reload the page, the number following jQuery changes.</p>

<p>If I use <code>wrap()</code> instead of <code>wrapInner()</code>, to wrap the <code>``` outside the  tag, both IE and Firefox handle it correctly. But shouldn't ```</code> work <em>inside</em> <code><code></code> as well?</p>

<p>I'd prefer to use <code>wrapInner()</code> because I can then add a CSS class to the <code>``` tag to handle all formatting, but if I use wrap(), I have to put page formatting CSS in the ``` tag and text/font formatting in the  tag, or Firefox and IE both choke. Not a huge deal, but I'd like to keep it as simple as possible.

Has anyone else encountered this? Am I missing something?

答:
You could use html() to wrap it:

```<code>$('code').each(function(i,e)
{
    var self = $(e);
    self.html('```' + self.html() + '```');
});
</code>```

As mentioned above, you'd be better off changing your html. But this solution should work.

OwnerDisplayName: aardvark

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to use jQuery to format code blocks, specifically to add a
 tag inside the  tag:

$(document).ready(function() {
   $("code").wrapInner("

");
});

Firefox applies the formatting correctly, but IE puts the entire code block on one line. If I add an alert

alert($("code").html());

I see that IE has inserted some additional text into the pre tag:

If I reload the page, the number following jQuery changes.

If I use wrap() instead of wrapInner(), to wrap the
 outside the  tag, both IE and Firefox handle it correctly. But shouldn't
 work inside  as well?

I'd prefer to use wrapInner() because I can then add a CSS class to the
 tag to handle all formatting, but if I use wrap(), I have to put page formatting CSS in the
 tag and text/font formatting in the  tag, or Firefox and IE both choke. Not a huge deal, but I'd like to keep it as simple as possible.

Has anyone else encountered this? Am I missing something?

LastEditorDisplayName: aardvark

Body:
You could use html() to wrap it:

$('code').each(function(i,e)
{
    var self = $(e);
    self.html('<pre>' + self.html() + '</pre>');
});

As mentioned above, you'd be better off changing your html. But this solution should work.


问:
Detection of reload button pressed in Java Script
How to detect whether the reload button is pressed and after that the the processes be held and after that reload. Like when reload is pressed or Ctrl + R then I want to save that it is reloaded in local storage.</p>

答:
The event handler for processing onbeforeunload events is the WindowEventHandlers mixin's onbeforeunload property. When a window is about to unload its resources, these events are triggered.

```<code>window.onbeforeunload = function(m) {
  return 'Your Statement';
};
</code>```

And you can refer to Mozilla docs for more because you didn't shared your source code. https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

Body:
The event handler for processing onbeforeunload events is the WindowEventHandlers mixin's onbeforeunload property. When a window is about to unload its resources, these events are triggered.

window.onbeforeunload = function(m) {
  return 'Your Statement';
};

And you can refer to Mozilla docs for more because you didn't shared your source code. https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload


问:
What does it " tk.Frame.__init__(self, *args, **kwargs) " mean?
I am a newbie. I've seen         tk.Frame.__init__(self, *args, **kwargs) this code here.
I am really confused. What exactly this would do?

答:
This is fundamental part of python's standard way of creating subclasses. It doesn't really have anything specific to do with tkinter. However, if you subclass a tkinter class -- like with any class -- this will make sure that the base class is properly initialized.

What you're seeing, however, is an older style of initializing a base class. For python 3.x and beyond you should be using something like super().__init__(*args, **kwargs). See super and the description of Class objects in the standard python documentation.


问:
How to parse the file name string from a file path in shell script?
I have files in directory  'new_kb'. I want to iterate on each file and execute a c++ binary on the file, like below:

```<code>kb_dir=./new_kb
for entry in "$kb_dir"/*
do
  echo "$entry"
   $file_name  = parse(entry)
  ./build "$file_name"/"$file_name".txt
  done
</code>```

One example of 'entry' is:

```<code>./new_kb/peopleObj.txt
</code>```

from the variable path 'entry', I need to parse the string below out:

```<code>'peopleObj'
</code>```

How to do this in a shell script?

答:
Using shell built in parameter expansion:

```<code>file_name=${entry##*/}
file_name=${file_name%.txt}
</code>```

Using basename(1):

```<code>file_name=$(basename "$entry" .txt)
</code>```

Note that whitespace is fundamental to how shell commands are parsed, and all variable declarations should have no whitespace around =.

Body:
I have files in directory  'new_kb'. I want to iterate on each file and execute a c++ binary on the file, like below:

kb_dir=./new_kb
for entry in "$kb_dir"/*
do
  echo "$entry"
   $file_name  = parse(entry)
  ./build "$file_name"/"$file_name".txt
  done

One example of 'entry' is:

./new_kb/peopleObj.txt

from the variable path 'entry', I need to parse the string below out:

'peopleObj'

How to do this in a shell script?

Body:
Using shell built in parameter expansion:

file_name=${entry##*/}
file_name=${file_name%.txt}

Using basename(1):

file_name=$(basename "$entry" .txt)

Note that whitespace is fundamental to how shell commands are parsed, and all variable declarations should have no whitespace around =.


问:
What PHP function(s) should I use to cut off the end of a string?
I have a filename stored with the directory as a value.

Ex. /var/www/remove_this.php

In my PHP script I want to remove everthing after the last '/', so I can use mkdir on this path without creating a directory from the filename also.

There are so many string editing functions, I don't know a good approach. Thanks!

答:
```<code><?php
$file="/var/www/remove_this.php";
$folder=dirname($var);
if (!file_exsts($folder))
{
  if (mkdir($folder,777,true))
  {
    echo "Folder created\n";
  } else
  {
    echo "Folder creation failed\n";
  }
} else
{
  echo "Folder exists already\n";
}
?>
</code>```


答:
Here is a way you can do this:</p>
```<code>while True:
    old_a = a #Create a variable for the old value of a
    a += 1

    if a > old_a: #Check the condition if value of a has increased.
        print('a has changed')
</code>```

Title: How do I check if a variable has gone up?

Body:
Here is a way you can do this:

while True:
    old_a = a #Create a variable for the old value of a
    a += 1

    if a > old_a: #Check the condition if value of a has increased.
        print('a has changed')


问:
AdMob "Cannot find an ad network adapter" and "No ad to show" error
My app has been showing ads for months without issue, but now it never shows. My ads were cut when my app's earnings increased. Could this have anything to do with earnings? I don't see a problem in my policy center.

Even with test ids, ads don't appear. I have this problem with banner ads and interstitials ads.

Debug mode errors:

"Request Error: No ad to show."

<Google> Cannot find an ad network adapter with the name(s): com.google.DummyAdapter. Remember to link all required ad network adapters and SDKs, and set -ObjC in the 'Other Linker Flags' setting of your build target.

I searched for these errors but found the answers didn't fix the error.

答:
Add Your Google AdMob ads.txt in website.
Set Up your APP-ADS.TXT And add it on Meta Tags</p>


问:
How does this nested loop output a list separated into 3 sections with 3 words in each section?
I'm very new to C#. I was curious on how this block of code printed out 3 separate lines with the 3 words in the arrays. Could someone explain how it works?

```<code>using System;

namespace MyFirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {

            String[,] parkingLot = {{ "Mustang", "F-150", "Explorer" }, { "Corvette", "Camaro", "Silverado" }, { "Corolla", "Camry", "Rav4" }};

            for(int i = 0; i < parkingLot.GetLength(0); i++)
            {
                for (int j = 0; j < parkingLot.GetLength(1); j++)
                {
                    Console.Write(parkingLot[i, j] + " ");
                }
                Console.WriteLine();
            }

            Console.ReadKey();
        }
    }
}```
```

答:
I'm going to break this down into each line of the code, and explain what it does.

```<code>String[,] parkingLot = { { "Mustang", "F-150", "Explorer" }, { "Corvette", "Camaro", "Silverado" }, { "Corolla", "Camry", "Rav4" } };
</code>```

parkingLot is a multi-dimensional string Array. This means this is a string array that hold other arrays of type string. Think of each {} within the bigger {} its own Array object that can be accessed.

```<code>for (int i = 0; i < parkingLot.GetLength(0); i++)
</code>```

For loops are designed to loop through a specified number of elements. the integer "i" created at the start indicates that the loop will start at index 0. We start at 0 because array indexing starts at 0.

The duration of this loop lasts as long as the number of arrays ({}) in the initialised array. In this case, because parkingLot contains 3 arrays, the length is 3.

```<code>for (int j = 0; j < parkingLot.GetLength(1); j++)
</code>```

This part of the code iterates within the for-loop above it, and iterates over every element inside a single array. The "GetLength(1)" part of the code grabs the length of a single array instance within the overall array. For example: the first array instance in this multi-dimensions array contains { "Mustang", "F-150", "Explorer" }, being 3 strings. Therefore, the length will also be 3.

```<code>Console.Write(parkingLot[i, j] + " ");
</code>```

Here, we can see that there's a reference to i and j. Let me show you what happens step by step:

when i=0, the code begins to iterate another loop, which must compute j = 0, j = 1 and j = 2 before moving to i = 1. This means that it must read every element in the array before moving to the next array.

For Example: say:

i = 0, and j = 0. this would be accessing "Mustang"

i = 1, and j = 2 would be accessing "Silverado"

i = 2 and j = 1 would be accessing "Camry"

```<code>Console.WriteLine();
</code>```

After writing each element in the j loop, this piece of code writes the responses to the console. That's why each elements of arrays appear on one line.

```<code>Console.ReadKey();
</code>```

After you press this key, the program closes.

I suggest you play around with the variables and create your own arrays and multi-dimensional arrays. That way you can see how they operate and what they don't like you doing with them.

Body:
I'm very new to C#. I was curious on how this block of code printed out 3 separate lines with the 3 words in the arrays. Could someone explain how it works?

using System;

namespace MyFirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {

            String[,] parkingLot = {{ "Mustang", "F-150", "Explorer" }, { "Corvette", "Camaro", "Silverado" }, { "Corolla", "Camry", "Rav4" }};

            for(int i = 0; i < parkingLot.GetLength(0); i++)
            {
                for (int j = 0; j < parkingLot.GetLength(1); j++)
                {
                    Console.Write(parkingLot[i, j] + " ");
                }
                Console.WriteLine();
            }

            Console.ReadKey();
        }
    }
}```

Body:
I'm going to break this down into each line of the code, and explain what it does.

String[,] parkingLot = { { "Mustang", "F-150", "Explorer" }, { "Corvette", "Camaro", "Silverado" }, { "Corolla", "Camry", "Rav4" } };

parkingLot is a multi-dimensional string Array. This means this is a string array that hold other arrays of type string. Think of each {} within the bigger {} its own Array object that can be accessed.

for (int i = 0; i < parkingLot.GetLength(0); i++)

For loops are designed to loop through a specified number of elements. the integer "i" created at the start indicates that the loop will start at index 0. We start at 0 because array indexing starts at 0.

The duration of this loop lasts as long as the number of arrays ({}) in the initialised array. In this case, because parkingLot contains 3 arrays, the length is 3.

for (int j = 0; j < parkingLot.GetLength(1); j++)

This part of the code iterates within the for-loop above it, and iterates over every element inside a single array. The "GetLength(1)" part of the code grabs the length of a single array instance within the overall array. For example: the first array instance in this multi-dimensions array contains { "Mustang", "F-150", "Explorer" }, being 3 strings. Therefore, the length will also be 3.

Console.Write(parkingLot[i, j] + " ");

Here, we can see that there's a reference to i and j. Let me show you what happens step by step:

when i=0, the code begins to iterate another loop, which must compute j = 0, j = 1 and j = 2 before moving to i = 1. This means that it must read every element in the array before moving to the next array.

For Example: say:

i = 0, and j = 0. this would be accessing "Mustang"

i = 1, and j = 2 would be accessing "Silverado"

i = 2 and j = 1 would be accessing "Camry"

Console.WriteLine();

After writing each element in the j loop, this piece of code writes the responses to the console. That's why each elements of arrays appear on one line.

Console.ReadKey();

After you press this key, the program closes.

I suggest you play around with the variables and create your own arrays and multi-dimensional arrays. That way you can see how they operate and what they don't like you doing with them.


问:
How to add key values pair in object in JAVASCRIPT?
how can I push keys and values in an empty object?

You are provided with an array, possibleIterable. Using a for loop, build out the object divByThree so that each key is an element of possibleIterable that is divisible by three. The value of each key should be the array index at which that key can be found in possibleIterable.

```<code>const possibleIterable = [4, 3, 9, 6, 23];
const divByThree = {};
// ADD CODE HERE
for (let i =0 ; i < possibleIterable.length; i++)
  {
    if (possibleIterable[i] % 3 === 0)
   {
      // ADD CODE HERE!

      }
  }
console.log(divByThree)
</code>```

答:
```<code>for (let i = 0; i < possibleIterable.length; i++) {
  if (possibleIterable[i] % 3 === 0) {
    divByThree[possibleIterable[i]] = i;
  }
}
</code>```

This is probably what you were looking for. This assigns new key-value pairs, where the key is an element in possibleIterable that is divisible by 3 and the value is the index position of that element.

So if you console.log(divByThree), it should print out

```<code>{ 3: 1, 6: 3, 9: 2 }
</code>```

I understand that this is an old post, but thought I should give an answer for anyone looking in the future.

Body:
how can I push keys and values in an empty object?

You are provided with an array, possibleIterable. Using a for loop, build out the object divByThree so that each key is an element of possibleIterable that is divisible by three. The value of each key should be the array index at which that key can be found in possibleIterable.

const possibleIterable = [4, 3, 9, 6, 23];
const divByThree = {};
// ADD CODE HERE
for (let i =0 ; i < possibleIterable.length; i++)
  {
    if (possibleIterable[i] % 3 === 0)
   {
      // ADD CODE HERE!

      }
  }
console.log(divByThree)

Body:
for (let i = 0; i < possibleIterable.length; i++) {
  if (possibleIterable[i] % 3 === 0) {
    divByThree[possibleIterable[i]] = i;
  }
}

This is probably what you were looking for. This assigns new key-value pairs, where the key is an element in possibleIterable that is divisible by 3 and the value is the index position of that element.

So if you console.log(divByThree), it should print out

{ 3: 1, 6: 3, 9: 2 }

I understand that this is an old post, but thought I should give an answer for anyone looking in the future.


问:
Change font size if the text exceeds the boundary of Textblock
I have a textblock with a dimension of Width=511, Height=159. FontSize=28. I want to change the font size if the text exceeds the dimension of the textblock so that all the text will be displayed. Is there a way of doing this? A formula maybe?</p>

答:
It depends on what font face you use, for instance, Courier New is designed to have each character the same width, so if you do research about what the width per character is you can use the get length function for the string(giving you the length in characters) and from there calculate its width in pixels. If its width exceeds 511px the you adjust the size accordingly.

If you use a different font like Arial, you can do the same and if you really want it accurate, you can group the alphabet into narrow letters, like 'i', 'l' etc. and medium letters like 't' and fat letters like 'o' and the capitals. Then you get the number of narrow, medium and fat letters and calculate the size from that data, but personally, that's too much for me.

Hope this was helpful.

Edit: Ignore this one, I just read about the measurestring function, It's a much smaller effort than my suggestion.


问:
How to make ob_start() working with curl?
I have the following methods in my class:

```<code>public function __construct(){
    $this->handle = curl_init();
}

public function setOptArrayAndExecute(){

    $curlArray = curl_setopt_array(
            $this->handle,
            array(
                    CURLOPT_URL             => $this->getUrl(),
                    CURLOPT_USERAGENT       => $this->getUserAgent(),
                    CURLOPT_COOKIEJAR       => $this->getCookie(),
                    CURLOPT_COOKIEFILE      => $this->getCookie(),
                    CURLOPT_REFERER         => $this->getReferer(),
                    CURLOPT_TIMEOUT         => $this->getTimeOut(),
                    CURLOPT_FOLLOWLOCATION  => true
            )
    );
    ob_start(); //<-- Execution stops here
    curl_exec($this->handle);
    $this->response = ob_get_contents();
    curl_close($this->handle);
    ob_end_clean();
    return $this->response;
}
</code>```

So I just wrote down the specific part of code instead of the whole class.
I watched my php.ini: Output buffering is set 'On'. I also have error reporting activated:

```<code>error_reporting(E_ALL);
ini_set('display_errors', 1);
</code>```

My PHP Version is 5.4.3.
The script just stops at ob_start() without any notice or error report ...
I have no clue what I missed out or what I did wrong. I really apreciate your help.

答: Also, you forgot to set CURLOPT_CONNECTTIMEOUT, which can cause 5 minute long connect attempts, which will hang your script.</p>

Body:
I have the following methods in my class:

public function __construct(){
    $this->handle = curl_init();
}

public function setOptArrayAndExecute(){

    $curlArray = curl_setopt_array(
            $this->handle,
            array(
                    CURLOPT_URL             => $this->getUrl(),
                    CURLOPT_USERAGENT       => $this->getUserAgent(),
                    CURLOPT_COOKIEJAR       => $this->getCookie(),
                    CURLOPT_COOKIEFILE      => $this->getCookie(),
                    CURLOPT_REFERER         => $this->getReferer(),
                    CURLOPT_TIMEOUT         => $this->getTimeOut(),
                    CURLOPT_FOLLOWLOCATION  => true
            )
    );
    ob_start(); //<-- Execution stops here
    curl_exec($this->handle);
    $this->response = ob_get_contents();
    curl_close($this->handle);
    ob_end_clean();
    return $this->response;
}

So I just wrote down the specific part of code instead of the whole class.
I watched my php.ini: Output buffering is set 'On'. I also have error reporting activated:

error_reporting(E_ALL);
ini_set('display_errors', 1);

My PHP Version is 5.4.3.
The script just stops at ob_start() without any notice or error report ...
I have no clue what I missed out or what I did wrong. I really apreciate your help.


问:
First Unique Character in a String
Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.

```<code>first_unique('leetcode')  # 0
first_unique('loveleetcode')  # 2
</code>```

I came up with the following solution.  How can I make it more efficient for very long input strings?

```<code>def first_unique(self, s):
    if s == '':
        return -1

    for item in s:
        if s.count(item) == 1:
            return s.index(item)
            break

    return -1
</code>```

答:
The below code iterates the string and checks if the character is present anywhere else in the string. Once found, it will skip the current character and move to the next.</p>
```<code>def getUniqueCharacter(s):
    for i in range(len(s)):
        flag=0
        for j in range(len(s)):
            if i==j:
                continue
            if s[i]==s[j]:
                flag=1
                break
    if flag==0:
        return i
return -1
</code>```

Title: First Unique Character in a String

Body:
Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.

first_unique('leetcode')  # 0
first_unique('loveleetcode')  # 2

I came up with the following solution.  How can I make it more efficient for very long input strings?

def first_unique(self, s):
    if s == '':
        return -1

    for item in s:
        if s.count(item) == 1:
            return s.index(item)
            break

    return -1

Body:
The below code iterates the string and checks if the character is present anywhere else in the string. Once found, it will skip the current character and move to the next.

def getUniqueCharacter(s):
    for i in range(len(s)):
        flag=0
        for j in range(len(s)):
            if i==j:
                continue
            if s[i]==s[j]:
                flag=1
                break
    if flag==0:
        return i
return -1


问:
Can anyone tell me why I got this error in Flutter?
I got this error when I clicked my login button, I was expecting the validator would work but I just got this error every time I clicked my login button

```<code>════════ Exception caught by gesture ═══════════════════════════════════════════
The following _CastError was thrown while handling a gesture:
Null check operator used on a null value

When the exception was thrown, this was the stack
#0      _LoginPageState.build.<anonymous closure>
package:project_ukk/…/login/login_page.dart:153
#1      _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:989
#2      GestureRecognizer.invokeCallback
package:flutter/…/gestures/recognizer.dart:198
#3      TapGestureRecognizer.handleTapUp
package:flutter/…/gestures/tap.dart:608
#4      BaseTapGestureRecognizer._checkUp
package:flutter/…/gestures/tap.dart:296
#5      BaseTapGestureRecognizer.handlePrimaryPointer
package:flutter/…/gestures/tap.dart:230
#6      PrimaryPointerGestureRecognizer.handleEvent
package:flutter/…/gestures/recognizer.dart:563
#7      PointerRouter._dispatch
package:flutter/…/gestures/pointer_router.dart:94
#8      PointerRouter._dispatchEventToRoutes.<anonymous closure>
package:flutter/…/gestures/pointer_router.dart:139
#9      _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:539:8)
#10     PointerRouter._dispatchEventToRoutes
package:flutter/…/gestures/pointer_router.dart:137
#11     PointerRouter.route
package:flutter/…/gestures/pointer_router.dart:123
#12     GestureBinding.handleEvent
package:flutter/…/gestures/binding.dart:439
#13     GestureBinding.dispatchEvent
package:flutter/…/gestures/binding.dart:419
#14     RendererBinding.dispatchEvent
package:flutter/…/rendering/binding.dart:322
#15     GestureBinding._handlePointerEventImmediately
package:flutter/…/gestures/binding.dart:374
#16     GestureBinding.handlePointerEvent
package:flutter/…/gestures/binding.dart:338
#17     GestureBinding._flushPointerEventQueue
package:flutter/…/gestures/binding.dart:296
#18     GestureBinding._handlePointerDataPacket
package:flutter/…/gestures/binding.dart:279
#22     _invoke1 (dart:ui/hooks.dart:170:10)
#23     PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:331:7)
#24     _dispatchPointerDataPacket (dart:ui/hooks.dart:94:31)
(elided 3 frames from dart:async)
Handler: "onTap"
Recognizer: TapGestureRecognizer#db891
    debugOwner: GestureDetector
    state: possible
    won arena
    finalPosition: Offset(296.1, 619.7)
    finalLocalPosition: Offset(266.1, 36.2)
    button: 1
    sent tap down
</code>```

This is my login_page.dart

```<code>import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:project_ukk/constants/color_constant.dart';
import 'package:project_ukk/constants/font_and_padding.dart';
import 'package:project_ukk/pages/reset_password/reset_password.dart';
import 'package:project_ukk/pages/signUp/signup_page.dart';
import 'package:project_ukk/pages/user_page/navbar.dart';
import 'package:flutter_svg/svg.dart';

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

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  //Form Key
  final _formKey = GlobalKey<FormState>();

  var email = "";
  var password = "";

  final emailController = TextEditingController();
  final passwordController = TextEditingController();

  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    emailController.dispose();
    passwordController.dispose();
    super.dispose();
  }

  clearText() {
    emailController.clear();
    passwordController.clear();
  }

  userLogin() async {
    try {
      await FirebaseAuth.instance
          .signInWithEmailAndPassword(email: email, password: password);
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => PageNavBar(),
        ),
      );
    } on FirebaseAuthException catch (e) {
      if (e.code == 'user-not-found') {
        print("No User Found for that Email");
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            backgroundColor: Colors.orangeAccent,
            content: Text(
              "No User Found for that Email",
              style: TextStyle(fontSize: 18.0, color: Colors.black),
            ),
          ),
        );
      } else if (e.code == 'wrong-password') {
        print("Wrong Password Provided by User");
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            backgroundColor: Colors.orangeAccent,
            content: Text(
              "Wrong Password Provided by User",
              style: TextStyle(fontSize: 18.0, color: Colors.black),
            ),
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    //Email Field
    final emailField = TextFormField(
      autofocus: false,
      controller: emailController,
      keyboardType: TextInputType.emailAddress,
      validator: (value) {
        if (value == null || value.isEmpty) {
          return 'Please Enter Email';
        } else if (!value.contains('@')) {
          return 'Please Enter Valid Email';
        }
        return null;
      },
      textInputAction: TextInputAction.next,
      decoration: InputDecoration(
        prefixIcon: Icon(Icons.mail),
        contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
        hintText: "Email",
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
        ),
      ),
    );
    //Password Field
    final passwordField = TextFormField(
      autofocus: false,
      controller: passwordController,
      obscureText: true,
      validator: (value) {
        if (value == null || value.isEmpty) {
          return 'Please Enter Password';
        }
        return null;
      },
      textInputAction: TextInputAction.next,
      decoration: InputDecoration(
        prefixIcon: Icon(Icons.vpn_key),
        contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
        hintText: "Password",
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
        ),
      ),
    );
    final loginButton = Material(
      elevation: 2,
      borderRadius: BorderRadius.circular(50),
      child: Container(
        width: MediaQuery.of(context).size.width,
        height: 60,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(50),
          gradient: LinearGradient(
            colors: const [kDarkModerateCyan, kModerateCyan],
            begin: Alignment.centerLeft,
            end: Alignment.centerRight,
          ),
        ),
        child: Material(
          borderRadius: BorderRadius.circular(50),
          color: Colors.transparent,
          child: Center(
            child: MaterialButton(
              child: Text(
                "Login",
                textAlign: TextAlign.center,
                style: textButton,
              ),
              padding: EdgeInsets.fromLTRB(20, 10, 20, 15),
              minWidth: MediaQuery.of(context).size.width,
              onPressed: () {
                // Validate returns true if the form is valid, otherwise false.
                if (_formKey.currentState!.validate()) {
                  setState(() {
                    email = emailController.text;
                    password = passwordController.text;
                  });
                  userLogin();
                }
              },
            ),
          ),
        ),
      ),
    );
    final forgotPassword = Container(
      padding: EdgeInsets.symmetric(
        vertical: 10,
      ),
      child: GestureDetector(
        onTap: () => {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => ResetPassword(),
            ),
          ),
        },
        child: Text(
          'Forgot Password ?',
          style: TextStyle(
            decoration: TextDecoration.underline,
            color: Colors.grey,
          ),
        ),
      ),
    );
    final registerNow = Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text(
          "Don't have an account? ",
          style: TextStyle(color: Colors.grey),
        ),
        GestureDetector(
          child: Text(
            "Register Now",
            style: TextStyle(
              color: kPrimaryColor,
              fontWeight: FontWeight.bold,
              fontSize: 15,
            ),
          ),
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => SignUpPage(),
              ),
            );
          },
        ),
      ],
    );

    return Scaffold(
      backgroundColor: kWhiteColor,
      body: Stack(
        key: _formKey,
        children: <Widget>[
          SingleChildScrollView(
            child: Column(
              children: <Widget>[
                Container(
                  width: MediaQuery.of(context).size.width,
                  height: 300,
                  decoration: BoxDecoration(
                    color: kWhiteColor,
                    borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(100),
                      bottomRight: Radius.circular(100),
                    ),
                    gradient: LinearGradient(
                      colors: [kDarkModerateCyan, kModerateCyan],
                      stops: [0.0, 1],
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                    ),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      SizedBox(
                        height: 60,
                      ),
                      SizedBox(
                        width: 200,
                        height: 200,
                        child: SvgPicture.asset(
                          'assets/logo.svg',
                          fit: BoxFit.contain,
                          color: kWhiteColor,
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 30,
                  ),
                  width: MediaQuery.of(context).size.width,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: <Widget>[
                      SizedBox(
                        height: 70,
                      ),
                      emailField,
                      SizedBox(
                        height: 20,
                      ),
                      passwordField,
                      SizedBox(
                        height: 20,
                      ),
                      forgotPassword,
                      SizedBox(
                        height: 30,
                      ),
                      loginButton,
                      SizedBox(
                        height: 50,
                      ),
                      registerNow,
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
</code>```

My code is not connected to Firebase yet because I want to test if my validator is working or not, but I got this error instead.

答:
You have set the form key in Stack instead of a Form

To fix this, you can simply wrap your Stack with a Form, and move your key to that Form

like

...
return Scaffold(
      body: Form(
        key: _formKey,
        child: Stack(
          children: <Widget>[
...
```

Apart from that, I'd suggest putting your UI elements(login, email, and forgotPassword) outside the build method, to achieve it you'll have to create methods for them instead of having a field/variable

Body:
I got this error when I clicked my login button, I was expecting the validator would work but I just got this error every time I clicked my login button

════════ Exception caught by gesture ═══════════════════════════════════════════
The following _CastError was thrown while handling a gesture:
Null check operator used on a null value

When the exception was thrown, this was the stack
#0      _LoginPageState.build.<anonymous closure>
package:project_ukk/…/login/login_page.dart:153
#1      _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:989
#2      GestureRecognizer.invokeCallback
package:flutter/…/gestures/recognizer.dart:198
#3      TapGestureRecognizer.handleTapUp
package:flutter/…/gestures/tap.dart:608
#4      BaseTapGestureRecognizer._checkUp
package:flutter/…/gestures/tap.dart:296
#5      BaseTapGestureRecognizer.handlePrimaryPointer
package:flutter/…/gestures/tap.dart:230
#6      PrimaryPointerGestureRecognizer.handleEvent
package:flutter/…/gestures/recognizer.dart:563
#7      PointerRouter._dispatch
package:flutter/…/gestures/pointer_router.dart:94
#8      PointerRouter._dispatchEventToRoutes.<anonymous closure>
package:flutter/…/gestures/pointer_router.dart:139
#9      _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:539:8)
#10     PointerRouter._dispatchEventToRoutes
package:flutter/…/gestures/pointer_router.dart:137
#11     PointerRouter.route
package:flutter/…/gestures/pointer_router.dart:123
#12     GestureBinding.handleEvent
package:flutter/…/gestures/binding.dart:439
#13     GestureBinding.dispatchEvent
package:flutter/…/gestures/binding.dart:419
#14     RendererBinding.dispatchEvent
package:flutter/…/rendering/binding.dart:322
#15     GestureBinding._handlePointerEventImmediately
package:flutter/…/gestures/binding.dart:374
#16     GestureBinding.handlePointerEvent
package:flutter/…/gestures/binding.dart:338
#17     GestureBinding._flushPointerEventQueue
package:flutter/…/gestures/binding.dart:296
#18     GestureBinding._handlePointerDataPacket
package:flutter/…/gestures/binding.dart:279
#22     _invoke1 (dart:ui/hooks.dart:170:10)
#23     PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:331:7)
#24     _dispatchPointerDataPacket (dart:ui/hooks.dart:94:31)
(elided 3 frames from dart:async)
Handler: "onTap"
Recognizer: TapGestureRecognizer#db891
    debugOwner: GestureDetector
    state: possible
    won arena
    finalPosition: Offset(296.1, 619.7)
    finalLocalPosition: Offset(266.1, 36.2)
    button: 1
    sent tap down

This is my login_page.dart

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:project_ukk/constants/color_constant.dart';
import 'package:project_ukk/constants/font_and_padding.dart';
import 'package:project_ukk/pages/reset_password/reset_password.dart';
import 'package:project_ukk/pages/signUp/signup_page.dart';
import 'package:project_ukk/pages/user_page/navbar.dart';
import 'package:flutter_svg/svg.dart';

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

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  //Form Key
  final _formKey = GlobalKey<FormState>();

  var email = "";
  var password = "";

  final emailController = TextEditingController();
  final passwordController = TextEditingController();

  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    emailController.dispose();
    passwordController.dispose();
    super.dispose();
  }

  clearText() {
    emailController.clear();
    passwordController.clear();
  }

  userLogin() async {
    try {
      await FirebaseAuth.instance
          .signInWithEmailAndPassword(email: email, password: password);
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => PageNavBar(),
        ),
      );
    } on FirebaseAuthException catch (e) {
      if (e.code == 'user-not-found') {
        print("No User Found for that Email");
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            backgroundColor: Colors.orangeAccent,
            content: Text(
              "No User Found for that Email",
              style: TextStyle(fontSize: 18.0, color: Colors.black),
            ),
          ),
        );
      } else if (e.code == 'wrong-password') {
        print("Wrong Password Provided by User");
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            backgroundColor: Colors.orangeAccent,
            content: Text(
              "Wrong Password Provided by User",
              style: TextStyle(fontSize: 18.0, color: Colors.black),
            ),
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    //Email Field
    final emailField = TextFormField(
      autofocus: false,
      controller: emailController,
      keyboardType: TextInputType.emailAddress,
      validator: (value) {
        if (value == null || value.isEmpty) {
          return 'Please Enter Email';
        } else if (!value.contains('@')) {
          return 'Please Enter Valid Email';
        }
        return null;
      },
      textInputAction: TextInputAction.next,
      decoration: InputDecoration(
        prefixIcon: Icon(Icons.mail),
        contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
        hintText: "Email",
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
        ),
      ),
    );
    //Password Field
    final passwordField = TextFormField(
      autofocus: false,
      controller: passwordController,
      obscureText: true,
      validator: (value) {
        if (value == null || value.isEmpty) {
          return 'Please Enter Password';
        }
        return null;
      },
      textInputAction: TextInputAction.next,
      decoration: InputDecoration(
        prefixIcon: Icon(Icons.vpn_key),
        contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
        hintText: "Password",
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
        ),
      ),
    );
    final loginButton = Material(
      elevation: 2,
      borderRadius: BorderRadius.circular(50),
      child: Container(
        width: MediaQuery.of(context).size.width,
        height: 60,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(50),
          gradient: LinearGradient(
            colors: const [kDarkModerateCyan, kModerateCyan],
            begin: Alignment.centerLeft,
            end: Alignment.centerRight,
          ),
        ),
        child: Material(
          borderRadius: BorderRadius.circular(50),
          color: Colors.transparent,
          child: Center(
            child: MaterialButton(
              child: Text(
                "Login",
                textAlign: TextAlign.center,
                style: textButton,
              ),
              padding: EdgeInsets.fromLTRB(20, 10, 20, 15),
              minWidth: MediaQuery.of(context).size.width,
              onPressed: () {
                // Validate returns true if the form is valid, otherwise false.
                if (_formKey.currentState!.validate()) {
                  setState(() {
                    email = emailController.text;
                    password = passwordController.text;
                  });
                  userLogin();
                }
              },
            ),
          ),
        ),
      ),
    );
    final forgotPassword = Container(
      padding: EdgeInsets.symmetric(
        vertical: 10,
      ),
      child: GestureDetector(
        onTap: () => {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => ResetPassword(),
            ),
          ),
        },
        child: Text(
          'Forgot Password ?',
          style: TextStyle(
            decoration: TextDecoration.underline,
            color: Colors.grey,
          ),
        ),
      ),
    );
    final registerNow = Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text(
          "Don't have an account? ",
          style: TextStyle(color: Colors.grey),
        ),
        GestureDetector(
          child: Text(
            "Register Now",
            style: TextStyle(
              color: kPrimaryColor,
              fontWeight: FontWeight.bold,
              fontSize: 15,
            ),
          ),
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => SignUpPage(),
              ),
            );
          },
        ),
      ],
    );

    return Scaffold(
      backgroundColor: kWhiteColor,
      body: Stack(
        key: _formKey,
        children: <Widget>[
          SingleChildScrollView(
            child: Column(
              children: <Widget>[
                Container(
                  width: MediaQuery.of(context).size.width,
                  height: 300,
                  decoration: BoxDecoration(
                    color: kWhiteColor,
                    borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(100),
                      bottomRight: Radius.circular(100),
                    ),
                    gradient: LinearGradient(
                      colors: [kDarkModerateCyan, kModerateCyan],
                      stops: [0.0, 1],
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                    ),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      SizedBox(
                        height: 60,
                      ),
                      SizedBox(
                        width: 200,
                        height: 200,
                        child: SvgPicture.asset(
                          'assets/logo.svg',
                          fit: BoxFit.contain,
                          color: kWhiteColor,
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 30,
                  ),
                  width: MediaQuery.of(context).size.width,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: <Widget>[
                      SizedBox(
                        height: 70,
                      ),
                      emailField,
                      SizedBox(
                        height: 20,
                      ),
                      passwordField,
                      SizedBox(
                        height: 20,
                      ),
                      forgotPassword,
                      SizedBox(
                        height: 30,
                      ),
                      loginButton,
                      SizedBox(
                        height: 50,
                      ),
                      registerNow,
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

My code is not connected to Firebase yet because I want to test if my validator is working or not, but I got this error instead.

Body:
You have set the form key in Stack instead of a Form

To fix this, you can simply wrap your Stack with a Form, and move your key to that Form

like

...
return Scaffold(
      body: Form(
        key: _formKey,
        child: Stack(
          children: <Widget>[
...

Apart from that, I'd suggest putting your UI elements(login, email, and forgotPassword) outside the build method, to achieve it you'll have to create methods for them instead of having a field/variable


问:
How to animate line clamp
I have a box with text. It shows only 2 lines by default and shows the whole text when the user hovers over it.
However, I have a problem animating it. The display property seems to be not animatable.

How can I animate it?

If it helps, I'm also using "framer-motion" and it's okay if you have a workaround using it.

.box {
  transition: all 0.3s ease-in-out; /* doesn't work */
}

.title {
  color: green;
  font-weight: bold;
}

.text {
   display: -webkit-box;
   -webkit-line-clamp: 2;
   -webkit-box-orient: vertical;
   overflow: hidden;

   transition: all 0.3s ease-in-out; /* doesn't work */
}

.box:hover .text {
   display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <span class="title">Title</span>
  <div class="text">
  Et eirmod erat diam ipsum sit diam ut et est at ut tempor consequat nisl duis ut justo sit. Aliquyam adipiscing et esse consetetur dolores et suscipit stet magna invidunt sea et sadipscing ea at magna labore. Molestie dolores justo consetetur consequat. Sed sit aliquyam eirmod amet nonummy facilisis diam. Diam lorem dolores stet labore eos duo illum facer qui justo duo stet consetetur diam magna.
  </div>
</div></code>```

Why it's not a duplicate question:

I want to specifically use the line-clamp (or if there's a similar property) to limit the number of lines by the number I want. I don't want to use guesses or probability!

答:
Here is my solution newer solution which I guess help you achieve what you are looking for, Display property doesn't work with transition, you can use height.

let div1 = document.querySelector("#div1");
let height = div1.offsetHeight;
div1.classList.add('text');
div1.addEventListener("mouseover", () => {
  div1.style.height = height + "px";
});
div1.addEventListener("mouseout", () => {
  div1.style.height = "39px";
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.text {
  overflow: hidden;
  height: 39px;
  transition: all 0.3s ease-in-out;
}

.text::after {
  content: "..";
  background-color: #fff;
  color: #000;
  z-index: 999;
  position: absolute;
  right: 20px;
  top: 28px;
  display: inline-block;
  width: 75px;
  transition: all 0.3s ease-in-out;
}

.text:hover::after {
  width: 0;
  visibility: hidden;
}</code>```

    Et eirmod erat diam ipsum sit diam ut et est at ut tempor consequat nisl duis ut justo sit. Aliquyam adipiscing et esse consetetur dolores et suscipit stet magna invidunt sea et sadipscing ea at magna labore. Molestie dolores justo consetetur consequat.
    Sed sit aliquyam eirmod amet nonummy facilisis diam. Diam lorem dolores stet labore eos duo illum facer qui justo duo stet consetetur diam magna. Et eirmod erat diam ipsum sit diam ut et est at ut tempor consequat nisl duis ut justo sit. Aliquyam
    adipiscing et esse consetetur dolores et suscipit stet magna invidunt sea et sadipscing ea at magna labore. Molestie dolores justo consetetur consequat. Sed sit aliquyam eirmod amet nonummy facilisis diam. Diam lorem dolores stet labore eos duo illum
    facer qui justo duo stet consetetur diam magna. Et eirmod erat diam ipsum sit diam ut et est at ut tempor consequat nisl duis ut justo sit. Aliquyam adipiscing et esse consetetur dolores et suscipit stet magna invidunt sea et sadipscing ea at magna
    labore. Molestie dolores justo consetetur consequat. Sed sit aliquyam eirmod amet nonummy facilisis diam. Diam lorem dolores stet labore eos duo illum facer qui justo duo stet consetetur diam magna. Et eirmod erat diam ipsum sit diam ut et est at
    ut tempor consequat nisl duis ut justo sit. Aliquyam adipiscing et esse consetetur dolores et suscipit stet magna invidunt sea et sadipscing ea at magna labore. Molestie dolores justo consetetur consequat. Sed sit aliquyam eirmod amet nonummy facilisis
    diam. Diam lorem dolores stet labore eos duo illum facer qui justo duo stet consetetur diam magna.

```

Title: How to animate line clamp

Body:
I have a box with text. It shows only 2 lines by default and shows the whole text when the user hovers over it.
However, I have a problem animating it. The display property seems to be not animatable.

How can I animate it?

If it helps, I'm also using "framer-motion" and it's okay if you have a workaround using it.

.box {
  transition: all 0.3s ease-in-out; /* doesn't work */
}

.title {
  color: green;
  font-weight: bold;
}

.text {
   display: -webkit-box;
   -webkit-line-clamp: 2;
   -webkit-box-orient: vertical;
   overflow: hidden;

   transition: all 0.3s ease-in-out; /* doesn't work */
}

.box:hover .text {
   display: block;
}

  Title

  Et eirmod erat diam ipsum sit diam ut et est at ut tempor consequat nisl duis ut justo sit. Aliquyam adipiscing et esse consetetur dolores et suscipit stet magna invidunt sea et sadipscing ea at magna labore. Molestie dolores justo consetetur consequat. Sed sit aliquyam eirmod amet nonummy facilisis diam. Diam lorem dolores stet labore eos duo illum facer qui justo duo stet consetetur diam magna.

Why it's not a duplicate question:

I want to specifically use the line-clamp (or if there's a similar property) to limit the number of lines by the number I want. I don't want to use guesses or probability!

Body:
Here is my solution newer solution which I guess help you achieve what you are looking for, Display property doesn't work with transition, you can use height.

let div1 = document.querySelector("#div1");
let height = div1.offsetHeight;
div1.classList.add('text');
div1.addEventListener("mouseover", () => {
  div1.style.height = height + "px";
});
div1.addEventListener("mouseout", () => {
  div1.style.height = "39px";
});

.text {
  overflow: hidden;
  height: 39px;
  transition: all 0.3s ease-in-out;
}

.text::after {
  content: "..";
  background-color: #fff;
  color: #000;
  z-index: 999;
  position: absolute;
  right: 20px;
  top: 28px;
  display: inline-block;
  width: 75px;
  transition: all 0.3s ease-in-out;
}

.text:hover::after {
  width: 0;
  visibility: hidden;
}

<div class="box">
  <div id="div1">
    Et eirmod erat diam ipsum sit diam ut et est at ut tempor consequat nisl duis ut justo sit. Aliquyam adipiscing et esse consetetur dolores et suscipit stet magna invidunt sea et sadipscing ea at magna labore. Molestie dolores justo consetetur consequat.
    Sed sit aliquyam eirmod amet nonummy facilisis diam. Diam lorem dolores stet labore eos duo illum facer qui justo duo stet consetetur diam magna. Et eirmod erat diam ipsum sit diam ut et est at ut tempor consequat nisl duis ut justo sit. Aliquyam
    adipiscing et esse consetetur dolores et suscipit stet magna invidunt sea et sadipscing ea at magna labore. Molestie dolores justo consetetur consequat. Sed sit aliquyam eirmod amet nonummy facilisis diam. Diam lorem dolores stet labore eos duo illum
    facer qui justo duo stet consetetur diam magna. Et eirmod erat diam ipsum sit diam ut et est at ut tempor consequat nisl duis ut justo sit. Aliquyam adipiscing et esse consetetur dolores et suscipit stet magna invidunt sea et sadipscing ea at magna
    labore. Molestie dolores justo consetetur consequat. Sed sit aliquyam eirmod amet nonummy facilisis diam. Diam lorem dolores stet labore eos duo illum facer qui justo duo stet consetetur diam magna. Et eirmod erat diam ipsum sit diam ut et est at
    ut tempor consequat nisl duis ut justo sit. Aliquyam adipiscing et esse consetetur dolores et suscipit stet magna invidunt sea et sadipscing ea at magna labore. Molestie dolores justo consetetur consequat. Sed sit aliquyam eirmod amet nonummy facilisis
    diam. Diam lorem dolores stet labore eos duo illum facer qui justo duo stet consetetur diam magna.
  </div>
</div>


问:
Prevent React Native Modal from returning focus to TextInput when closed
I have a situation where I am using the onFocus method of a TextInput (call it "main TextInput") to open a Modal. The problem I'm having is when I focus on a separate TextInput inside the Modal (call it "Modal TextInput") and then close the Modal, the onFocus method of the main TextInput fires again and reopens the Modal. If at that point I close the Modal without focusing on the Modal TextInput, the main TextInput doesn't lose and regain focus, so the Modal does not reopen.

It's as if the main TextInput loses focus to the Modal TextInput and then closing the Modal returns the focus to the main TextInput with the following catch. As far as I can tell, the main TextInput does not actually lose focus because I created a simple console log test of the onBlur method and it's not firing.

I've seen a solution where someone used the blur method prior to actually opening the Modal, but they were using a button to open the Modal so they had an onPress they could use to execute multiple commands whereas I'm using the onFocus so the Modal immediately opens.

I attempted using the useRef hook to focus on an "invisible" TextInput when the onDismiss method of the Modal is called, but the behavior is the same. The weird thing there is using console logs (yes I'm an amateur) to see the order of events shows the onFocus of the main TextInput occurring again before the Modal onDismiss.

If someone knows a way to prevent this behavior, I would appreciate it.

答:
Here's one option.

Set a new piece of state to track whether the modal should open.  If you're using hooks:

// screen body
const [modalShouldOpen, setModalShouldOpen] = useState(true);
```
<p>You probably already have a piece of state that tracks whether the modal is open:</p>
<pre class="lang-js prettyprint-override"><code>const [isModalOpen, setIsModalOpen] = useState(false);
</code>```

When you invoke setIsModalOpen(true) in the onFocus callback of your main text input, also invoke setModalShouldOpen(false).  The callback must also be altered to only open the modal if it should open.

const onFocus = () => {
  if (!modalShouldOpen) return;

  setIsModalOpen(true);
  setModalShouldOpen(false);
}
```
<p>Then you can set modalShouldOpen back to true in the onBlur method of the main TextInput.  Full pseudocode below.</p>
<pre class="lang-js prettyprint-override"><code>export default function MainScreen() {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modalShouldOpen, setModalShouldOpen] = useState(true);

  const onMainTextInputFocus = () => {
    if (!modalShouldOpen) return;

    setIsModalOpen(true);
    setModalShouldOpen(false);
  }

  const onMainTextInputBlur = () => {
    setModalShouldOpen(true);
  }

  return (
    <View style={styles.container}>
      <TextInput onFocus={onMainTextInputFocus} onBlur={onMainInputBlur} />

      <Modal show={isModalOpen}>
        ...
      </Modal>
    </View>
  );
}
</code>```

Body:
Here's one option.

Set a new piece of state to track whether the modal should open.  If you're using hooks:

// screen body
const [modalShouldOpen, setModalShouldOpen] = useState(true);

You probably already have a piece of state that tracks whether the modal is open:

const [isModalOpen, setIsModalOpen] = useState(false);

When you invoke setIsModalOpen(true) in the onFocus callback of your main text input, also invoke setModalShouldOpen(false).  The callback must also be altered to only open the modal if it should open.

const onFocus = () => {
  if (!modalShouldOpen) return;

  setIsModalOpen(true);
  setModalShouldOpen(false);
}

Then you can set modalShouldOpen back to true in the onBlur method of the main TextInput.  Full pseudocode below.

export default function MainScreen() {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modalShouldOpen, setModalShouldOpen] = useState(true);

  const onMainTextInputFocus = () => {
    if (!modalShouldOpen) return;

    setIsModalOpen(true);
    setModalShouldOpen(false);
  }

  const onMainTextInputBlur = () => {
    setModalShouldOpen(true);
  }

  return (
    <View style={styles.container}>
      <TextInput onFocus={onMainTextInputFocus} onBlur={onMainInputBlur} />

      <Modal show={isModalOpen}>
        ...
      </Modal>
    </View>
  );
}


问:
How to insert extra content in form?
I have form:

```<code>class ItemForm(forms.ModelForm):
    id = forms.ModelChoiceField(queryset=Item.objects.all(), widget=forms.HiddenInput())
    temp = forms.BooleanField(widget=forms.HiddenInput(), required=False)
    date = forms.SplitDateTimeField(widget=forms.SplitDateTimeWidget())
    ... etc
</code>```

and in template i have:

```<code>    {% for field in itemForm %}
        {% if field.is_hidden %}
            {{ field }}
        {% else %}
            <div class="fieldWrapper">
                 {% if field.errors %}<div class="errorbox">{% endif %}
                    <p>{{ field.label_tag }}</p>
                    <p>{{ field }}</p>
                    <p></p>
                {% if field.errors %}<p>{{ field.errors }}</p></div>{% endif %}
            </div>
        {% endif %}
    {% endfor %}
</code>```

it is a universal template for different forms. And now in one form:

```<code>class DifferentForm(forms.ModelForm):
    id = forms.ModelChoiceField(queryset=DifferentItem.objects.all(), widget=forms.HiddenInput())
    option = forms.ModelChoiceField(queryset=Option.objects.all(), widget=forms.HiddenInput())
    (????)
    temp = forms.BooleanField(widget=forms.HiddenInput(), required=False)
    date = forms.SplitDateTimeField(widget=forms.SplitDateTimeWidget())
    ... etc
</code>```

i want put an additional link in such a way as to show in this way:

```<code><select ...>
    <option>...</option>
</select>
(my additional link, button, text, whatever)
<input ...
</code>```

How to do it?

答:
The way I usually do this is in the template:</p>

```<code>{% for field in itemForm %}
    {% if field.name == "option" %}
       Custom stuff I want to go before this field
    {% endif %}

    <!-- Regular field stuff goes here -->
    {% if field.is_hidden %}
        {{ field }}
    {% else %}
        <div class="fieldWrapper">
            ...
        </div>
    {% endif %}
    <!-- End Regular Field Stuff -->

    {% if field.name == "option" %}
       Custom stuff I want to go after the field
    {% endif %}
    {% if field.name == "another_field_name"%}
       Custom stuff I want to go after the field
    {% endif %}
{% endfor %}
</code>```

Title: How to insert extra content in form?

Body:
I have form:

class ItemForm(forms.ModelForm):
    id = forms.ModelChoiceField(queryset=Item.objects.all(), widget=forms.HiddenInput())
    temp = forms.BooleanField(widget=forms.HiddenInput(), required=False)
    date = forms.SplitDateTimeField(widget=forms.SplitDateTimeWidget())
    ... etc

and in template i have:

    {% for field in itemForm %}
        {% if field.is_hidden %}
            {{ field }}
        {% else %}

                 {% if field.errors %}
{% endif %}

{{ field.label_tag }}

{{ field }}

                {% if field.errors %}
{{ field.errors }}

{% endif %}

        {% endif %}
    {% endfor %}

it is a universal template for different forms. And now in one form:

class DifferentForm(forms.ModelForm):
    id = forms.ModelChoiceField(queryset=DifferentItem.objects.all(), widget=forms.HiddenInput())
    option = forms.ModelChoiceField(queryset=Option.objects.all(), widget=forms.HiddenInput())
    (????)
    temp = forms.BooleanField(widget=forms.HiddenInput(), required=False)
    date = forms.SplitDateTimeField(widget=forms.SplitDateTimeWidget())
    ... etc

i want put an additional link in such a way as to show in this way:

<select ...>
    <option>...</option>
</select>
(my additional link, button, text, whatever)
<input ...

How to do it?

Body:
The way I usually do this is in the template:

{% for field in itemForm %}
    {% if field.name == "option" %}
       Custom stuff I want to go before this field
    {% endif %}

    <!-- Regular field stuff goes here -->
    {% if field.is_hidden %}
        {{ field }}
    {% else %}
        <div class="fieldWrapper">
            ...
        </div>
    {% endif %}
    <!-- End Regular Field Stuff -->

    {% if field.name == "option" %}
       Custom stuff I want to go after the field
    {% endif %}
    {% if field.name == "another_field_name"%}
       Custom stuff I want to go after the field
    {% endif %}
{% endfor %}


问:
Inconsistency in interpreting python float in pytorch - why?
In pytorch, the default dtype of python float in torch.Tensor creation is torch.float32:

```<code>a = torch.tensor([1.])
a.dtype
>>> torch.float32
</code>```

But when dtype is explicitly given as float, or in torch.Tensor.to method, python float is casted as torch.float64:

```<code>a = torch.tensor([1.], dtype=float)
a.dtype
>>> torch.float64

a = torch.tensor([1.]).to(float)
a.dtype
>>> torch.float64
</code>```

Q. What kind of reasonings behind this inconsistency? I naturally assume that there must be some benefit/avoidance of nasty bugs in bearing with this mismatch in default dtype for python float on the level of such basic tensor operations.

Edit. I just wonder why pytorch team choose torch.tensor(x) different from torch.tensor(x).to(float) when x consists of floats.

答:
As stated in Python's docs:

Floating point numbers are usually implemented using double in C

double in C is normally a 64-bit number (double-precision, as opposed to the single-precision 32-bit float type), and it's also known as float64. So, what we call float in plain Python is usually a 64-bit float, or torch.float64.

PyTorch itself, however, uses float32 by default. AFAIK, this is done to save memory: you'll likely be training models with quite a lot of parameters, and using 32-bit floats will take two times less memory than Python's 64-bit float.

Body:
In pytorch, the default dtype of python float in torch.Tensor creation is torch.float32:

a = torch.tensor([1.])
a.dtype
>>> torch.float32

But when dtype is explicitly given as float, or in torch.Tensor.to method, python float is casted as torch.float64:

a = torch.tensor([1.], dtype=float)
a.dtype
>>> torch.float64

a = torch.tensor([1.]).to(float)
a.dtype
>>> torch.float64

Q. What kind of reasonings behind this inconsistency? I naturally assume that there must be some benefit/avoidance of nasty bugs in bearing with this mismatch in default dtype for python float on the level of such basic tensor operations.

Edit. I just wonder why pytorch team choose torch.tensor(x) different from torch.tensor(x).to(float) when x consists of floats.


问:
rx dart combine multiple streams to emit value whenever any of the streams emit a value
In RX dart there is the RX.combineLatest method to combine the results of a stream using a callback function.
Problem is that it only emits a value when every stream has emitted a value. If one has not it does not emit.

Merges the given Streams into a single Stream sequence by using the combiner function whenever any of the stream sequences emits an item.
The Stream will not emit until all streams have emitted at least one item.

Im trying to combine multiple streams into one stream for validation which should emit false or true when the streams have not emitted or emitted an empty value.

class FormBloc {
  final BehaviorSubject<bool> _result = BehaviorSubject();
  final BehaviorSubject<String?> _usernameController = BehaviorSubject();
  final BehaviorSubject<String?> _emailController = BehaviorSubject();

  // Will only emit if each stream emitted a value
  // If only username is emitted valid is not emitted
  Stream<bool> get valid$ => Rx.combineLatest2(
    _usernameController.stream,
    _emailController.stream,
    (username, email) => username != null || email != null
  );

}

```

How can I join those streams so valid$ emits a value if any of the streams change?

答:
Creating new stream which emits current value and listen the stream is my best practice.

class FormBloc {
  final BehaviorSubject<bool> _result = BehaviorSubject();
  final BehaviorSubject<String?> _usernameController = BehaviorSubject();
  final BehaviorSubject<String?> _emailController = BehaviorSubject();

  final _usernameStreamController = StreamController<String?>()
    ..add(_usernameController.value)
    ..addStream(_usernameController.stream);
  final _emailStreamController = StreamController<String?>()
    ..add(_emailController.value)
    ..addStream(_emailController.stream);

  Stream<bool> get valid$ => Rx.combineLatest2(
    _usernameStreamController.stream,  // use streamController instead
    _emailStreamController.stream,  // use streamController instead
    (username, email) => username != null || email != null
  );
}
```

Body:
In RX dart there is the RX.combineLatest method to combine the results of a stream using a callback function.
Problem is that it only emits a value when every stream has emitted a value. If one has not it does not emit.

Merges the given Streams into a single Stream sequence by using the combiner function whenever any of the stream sequences emits an item.
The Stream will not emit until all streams have emitted at least one item.

Im trying to combine multiple streams into one stream for validation which should emit false or true when the streams have not emitted or emitted an empty value.

class FormBloc {
  final BehaviorSubject<bool> _result = BehaviorSubject();
  final BehaviorSubject<String?> _usernameController = BehaviorSubject();
  final BehaviorSubject<String?> _emailController = BehaviorSubject();

  // Will only emit if each stream emitted a value
  // If only username is emitted valid is not emitted
  Stream<bool> get valid$ => Rx.combineLatest2(
    _usernameController.stream,
    _emailController.stream,
    (username, email) => username != null || email != null
  );

}

How can I join those streams so valid$ emits a value if any of the streams change?


问:
Android Navigation Component : BottomNavigationView's selected tab icon is not updated
I'm using BottomNavigationView with Navigation Component. When showing fragment is not root fragment, the tab icon is not updated (selected).

Example:

When I switch between Tab Home with Fragment A (which is root fragment) and Tab Star with Fragment B (which is also root fragment) it is working fine.

But when I navigate from Tab Home to another fragment, like fragment A2, and tap on Tab Star and again return to Tab Home, still Tab Star is selected in BottomNavigationView.

It was working fine with version 2.4.0-alpha05, This is happening when I updated it to 2.5.0-alpha01.

build.gradle (app)

```<code>implementation "androidx.navigation:navigation-fragment-ktx:2.5.0-alpha01"
implementation "androidx.navigation:navigation-ui-ktx:2.5.0-alpha01"
implementation "androidx.navigation:navigation-dynamic-features-fragment:2.5.0-alpha01"
</code>```

build.gradle (root)

```<code>classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.5.0-alpha01"
</code>```

Graph:

```<code><navigation xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/graph"
        app:startDestination="@id/fragmentA">
    <fragment
            android:id="@+id/fragmentA"
            android:name="ui.test.FragmentA"
            tools:layout="@layout/fragment_test"
            android:label="FragmentA" >
        <action
                android:id="@+id/action_fragmentA_to_fragmentA2"
                app:destination="@id/fragmentA2" />
    </fragment>
    <fragment
            android:id="@+id/fragmentA2"
            android:name="ui.test.FragmentA2"
            tools:layout="@layout/fragment_test"
            android:label="FragmentA2" />
    <fragment
            android:id="@+id/fragmentB"
            android:name="ui.test.FragmentB"
            tools:layout="@layout/fragment_test"
            android:label="FragmentB" />
</navigation>
</code>```

Menu:

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
            android:id="@+id/fragmentA"
            android:icon="@drawable/ic_home"
            android:title="" />
    <item
            android:id="@+id/fragmentB"
            android:icon="@drawable/ic_star"
            android:title="" />
</menu>
</code>```

Am I doing something wrong? or this is bug?

How can I resolve this problem?

答:
Given your navigation graph, there is no way to associate fragmentA2 with your menu item fragmentA, so fragmentA is not selected when you return to fragmentA2. As per this issue:

NavigationUI has always used the current destination and what graph it is part of as the source of truth for what tab should be selected.

This can be seen by calling navigate() to go to your SecondFragment - even though you haven't used the bottom nav button, the selected tab was changed because the current destination has changed to R.id.frag_second.

So when you navigate() to R.id.frag_hint via your button in HomeFragment, NavigationUI receives a callback that the current destination has changed to R.id.frag_hint. It looks at that NavDestination and notes that there's no menu item that matches R.id.frag_hint. It then looks at the destination's parent graph - your R.id.sample <navigation> element. There's no menu item that matches that ID either, so NavigationUI can't associated that destination with any menu item and therefore simply does nothing. That is true on all versions of Navigation.

So what is different when you tap on a bottom navigation item? Well, nothing different from a NavigationUI perspective in fact: the exact same code runs and the current destination and what graph it is part of is the source of truth for what tab should be selected. In the Navigation 2.3.5, there was no state saved for each tab, so it only 'worked' because selecting a tab forced the ID of the current destination to match the destination of the menu item you just tapped.

So what you're seeing in your sample app is that there's no link between R.id.frag_hint and any menu item, which means NavigationUI does nothing. If you want to link R.id.frag_hint to your Home tab, then that's exactly what a nested navigation graph can be used for.

I.e., your navigation graph should instead look like:

```<code><navigation
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/sample"
    app:startDestination="@id/home">

    <navigation
        android:id="@+id/home"
        app:startDestination="@id/frag_home">
        <fragment
            android:id="@+id/frag_home"
            android:name="eu.rekisoft.android.navbug.HomeFragment"
            tools:layout="@layout/fragment_home">
            <action
                android:id="@+id/cause_bug"
                app:destination="@id/frag_hint"/>
        </fragment>

        <fragment
            android:id="@+id/frag_hint"
            android:name="eu.rekisoft.android.navbug.HintFragment"
            android:label="Hint"
            tools:layout="@layout/fragment_hint"/>
    </navigation>

    <fragment
        android:id="@+id/frag_second"
        android:name="eu.rekisoft.android.navbug.SecondFragment"
        android:label="Second Fragment"
        tools:layout="@layout/fragment_second"/>

</navigation>
</code>```

And your menu XML should be updated to use android:id="@id/home" to match your navigation graph.

Now, when you select the Home bottom nav item, the current destination changes to R.id.frag_hint (as your state was restored due to Navigation 2.4's support for multiple back stacks) and NavigationUI looks at the ID - R.id.frag_hint still doesn't match any menu item, but now the parent graph's ID, R.id.home does match a menu item - your Home menu item, hence, it becomes selected.

The intention that your navigation graph and its structure drives the UI is a key part of how NavigationUI works and is working as intended (there was a bug on earlier versions of Navigation 2.4 that broke this driving principle, but that has since been fixed in beta02). All of NavigationUI is built on public APIs specifically so that if you want to use some different logic for which bottom nav item is selected that is independent from your navigation graph structure, you can absolutely do that.

You'll note from the source code that you can call the public onNavDestinationSelected with your MenuItem to get the exact same navigate() logic which retaining your own ability to return any value from the setOnItemSelectedListener (which is what controls whether the tab becomes selected). Similarly, your own OnDestinationChangedListener can choose to look at the hierarchy of a destination to choose whether to change the selected bottom nav item or not.

So your graphs should also be using nested graphs for each tab:

```<code><navigation xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/graph"
        app:startDestination="@id/graphA">
    <navigation
        android:id="@+id/graphA"
        app:startDestination="@id/fragmentA">
        <fragment
            android:id="@+id/fragmentA"
            android:name="ui.test.FragmentA"
            tools:layout="@layout/fragment_test"
            android:label="FragmentA" >
            <action
                android:id="@+id/action_fragmentA_to_fragmentA2"
                app:destination="@id/fragmentA2" />
        </fragment>
        <fragment
            android:id="@+id/fragmentA2"
            android:name="ui.test.FragmentA2"
            tools:layout="@layout/fragment_test"
            android:label="FragmentA2" />
    </navigation>
    <navigation
        android:id="@+id/graphB"
        app:startDestination="@id/fragmentB">
        <fragment
            android:id="@+id/fragmentB"
            android:name="ui.test.FragmentB"
            tools:layout="@layout/fragment_test"
            android:label="FragmentB" />
    </navigation>
</navigation>
</code>```

Menu:

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
            android:id="@+id/graphA"
            android:icon="@drawable/ic_home"
            android:title="" />
    <item
            android:id="@+id/graphB"
            android:icon="@drawable/ic_star"
            android:title="" />
</menu>
</code>```

Body:
I'm using BottomNavigationView with Navigation Component. When showing fragment is not root fragment, the tab icon is not updated (selected).

Example:

When I switch between Tab Home with Fragment A (which is root fragment) and Tab Star with Fragment B (which is also root fragment) it is working fine.

But when I navigate from Tab Home to another fragment, like fragment A2, and tap on Tab Star and again return to Tab Home, still Tab Star is selected in BottomNavigationView.

It was working fine with version 2.4.0-alpha05, This is happening when I updated it to 2.5.0-alpha01.

build.gradle (app)

implementation "androidx.navigation:navigation-fragment-ktx:2.5.0-alpha01"
implementation "androidx.navigation:navigation-ui-ktx:2.5.0-alpha01"
implementation "androidx.navigation:navigation-dynamic-features-fragment:2.5.0-alpha01"

build.gradle (root)

classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.5.0-alpha01"

Graph:

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/graph"
        app:startDestination="@id/fragmentA">
    <fragment
            android:id="@+id/fragmentA"
            android:name="ui.test.FragmentA"
            tools:layout="@layout/fragment_test"
            android:label="FragmentA" >
        <action
                android:id="@+id/action_fragmentA_to_fragmentA2"
                app:destination="@id/fragmentA2" />
    </fragment>
    <fragment
            android:id="@+id/fragmentA2"
            android:name="ui.test.FragmentA2"
            tools:layout="@layout/fragment_test"
            android:label="FragmentA2" />
    <fragment
            android:id="@+id/fragmentB"
            android:name="ui.test.FragmentB"
            tools:layout="@layout/fragment_test"
            android:label="FragmentB" />
</navigation>

Menu:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
            android:id="@+id/fragmentA"
            android:icon="@drawable/ic_home"
            android:title="" />
    <item
            android:id="@+id/fragmentB"
            android:icon="@drawable/ic_star"
            android:title="" />
</menu>

Am I doing something wrong? or this is bug?

How can I resolve this problem?

Body:
Given your navigation graph, there is no way to associate fragmentA2 with your menu item fragmentA, so fragmentA is not selected when you return to fragmentA2. As per this issue:

NavigationUI has always used the current destination and what graph it is part of as the source of truth for what tab should be selected.

This can be seen by calling navigate() to go to your SecondFragment - even though you haven't used the bottom nav button, the selected tab was changed because the current destination has changed to R.id.frag_second.

So when you navigate() to R.id.frag_hint via your button in HomeFragment, NavigationUI receives a callback that the current destination has changed to R.id.frag_hint. It looks at that NavDestination and notes that there's no menu item that matches R.id.frag_hint. It then looks at the destination's parent graph - your R.id.sample <navigation> element. There's no menu item that matches that ID either, so NavigationUI can't associated that destination with any menu item and therefore simply does nothing. That is true on all versions of Navigation.

So what is different when you tap on a bottom navigation item? Well, nothing different from a NavigationUI perspective in fact: the exact same code runs and the current destination and what graph it is part of is the source of truth for what tab should be selected. In the Navigation 2.3.5, there was no state saved for each tab, so it only 'worked' because selecting a tab forced the ID of the current destination to match the destination of the menu item you just tapped.

So what you're seeing in your sample app is that there's no link between R.id.frag_hint and any menu item, which means NavigationUI does nothing. If you want to link R.id.frag_hint to your Home tab, then that's exactly what a nested navigation graph can be used for.

I.e., your navigation graph should instead look like:

<navigation
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/sample"
    app:startDestination="@id/home">

    <navigation
        android:id="@+id/home"
        app:startDestination="@id/frag_home">
        <fragment
            android:id="@+id/frag_home"
            android:name="eu.rekisoft.android.navbug.HomeFragment"
            tools:layout="@layout/fragment_home">
            <action
                android:id="@+id/cause_bug"
                app:destination="@id/frag_hint"/>
        </fragment>

        <fragment
            android:id="@+id/frag_hint"
            android:name="eu.rekisoft.android.navbug.HintFragment"
            android:label="Hint"
            tools:layout="@layout/fragment_hint"/>
    </navigation>

    <fragment
        android:id="@+id/frag_second"
        android:name="eu.rekisoft.android.navbug.SecondFragment"
        android:label="Second Fragment"
        tools:layout="@layout/fragment_second"/>

</navigation>

And your menu XML should be updated to use android:id="@id/home" to match your navigation graph.

Now, when you select the Home bottom nav item, the current destination changes to R.id.frag_hint (as your state was restored due to Navigation 2.4's support for multiple back stacks) and NavigationUI looks at the ID - R.id.frag_hint still doesn't match any menu item, but now the parent graph's ID, R.id.home does match a menu item - your Home menu item, hence, it becomes selected.

The intention that your navigation graph and its structure drives the UI is a key part of how NavigationUI works and is working as intended (there was a bug on earlier versions of Navigation 2.4 that broke this driving principle, but that has since been fixed in beta02). All of NavigationUI is built on public APIs specifically so that if you want to use some different logic for which bottom nav item is selected that is independent from your navigation graph structure, you can absolutely do that.

You'll note from the source code that you can call the public onNavDestinationSelected with your MenuItem to get the exact same navigate() logic which retaining your own ability to return any value from the setOnItemSelectedListener (which is what controls whether the tab becomes selected). Similarly, your own OnDestinationChangedListener can choose to look at the hierarchy of a destination to choose whether to change the selected bottom nav item or not.

So your graphs should also be using nested graphs for each tab:

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/graph"
        app:startDestination="@id/graphA">
    <navigation
        android:id="@+id/graphA"
        app:startDestination="@id/fragmentA">
        <fragment
            android:id="@+id/fragmentA"
            android:name="ui.test.FragmentA"
            tools:layout="@layout/fragment_test"
            android:label="FragmentA" >
            <action
                android:id="@+id/action_fragmentA_to_fragmentA2"
                app:destination="@id/fragmentA2" />
        </fragment>
        <fragment
            android:id="@+id/fragmentA2"
            android:name="ui.test.FragmentA2"
            tools:layout="@layout/fragment_test"
            android:label="FragmentA2" />
    </navigation>
    <navigation
        android:id="@+id/graphB"
        app:startDestination="@id/fragmentB">
        <fragment
            android:id="@+id/fragmentB"
            android:name="ui.test.FragmentB"
            tools:layout="@layout/fragment_test"
            android:label="FragmentB" />
    </navigation>
</navigation>

Menu:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
            android:id="@+id/graphA"
            android:icon="@drawable/ic_home"
            android:title="" />
    <item
            android:id="@+id/graphB"
            android:icon="@drawable/ic_star"
            android:title="" />
</menu>