问:
Unable to save the chosen item in the first spot of the array
I cant save my input in my array, so when i put all the answers in, and i want to see what i have in my array, all the spots are empty. This is whats happening since i put the if-statement there. If i remove the if-statement, the input will be saved in my array but it will miss the first input, so i will have 23 out of 24 answers.

I've tried to write an else-statement as well, but same problem with the one missing, same if i delete the whole if-statement.

```<code>    {

        if (numberOfBottles < 24)
        {
            Console.WriteLine("");
            Console.WriteLine("Write what sodas u want in the crate:"); // Skriver ut text och ber användaren skriva drycken.

            int soda_input = 0;

            string chosenSoda = "";
            do
            {

                Console.WriteLine("1: Coca-cola"); // skriver ut alternativen för flaska
                Console.WriteLine("2: Fanta");
                Console.WriteLine("3: Pepsi");
                Console.WriteLine("4: Beer");
                Console.WriteLine("5: Redbull");
                Console.WriteLine("6: Cider");
                Console.WriteLine("7: Water");

                try
                {
                    soda_input = int.Parse(Console.ReadLine());
                }
                catch (Exception e)
                {
                    Console.WriteLine("Just numbers, my friend");
                    continue;
                }

                if (chosenSoda == null)**
                {
                    crate[numberOfBottles] = chosenSoda; // lagrar svaren i min vektor
                } THIS IS THE IF-STATEMENT THAT IS MESSING EVERYTHING UP

                numberOfBottles++;  // för varje svar jag skriver så ökar det med 1 i vektorn hela vägen till 24

                switch (soda_input) // Skapar en meny, som skriver ut vilken dryck användaren väljer tills backen blir full.
                {

                    case 1:
                        chosenSoda = "Coca-Cola";
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Du valde Coca-Cola");
                        Console.WriteLine("-------------------");
                        break;

                    case 2:
                        chosenSoda = "Fanta";
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Du valde Fanta");
                        Console.WriteLine("-------------------");
                        break;

                    case 3:
                        chosenSoda = "Pepsi";
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Du valde Pepsi");
                        Console.WriteLine("-------------------");
                        break;

                    case 4:
                        chosenSoda = "Öl";
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Du valde Öl");
                        Console.WriteLine("-------------------");
                        break;

                    case 5:
                        chosenSoda = "Redbull";
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Du valde Redbull");
                        Console.WriteLine("-------------------");
                        break;

                    case 6:
                        chosenSoda = "Cider";
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Du valde Cider");
                        Console.WriteLine("-------------------");
                        break;

                    case 7:
                        chosenSoda = "Vatten";
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Du valde Vatten");
                        Console.WriteLine("-------------------");
                        break;

                    default: // om man skriver siffror ovanför 1-7 så skrivs detta ut.
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Siffor mellan 1-7 min vän");
                        Console.WriteLine("-------------------");
                        break;
                }

            } while (numberOfBottles != 24);

        }
        else
            Console.WriteLine("");
        Console.WriteLine("The crate is full, choose some of the alteratives to check the crate:");
        Console.WriteLine("");

    }
</code>```

EDIT: "Du valde, means U chose.. in swedish.

答:
You are assigning the array value before you have chosen anything.

Additionally, you probably want to keep them in the loop and not assign a value if the input is invalid.

To do this you move the if to after the switch, but before the while statement.  By checking for not equal (!=) to null (which I don't think it will ever be) and also checking for not equal to "", you are forcing them to stay on the current bottle and keep inputting until they make a valid selection.

Try this:

```<code>do
        {

            Console.WriteLine("1: Coca-cola"); // skriver ut alternativen för flaska
            Console.WriteLine("2: Fanta");
            Console.WriteLine("3: Pepsi");
            Console.WriteLine("4: Beer");
            Console.WriteLine("5: Redbull");
            Console.WriteLine("6: Cider");
            Console.WriteLine("7: Water");

            try
            {
                soda_input = int.Parse(Console.ReadLine());
            }
            catch (Exception e)
            {
                Console.WriteLine("Just numbers, my friend");
                continue;
            }

            switch (soda_input) // Skapar en meny, som skriver ut vilken dryck användaren väljer tills backen blir full.
            {

                case 1:
                    chosenSoda = "Coca-Cola";
                    Console.WriteLine("-------------------");
                    Console.WriteLine("Du valde Coca-Cola");
                    Console.WriteLine("-------------------");
                    break;

                case 2:
                    chosenSoda = "Fanta";
                    Console.WriteLine("-------------------");
                    Console.WriteLine("Du valde Fanta");
                    Console.WriteLine("-------------------");
                    break;

                case 3:
                    chosenSoda = "Pepsi";
                    Console.WriteLine("-------------------");
                    Console.WriteLine("Du valde Pepsi");
                    Console.WriteLine("-------------------");
                    break;

                case 4:
                    chosenSoda = "Öl";
                    Console.WriteLine("-------------------");
                    Console.WriteLine("Du valde Öl");
                    Console.WriteLine("-------------------");
                    break;

                case 5:
                    chosenSoda = "Redbull";
                    Console.WriteLine("-------------------");
                    Console.WriteLine("Du valde Redbull");
                    Console.WriteLine("-------------------");
                    break;

                case 6:
                    chosenSoda = "Cider";
                    Console.WriteLine("-------------------");
                    Console.WriteLine("Du valde Cider");
                    Console.WriteLine("-------------------");
                    break;

                case 7:
                    chosenSoda = "Vatten";
                    Console.WriteLine("-------------------");
                    Console.WriteLine("Du valde Vatten");
                    Console.WriteLine("-------------------");
                    break;

                default: // om man skriver siffror ovanför 1-7 så skrivs detta ut.
                    Console.WriteLine("-------------------");
                    Console.WriteLine("Siffor mellan 1-7 min vän");
                    Console.WriteLine("-------------------");
                    break;
            }

 if (chosenSoda != null && chosenSoda != "")
            {
                crate[numberOfBottles] = chosenSoda; // lagrar svaren i min vektor
            numberOfBottles++;
            }

        } while (numberOfBottles != 24);
</code>```

Body:
I cant save my input in my array, so when i put all the answers in, and i want to see what i have in my array, all the spots are empty. This is whats happening since i put the if-statement there. If i remove the if-statement, the input will be saved in my array but it will miss the first input, so i will have 23 out of 24 answers.

I've tried to write an else-statement as well, but same problem with the one missing, same if i delete the whole if-statement.

    {

        if (numberOfBottles < 24)
        {
            Console.WriteLine("");
            Console.WriteLine("Write what sodas u want in the crate:"); // Skriver ut text och ber användaren skriva drycken.

            int soda_input = 0;

            string chosenSoda = "";
            do
            {

                Console.WriteLine("1: Coca-cola"); // skriver ut alternativen för flaska
                Console.WriteLine("2: Fanta");
                Console.WriteLine("3: Pepsi");
                Console.WriteLine("4: Beer");
                Console.WriteLine("5: Redbull");
                Console.WriteLine("6: Cider");
                Console.WriteLine("7: Water");

                try
                {
                    soda_input = int.Parse(Console.ReadLine());
                }
                catch (Exception e)
                {
                    Console.WriteLine("Just numbers, my friend");
                    continue;
                }

                if (chosenSoda == null)**
                {
                    crate[numberOfBottles] = chosenSoda; // lagrar svaren i min vektor
                } THIS IS THE IF-STATEMENT THAT IS MESSING EVERYTHING UP

                numberOfBottles++;  // för varje svar jag skriver så ökar det med 1 i vektorn hela vägen till 24

                switch (soda_input) // Skapar en meny, som skriver ut vilken dryck användaren väljer tills backen blir full.
                {

                    case 1:
                        chosenSoda = "Coca-Cola";
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Du valde Coca-Cola");
                        Console.WriteLine("-------------------");
                        break;

                    case 2:
                        chosenSoda = "Fanta";
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Du valde Fanta");
                        Console.WriteLine("-------------------");
                        break;

                    case 3:
                        chosenSoda = "Pepsi";
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Du valde Pepsi");
                        Console.WriteLine("-------------------");
                        break;

                    case 4:
                        chosenSoda = "Öl";
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Du valde Öl");
                        Console.WriteLine("-------------------");
                        break;

                    case 5:
                        chosenSoda = "Redbull";
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Du valde Redbull");
                        Console.WriteLine("-------------------");
                        break;

                    case 6:
                        chosenSoda = "Cider";
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Du valde Cider");
                        Console.WriteLine("-------------------");
                        break;

                    case 7:
                        chosenSoda = "Vatten";
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Du valde Vatten");
                        Console.WriteLine("-------------------");
                        break;

                    default: // om man skriver siffror ovanför 1-7 så skrivs detta ut.
                        Console.WriteLine("-------------------");
                        Console.WriteLine("Siffor mellan 1-7 min vän");
                        Console.WriteLine("-------------------");
                        break;
                }

            } while (numberOfBottles != 24);

        }
        else
            Console.WriteLine("");
        Console.WriteLine("The crate is full, choose some of the alteratives to check the crate:");
        Console.WriteLine("");

    }

EDIT: "Du valde, means U chose.. in swedish.

Body:
You are assigning the array value before you have chosen anything.

Additionally, you probably want to keep them in the loop and not assign a value if the input is invalid.

To do this you move the if to after the switch, but before the while statement.  By checking for not equal (!=) to null (which I don't think it will ever be) and also checking for not equal to "", you are forcing them to stay on the current bottle and keep inputting until they make a valid selection.

Try this:

do
        {

            Console.WriteLine("1: Coca-cola"); // skriver ut alternativen för flaska
            Console.WriteLine("2: Fanta");
            Console.WriteLine("3: Pepsi");
            Console.WriteLine("4: Beer");
            Console.WriteLine("5: Redbull");
            Console.WriteLine("6: Cider");
            Console.WriteLine("7: Water");

            try
            {
                soda_input = int.Parse(Console.ReadLine());
            }
            catch (Exception e)
            {
                Console.WriteLine("Just numbers, my friend");
                continue;
            }

            switch (soda_input) // Skapar en meny, som skriver ut vilken dryck användaren väljer tills backen blir full.
            {

                case 1:
                    chosenSoda = "Coca-Cola";
                    Console.WriteLine("-------------------");
                    Console.WriteLine("Du valde Coca-Cola");
                    Console.WriteLine("-------------------");
                    break;

                case 2:
                    chosenSoda = "Fanta";
                    Console.WriteLine("-------------------");
                    Console.WriteLine("Du valde Fanta");
                    Console.WriteLine("-------------------");
                    break;

                case 3:
                    chosenSoda = "Pepsi";
                    Console.WriteLine("-------------------");
                    Console.WriteLine("Du valde Pepsi");
                    Console.WriteLine("-------------------");
                    break;

                case 4:
                    chosenSoda = "Öl";
                    Console.WriteLine("-------------------");
                    Console.WriteLine("Du valde Öl");
                    Console.WriteLine("-------------------");
                    break;

                case 5:
                    chosenSoda = "Redbull";
                    Console.WriteLine("-------------------");
                    Console.WriteLine("Du valde Redbull");
                    Console.WriteLine("-------------------");
                    break;

                case 6:
                    chosenSoda = "Cider";
                    Console.WriteLine("-------------------");
                    Console.WriteLine("Du valde Cider");
                    Console.WriteLine("-------------------");
                    break;

                case 7:
                    chosenSoda = "Vatten";
                    Console.WriteLine("-------------------");
                    Console.WriteLine("Du valde Vatten");
                    Console.WriteLine("-------------------");
                    break;

                default: // om man skriver siffror ovanför 1-7 så skrivs detta ut.
                    Console.WriteLine("-------------------");
                    Console.WriteLine("Siffor mellan 1-7 min vän");
                    Console.WriteLine("-------------------");
                    break;
            }

 if (chosenSoda != null && chosenSoda != "")
            {
                crate[numberOfBottles] = chosenSoda; // lagrar svaren i min vektor
            numberOfBottles++;
            }

        } while (numberOfBottles != 24);


来源: stackexchange

问:
How can I make my bot make embeds from collected messages
I want to make my bot to collect messages and then put them in to a embed

I already tried collectmessages and awaitmessages but it's not working.

```<code>const colectoraddbuilding = await new  Discord.MessageCollector(msgobject.channel, msg => msg.author ==  msgobject.author ,{time: 10000});

building1 = ${colectoraddbuilding.collected};
</code>```

there are not errors but when i try to send the embed where the building 1 var is is then its not adding the new text to the building 1 var

答:
I believe there are a few problems with your code that show a lack of understanding of some JavaScript concepts. You may want to read up more before tackling message collectors and rich embeds, by checking out the links I have provided below.

Your await operator would require an asynchronous context, which you can read more about here.

However, for the goal you want to achieve, you could avoid async-await altogether and instead attach an event listener to the end event emitted by your MessageCollector instance, using Node.js' EventEmitter.on method. You can find a helpful guide about collecting messages here.

Your template literal isn't valid either. For starters, it should be wrapped in backticks (`). You can read more about that here.

Once you have successfully collected messages, you can follow this guide to try your hand at rich embeds.

ContentLicense: CC BY-SA 4.0

Body:
I want to make my bot to collect messages and then put them in to a embed

I already tried collectmessages and awaitmessages but it's not working.

const colectoraddbuilding = await new  Discord.MessageCollector(msgobject.channel, msg => msg.author ==  msgobject.author ,{time: 10000});

building1 = ${colectoraddbuilding.collected};

there are not errors but when i try to send the embed where the building 1 var is is then its not adding the new text to the building 1 var


问:
„Can't convert object to primitive value" in Internet Explorer
I'm coding a webpage with Angular 7. Everything workes fine in Chrome, but in IE get en Exception while running:

Can't convert object to primitive value (polyfills.ts)

I really don't know where exactly the error came from....

I already found a Thread, where it says, that all Classes need a toString Method, so i added one, but this doesn't worked. Also i removed every ${}... Nothing.

IE Konsole: IE-Konsole

Debugger: Debugger

答:
Belive it or not, but the problem was this line in index.html:

```<code><script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=true&key=MY_KEY&libraries=places&language=de_DE"></script>
</code>```

Removing it worked. But i need it, so i added dynamicly via javascript. This worked... Thats so random^^

Body:
Belive it or not, but the problem was this line in index.html:

<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=true&key=MY_KEY&libraries=places&language=de_DE"></script>

Removing it worked. But i need it, so i added dynamicly via javascript. This worked... Thats so random^^


问:
How Can I Correctly Use Registry Permissions to Delete a Registry Subkey in C#?
In the Windows Registry I have the subkey \HKEY_CURRENT_USER\HTMPTK, which has two values: Secret Token and Token. I want to delete the two values.

I attempted to use key.DeleteValue("Secret Token") (key is a RegistryKey variable), but I got an UnauthorizedAccessException, with the message Cannot write to the registry key.

Tinkering around MSDN and Google, to allow the program the access it needs, I found the RegistryPermission class, along with some examples as guidance. Thus, I wrote the following code:

```<code>private bool DeleteTokensFromRegistryEngine()
        {
            RegistryPermission perm = new RegistryPermission(PermissionState.Unrestricted);
            perm.AddPathList(RegistryPermissionAccess.AllAccess, "HKEY_CURRENT_USER\\HTMPTK");
            RegistryKey key = Registry.CurrentUser.OpenSubKey("HTMPTK");
            try
            {
                if (key != null)
                {
                    key.DeleteValue("Secret Token"); //the same error message here
                    key.DeleteValue("Token");
                }
            }
            catch (UnauthorizedAccessException U)
            {
                MessageBox.Show(U.Message);
                return false;
            }
            finally
            {
                key.Close();
            }
            return true;
        }
</code>```

The problem did not disappear.

What am I doing wrong? How can I solve this problem?

Later edit:

I double checked to see if I run the program as an Administrator. I do;

Nothing suspicious signaled by Windows Defender;

If it helps, I can delete the values from Registry Editor;

答:
The reason was because I was using the wrong OpenSubKey ctor. The correct one was:

OpenSubKey(String, RegistryRights)

In my case, the subkey should have been opened with:

RegistryKey key = Registry.CurrentUser.OpenSubKey("HTMPTK",RegistryKeyPermissionCheck.ReadWriteSubtree);

However, there is a better way: because I want to delete both values, it's easier if to delete the whole subkey. I applied this method, and the resulting code was:

```<code>        try
        {
            Registry.CurrentUser.DeleteSubKeyTree("HTMPTK", true);
        }
        catch (UnauthorizedAccessException U)
        {
            MessageBox.Show(U.Message);
            return false;
        }
</code>```

Body:
In the Windows Registry I have the subkey \HKEY_CURRENT_USER\HTMPTK, which has two values: Secret Token and Token. I want to delete the two values.

I attempted to use key.DeleteValue("Secret Token") (key is a RegistryKey variable), but I got an UnauthorizedAccessException, with the message Cannot write to the registry key.

Tinkering around MSDN and Google, to allow the program the access it needs, I found the RegistryPermission class, along with some examples as guidance. Thus, I wrote the following code:

private bool DeleteTokensFromRegistryEngine()
        {
            RegistryPermission perm = new RegistryPermission(PermissionState.Unrestricted);
            perm.AddPathList(RegistryPermissionAccess.AllAccess, "HKEY_CURRENT_USER\\HTMPTK");
            RegistryKey key = Registry.CurrentUser.OpenSubKey("HTMPTK");
            try
            {
                if (key != null)
                {
                    key.DeleteValue("Secret Token"); //the same error message here
                    key.DeleteValue("Token");
                }
            }
            catch (UnauthorizedAccessException U)
            {
                MessageBox.Show(U.Message);
                return false;
            }
            finally
            {
                key.Close();
            }
            return true;
        }

The problem did not disappear.

What am I doing wrong? How can I solve this problem?

Later edit:

I double checked to see if I run the program as an Administrator. I do;

Nothing suspicious signaled by Windows Defender;

If it helps, I can delete the values from Registry Editor;

Body:
The reason was because I was using the wrong OpenSubKey ctor. The correct one was:

OpenSubKey(String, RegistryRights)

In my case, the subkey should have been opened with:

RegistryKey key = Registry.CurrentUser.OpenSubKey("HTMPTK",RegistryKeyPermissionCheck.ReadWriteSubtree);

However, there is a better way: because I want to delete both values, it's easier if to delete the whole subkey. I applied this method, and the resulting code was:

        try
        {
            Registry.CurrentUser.DeleteSubKeyTree("HTMPTK", true);
        }
        catch (UnauthorizedAccessException U)
        {
            MessageBox.Show(U.Message);
            return false;
        }


问:
React hook equivalent to callback function after setting state
In react (before hooks) when we set state we could call a function after state had been set as such:

```<code>this.setState({}, () => {//Callback})
</code>```

What is the equivalent of this with hooks?

I tried doing this

```<code>const [currentRange, setCurrentRange] = useState("24h");

setCurrentRange(someRange, () => console.log('hi'))

</code>```

But this did not work

Anyone know a solution for this?

答:
You can use useEffect/useLayoutEffect to achieve this:

```<code>const SomeComponent = () => {
  const [count, setCount] = React.useState(0)

  React.useEffect(() => {
    if (count > 1) {
      document.title = 'Threshold of over 1 reached.';
    } else {
      document.title = 'No threshold reached.';
    }
  }, [count]);

  return (
    <div>
      <p>{count}</p>

      <button type="button" onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
};
</code>```

If you are looking for an out of the box solution, check out this custom hook that works like useState but accepts as second parameter a callback function:

```<code>import useStateWithCallback from 'use-state-with-callback';

const SomeOtherComponent = () => {
  const [count, setCount] = useStateWithCallback(0, count => {
    if (count > 1) {
      document.title = 'Threshold of over 1 reached.';
    } else {
      document.title = 'No threshold reached.';
    }
  });

  return (
    <div>
      <p>{count}</p>

      <button type="button" onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
};
</code>```

It can be installed via npm install use-state-with-callback

Body:
In react (before hooks) when we set state we could call a function after state had been set as such:

this.setState({}, () => {//Callback})

What is the equivalent of this with hooks?

I tried doing this

const [currentRange, setCurrentRange] = useState("24h");

setCurrentRange(someRange, () => console.log('hi'))

But this did not work

Anyone know a solution for this?

Body:
You can use useEffect/useLayoutEffect to achieve this:

const SomeComponent = () => {
  const [count, setCount] = React.useState(0)

  React.useEffect(() => {
    if (count > 1) {
      document.title = 'Threshold of over 1 reached.';
    } else {
      document.title = 'No threshold reached.';
    }
  }, [count]);

  return (
    <div>
      <p>{count}</p>

      <button type="button" onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
};

If you are looking for an out of the box solution, check out this custom hook that works like useState but accepts as second parameter a callback function:

import useStateWithCallback from 'use-state-with-callback';

const SomeOtherComponent = () => {
  const [count, setCount] = useStateWithCallback(0, count => {
    if (count > 1) {
      document.title = 'Threshold of over 1 reached.';
    } else {
      document.title = 'No threshold reached.';
    }
  });

  return (
    <div>
      <p>{count}</p>

      <button type="button" onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
};

It can be installed via npm install use-state-with-callback


问:
Count frequency of text in list in dataframe
I’m new to python / pandas but have a question which I’ll ask logically to help me learn

I have a dataframe called parties with the following data

```<code>(index)    name                  invitees
0            birthday party     [mike, peter]
1            Retirement          [peter]
2            office opening     [simon, mike, peter]
</code>```

I’d like to be able to create a dictionary which will show the distinct names from the invitees column along with frequency e.g. something like this

```<code>mike: 2, peter: 3, simon: 1
</code>```

I’ve tried to find something similar on here but I’m not too sure of the right terminology to use.

Any help would be greatly appreciated
Thanks a lot

答:
You can use Counter from collections and chain from itertools to solve your problem:

```<code>from collections import Counter
from itertools import chain

df2= pd.DataFrame({
    'name':["blah", "blah-blah", "waka-waka"],
    'invites':[['mike', 'peter'], ['peter', 'mike'], ['waka', 'peter', 'simon']]
})
Counter([elem for elem in chain.from_iterable(df2['invites'].values)])
</code>```

Counter({'mike': 2, 'peter': 3, 'simon': 1, 'waka': 1})

Body:
I’m new to python / pandas but have a question which I’ll ask logically to help me learn

I have a dataframe called parties with the following data

(index)    name                  invitees
0            birthday party     [mike, peter]
1            Retirement          [peter]
2            office opening     [simon, mike, peter]

I’d like to be able to create a dictionary which will show the distinct names from the invitees column along with frequency e.g. something like this

mike: 2, peter: 3, simon: 1

I’ve tried to find something similar on here but I’m not too sure of the right terminology to use.

Any help would be greatly appreciated
Thanks a lot

Body:
You can use Counter from collections and chain from itertools to solve your problem:

from collections import Counter
from itertools import chain

df2= pd.DataFrame({
    'name':["blah", "blah-blah", "waka-waka"],
    'invites':[['mike', 'peter'], ['peter', 'mike'], ['waka', 'peter', 'simon']]
})
Counter([elem for elem in chain.from_iterable(df2['invites'].values)])

Counter({'mike': 2, 'peter': 3, 'simon': 1, 'waka': 1})


问:
Eloquent query with two models
I need your help, please!
I have two models customer and membership. Customer hasMany Memberships.
I need to extract all customers with a membership active. I did this but it extracts only memberships, without customers data. How can I change it to solve the problem?

```<code>Membership::has("customer")
    ->forCompany($companyId)
    ->whereIn('state', ['ATTIVA', 'IN ATTESA DI ESITO', 'DA INVIARE'])
    ->where(function ($query) {
        $query
            ->where('end_date', '>=', Carbon::now()->toDateString())
            ->orWhereNull('end_date');
    })
</code>```

答:
If you want the customers data with membership you must write the query from Customers model and not the Membership model. In case you want to eager load the membership with customers data, you must use with() method.

So here is the query you want:

```<code>$customers = Customer::whereHas("memberships",function($q) use ($companyId){

    return $q->forCompany($companyId)
              ->whereIn('state', ['ATTIVA', 'IN ATTESA DI ESITO', 'DA INVIARE'])
              ->where(function ($query) {
                   $query->where('end_date', '>=', Carbon::now()->toDateString())
                         ->orWhereNull('end_date');
               });

})->with('memberships')->get();
</code>```

So, you can access the memberships of each customer like so:

```<code>foreach($customers as $customer)
    $memberships = $customer->memberships;
</code>```

Notice : don't forget to define the membersips() method in Customer model. Remember to eager load the memberships with customer data using ->with() method. and don't forget to use ->get() at the end of query.

Here you can read about eager loading.

Title: Eloquent query with two models

Body:
I need your help, please!
I have two models customer and membership. Customer hasMany Memberships.
I need to extract all customers with a membership active. I did this but it extracts only memberships, without customers data. How can I change it to solve the problem?

Membership::has("customer")
    ->forCompany($companyId)
    ->whereIn('state', ['ATTIVA', 'IN ATTESA DI ESITO', 'DA INVIARE'])
    ->where(function ($query) {
        $query
            ->where('end_date', '>=', Carbon::now()->toDateString())
            ->orWhereNull('end_date');
    })

Body:
If you want the customers data with membership you must write the query from Customers model and not the Membership model. In case you want to eager load the membership with customers data, you must use with() method.

So here is the query you want:

$customers = Customer::whereHas("memberships",function($q) use ($companyId){

    return $q->forCompany($companyId)
              ->whereIn('state', ['ATTIVA', 'IN ATTESA DI ESITO', 'DA INVIARE'])
              ->where(function ($query) {
                   $query->where('end_date', '>=', Carbon::now()->toDateString())
                         ->orWhereNull('end_date');
               });

})->with('memberships')->get();

So, you can access the memberships of each customer like so:

foreach($customers as $customer)
    $memberships = $customer->memberships;

Notice : don't forget to define the membersips() method in Customer model. Remember to eager load the memberships with customer data using ->with() method. and don't forget to use ->get() at the end of query.

Here you can read about eager loading.


问:
scrollViewDidScroll called with strange contentOffsetY
I have a UIViewController that holds a NSFetchedResultsController. After the insertion of rows to the top, I want to keep the rows visible as they where before the insertions. This means I need to make some calculations to keep the contentOffSetY right after the update. The calculation is correct, but I noticed that scrollViewDidScroll gets called after it scrolled to my specified contentOffsetY, this results in a corrupted state. This is the logging:

```<code>Will apply an corrected Y value of: 207.27359771728516
Scrolled to: 207.5
Corrected to: 207.27359771728516
Scrolled to: 79.5 <-- Why is this logline here?
</code>```

You can directly clone an example project: https://github.com/Jasperav/FetchResultControllerGlitch (commit https://github.com/Jasperav/FetchResultControllerGlitch/commit/d46054040139afeeb648e1e0b5b113bd98685b4a, the newest version of the project only glitches, the weird call to the scrollViewDidScroll method is now gone. If you fix the glitch I award the bounty. Just clone the newest version, run it and scroll a little bit. You will see strange content offset's (glitches)). Run the project and you will see the strange output. This is the controllerDidChangeContent method:

```<code>public func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    let currentSize = tableView.contentSize.height

    UIView.performWithoutAnimation {
        tableView.endUpdates()

        let newSize = tableView.contentSize.height
        let correctedY = tableView.contentOffset.y + newSize - currentSize

        print("Will apply an corrected Y value of: \(correctedY)")
        tableView.setContentOffset(CGPoint(x: 0,
                                           y: correctedY),
                                   animated: false)
        print("Corrected to: \(correctedY)")
    }
}
</code>```

If I call tableView.layoutIfNeeded right after the tableView.endUpdates(), the delegate is already called. What does it cause to call the delegate method? Is there any way it does not scroll?

答:
I downloaded your code and made some tweaks to fix the glitching issue. Here is what I have done.

set estimatedRowHeight property of table view to some number

```<code>    init() {
        super.init(frame: .zero, style: .plain)
        estimatedRowHeight = 50.0
        register(MyTableViewCell.self, forCellReuseIdentifier: "cell")
    }
</code>```

created a function to handle the UITableView reload action without modifying the current contentOffset

```<code>    func reloadDataWithoutScroll() {
        let lastScrollOffset = contentOffset
        beginUpdates()
        reloadData()
        layoutIfNeeded()
        endUpdates()
        layer.removeAllAnimations()
        setContentOffset(lastScrollOffset, animated: false)
    }
</code>```

Updated controllerDidChangeContent function to make use of the reloadDataWithoutScroll function

```<code>    UIView.performWithoutAnimation {
        tableView.performBatchUpdates({
            tableView.insertRows(at: inserts, with: .automatic)
        })
        inserts.removeAll()
        tableView.reloadDataWithoutScroll()
    }
</code>```

When I execute with these changes, it doesn't scroll when a new row is added. However, it does scroll to show the new added row when the current contentOffset is 0. And I don't think that would be a problem, logically speaking.

Body:
I have a UIViewController that holds a NSFetchedResultsController. After the insertion of rows to the top, I want to keep the rows visible as they where before the insertions. This means I need to make some calculations to keep the contentOffSetY right after the update. The calculation is correct, but I noticed that scrollViewDidScroll gets called after it scrolled to my specified contentOffsetY, this results in a corrupted state. This is the logging:

Will apply an corrected Y value of: 207.27359771728516
Scrolled to: 207.5
Corrected to: 207.27359771728516
Scrolled to: 79.5 <-- Why is this logline here?

You can directly clone an example project: https://github.com/Jasperav/FetchResultControllerGlitch (commit https://github.com/Jasperav/FetchResultControllerGlitch/commit/d46054040139afeeb648e1e0b5b113bd98685b4a, the newest version of the project only glitches, the weird call to the scrollViewDidScroll method is now gone. If you fix the glitch I award the bounty. Just clone the newest version, run it and scroll a little bit. You will see strange content offset's (glitches)). Run the project and you will see the strange output. This is the controllerDidChangeContent method:

public func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    let currentSize = tableView.contentSize.height

    UIView.performWithoutAnimation {
        tableView.endUpdates()

        let newSize = tableView.contentSize.height
        let correctedY = tableView.contentOffset.y + newSize - currentSize

        print("Will apply an corrected Y value of: \(correctedY)")
        tableView.setContentOffset(CGPoint(x: 0,
                                           y: correctedY),
                                   animated: false)
        print("Corrected to: \(correctedY)")
    }
}

If I call tableView.layoutIfNeeded right after the tableView.endUpdates(), the delegate is already called. What does it cause to call the delegate method? Is there any way it does not scroll?

Body:
I downloaded your code and made some tweaks to fix the glitching issue. Here is what I have done.

set estimatedRowHeight property of table view to some number

    init() {
        super.init(frame: .zero, style: .plain)
        estimatedRowHeight = 50.0
        register(MyTableViewCell.self, forCellReuseIdentifier: "cell")
    }

created a function to handle the UITableView reload action without modifying the current contentOffset

    func reloadDataWithoutScroll() {
        let lastScrollOffset = contentOffset
        beginUpdates()
        reloadData()
        layoutIfNeeded()
        endUpdates()
        layer.removeAllAnimations()
        setContentOffset(lastScrollOffset, animated: false)
    }

Updated controllerDidChangeContent function to make use of the reloadDataWithoutScroll function

    UIView.performWithoutAnimation {
        tableView.performBatchUpdates({
            tableView.insertRows(at: inserts, with: .automatic)
        })
        inserts.removeAll()
        tableView.reloadDataWithoutScroll()
    }

When I execute with these changes, it doesn't scroll when a new row is added. However, it does scroll to show the new added row when the current contentOffset is 0. And I don't think that would be a problem, logically speaking.


问:
PowerShell Array w/ Filter ~ ParameterBindingException
I am trying to make a list of users and compare their SamAccount Names to Active Directory and to filter which user AD accounts are disabled.

I receive the error message below when I execute the script.

I do the following:

```<code>$Names = @("Shannon.Hoffman","Kameron.Mack","Ashleigh.Reeves","Diego.Colon","Mayra Ortega","Mark.Dunn")
Get-ADUser -Filter {(Enabled -eq "False") -and (SAMAccountName -like $Names)}
</code>```

I recieve this error message:

```<code>Get-ADUser : Cannot convert 'System.Object[]' to the type 'Microsoft.ActiveDirectory.Management.ADUser' required by parameter 'Identity'. Specified method is not supported.
</code>```

I also get an error saying ParameterBindingException

I am relatively new to PowerShell. Can you please help me understand what I am doing wrong?

Many Thanks!

答:
I would really suggest that you learn PowerShell before trying to do useful things. Things can go badly very quickly.

For one thing, you are filtering using the entire list instead of per user, so you would need to use a loop. Something like the below could do what you require:

```<code>$Names = @("username1","username2")
Foreach ($Name in $Names){
    $User = Get-ADUser -Identity $Name
    if ($User.Enabled){
        #user is enabled, add to your list
    }
}
</code>```

Heres some extra reading:

Foreach

Pipeline

PS AD

Body:
I am trying to make a list of users and compare their SamAccount Names to Active Directory and to filter which user AD accounts are disabled.

I receive the error message below when I execute the script.

I do the following:

$Names = @("Shannon.Hoffman","Kameron.Mack","Ashleigh.Reeves","Diego.Colon","Mayra Ortega","Mark.Dunn")
Get-ADUser -Filter {(Enabled -eq "False") -and (SAMAccountName -like $Names)}

I recieve this error message:

Get-ADUser : Cannot convert 'System.Object[]' to the type 'Microsoft.ActiveDirectory.Management.ADUser' required by parameter 'Identity'. Specified method is not supported.

I also get an error saying ParameterBindingException

I am relatively new to PowerShell. Can you please help me understand what I am doing wrong?

Many Thanks!

Body:
I would really suggest that you learn PowerShell before trying to do useful things. Things can go badly very quickly.

For one thing, you are filtering using the entire list instead of per user, so you would need to use a loop. Something like the below could do what you require:

$Names = @("username1","username2")
Foreach ($Name in $Names){
    $User = Get-ADUser -Identity $Name
    if ($User.Enabled){
        #user is enabled, add to your list
    }
}

Heres some extra reading:

Foreach

Pipeline

PS AD


问:
C# if directive
Can I write in code to set the variable to true or false depending on a button I pressed? See example below.

If not, what other ways are there to achieve similar effects? I have already marked the codes for different modes using directives and only want developers to have the option of switching the modes, but now I wish to give the user the option of switching between the modes. The choice of the mode will only be given at the start of the program, and user is not allowed to switch the mode. To switch the mode, he can only restart the program again.

If cannot use directives, what is the fastest way can I use? (note: the statements are all around the solution)

In pseduocode of what I wish to achieve:

```<code>void button_click(...){
    if(!CONDITION)
        CONDITION = true;
    else
        CONDITION = false;
}

...
#if CONDITION
   //mode X with addtional steps
#endif
</code>```

答:
The #IF directive is a preprocessor option and will have no meaning once you compile the code so you can't use these to control program flow after compilation.

As for your other options, you should be able to convert them to class-level variables rather easily but, on the negative side, your code will be littered with if CONDITION ... else ... statements that could end up being a pain in the butt to manage.

Another more OOP-friendly option, is to implement the State pattern.  You could encapsulate the behavior of each "Condition" into its own State and toggle between them in the pattern.  This could be overkill for two states (most likely is).

Another reference:  http://www.dofactory.com/Patterns/PatternState.aspx

Title: C# if directive

Body:
Can I write in code to set the variable to true or false depending on a button I pressed? See example below.

If not, what other ways are there to achieve similar effects? I have already marked the codes for different modes using directives and only want developers to have the option of switching the modes, but now I wish to give the user the option of switching between the modes. The choice of the mode will only be given at the start of the program, and user is not allowed to switch the mode. To switch the mode, he can only restart the program again.

If cannot use directives, what is the fastest way can I use? (note: the statements are all around the solution)

In pseduocode of what I wish to achieve:

void button_click(...){
    if(!CONDITION)
        CONDITION = true;
    else
        CONDITION = false;
}

...
#if CONDITION
   //mode X with addtional steps
#endif

ContentLicense: CC BY-SA 3.0


问:
Stuck Implementing Tricky Scroll Behavior
I'm facing a pretty tricky problem in an app I'm working on and have been banging my head on my desk for a while now trying to solve it. Any tips would be greatly appreciated!

Basically, I have a container that contains many elements inside it; so many that they overflow and the container scrolls. There is one special element in the container that I want to always be in the middle of the container -- even as items are continuously added above and below it. I have achieved this, however, here's the catch: as soon as the user manually scrolls this container, I would like to disable the previous behavior where that one special item remains in the center of the container, which I haven't been able to do.

Below is my best attempt at implementing an example of this and here is a link to a codesandbox of my attempt. The way my implementation works is I have a container which contains a list of items rendered from an array, then the "special item," and then a bunch more items rendered from a different array. When the component mounts I run two functions: center and updater. center initally centers the special item, and updater starts adding items to both arrays every so often with setInterval. Every time an item is added to one of the arrays, center is run again to keep the special item centered in its parent container. So far this works perfectly to keep the special item centered.

To disable this centering behavior, I have a boolean that's initially false called hasScrolled in state, and an event listener attached to the main container's onWheel event called userScrollHandler that sets hasScrolled to true. My center function only centers the special item if hasScrolled is false, so theoretically once the user scrolls, hasScrolled will be true and then the centering behavior will stop. Unfortunately, this doesn't seem to work. I'm positive that both the event is behing called when the user scrolls the container (open the console to see a log on each scroll) and that hasScrolled is being set to true. For some reason the center function thinks that hasScrolled is false. I have tried numerous other things like passing these value to the center function, not keeping hasScrolled in state and just having it be a relgular variable, using context, etc. I'm a loss as to how to do this and why none of my implementations don't work. Anyone have an idea of how to do this or what I'm doing wrong?

My implementation:

```<code>import React, { useState, useEffect, useRef, useReducer } from "react";
import ReactDOM from "react-dom";

const items1 = [];
for (let i = 0; i < 10; i++) {
  items1.push("top");
}
const items2 = [];
for (let i = 0; i < 10; i++) {
  items2.push("bottom");
}

const App = () => {
  const [hasScrolled, setHasScrolled] = useState(false);
  const [tops, addTopItem] = useReducer(state => {
    const stateCopy = [...state];
    stateCopy.push(Math.random());
    return stateCopy;
  }, items1);
  const [bottoms, addBottomItem] = useReducer(state => {
    const stateCopy = [...state];
    stateCopy.unshift(Math.random());
    return stateCopy;
  }, items2);

  const middle = useRef(null);
  const container = useRef(null);

  const center = () => {
    if (hasScrolled) return;

    container.current.scrollTo(
      0,
      middle.current.offsetTop -
        container.current.offsetTop -
        container.current.clientHeight / 2
    );
  };

  const updater = () => {
    setInterval(() => {
      addTopItem();
      if (container.current && middle.current) center();
    }, 500);

    setInterval(() => {
      addBottomItem();
      if (container.current && middle.current) center();
    }, 700);
  };

  const userScrollHandler = e => {
    console.log("user scrolled");
    setHasScrolled(true);
  };

  useEffect(() => {
    center();
    updater();
  }, []);

  return (
    <div ref={container} onWheel={userScrollHandler} style={containerStyle}>
      {tops.map((item, idx) => {
        return (
          <div key={idx} style={itemStyle}>
            {item}
          </div>
        );
      })}
      <div ref={middle} style={middleItemStyle}>
        Middle
      </div>
      {bottoms.map((item, idx) => {
        return (
          <div key={idx} style={itemStyle}>
            {item}
          </div>
        );
      })}
    </div>
  );
};

const containerStyle = {
  margin: "0 auto",
  marginTop: "10vh",
  height: "400px",
  width: "300px",
  background: "#eee",
  overflow: "auto"
};

const itemStyle = {
  width: "100%",
  height: "40px",
  borderBottom: "1px solid blue",
  display: "flex",
  justifyContent: "center",
  alignItems: "center"
};

const middleItemStyle = { ...itemStyle };
middleItemStyle.background = "lime";

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
</code>```

答:
Can you make Middle element independent and just not render it?</p>

```<code>{hasScrolled && <div ref={middle} style={middleItemStyle}>
        Middle
      </div>}
</code>```

Body:
I'm facing a pretty tricky problem in an app I'm working on and have been banging my head on my desk for a while now trying to solve it. Any tips would be greatly appreciated!

Basically, I have a container that contains many elements inside it; so many that they overflow and the container scrolls. There is one special element in the container that I want to always be in the middle of the container -- even as items are continuously added above and below it. I have achieved this, however, here's the catch: as soon as the user manually scrolls this container, I would like to disable the previous behavior where that one special item remains in the center of the container, which I haven't been able to do.

Below is my best attempt at implementing an example of this and here is a link to a codesandbox of my attempt. The way my implementation works is I have a container which contains a list of items rendered from an array, then the "special item," and then a bunch more items rendered from a different array. When the component mounts I run two functions: center and updater. center initally centers the special item, and updater starts adding items to both arrays every so often with setInterval. Every time an item is added to one of the arrays, center is run again to keep the special item centered in its parent container. So far this works perfectly to keep the special item centered.

To disable this centering behavior, I have a boolean that's initially false called hasScrolled in state, and an event listener attached to the main container's onWheel event called userScrollHandler that sets hasScrolled to true. My center function only centers the special item if hasScrolled is false, so theoretically once the user scrolls, hasScrolled will be true and then the centering behavior will stop. Unfortunately, this doesn't seem to work. I'm positive that both the event is behing called when the user scrolls the container (open the console to see a log on each scroll) and that hasScrolled is being set to true. For some reason the center function thinks that hasScrolled is false. I have tried numerous other things like passing these value to the center function, not keeping hasScrolled in state and just having it be a relgular variable, using context, etc. I'm a loss as to how to do this and why none of my implementations don't work. Anyone have an idea of how to do this or what I'm doing wrong?

My implementation:

import React, { useState, useEffect, useRef, useReducer } from "react";
import ReactDOM from "react-dom";

const items1 = [];
for (let i = 0; i < 10; i++) {
  items1.push("top");
}
const items2 = [];
for (let i = 0; i < 10; i++) {
  items2.push("bottom");
}

const App = () => {
  const [hasScrolled, setHasScrolled] = useState(false);
  const [tops, addTopItem] = useReducer(state => {
    const stateCopy = [...state];
    stateCopy.push(Math.random());
    return stateCopy;
  }, items1);
  const [bottoms, addBottomItem] = useReducer(state => {
    const stateCopy = [...state];
    stateCopy.unshift(Math.random());
    return stateCopy;
  }, items2);

  const middle = useRef(null);
  const container = useRef(null);

  const center = () => {
    if (hasScrolled) return;

    container.current.scrollTo(
      0,
      middle.current.offsetTop -
        container.current.offsetTop -
        container.current.clientHeight / 2
    );
  };

  const updater = () => {
    setInterval(() => {
      addTopItem();
      if (container.current && middle.current) center();
    }, 500);

    setInterval(() => {
      addBottomItem();
      if (container.current && middle.current) center();
    }, 700);
  };

  const userScrollHandler = e => {
    console.log("user scrolled");
    setHasScrolled(true);
  };

  useEffect(() => {
    center();
    updater();
  }, []);

  return (

      {tops.map((item, idx) => {
        return (

            {item}

        );
      })}

        Middle

      {bottoms.map((item, idx) => {
        return (

            {item}

        );
      })}

  );
};

const containerStyle = {
  margin: "0 auto",
  marginTop: "10vh",
  height: "400px",
  width: "300px",
  background: "#eee",
  overflow: "auto"
};

const itemStyle = {
  width: "100%",
  height: "40px",
  borderBottom: "1px solid blue",
  display: "flex",
  justifyContent: "center",
  alignItems: "center"
};

const middleItemStyle = { ...itemStyle };
middleItemStyle.background = "lime";

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Body:
Can you make Middle element independent and just not render it?

{hasScrolled && <div ref={middle} style={middleItemStyle}>
        Middle
      </div>}


问:
How to wait for multiple conditions on invisibility_of_element_located using Selenium through Python
I want to wait for the element to disappear on Selenium, but at the same time I must ensure that all the elements are gone. Right now, it is something like this:

```<code>element = WebDriverWait(driver, 30).until(
    expected_conditions.element_to_be_clickable((By.XPATH, xpath))
)
is_clickable = WebDriverWait(driver, 30).until(
    expected_conditions.invisibility_of_element_located((By.XPATH, layovers[0]))
)
is_clickable_2 = WebDriverWait(driver, 30).until(
    expected_conditions.invisibility_of_element_located((By.XPATH, layovers[1]))
)

if is_clickable and is_clickable_2:
    element.click()
</code>```

And there are more than two elements on the layovers list, which store xpaths as str.

In this case, can I make all of them into a single function that checks the invisibility of the elements, instead of repeating them? (I mean, make the WebDriverWait takes only one call, and not define another wrapper function.)

答:
until_not()

The until_not(method, message='') method from WebDriverWait class calls the method provided with the driver as an argument until the return value is False.

This usecase

As your usecase is to wait for multiple conditions on invisibility_of_element_located() through xpath you can club up both the expected_conditions:

WebDriverWait(driver, 30).until(expected_conditions.invisibility_of_element_located((By.XPATH, layovers[0])))

WebDriverWait(driver, 30).until(expected_conditions.invisibility_of_element_located((By.XPATH, layovers[1])))

within a single expression using until_not() method through a lambda  expression as follows:

```<code>WebDriverWait(driver,15).until_not(lambda driver: driver.find_element(By.XPATH,layovers[0]) and driver.find_element(By.XPATH,layovers[1]))
</code>```

Outro

You can find a couple of similar relevant discussions in:

Python / Selenium: Logic Operators in WebDriverWait Expected Conditions

How to extract dynamic text from multiple child nodes within the html through getText()

Body:
I want to wait for the element to disappear on Selenium, but at the same time I must ensure that all the elements are gone. Right now, it is something like this:

element = WebDriverWait(driver, 30).until(
    expected_conditions.element_to_be_clickable((By.XPATH, xpath))
)
is_clickable = WebDriverWait(driver, 30).until(
    expected_conditions.invisibility_of_element_located((By.XPATH, layovers[0]))
)
is_clickable_2 = WebDriverWait(driver, 30).until(
    expected_conditions.invisibility_of_element_located((By.XPATH, layovers[1]))
)

if is_clickable and is_clickable_2:
    element.click()

And there are more than two elements on the layovers list, which store xpaths as str.

In this case, can I make all of them into a single function that checks the invisibility of the elements, instead of repeating them? (I mean, make the WebDriverWait takes only one call, and not define another wrapper function.)

Body:
until_not()

The until_not(method, message='') method from WebDriverWait class calls the method provided with the driver as an argument until the return value is False.

This usecase

As your usecase is to wait for multiple conditions on invisibility_of_element_located() through xpath you can club up both the expected_conditions:

WebDriverWait(driver, 30).until(expected_conditions.invisibility_of_element_located((By.XPATH, layovers[0])))

WebDriverWait(driver, 30).until(expected_conditions.invisibility_of_element_located((By.XPATH, layovers[1])))

within a single expression using until_not() method through a lambda  expression as follows:

WebDriverWait(driver,15).until_not(lambda driver: driver.find_element(By.XPATH,layovers[0]) and driver.find_element(By.XPATH,layovers[1]))

Outro

You can find a couple of similar relevant discussions in:

Python / Selenium: Logic Operators in WebDriverWait Expected Conditions

How to extract dynamic text from multiple child nodes within the html through getText()


问:
Set dynamic headers in axios from an ExpressJS app
I have a requirement where I need to set a Request-Id header with each axios request. This header's value gets dynamically generated by another express middleware.

Now I can do :

```<code>axios.get(url, headers: {'Request-Id': req.requestId});
</code>```

But I'd like to move this abstraction someplace common, so that this can be reused everywhere. I came up with a custom express middleware :

```<code>app.use(function (req, res, next) {
  req.fetch = axios;
  req.fetch.defaults.headers.common['Request-Id'] = req.requestId;
  next();
})
</code>```

Now I can use req.fetch in any route without having to set the header individually, but is this a recommended approach ?
It would be helpful if someone could explain if this approach has any pitfalls, or a better solution.

答:
This does look fine to me right now.

You could use some config file as well to let the server consume or not your the middleware you just wrote :)

Maybe some other people might tell us their thoughts about it

Body:
I have a requirement where I need to set a Request-Id header with each axios request. This header's value gets dynamically generated by another express middleware.

Now I can do :

axios.get(url, headers: {'Request-Id': req.requestId});

But I'd like to move this abstraction someplace common, so that this can be reused everywhere. I came up with a custom express middleware :

app.use(function (req, res, next) {
  req.fetch = axios;
  req.fetch.defaults.headers.common['Request-Id'] = req.requestId;
  next();
})

Now I can use req.fetch in any route without having to set the header individually, but is this a recommended approach ?
It would be helpful if someone could explain if this approach has any pitfalls, or a better solution.


问:
How to display a page only, if certain parameters are provided in the URL?
I want to create a page in Spring, which has the url

http://myapp.com/sign-in?email=myemail@provider.com&pw=password

password is a one-time password that the user receives via e-mail every time they want to sign in.

Whenever the user visits this page, I want two things to happen:

Check whether or not the provided credentials are correct.

If they are, display the HTML content of the page.

I've done the first part:

```<code>    @Autowired
    private var userRepository: UserRepository? = null

    @GetMapping
    fun signIn(@RequestParam email:String, @RequestParam(name="pw") password:String): RedirectView {
        // Is the password correct?

        // TODO: Read password hash of the user
        val existingUser: Optional<UserInfo>? = userRepository?.findById(email)
        if (existingUser == null) {
            return redirectToErrorPage("Please register with your e-mail address first")
        }
        if (!existingUser.isPresent) {
            return redirectToErrorPage("Please register with your e-mail address first")
        }
        val hashInDb = existingUser.get().passwordHash
        val hashInParam = PasswordHashCalculator.calculateHash(password)
        if (!hashInDb.equals(hashInParam)) {
            return redirectToErrorPage("Invalid user name and/or password")
        }

        // TODO: Display the main page
        return null
    }
</code>```

How do I need to change the code in order to display the main page (HTML file in src/main/resources/static), but only if the authentication checks are passed?

Update 1: Using return ClassPathResource("main.html") as recommended here did not help.

答:
```<code>return ClassPathResource("static/main.html") should answer your question, don't forget to specify `static` folder at the beginning as `ClassPathResource` points to the `resources` folder
</code>```

Body:
I want to create a page in Spring, which has the url

http://myapp.com/sign-in?email=myemail@provider.com&pw=password

password is a one-time password that the user receives via e-mail every time they want to sign in.

Whenever the user visits this page, I want two things to happen:

Check whether or not the provided credentials are correct.

If they are, display the HTML content of the page.

I've done the first part:

    @Autowired
    private var userRepository: UserRepository? = null

    @GetMapping
    fun signIn(@RequestParam email:String, @RequestParam(name="pw") password:String): RedirectView {
        // Is the password correct?

        // TODO: Read password hash of the user
        val existingUser: Optional<UserInfo>? = userRepository?.findById(email)
        if (existingUser == null) {
            return redirectToErrorPage("Please register with your e-mail address first")
        }
        if (!existingUser.isPresent) {
            return redirectToErrorPage("Please register with your e-mail address first")
        }
        val hashInDb = existingUser.get().passwordHash
        val hashInParam = PasswordHashCalculator.calculateHash(password)
        if (!hashInDb.equals(hashInParam)) {
            return redirectToErrorPage("Invalid user name and/or password")
        }

        // TODO: Display the main page
        return null
    }

How do I need to change the code in order to display the main page (HTML file in src/main/resources/static), but only if the authentication checks are passed?

Update 1: Using return ClassPathResource("main.html") as recommended here did not help.


问:
Box collision detection and bouncing
I'm making pong, and am finding it really difficult to write an algorithm that bounces the ball off the four walls properly (I will deal with scoring later on, because only part of the West+East sides will be goals). So at the moment I want the ball to bounce around the box.

Detecting whether the ball has hit a wall is easy, but I'm having trouble calculating the new angle.

This is what I've come up with so far:

```<code>        if(dstY == 0) {
            // North wall
            if(angle < 90) {
                newAngle = angle + 90;
            } else {
                newAngle = angle - 90;
            }
        } else if(dstX == maxWidth) {
            // East wall
            if(angle < 90) {
                newAngle = angle + 270;
            } else {
                newAngle = angle + 90;
            }
        } else if(dstY == maxHeight) {
            // South wall
            newAngle = angle + 90;
        } else if(dstX == 1) {
            // West wall
            if(angle < 270) {
                newAngle = angle - 90;
            } else {
                newAngle = angle - 270;
            }
        }
</code>```

That only works for about half of the collisions, and looks really ugly. I'm sure this should be really simple and that it's been done many times before.

In my code, dstX/dstY are the X/Y destination coordinates. X=0 and y=0 at the top left.

答:
Thanks @jbx, I knew there was a simpler way :) However, that doesn't seem to work for the east and west walls and the paddles (if they're on those walls). This seems to work for me on the east and west walls though:

```<code>(180 - (angle + 90)) - 90.
</code>```

which simplifies to just (180-angle).
Hope that helps.

ContentLicense: CC BY-SA 2.5

Title: Box collision detection and bouncing

Body:
I'm making pong, and am finding it really difficult to write an algorithm that bounces the ball off the four walls properly (I will deal with scoring later on, because only part of the West+East sides will be goals). So at the moment I want the ball to bounce around the box.

Detecting whether the ball has hit a wall is easy, but I'm having trouble calculating the new angle.

This is what I've come up with so far:

        if(dstY == 0) {
            // North wall
            if(angle < 90) {
                newAngle = angle + 90;
            } else {
                newAngle = angle - 90;
            }
        } else if(dstX == maxWidth) {
            // East wall
            if(angle < 90) {
                newAngle = angle + 270;
            } else {
                newAngle = angle + 90;
            }
        } else if(dstY == maxHeight) {
            // South wall
            newAngle = angle + 90;
        } else if(dstX == 1) {
            // West wall
            if(angle < 270) {
                newAngle = angle - 90;
            } else {
                newAngle = angle - 270;
            }
        }

That only works for about half of the collisions, and looks really ugly. I'm sure this should be really simple and that it's been done many times before.

In my code, dstX/dstY are the X/Y destination coordinates. X=0 and y=0 at the top left.

Body:
Thanks @jbx, I knew there was a simpler way :) However, that doesn't seem to work for the east and west walls and the paddles (if they're on those walls). This seems to work for me on the east and west walls though:

(180 - (angle + 90)) - 90.

which simplifies to just (180-angle).
Hope that helps.


问:
F#: Rule of thumb to use specific types / aliased types?
I am creating a sort of "envelope" to keep track of what (Commands and Events) I am sending over RabbitMQ in an application as follows:

type Envelope<'T> = {
    Id: Guid
    CausationId: Guid
    CorrelationId: Guid
    Payload: 'T
    Timestamp: DateTimeOffset
}
```

<p><code>'T</code> being usually a command or event of the form:</p>

<pre class="lang-ml prettyprint-override"><code>type Commands =
    | DoA of Stuff
    | DoB of Stuff
    | DoC of Stuff

type Events =
    | AHappened of Stuff
    | BHappened of Stuff
    | CHappened of Stuff
</code>```

Note: I purposefully use relatively generic names

However, I could also have used specific types:

type CausationId = CausationId of Guid
type CorrelationId = CorrelationId of Guid
type CommandId = CommandId of Guid
type EventId = EventId of Guid
type Timestamp = Timestamp of DateTimeOffset

type DataToDoA = DataToDoA of Stuff
type DataToDoB = DataToDoB of Stuff
type DataToDoC = DataToDoC of Stuff

type Commands =
    | DoA of DataToDoA
    | DoB of DataToDoB
    | DoC of DataToDoC

type DataLeftByA = DataLeftByA of Stuff
type DataLeftByB = DataLeftByB of Stuff
type DataLeftByC = DataLeftByC of Stuff

type Events =
    | AHappened of DataLeftByA
    | BHappened of DataLeftByB
    | CHappened of DataLeftByC
```

<p>Which would have led to:</p>

<pre class="lang-ml prettyprint-override"><code>type CommandEnvelope<`T> = {
    Id: CommandId
    CausationId: CausationId
    CorrelationId: CorrelationId
    Payload: `T
    Timestamp: Timestamp
}

type EventEnvelope<`T> = {
    Id: EventId
    CausationId: CausationId
    CorrelationId: CorrelationId
    Payload: `T
    Timestamp: Timestamp
}
</code>```

Is there a rule of thumb to decide when to use those specific types / aliases-ish?

答:
I don't think there is a rule of thumb for this, but one systematic way of thinking about this is to consider whether values represented by those extra types will ever need to be passed around in your code on their own. If no, then you do not need those extra types. If yes, then they might be useful.

Let's say you have just Stuff and:

```<code>type DataLeftByA = DataLeftByA of Stuff
type DataLeftByB = DataLeftByB of Stuff

type Events =
    | AHappened of DataLeftByA
    | BHappened of DataLeftByB
</code>```

One thing that this lets you do is to write a function:

```<code>let processDataA (DataLeftByA stuff) = (...)
</code>```

This function takes DataLeftByA containing some Stuff. However, the type makes it clear that the function should only be used for events caused by A. The following will be a type error:

```<code>let handleEvent = function
    | AHappened adata -> processDataA adata
    | BHappened bdata -> processDataA bdata // Type error here!
</code>```

If you defined your Events as just events contianing the same Stuff:

```<code>type Events =
    | AHappened of Stuff
    | BHappened of Stuff
</code>```

Then the data that your events carry is the same, but you are losing the ability to define a function such as processDataA, because there is no separate type for data carried by event A. You can just define processStuff, but that can then be invoked in both the A and B case.

I think this is the only thing that makes a real practical difference between the two versions. So, the rule of thumb would be - do you ever need to define a function like processDataA or not?

Body:
I am creating a sort of "envelope" to keep track of what (Commands and Events) I am sending over RabbitMQ in an application as follows:

type Envelope<'T> = {
    Id: Guid
    CausationId: Guid
    CorrelationId: Guid
    Payload: 'T
    Timestamp: DateTimeOffset
}

'T being usually a command or event of the form:

type Commands =
    | DoA of Stuff
    | DoB of Stuff
    | DoC of Stuff

type Events =
    | AHappened of Stuff
    | BHappened of Stuff
    | CHappened of Stuff

Note: I purposefully use relatively generic names

However, I could also have used specific types:

type CausationId = CausationId of Guid
type CorrelationId = CorrelationId of Guid
type CommandId = CommandId of Guid
type EventId = EventId of Guid
type Timestamp = Timestamp of DateTimeOffset

type DataToDoA = DataToDoA of Stuff
type DataToDoB = DataToDoB of Stuff
type DataToDoC = DataToDoC of Stuff

type Commands =
    | DoA of DataToDoA
    | DoB of DataToDoB
    | DoC of DataToDoC

type DataLeftByA = DataLeftByA of Stuff
type DataLeftByB = DataLeftByB of Stuff
type DataLeftByC = DataLeftByC of Stuff

type Events =
    | AHappened of DataLeftByA
    | BHappened of DataLeftByB
    | CHappened of DataLeftByC

Which would have led to:

type CommandEnvelope<`T> = {
    Id: CommandId
    CausationId: CausationId
    CorrelationId: CorrelationId
    Payload: `T
    Timestamp: Timestamp
}

type EventEnvelope<`T> = {
    Id: EventId
    CausationId: CausationId
    CorrelationId: CorrelationId
    Payload: `T
    Timestamp: Timestamp
}

Is there a rule of thumb to decide when to use those specific types / aliases-ish?

Body:
I don't think there is a rule of thumb for this, but one systematic way of thinking about this is to consider whether values represented by those extra types will ever need to be passed around in your code on their own. If no, then you do not need those extra types. If yes, then they might be useful.

Let's say you have just Stuff and:

type DataLeftByA = DataLeftByA of Stuff
type DataLeftByB = DataLeftByB of Stuff

type Events =
    | AHappened of DataLeftByA
    | BHappened of DataLeftByB

One thing that this lets you do is to write a function:

let processDataA (DataLeftByA stuff) = (...)

This function takes DataLeftByA containing some Stuff. However, the type makes it clear that the function should only be used for events caused by A. The following will be a type error:

let handleEvent = function
    | AHappened adata -> processDataA adata
    | BHappened bdata -> processDataA bdata // Type error here!

If you defined your Events as just events contianing the same Stuff:

type Events =
    | AHappened of Stuff
    | BHappened of Stuff

Then the data that your events carry is the same, but you are losing the ability to define a function such as processDataA, because there is no separate type for data carried by event A. You can just define processStuff, but that can then be invoked in both the A and B case.

I think this is the only thing that makes a real practical difference between the two versions. So, the rule of thumb would be - do you ever need to define a function like processDataA or not?


问:
using declaration in class definition
I found that 'using' keyword can be used in class definition.
according to https://en.cppreference.com/w/cpp/language/using_declaration, its used for member function is as follows:

If the name is the name of an overloaded member function of the base
  class, all base class member functions with that name are introduced.
  If the derived class already has a member with the same name,
  parameter list, and qualifications, the derived class member hides or
  overrides (doesn't conflict with) the member that is introduced from
  the base class.

an example code is as follows:

```<code>#include <iostream>
struct B {
    virtual void f(int) { std::cout << "B::f\n"; }
    void g(char)        { std::cout << "B::g\n"; }
    void h(int)         { std::cout << "B::h\n"; }
 protected:
    int m; // B::m is protected
    typedef int value_type;
};

struct D : B {
    using B::m; // D::m is public
    using B::value_type; // D::value_type is public

    using B::f;
    void f(int) { std::cout << "D::f\n"; } // D::f(int) overrides     B::f(int)
    using B::g;
    void g(int) { std::cout << "D::g\n"; } // both g(int) and g(char) are visible
                                       // as members of D
    using B::h;
    void h(int) { std::cout << "D::h\n"; } // D::h(int) hides B::h(int)
};

int main()
{
    D d;
    B& b = d;

//    b.m = 2; // error, B::m is protected
    d.m = 1; // protected B::m is accessible as public D::m
    b.f(1); // calls derived f()
    d.f(1); // calls derived f()
    d.g(1); // calls derived g(int)
    d.g('a'); // calls base g(char)
    b.h(1); // calls base h()
    d.h(1); // calls derived h()
}
</code>```

From the above code, I am not sure what is the difference, for instance

```<code>using B::f;
void f(int)
</code>```

and

```<code>virtual void f(int)
</code>```

Is there definite difference for using 'using' keyword in order to override class member function?

答:
The wording from that article is unfortunate. They tried to fix it with the parenthetical, but…

This has nothing to do with virtual function overriding.

The two examples you give are different and unrelated.

One brings the base class f into scope, then chucks that away and introduces a new D::f function. (This will not be virtual unless B::f already was, per the normal rules).

The other declares a virtual D::f.

Title: using declaration in class definition

Body:
I found that 'using' keyword can be used in class definition.
according to https://en.cppreference.com/w/cpp/language/using_declaration, its used for member function is as follows:

If the name is the name of an overloaded member function of the base
  class, all base class member functions with that name are introduced.
  If the derived class already has a member with the same name,
  parameter list, and qualifications, the derived class member hides or
  overrides (doesn't conflict with) the member that is introduced from
  the base class.

an example code is as follows:

#include <iostream>
struct B {
    virtual void f(int) { std::cout << "B::f\n"; }
    void g(char)        { std::cout << "B::g\n"; }
    void h(int)         { std::cout << "B::h\n"; }
 protected:
    int m; // B::m is protected
    typedef int value_type;
};

struct D : B {
    using B::m; // D::m is public
    using B::value_type; // D::value_type is public

    using B::f;
    void f(int) { std::cout << "D::f\n"; } // D::f(int) overrides     B::f(int)
    using B::g;
    void g(int) { std::cout << "D::g\n"; } // both g(int) and g(char) are visible
                                       // as members of D
    using B::h;
    void h(int) { std::cout << "D::h\n"; } // D::h(int) hides B::h(int)
};

int main()
{
    D d;
    B& b = d;

//    b.m = 2; // error, B::m is protected
    d.m = 1; // protected B::m is accessible as public D::m
    b.f(1); // calls derived f()
    d.f(1); // calls derived f()
    d.g(1); // calls derived g(int)
    d.g('a'); // calls base g(char)
    b.h(1); // calls base h()
    d.h(1); // calls derived h()
}

From the above code, I am not sure what is the difference, for instance

using B::f;
void f(int)

and

virtual void f(int)

Is there definite difference for using 'using' keyword in order to override class member function?


问:
can anyone tell me how to use switch?

Possible Duplicate:

  How to apply setting by toggle switch?

I want to use switch button to toggle on and off of a setting

can anyone tell me how to set it up? I already have the following code

Thanks!

declaration

```<code>- (IBAction) changeMode:(id)sender;
</code>```

implementation

```<code>-(IBAction) changeMode:(id)sender
{
}
</code>```

答:
After you hook up the UISwitch in Interface Builder, you can check if it's on like this:</p>

```<code>-(IBAction) changeMode:(id)sender
{
     if ([(UISwitch *)sender on])
     {
          NSLog(@"The switch is on.");
     }
     else
     {
          NSLog(@"The switch is off.");
     }
}
</code>```

Title: can anyone tell me how to use switch?

Body:
Possible Duplicate:

  How to apply setting by toggle switch?

I want to use switch button to toggle on and off of a setting

can anyone tell me how to set it up? I already have the following code

Thanks!

declaration

- (IBAction) changeMode:(id)sender;

implementation

-(IBAction) changeMode:(id)sender
{
}

Body:
After you hook up the UISwitch in Interface Builder, you can check if it's on like this:

-(IBAction) changeMode:(id)sender
{
     if ([(UISwitch *)sender on])
     {
          NSLog(@"The switch is on.");
     }
     else
     {
          NSLog(@"The switch is off.");
     }
}


问:
console.log(this) following by console.log(this.props) don't show same common values
All is in the title.
I am using :"react": "16.8.6"

console.log(this) is showing good information

line following: console.log(this.props) is showing not expected data different from the one in console.log(this)

The plugin React dev tools gives me same good information as console.log(this)

Not the same "this" in both case? How is it possible?

答:
Here is my code. You can point at console.log(this.props) in the getPost method!

```<code>import React from 'react'
import { Container, Row, Col, Alert } from 'reactstrap'

const Api = require('../lib/Api.js')

class PageComponent extends React.Component {

  constructor(props) {
    super(props)

    this.state = {
      page: {
        id: props.match.params.id,
        content: ''
      },
      loading: true,
      flashMessage: {
        message: undefined,
        style: 'success'
      }
    }

  }

  render() {
    if (this.state.loading) {
      return null
    }

    return (
      <Container>
        <Row>
          <Col xs="12" md="12">

            {this.state.flashMessage.message &&
              <Container>
                <Row>
                  <Col xs="12" md="12">
                    <Alert color={this.state.flashMessage.style}>
                      {this.state.flashMessage.message}
                    </Alert>
                  </Col>
                </Row>
              </Container>
            }

            <div>{this.state.page.content}</div>

          </Col>
        </Row>
      </Container>
    )
  }

  componentDidMount() {
    this.getPage()
  }

  componentWillReceiveProps(nextProps) {

    let prevPageId = this.props.match.params.id
    let newPageId = nextProps.match.params.id

    // check if page component is being reloaded with new page props && reload page from Api
    if (prevPageId !== newPageId) {
      this.setState({
        page: {
          id: newPageId,
          content: ''
        }
      })
      this.getPage(newPageId)
    }
  }

  getPage(pageId = null) {
    pageId = pageId || this.state.page.id

    this.setState({
      loading: true,
      flashMessage: {
        message: undefined,
        style: 'success'
      }
    })
    console.log("from Page1")
    console.log(this)
    console.log(this.props)
    console.log(this.state)
    let jwt = this.props.appState.jwt
    console.log(jwt)

    Api.getPage(jwt, pageId).then(response => {
      if (response) {
        this.setState({
          page: response,
          loading: false
        })
      }
      else {
        this.setState({
          loading: false,
          flashMessage: {
            message: 'Access Denied.',
            style: 'danger'
          }
        })
      }
    })
  }

}

export default PageComponent
</code>```

In console for console.log(this) I got:

PageComponent {props: {…}, context: {…}, refs: {…}, updater: {…}, state: {…}, …}

context: {}

props:

appState:

cookieName: "rails-react-token-auth-jwt"

email: "eric.london@example.com"

jwt:
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NTkzODI3MTAsInN1YiI6MX0.hMSIIHK6jl3ftEkTCfbuVtgiUKjt-8dsfR2U-VAUjec"

pages: (4) [{…}, {…}, {…}, {…}]

user_id: 1

In console for console.log(this.props) I got:

appState:

cookieName: "rails-react-token-auth-jwt"

email: undefined

jwt: undefined

pages: []

user_id: undefined

Body:
Here is my code. You can point at console.log(this.props) in the getPost method!

import React from 'react'
import { Container, Row, Col, Alert } from 'reactstrap'

const Api = require('../lib/Api.js')

class PageComponent extends React.Component {

  constructor(props) {
    super(props)

    this.state = {
      page: {
        id: props.match.params.id,
        content: ''
      },
      loading: true,
      flashMessage: {
        message: undefined,
        style: 'success'
      }
    }

  }

  render() {
    if (this.state.loading) {
      return null
    }

    return (
      <Container>
        <Row>
          <Col xs="12" md="12">

            {this.state.flashMessage.message &&
              <Container>
                <Row>
                  <Col xs="12" md="12">
                    <Alert color={this.state.flashMessage.style}>
                      {this.state.flashMessage.message}
                    </Alert>
                  </Col>
                </Row>
              </Container>
            }

            <div>{this.state.page.content}</div>

          </Col>
        </Row>
      </Container>
    )
  }

  componentDidMount() {
    this.getPage()
  }

  componentWillReceiveProps(nextProps) {

    let prevPageId = this.props.match.params.id
    let newPageId = nextProps.match.params.id

    // check if page component is being reloaded with new page props && reload page from Api
    if (prevPageId !== newPageId) {
      this.setState({
        page: {
          id: newPageId,
          content: ''
        }
      })
      this.getPage(newPageId)
    }
  }

  getPage(pageId = null) {
    pageId = pageId || this.state.page.id

    this.setState({
      loading: true,
      flashMessage: {
        message: undefined,
        style: 'success'
      }
    })
    console.log("from Page1")
    console.log(this)
    console.log(this.props)
    console.log(this.state)
    let jwt = this.props.appState.jwt
    console.log(jwt)

    Api.getPage(jwt, pageId).then(response => {
      if (response) {
        this.setState({
          page: response,
          loading: false
        })
      }
      else {
        this.setState({
          loading: false,
          flashMessage: {
            message: 'Access Denied.',
            style: 'danger'
          }
        })
      }
    })
  }

}

export default PageComponent

In console for console.log(this) I got:

PageComponent {props: {…}, context: {…}, refs: {…}, updater: {…}, state: {…}, …}

context: {}

props:

appState:

cookieName: "rails-react-token-auth-jwt"

email: "eric.london@example.com"

jwt:
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NTkzODI3MTAsInN1YiI6MX0.hMSIIHK6jl3ftEkTCfbuVtgiUKjt-8dsfR2U-VAUjec"

pages: (4) [{…}, {…}, {…}, {…}]

user_id: 1

In console for console.log(this.props) I got:

appState:

cookieName: "rails-react-token-auth-jwt"

email: undefined

jwt: undefined

pages: []

user_id: undefined


问:
Enable all notification settings by default in my android app
Is there any way I can enable all notification settings by default when my app gets installed ?

Users are receiving notifications but sound is disabled by default and we need to manually enable it on the device. Not all users can do this manually. It would be great to know if there is any way we can check all these things when our app gets installed like WhatsApp or Telegram (they have everything checked by default)

答:
Try using with this below permission in AndroidManifest file

```<code><uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY"/>
</code>```

and set notification priority for both below and above Oreo versions IMPORTANCE_HIGH for Oreo and above, and PRIORITY_HIGH or PRIORITY_MAX for below Oreo versions

Reference link for priority note

Priority for version below Oreo

```<code>mBuilder.setSmallIcon(R.drawable.app_logo)
            .setAutoCancel(true)
            .setContentIntent(resultPendingIntent)
            .setContentTitle(title)
            .setStyle(bigPictureStyle)
            .setSound(soundUri)
            .setPriority(NotificationCompat.PRIORITY_HIGH) // prirority here for version below Oreo
            .setWhen(System.currentTimeMillis())
            .setLargeIcon(BitmapFactory.decodeResource(mCtx.getResources(), R.drawable.app_logo))
            .setContentText(message)
            .build();
</code>```

Priority for Oreo and above

Refer this link

Body:
Try using with this below permission in AndroidManifest file

<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY"/>

and set notification priority for both below and above Oreo versions IMPORTANCE_HIGH for Oreo and above, and PRIORITY_HIGH or PRIORITY_MAX for below Oreo versions

Reference link for priority note

Priority for version below Oreo

mBuilder.setSmallIcon(R.drawable.app_logo)
            .setAutoCancel(true)
            .setContentIntent(resultPendingIntent)
            .setContentTitle(title)
            .setStyle(bigPictureStyle)
            .setSound(soundUri)
            .setPriority(NotificationCompat.PRIORITY_HIGH) // prirority here for version below Oreo
            .setWhen(System.currentTimeMillis())
            .setLargeIcon(BitmapFactory.decodeResource(mCtx.getResources(), R.drawable.app_logo))
            .setContentText(message)
            .build();

Priority for Oreo and above

Refer this link


问:
Type 'string' is not assignable to type 'number'
I really did not understand how the type assignment system works for variables in typescript.
Can anyone help me why this does not work.
Thank you

```<code>valorParcela:number;
totalCost:number;
VendaProdutoVendaNParcelas: number;

this.valorParcela = Number( this.totalCost / this.VendaProdutoVendaNParcelas).toFixed(2);
</code>```

I expected a simple parseFloat

答:
toFixed returns a string which you are assigning to a variable which should be number. You need another pair of () to convert the result of toFixed back to number

```<code>this.valorParcela = Number(( this.totalCost / this.VendaProdutoVendaNParcelas).toFixed(2));
</code>```

Or you can use the unary + trick to perform number conversion:

```<code>this.valorParcela = +(this.totalCost / this.VendaProdutoVendaNParcelas).toFixed(2);
</code>```

Body:
I really did not understand how the type assignment system works for variables in typescript.
Can anyone help me why this does not work.
Thank you

valorParcela:number;
totalCost:number;
VendaProdutoVendaNParcelas: number;

this.valorParcela = Number( this.totalCost / this.VendaProdutoVendaNParcelas).toFixed(2);

I expected a simple parseFloat

Body:
toFixed returns a string which you are assigning to a variable which should be number. You need another pair of () to convert the result of toFixed back to number

this.valorParcela = Number(( this.totalCost / this.VendaProdutoVendaNParcelas).toFixed(2));

Or you can use the unary + trick to perform number conversion:

this.valorParcela = +(this.totalCost / this.VendaProdutoVendaNParcelas).toFixed(2);