问:
Delete function (imported from .py file) does not work in VS Code Jupyter Notebook
I am working within a .ipynb file in VS Code where I build my code for my master thesis project (i later copy them into .py files, when Im finished). The .py-file "f_functions" contains some functions that I use in multiple files.
I import it like this.

```<code># Import #####
# Packages ###
import pandas as pd
import networkx as nx
from copy import copy
import f_functions as ff
</code>```

The code for the function in the "f_functions.py" file is like this.

```<code>def clean(data):
"""This function is used to remove variables/data objects that are no longer needed.
Its used to keep (especially the jupyter notebook variables viewer cleaner."""

try:
    del(data)
except:
    pass
</code>```

When I then use the function in my .ipynb file, it doesnt delete the object that I want to delete. For example:

```<code>test = "test"
ff.clean(test)
</code>```

When I write it like this:

```<code>test = "test"
try:
    del(test)
except:
    pass
</code>```

It works.

So my question is: Why .ipynb files sometimes have trouble handling imported code? Or did I overlook something?

答:
If you want to delete a variable p but you don't know if it already exists, you just assign anything to p, so type:

p=0; del p
```

If you use a function you only delete the local variable.

Body:
I am working within a .ipynb file in VS Code where I build my code for my master thesis project (i later copy them into .py files, when Im finished). The .py-file "f_functions" contains some functions that I use in multiple files.
I import it like this.

# Import #####
# Packages ###
import pandas as pd
import networkx as nx
from copy import copy
import f_functions as ff

The code for the function in the "f_functions.py" file is like this.

def clean(data):
"""This function is used to remove variables/data objects that are no longer needed.
Its used to keep (especially the jupyter notebook variables viewer cleaner."""

try:
    del(data)
except:
    pass

When I then use the function in my .ipynb file, it doesnt delete the object that I want to delete. For example:

test = "test"
ff.clean(test)

When I write it like this:

test = "test"
try:
    del(test)
except:
    pass

It works.

So my question is: Why .ipynb files sometimes have trouble handling imported code? Or did I overlook something?

Body:
If you want to delete a variable p but you don't know if it already exists, you just assign anything to p, so type:

p=0; del p

If you use a function you only delete the local variable.


来源: stackexchange

问:
Vagrant hangs at "SSH auth method: Private key
I am running VirtualBox 5.0.24 and Vagrant 1.8.5 on Digital Ocean VPS running on Ubuntu 14.04 LTS Precise
I am using the box ubuntu/precise64
Everything works fine but when i do vagrant up it hangs at the

```<code>SSH auth method: Private key
</code>```

and the exit out giving time out. Now, i can consider increasing the execution time but it already takes a fare amount of time before giving that error. I don't know what I am doing wrong.
Here is my VAGRANTFILE

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|

  config.vm.box = "ubuntu/precise64"

  config.vm.provider :virtualbox do |vb|
    vb.customize ['modifyvm', :'1cf9e703-607e-4338-9162-20abbeca94b0', '--pae', 'on']
    vb.customize ['modifyvm', :'1cf9e703-607e-4338-9162-20abbeca94b0', '--hwvirtex', 'off']
    vb.customize ['modifyvm', :'1cf9e703-607e-4338-9162-20abbeca94b0', '--vtxvpid', 'off']
  end

end
```

答:
Following the advice from user Kokokoko above I added the following lines to my vagrnt file.

```<code>vb.customize ["modifyvm", :id, "--uart1", "0x3F8", "4"]
vb.customize ["modifyvm", :id, "--uartmode1", "file", File::NULL]
</code>```

installed the latest virtualbox, made sure the vm was halted properly and it worked for me.

using Virtualbox 6.1.32 with Vagrant 2.2.10 with Ubuntu/Xenial64

ContentLicense: CC BY-SA 4.0

Body:
I am running VirtualBox 5.0.24 and Vagrant 1.8.5 on Digital Ocean VPS running on Ubuntu 14.04 LTS Precise
I am using the box ubuntu/precise64
Everything works fine but when i do vagrant up it hangs at the

SSH auth method: Private key

and the exit out giving time out. Now, i can consider increasing the execution time but it already takes a fare amount of time before giving that error. I don't know what I am doing wrong.
Here is my VAGRANTFILE

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|

  config.vm.box = "ubuntu/precise64"

  config.vm.provider :virtualbox do |vb|
    vb.customize ['modifyvm', :'1cf9e703-607e-4338-9162-20abbeca94b0', '--pae', 'on']
    vb.customize ['modifyvm', :'1cf9e703-607e-4338-9162-20abbeca94b0', '--hwvirtex', 'off']
    vb.customize ['modifyvm', :'1cf9e703-607e-4338-9162-20abbeca94b0', '--vtxvpid', 'off']
  end

end

Body:
Following the advice from user Kokokoko above I added the following lines to my vagrnt file.

vb.customize ["modifyvm", :id, "--uart1", "0x3F8", "4"]
vb.customize ["modifyvm", :id, "--uartmode1", "file", File::NULL]

installed the latest virtualbox, made sure the vm was halted properly and it worked for me.

using Virtualbox 6.1.32 with Vagrant 2.2.10 with Ubuntu/Xenial64


问:
Embedding a Plotly graph to Java GUI
I have a interactive plotly graph which I wish to put in to a Java GUI.

I am using swing for the Java GUI.

the plotly functions and displays correctly on Chrome, but not on Java swing components.

How should I go about doing this?

答: You need to start plotly as a seperated web service and call it via embedded browser.</p>

Title: Embedding a Plotly graph to Java GUI


问:
php $_GET passing variables from one page to another
I'm trying to pass my variables from one page to another, I'm using $_GET and it's grabbing my variables but on the same page instead of a new one, is it possible to pass them to a new page using $_GET or do I have to do another method, I've seen this done on the site using javascript asp and jquery but cant seem to find one with PHP that is explaining things very well.

this is what I have, other then this I'm pretty clueless on how to make this happen.

```<code>foreach($obj->jigsawes as $jigsaw):

   if(isset($_GET['p']) && $_GET['p']==''.$query.'') {
echo "<a href='?p=$jigsaw_url'><img border=0 src='".$jigsaw->photo_url."'></a><br />";

echo "$jigsaw->name</ br>
 $jigsaw->address1<br />
 $jigsaw->phone<br />
 $jigsaw->city<br />
 $jigsaw->state<br />
 $jigsaw->zip<br />";

}else{
$query = htmlspecialchars($_SERVER['QUERY_STRING'], ENT_QUOTES);

echo "<div><a href='?$query'>$jigsaw->name</a></div>";
    }
endforeach;
}
</code>```

答:
You have to build a new query string out of your post vars and attach them to your links.
http_build_query() is helpful for this.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to pass my variables from one page to another, I'm using $_GET and it's grabbing my variables but on the same page instead of a new one, is it possible to pass them to a new page using $_GET or do I have to do another method, I've seen this done on the site using javascript asp and jquery but cant seem to find one with PHP that is explaining things very well.

this is what I have, other then this I'm pretty clueless on how to make this happen.

foreach($obj->jigsawes as $jigsaw):

   if(isset($_GET['p']) && $_GET['p']==''.$query.'') {
echo "photo_url."'>
";

echo "$jigsaw->name

 $jigsaw->address1

 $jigsaw->phone

 $jigsaw->city

 $jigsaw->state

 $jigsaw->zip
";

}else{
$query = htmlspecialchars($_SERVER['QUERY_STRING'], ENT_QUOTES);

echo "
$jigsaw->name
";
    }
endforeach;
}


问:
process exited due to signal 6/11 c++
I didn't have any problems with compiling my program, but I have a big one when I try to use a bot to check output data. It says: "process exited due to signal 6" or "process exited due to signal 11". I thought it was a matter of dynamic arrays (i have two in this program) but both are deleted at the end.
I would be very grateful for any tip!</p>
```<code>#include <iostream>

using namespace std;

void input_data (int p_n, int **p_arr);
void output_data (int p_n, int **p_arr);
void check_salary(int p_n, int **p_arr);

int main()
{
    int n;
    cin >> n;
    int** arr = new int*[n];
    for(int i = 0; i < n; ++i){
    arr[i] = new int[2];}
    input_data(n, arr);
    check_salary(n, arr);
    output_data(n, arr);

    for(int i=0; i<n; i++) {
        delete [] arr[i];
    }
    delete[] arr;

    return 0;
}

void check_salary(int p_n, int **p_arr)
{
    bool fit, flag, exist;
    int *used = new int(p_n);
    int boss, salary, i_temp, i_salarless, min_sal ,i_used = 0,boss_salary, id;
    for (int i=0; i<p_n; i++)
        {
            if(p_arr[i][1] != 0)
            {
                used[i_used]=p_arr[i][1];
                i_used++;
            }
        }
    do{
        flag = false;
        exist=false;
        for (int i=0; i<p_n; i++)
        {

            i_salarless = 0;
            id = i+1;
            boss = p_arr[i][0];
            salary=p_arr[i][1];
            boss_salary = p_arr[boss-1][1];

            if(salary==0)
            {
                if(boss==id){
                    p_arr[i][1] = p_n;
                    flag = true;
                }else if(boss_salary>0){
                    for (int j=0; j<p_n; j++)
                        {
                            if (p_arr[j][0]==boss && p_arr[j][1] == 0){i_salarless++;}
                        }

                    if (i_salarless == 1){
                        do{
                            --boss_salary;
                            exist = false;
                            for (int i=0; i< i_used; i++){
                                {
                                    if(boss_salary == used[i]){exist = true;}
                                }
                            }

                        }while(exist);
                        p_arr[i][1]= boss_salary;
                        used[i_used]= p_arr[i][1];
                        i_used++;
                        flag = true;
                    }
                }
            }else{}
        }
    } while(flag);
    delete []used;

}

void output_data (int p_n, int **p_arr)
{
    for (int i=0; i<p_n; i++)
    {
        cout<< p_arr[i][1] << "\n";
    }
}

void input_data (int p_n, int **p_arr)
{
    for (int i=0; i<p_n; i++)
    {
        for (int j=0; j<2; j++)
        {
            cin>> p_arr[i][j];
        }

    }

}
</code>```

答:
I think the main issue is that you are doing int *used = new int(p_n);, this will create a pointer to an integer that has initial value equal to p_n. But, the problem comes here: used[i_used]=p_arr[i][1]; -- this may lead to a segmentation fault, as you may end up using memory outside the valid bounds.

I'm not sure about the algorithm, but based on the code, I think you should use this instead:

```<code>used = new int[p_n]; // assuming p_n > 0
</code>```

Title: process exited due to signal 6/11 c++

Body:
I didn't have any problems with compiling my program, but I have a big one when I try to use a bot to check output data. It says: "process exited due to signal 6" or "process exited due to signal 11". I thought it was a matter of dynamic arrays (i have two in this program) but both are deleted at the end.
I would be very grateful for any tip!

#include <iostream>

using namespace std;

void input_data (int p_n, int **p_arr);
void output_data (int p_n, int **p_arr);
void check_salary(int p_n, int **p_arr);

int main()
{
    int n;
    cin >> n;
    int** arr = new int*[n];
    for(int i = 0; i < n; ++i){
    arr[i] = new int[2];}
    input_data(n, arr);
    check_salary(n, arr);
    output_data(n, arr);

    for(int i=0; i<n; i++) {
        delete [] arr[i];
    }
    delete[] arr;

    return 0;
}

void check_salary(int p_n, int **p_arr)
{
    bool fit, flag, exist;
    int *used = new int(p_n);
    int boss, salary, i_temp, i_salarless, min_sal ,i_used = 0,boss_salary, id;
    for (int i=0; i<p_n; i++)
        {
            if(p_arr[i][1] != 0)
            {
                used[i_used]=p_arr[i][1];
                i_used++;
            }
        }
    do{
        flag = false;
        exist=false;
        for (int i=0; i<p_n; i++)
        {

            i_salarless = 0;
            id = i+1;
            boss = p_arr[i][0];
            salary=p_arr[i][1];
            boss_salary = p_arr[boss-1][1];

            if(salary==0)
            {
                if(boss==id){
                    p_arr[i][1] = p_n;
                    flag = true;
                }else if(boss_salary>0){
                    for (int j=0; j<p_n; j++)
                        {
                            if (p_arr[j][0]==boss && p_arr[j][1] == 0){i_salarless++;}
                        }

                    if (i_salarless == 1){
                        do{
                            --boss_salary;
                            exist = false;
                            for (int i=0; i< i_used; i++){
                                {
                                    if(boss_salary == used[i]){exist = true;}
                                }
                            }

                        }while(exist);
                        p_arr[i][1]= boss_salary;
                        used[i_used]= p_arr[i][1];
                        i_used++;
                        flag = true;
                    }
                }
            }else{}
        }
    } while(flag);
    delete []used;

}

void output_data (int p_n, int **p_arr)
{
    for (int i=0; i<p_n; i++)
    {
        cout<< p_arr[i][1] << "\n";
    }
}

void input_data (int p_n, int **p_arr)
{
    for (int i=0; i<p_n; i++)
    {
        for (int j=0; j<2; j++)
        {
            cin>> p_arr[i][j];
        }

    }

}

Body:
I think the main issue is that you are doing int *used = new int(p_n);, this will create a pointer to an integer that has initial value equal to p_n. But, the problem comes here: used[i_used]=p_arr[i][1]; -- this may lead to a segmentation fault, as you may end up using memory outside the valid bounds.

I'm not sure about the algorithm, but based on the code, I think you should use this instead:

used = new int[p_n]; // assuming p_n > 0


问:
How and where to call a method in a Class based view Django
As part of a News Years resolution, I have promised to myself that I would learn to write Class Based Views, but as it turns out, I need some help..

What I am trying to do is call a method that generates a random number and then sends an email before the page loads, which I comfortable doing (I'll probably use celery to send the mail in the background).

What I don't understand is how and where to call the methods random_code() and send_email() (see below)?

Do I do this by overriding setup(), dispatch() or get() etc?

Can someone please give me a basic example of what to do?

The class is going to look something like this:

```<code>class VerifyCode(FormView):

    template_name = "account/verify.html"
    form_class = VerifyForm

    def random_code(self):
        #random_code generator
        return random_code

    def send_email(self):
        #code to send email
</code>```

Many thanks in advance.

答:
It depends on which REST method do you want to call it. If you are using simple GET, then call it in get() like this:

```<code>class VerifyCode(FormView):

    template_name = "account/verify.html"
    form_class = VerifyForm

    def random_code(self):
        #random_code generator
        return random_code

    def send_email(self):
        #code to send email

    def get(self, request, *args, **kwargs):
        ...
        self.random_code()
        self.send_email()
        return super().get(request, *args, **kwargs)
</code>```

In similar way in post() for POST method.

Another thing is you can send emails directly with Django. I do that and it's pretty simple. Check this DOCS. You can post another question about that if you have something.

Body:
As part of a News Years resolution, I have promised to myself that I would learn to write Class Based Views, but as it turns out, I need some help..

What I am trying to do is call a method that generates a random number and then sends an email before the page loads, which I comfortable doing (I'll probably use celery to send the mail in the background).

What I don't understand is how and where to call the methods random_code() and send_email() (see below)?

Do I do this by overriding setup(), dispatch() or get() etc?

Can someone please give me a basic example of what to do?

The class is going to look something like this:

class VerifyCode(FormView):

    template_name = "account/verify.html"
    form_class = VerifyForm

    def random_code(self):
        #random_code generator
        return random_code

    def send_email(self):
        #code to send email

Many thanks in advance.

Body:
It depends on which REST method do you want to call it. If you are using simple GET, then call it in get() like this:

class VerifyCode(FormView):

    template_name = "account/verify.html"
    form_class = VerifyForm

    def random_code(self):
        #random_code generator
        return random_code

    def send_email(self):
        #code to send email

    def get(self, request, *args, **kwargs):
        ...
        self.random_code()
        self.send_email()
        return super().get(request, *args, **kwargs)

In similar way in post() for POST method.

Another thing is you can send emails directly with Django. I do that and it's pretty simple. Check this DOCS. You can post another question about that if you have something.


问:
Compare byte array (received mqtt message) to zero to send notification
I'm building android app that receives an mqtt message from esp8266 with the percent of water on water sensor for my school project.
So, I need to send app notification, when the percent is not equal to zero, but there's one problem. Received message is a byte array, but for some reason it's not just number, it has specific U+FFFD � replacement character, so I can't compare this byte array to another array like [0]. I'm trying to convert received message into string, remove all strange symbols and compare it to "0". But for some reason again I can't. For example, String "0����" clears from all the � characters, but the java code still considers that it is not equal to "0".

My code:

```<code>if (topic.equals(topicstr2)){
                    byte[] res = message.getPayload();
                    result_notif = new String(res).replaceAll("�", "");
                    if (result_notif != "0"){
                        sendNotif();
                    }
                }
</code>```

result_notif is a string, it was declared in the beggining of code.

P.S. sorry for my bad english, I hope I've made my problem pretty clear.

答:
Using !result_notif.equals("0") instead of "result_info != "0"" and using the .trim() method was the solution of my problem.

Code:

```<code>if (topic.equals(topicstr2)){
    byte[] res = message.getPayload();
    result_notif = new String(res).replaceAll("�", "").trim();
    intent.putExtra(MainActivity.PARAM_RESULT, result_notif);
    sendBroadcast(intent);
    if (!result_notif.equals("0")){
        sendNotif();
    }
}
</code>```

Body:
I'm building android app that receives an mqtt message from esp8266 with the percent of water on water sensor for my school project.
So, I need to send app notification, when the percent is not equal to zero, but there's one problem. Received message is a byte array, but for some reason it's not just number, it has specific U+FFFD � replacement character, so I can't compare this byte array to another array like [0]. I'm trying to convert received message into string, remove all strange symbols and compare it to "0". But for some reason again I can't. For example, String "0����" clears from all the � characters, but the java code still considers that it is not equal to "0".

My code:

if (topic.equals(topicstr2)){
                    byte[] res = message.getPayload();
                    result_notif = new String(res).replaceAll("�", "");
                    if (result_notif != "0"){
                        sendNotif();
                    }
                }

result_notif is a string, it was declared in the beggining of code.

P.S. sorry for my bad english, I hope I've made my problem pretty clear.

Body:
Using !result_notif.equals("0") instead of "result_info != "0"" and using the .trim() method was the solution of my problem.

Code:

if (topic.equals(topicstr2)){
    byte[] res = message.getPayload();
    result_notif = new String(res).replaceAll("�", "").trim();
    intent.putExtra(MainActivity.PARAM_RESULT, result_notif);
    sendBroadcast(intent);
    if (!result_notif.equals("0")){
        sendNotif();
    }
}


问:
What is the most rng-efficient uniform random integer algorithm?
This is not a duplicate of #11766794 “What is the optimal algorithm for generating an unbiased random integer within a range?”. Both its top-upvoted answer and its Accepted answer have to do with floating-point extrapolation, which will not even yield perfectly uniform integers. That question is asking after ways to quickly get good approximations of a uniform random integer given a serviceably uniform floating-point rand() value; I am asking this question in the context of a perfectly uniform random integer algorithm given a true random bit generator (deterministic or otherwise; the question applies equally either way).

I am asking, specifically, about theoretical optimality in terms only of efficiency w/r/t random bits used: given a random bit stream, what is the algorithm which consumes the fewest number of bits from it in the process of generating a perfectly uniform random integer within a given range?

For instance, CPython 3.9.0's random.randbelow has at least one trivial inefficiency—it wastes a random bit when called over any power of 2 (including the trivial range):

def randbelow(n):
    "Return a random int in the range [0,n).  Returns 0 if n==0."
    if not n:
        return 0
    k = n.bit_length()  # don't use (n-1) here because n can be 1
    r = getrandbits(k)  # 0 <= r < 2**k
    while r >= n:
        r = getrandbits(k)
    return r
```
<p>While this is easily enough patched by replacing "<code>not n</code>" with "<code>n <= 1</code>" and "<code>n.bit_length()</code>" with "<code>(n-1).bit_length()</code>", a little analysis shows it leaves even more to be desired:</p>
<p>Say one is generating an integer over the range <code>[0, 4097)</code>: <em>half</em> of all the calls to <code>getrandbits(13)</code> will overshoot the value: if the first bit and, <em>say</em>, the second bit are high, it will consume 11 <em>more</em> bits anyway, and discard them when it seemingly didn't need to. So it would seem that this algorithm is obviously nonoptimal.</p>
<p>The best I could come with in an hour this evening was the following algorithm:</p>
<pre class="lang-py prettyprint-override"><code>def randbelow(n):
    if n <= 1:
        return 0
    k = (n - 1).bit_length() # this is POPCNT for bignums
    while True:
        r = 0
        for i in reversed(range(k)):
            r |= getrandbits(1) << i
            if r >= n:
                break
        else:
            return r
</code>```

However, I am no mathematician, and just because I fixed the inefficiencies that I could immediately see doesn't give me any confidence that I have just instantly stumbled in an afternoon on the most efficient possible uniform integer selection algorithm.

Say, for instance, the bits are being purchased from a quantum or atmospheric RNG service; or as part of a multi-party protocol in which every individual bit generation takes several round-trips; or on an embedded device without any hardware RNG support… whatever the case may be, I'm only asking the direct question: what algorithm for generating (perfectly) uniformly random integers from a true random bit stream is the most efficient with respect to random bits consumed? (Or, if not known with certainty, what is the best current candidate?)

(I have used Python in these examples because it's what I am working in primarily this season, but the question is by no means specific to any language, except inasfaras the algorithm itself must generalize to numbers above 264.)

答:
The Python below implements arithmetic coding in exact arithmetic. This becomes very expensive computationally but achieves entropy + O(1) bits in expectation, which is basically optimal.</p>
```<code>from fractions import Fraction
from math import floor, log2
import random

meter = 0

def metered_random_bits():
    global meter
    while True:
        yield bool(random.randrange(2))
        meter += 1

class ArithmeticDecoder:
    def __init__(self, bits):
        self._low = Fraction(0)
        self._width = Fraction(1)
        self._bits = bits

    def randrange(self, n):
        self._low *= n
        self._width *= n
        while True:
            f = floor(self._low)
            if self._low + self._width <= f + 1:
                self._low -= f
                return f
            self._width /= 2
            if next(self._bits):
                self._low += self._width

import collections

if __name__ == "__main__":
    k = 3000
    n = 7
    decoder = ArithmeticDecoder(metered_random_bits())
    print(collections.Counter(decoder.randrange(n) for i in range(k)))
    print("used", meter, "bits")
    print("entropy", k * log2(n), "bits")
</code>```

Body:
This is not a duplicate of #11766794 “What is the optimal algorithm for generating an unbiased random integer within a range?”. Both its top-upvoted answer and its Accepted answer have to do with floating-point extrapolation, which will not even yield perfectly uniform integers. That question is asking after ways to quickly get good approximations of a uniform random integer given a serviceably uniform floating-point rand() value; I am asking this question in the context of a perfectly uniform random integer algorithm given a true random bit generator (deterministic or otherwise; the question applies equally either way).

I am asking, specifically, about theoretical optimality in terms only of efficiency w/r/t random bits used: given a random bit stream, what is the algorithm which consumes the fewest number of bits from it in the process of generating a perfectly uniform random integer within a given range?

For instance, CPython 3.9.0's random.randbelow has at least one trivial inefficiency—it wastes a random bit when called over any power of 2 (including the trivial range):

def randbelow(n):
    "Return a random int in the range [0,n).  Returns 0 if n==0."
    if not n:
        return 0
    k = n.bit_length()  # don't use (n-1) here because n can be 1
    r = getrandbits(k)  # 0 <= r < 2**k
    while r >= n:
        r = getrandbits(k)
    return r

While this is easily enough patched by replacing "not n" with "n <= 1" and "n.bit_length()" with "(n-1).bit_length()", a little analysis shows it leaves even more to be desired:

Say one is generating an integer over the range [0, 4097): half of all the calls to getrandbits(13) will overshoot the value: if the first bit and, say, the second bit are high, it will consume 11 more bits anyway, and discard them when it seemingly didn't need to. So it would seem that this algorithm is obviously nonoptimal.

The best I could come with in an hour this evening was the following algorithm:

def randbelow(n):
    if n <= 1:
        return 0
    k = (n - 1).bit_length() # this is POPCNT for bignums
    while True:
        r = 0
        for i in reversed(range(k)):
            r |= getrandbits(1) <= n:
                break
        else:
            return r

However, I am no mathematician, and just because I fixed the inefficiencies that I could immediately see doesn't give me any confidence that I have just instantly stumbled in an afternoon on the most efficient possible uniform integer selection algorithm.

Say, for instance, the bits are being purchased from a quantum or atmospheric RNG service; or as part of a multi-party protocol in which every individual bit generation takes several round-trips; or on an embedded device without any hardware RNG support… whatever the case may be, I'm only asking the direct question: what algorithm for generating (perfectly) uniformly random integers from a true random bit stream is the most efficient with respect to random bits consumed? (Or, if not known with certainty, what is the best current candidate?)

(I have used Python in these examples because it's what I am working in primarily this season, but the question is by no means specific to any language, except inasfaras the algorithm itself must generalize to numbers above 264.)

Body:
The Python below implements arithmetic coding in exact arithmetic. This becomes very expensive computationally but achieves entropy + O(1) bits in expectation, which is basically optimal.

from fractions import Fraction
from math import floor, log2
import random

meter = 0

def metered_random_bits():
    global meter
    while True:
        yield bool(random.randrange(2))
        meter += 1

class ArithmeticDecoder:
    def __init__(self, bits):
        self._low = Fraction(0)
        self._width = Fraction(1)
        self._bits = bits

    def randrange(self, n):
        self._low *= n
        self._width *= n
        while True:
            f = floor(self._low)
            if self._low + self._width <= f + 1:
                self._low -= f
                return f
            self._width /= 2
            if next(self._bits):
                self._low += self._width

import collections

if __name__ == "__main__":
    k = 3000
    n = 7
    decoder = ArithmeticDecoder(metered_random_bits())
    print(collections.Counter(decoder.randrange(n) for i in range(k)))
    print("used", meter, "bits")
    print("entropy", k * log2(n), "bits")


问:
Correlated subquery (selecting within a select) in SQLite returns error "Error: sub-select returns 2 columns - expected 1"
```<code>SELECT employeeId, (select 1 as first, 2 as second from 'employee') as nested
FROM 'employee'
</code>```

returns the error in SQLite

```<code>Error: sub-select returns 2 columns - expected 1
</code>```

The reason why I'm doing the query like is because I want the returned data structure in my Node.js app to have a nested object like so:

```<code>[employeeId: 123, nested: {first: 1, second: 2} }]
</code>```

How would I go about fixing this? Thanks

答:
you can return only one column from correlated so you must convert a multi-column select into a json like so:

```<code> select e.id , (select to_json(first: 1 , second: 2) from emp ee where e.id = ee.id group by ee.id) from emp e
</code>```

replace to_json with sqlites json aggregate

however sqlite does not have the json aggregate built in so you will need to download and load it into your app. Download here: https://www.sqlite.org/json1.html

Body:
SELECT employeeId, (select 1 as first, 2 as second from 'employee') as nested
FROM 'employee'

returns the error in SQLite

Error: sub-select returns 2 columns - expected 1

The reason why I'm doing the query like is because I want the returned data structure in my Node.js app to have a nested object like so:

[employeeId: 123, nested: {first: 1, second: 2} }]

How would I go about fixing this? Thanks

Body:
you can return only one column from correlated so you must convert a multi-column select into a json like so:

 select e.id , (select to_json(first: 1 , second: 2) from emp ee where e.id = ee.id group by ee.id) from emp e

replace to_json with sqlites json aggregate

however sqlite does not have the json aggregate built in so you will need to download and load it into your app. Download here: https://www.sqlite.org/json1.html


问:
Looping in R to only add leading zeros to specified length
how would I be able to go from a column like this:
1
1
1
2
3
4
9
25
100

to one like this:
01
01
01
02
03
04
09
25
100

Basically, I want to add a leading zero to any value with only length 1. The actual data frame is much bigger than this. Thanks!

Body:
You can use sprintf in base R

vec <-  c(1, 1, 1, 2, 3, 4, 9, 25, 100)

sprintf("%02d", vec)
#> [1] "01"  "01"  "01"  "02"  "03"  "04"  "09"  "25"  "100"


问:
What exactly is undefined in accessing out of bound of array?
Let's say I have the following array

```<code>unsigned char array[5];
</code>```

So I'm trying to understand what exactly is undefined in accessing

```<code>array[6]
</code>```

for my understanding, the compiler will try to read the value inside *(array+6), so it is defined. So, if I understand right, what is undefined is what happens when you try to read uninitialized memory.

If this is the case, then the top answer here says that reading uninitialized value is defined unless you have trap representation, but we know that unsigned char does not have that.

So is it defined well here? Will it always read the *(array+6)?

答:
It seems that you are confusing "undefined behaviour" with "unclear address" or "accessing non-initialised parts of an array".

The problem here is not that the memory which you would access is non-initialised.

The problem here is not that it is unclear what array[6] should mean.

The problem is that the assumption of non-initialised memory existing at that address  is no allowed and the assumption that it is possible to access that memory is not allowed.

Compilers are given as much leeway for optimisations as possible. Most models of memorys are only that, models.

C standard requires in many cases that an executable created by a compiler etc. should "act as if ...", without ever defining to actually "do ...".

The result is that there are many examples of Undefined Behaviour (capitals, because this is a more specific term than "the way a program acts in certain situations which nobody did bother to clearly explain"). They are very important for minimising restrictions which would impede optimisations.

So in short (and somewhat blunt), if something is UB, then stop thinking about it. Many answers here on StackOverflow reach a point of explanation where they state "UB, end of explanation". Some then go on, but only after making explicit that they are speculating on what might have happened in the specific observed case.

Body:
Let's say I have the following array

unsigned char array[5];

So I'm trying to understand what exactly is undefined in accessing

array[6]

for my understanding, the compiler will try to read the value inside *(array+6), so it is defined. So, if I understand right, what is undefined is what happens when you try to read uninitialized memory.

If this is the case, then the top answer here says that reading uninitialized value is defined unless you have trap representation, but we know that unsigned char does not have that.

So is it defined well here? Will it always read the *(array+6)?


答:
Quite simply, what you're doing is undefined behavior because the C standard says it is.

From section 6.5.6p8 regarding additive operators:

... If both the pointer
operand and the result point to elements of the same array object, or one past the last
element of the array object, the evaluation shall not produce an overflow; otherwise, the
behavior is undefined. ...

So given that array has 5 elements, array + 6 would point more than one element past the end of the array, so creating such a pointer is undefined even if it is not dereferenced.

As to what can happen in a particular implementation, some possibilities are:

You get a pointer to something two bytes past the end of the array.  This could be some other object, padding between objects, or part of the return address for the current function.

The result points to memory that hasn't yet been mapped into the process's memory space, and attempting to dereference the pointer can result in a segmentation fault.

The compiler can perform optimizations that assume that undefined behavior does not exist and something else may happen.

These are just a few examples of how undefined behavior can manifest.

The bottom line: the C standard says not to do it, so don't do it.

Title: What exactly is undefined in accessing out of bound of array?


问:
Is there a way to implement captive portal on windows hotspot?
I am looking for a way to implement a captive portal for the windows 10 - mobile hotspot. The idea is to redirect all devices that connect to the hotspot to a webpage.

I was able to find this article which shows how to do it in linux.

But I have been unsuccessful in finding a similar one for windows. Posts like this one proved to be dead ends.

I am okay with using a simple nginx server to give 302 redirect response to clients if needed, but prefer not to use any existing software that implements a captive portal.

UPDATE

I have succeeded in triggering a captive portal on clients (linux laptop, android device etc) using a workaround.

Whenever a device connects to the hotspot it sends a request to some predefined websites to check if the wifi connection has internet access. If it gets a 302 response it generates the captive portal window.

So I added the following entries to the hosts file on windows machine.

```<code>127.0.0.1 clients3.google.com  #android
127.0.0.1 connectivitycheck.gstatic.com  #android
127.0.0.1 nmcheck.gnome.org  #ubuntu
</code>```

These requests will then be resolved locally using the hosts file entries and sent to the nginx server which gives a 302 redirect to all http requests.

答:
I tried a similar approach using dnscrypt-proxy which provides dedicated captive-portal support. Since, this is nothing more than dns cloaking there are several ways to achieve, that requests to certain "connection-checking" domains are directed to a local webserver.

Unlike in the accepted answer, I figured out an even easier and more flexible way by using the windows hosts file without any third-party dns proxy. Instead of associating the connection-checking domains with localhost, I mapped them with the physical wifi accespoint ip address (which is 192.168.137.1). This causes wifi clients to directly send their connection-checking requests to the webserver, that is running on the local pc and listens to all connections on port 80.

hosts file:

```<code>192.168.137.1       captive.apple.com
192.168.137.1       clients3.google.com
192.168.137.1       nmcheck.gnome.org
192.168.137.1       connectivitycheck.gstatic.com
192.168.137.1       connectivitycheck.android.com
192.168.137.1       www.msftncsi.com
192.168.137.1       dns.msftncsi.com
192.168.137.1       www.msftconnecttest.com
192.168.137.1       ipv6.msftconnecttest.com
192.168.137.1       ipv4only.arpa
</code>```

This webserver (in my case asp.net core) redirects clients to a login page, unless they are already registered. In this case the webserver may answer to the calls just like the "real" servers do, that sit behind those connection-checking domains, in order not to redirect clients, that have already been logged in successfully.

Body:
I am looking for a way to implement a captive portal for the windows 10 - mobile hotspot. The idea is to redirect all devices that connect to the hotspot to a webpage.

I was able to find this article which shows how to do it in linux.

But I have been unsuccessful in finding a similar one for windows. Posts like this one proved to be dead ends.

I am okay with using a simple nginx server to give 302 redirect response to clients if needed, but prefer not to use any existing software that implements a captive portal.

UPDATE

I have succeeded in triggering a captive portal on clients (linux laptop, android device etc) using a workaround.

Whenever a device connects to the hotspot it sends a request to some predefined websites to check if the wifi connection has internet access. If it gets a 302 response it generates the captive portal window.

So I added the following entries to the hosts file on windows machine.

127.0.0.1 clients3.google.com  #android
127.0.0.1 connectivitycheck.gstatic.com  #android
127.0.0.1 nmcheck.gnome.org  #ubuntu

These requests will then be resolved locally using the hosts file entries and sent to the nginx server which gives a 302 redirect to all http requests.

Body:
I tried a similar approach using dnscrypt-proxy which provides dedicated captive-portal support. Since, this is nothing more than dns cloaking there are several ways to achieve, that requests to certain "connection-checking" domains are directed to a local webserver.

Unlike in the accepted answer, I figured out an even easier and more flexible way by using the windows hosts file without any third-party dns proxy. Instead of associating the connection-checking domains with localhost, I mapped them with the physical wifi accespoint ip address (which is 192.168.137.1). This causes wifi clients to directly send their connection-checking requests to the webserver, that is running on the local pc and listens to all connections on port 80.

hosts file:

192.168.137.1       captive.apple.com
192.168.137.1       clients3.google.com
192.168.137.1       nmcheck.gnome.org
192.168.137.1       connectivitycheck.gstatic.com
192.168.137.1       connectivitycheck.android.com
192.168.137.1       www.msftncsi.com
192.168.137.1       dns.msftncsi.com
192.168.137.1       www.msftconnecttest.com
192.168.137.1       ipv6.msftconnecttest.com
192.168.137.1       ipv4only.arpa

This webserver (in my case asp.net core) redirects clients to a login page, unless they are already registered. In this case the webserver may answer to the calls just like the "real" servers do, that sit behind those connection-checking domains, in order not to redirect clients, that have already been logged in successfully.


问:
JavaScript convert [object Object] to JSON
I am implementing a token based authentication and I need to access the token I have set when i check if the user is authenticated.

I am using this method to check if the user is authenticated:

```<code>function isAuthenticated(req, res, next) {
    const token = req.headers['authorization'];
    console.log(token);
    if (token) {
        req.token = token;
        next();
    } else {
        res.sendStatus(401);
    }
}
</code>```

The console.log(token) prints out [object Object] how can I convert this to a json object?

The token is generated with the jsonwebtoken module this way:

```<code>jwt.sign({ user_id: user.user_id }, config.app.secretKey, { expiresIn: 60 * 60 * 24 * 7 }, (err, token) => {
    return res.send(token);
});
</code>```

答: Unfortunately, the string "[object Object]" doesn't have enough information to recreate back the original object. You'll have to debug the logic and find out why req.headers['authorization'] has such value in the first place.

Body:
I am implementing a token based authentication and I need to access the token I have set when i check if the user is authenticated.

I am using this method to check if the user is authenticated:

function isAuthenticated(req, res, next) {
    const token = req.headers['authorization'];
    console.log(token);
    if (token) {
        req.token = token;
        next();
    } else {
        res.sendStatus(401);
    }
}

The console.log(token) prints out [object Object] how can I convert this to a json object?

The token is generated with the jsonwebtoken module this way:

jwt.sign({ user_id: user.user_id }, config.app.secretKey, { expiresIn: 60 * 60 * 24 * 7 }, (err, token) => {
    return res.send(token);
});


问:
Spring CORS No 'Access-Control-Allow-Origin' header is present
I am getting the following problem after porting web.xml to java config

```<code>No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
</code>```

Based on a few Spring references, the following attempt has been tried:

```<code>@Configuration
@ComponentScan(basePackageClasses = AppConfig.class, useDefaultFilters = false, includeFilters = {
        @Filter(org.springframework.stereotype.Controller.class) })
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/*").allowedOrigins("*").allowedMethods("GET", "POST", "OPTIONS", "PUT")
                .allowedHeaders("Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method",
                        "Access-Control-Request-Headers")
                .exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")
                .allowCredentials(true).maxAge(3600);
    }

}
</code>```

The values chosen were taken from a working web.xml filter:

```<code><filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value>*</param-value>
</init-param>
<init-param>
    <param-name>cors.allowed.methods</param-name>
    <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
</init-param>
<init-param>
    <param-name>cors.allowed.headers</param-name>
    <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
</init-param>
<init-param>
    <param-name>cors.exposed.headers</param-name>
    <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
</init-param>
<init-param>
    <param-name>cors.support.credentials</param-name>
    <param-value>true</param-value>
</init-param>
<init-param>
    <param-name>cors.preflight.maxage</param-name>
    <param-value>10</param-value>
</init-param> </filter> <filter-mapping>

<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</code>```

Any ideas why the Spring java config approach is not working like the web.xml file did?

答:
reversebind was correct in his answer that Spring Data Rest does indeed have a different approach.  However I couldn't get the code sample they provided to work as I couldn't import RepositoryRestConfigurerAdapter.  After digging through the documentation, I instead used this class which worked for me.</p>
```<code>import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;

@Configuration
class CustomRestMvcConfiguration {

    @Bean
    public RepositoryRestConfigurer repositoryRestConfigurer() {
        return new RepositoryRestConfigurer() {
            @Override
            public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config, CorsRegistry cors) {
                cors.addMapping("/**")
                    .allowedOrigins("http://localhost:4200");
      }
    };
  }
}
</code>```

Body:
I am getting the following problem after porting web.xml to java config

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.

Based on a few Spring references, the following attempt has been tried:

@Configuration
@ComponentScan(basePackageClasses = AppConfig.class, useDefaultFilters = false, includeFilters = {
        @Filter(org.springframework.stereotype.Controller.class) })
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/*").allowedOrigins("*").allowedMethods("GET", "POST", "OPTIONS", "PUT")
                .allowedHeaders("Content-Type", "X-Requested-With", "accept", "Origin", "Access-Control-Request-Method",
                        "Access-Control-Request-Headers")
                .exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")
                .allowCredentials(true).maxAge(3600);
    }

}

The values chosen were taken from a working web.xml filter:

<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value>*</param-value>
</init-param>
<init-param>
    <param-name>cors.allowed.methods</param-name>
    <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
</init-param>
<init-param>
    <param-name>cors.allowed.headers</param-name>
    <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
</init-param>
<init-param>
    <param-name>cors.exposed.headers</param-name>
    <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
</init-param>
<init-param>
    <param-name>cors.support.credentials</param-name>
    <param-value>true</param-value>
</init-param>
<init-param>
    <param-name>cors.preflight.maxage</param-name>
    <param-value>10</param-value>
</init-param> </filter> <filter-mapping>

<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Any ideas why the Spring java config approach is not working like the web.xml file did?

Body:
reversebind was correct in his answer that Spring Data Rest does indeed have a different approach.  However I couldn't get the code sample they provided to work as I couldn't import RepositoryRestConfigurerAdapter.  After digging through the documentation, I instead used this class which worked for me.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;

@Configuration
class CustomRestMvcConfiguration {

    @Bean
    public RepositoryRestConfigurer repositoryRestConfigurer() {
        return new RepositoryRestConfigurer() {
            @Override
            public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config, CorsRegistry cors) {
                cors.addMapping("/**")
                    .allowedOrigins("http://localhost:4200");
      }
    };
  }
}


问:
Fail to install certain version package with Conda install
I am trying to install a specific version of TopHat (v. 2.0.14) in my conda (v. 4.10.3) environment (built on python 2.7). I cannot download this version because it cannot be found from any channel. The TopHat can be downloaded from TopHat

The operating system of my computer is macOS Mojave Version 10.14.6, so I chose OSX_x86_64 and downloaded it.

Back to my terminal, I tried to install with the following code:

```<code>conda install --offline /Users/kenhsu/Desktop/tophat-2.0.14/tophat-
2.0.14.OSX_x86_64.tar
conda install --use-local /Users/kenhsu/Desktop/tophat-2.0.14/tophat-
2.0.14.OSX_x86_64.tar
</code>```

They both failed and reported as below:

```<code>Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.

PackagesNotFoundError: The following packages are not available from current
channels:

- /users/kenhsu/desktop/tophat-2.0.14/tophat-2.0.14.osx_x86_64.tar

Current channels:

- https://conda.anaconda.org/bioconda/osx-64
- https://conda.anaconda.org/bioconda/noarch
- https://repo.anaconda.com/pkgs/main/osx-64
- https://repo.anaconda.com/pkgs/main/noarch
- https://repo.anaconda.com/pkgs/r/osx-64
- https://repo.anaconda.com/pkgs/r/noarch
- https://conda.anaconda.org/conda-forge/osx-64
- https://conda.anaconda.org/conda-forge/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

https://anaconda.org

and use the search bar at the top of the page.
</code>```

I need this version of TopHat to process the example data from coursera class.

答:
Those *.tar files are not Conda packages. As such, Conda does not know how to install them. It looks like you can simply extract them and look at the README file within to see how to use it.

If you want to install with Conda, the package appears to be available from the Bioconda channel. You can run

```<code>conda install -c bioconda tophat
</code>```

to install.

Body:
I am trying to install a specific version of TopHat (v. 2.0.14) in my conda (v. 4.10.3) environment (built on python 2.7). I cannot download this version because it cannot be found from any channel. The TopHat can be downloaded from TopHat

The operating system of my computer is macOS Mojave Version 10.14.6, so I chose OSX_x86_64 and downloaded it.

Back to my terminal, I tried to install with the following code:

conda install --offline /Users/kenhsu/Desktop/tophat-2.0.14/tophat-
2.0.14.OSX_x86_64.tar
conda install --use-local /Users/kenhsu/Desktop/tophat-2.0.14/tophat-
2.0.14.OSX_x86_64.tar

They both failed and reported as below:

Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.

PackagesNotFoundError: The following packages are not available from current
channels:

- /users/kenhsu/desktop/tophat-2.0.14/tophat-2.0.14.osx_x86_64.tar

Current channels:

- https://conda.anaconda.org/bioconda/osx-64
- https://conda.anaconda.org/bioconda/noarch
- https://repo.anaconda.com/pkgs/main/osx-64
- https://repo.anaconda.com/pkgs/main/noarch
- https://repo.anaconda.com/pkgs/r/osx-64
- https://repo.anaconda.com/pkgs/r/noarch
- https://conda.anaconda.org/conda-forge/osx-64
- https://conda.anaconda.org/conda-forge/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

https://anaconda.org

and use the search bar at the top of the page.

I need this version of TopHat to process the example data from coursera class.

Body:
Those *.tar files are not Conda packages. As such, Conda does not know how to install them. It looks like you can simply extract them and look at the README file within to see how to use it.

If you want to install with Conda, the package appears to be available from the Bioconda channel. You can run

conda install -c bioconda tophat

to install.


问:
Call function of class ONE from class TWO without extend?
If i have two classes A, B and one does not extend another they are separate but both loaded into script can i still reference function in A from B?</p>

```<code>class A {
    function one() {
        echo "Class A";
    }
}

class B {
    function two() {
        echo "Class B";
        A::one();
    }
}

$a new A;
$b = new B;

$b->two();
</code>```

答:
On the face of it, yes, you can do this. However, function one() in class A needs to be declared as static for your call notation to work. (This makes it a class method.)

The other alternative, suggested by the last lines in your code, is for the instance $b to call a function in instance $a. Such functions are called instance methods and are how you normally interact with an object. To access these methods, they must be declared as public. Methods declared as private can only be called by other methods inside that class.

There are several ways to call an instance method in your code. These are the obvious two you can pass in $a as a parameter to the function, or you can create an instance of class A inside your method.

What are you actually trying to achieve?

Body:
If i have two classes A, B and one does not extend another they are separate but both loaded into script can i still reference function in A from B?

class A {
    function one() {
        echo "Class A";
    }
}

class B {
    function two() {
        echo "Class B";
        A::one();
    }
}

$a new A;
$b = new B;

$b->two();


问:
I applied a range to a goroutine channel, but I am getting an error. what's the problem?
I am studying goroutines and channels. I wrote a practice code to figure out the concurrency problem of goroutine and solve it. Deposit() is called 10 times, passing a bool to the done channel. After that, this is the code that resolves the concurrency while receiving done.

I am getting an error when I run the following code:

package main

import (
    "bank"
    "fmt"
    "log"
    "time"
)

func main() {
    start := time.Now()

    done := make(chan bool)

    // Alice
    for i := 0; i < 10; i++ {
        go func() {
            bank.Deposit(1)
            done <- true
        }()
    }

    // Wait for both transactions.
    for flag := range done {
        if !flag {
            panic("error")
        }
    }

    fmt.Printf("Balance = %d\n", bank.Balance())
    defer log.Printf("[time] Elipsed Time: %s", time.Since(start))
}
```
<pre class="lang-golang prettyprint-override"><code>package bank

var deposits = make(chan int) // send amount to deposit
var balances = make(chan int) // receive balance

func Deposit(amount int) { deposits <- amount }
func Balance() int       { return <-balances }

func teller() {
    var balance int // balance is confined to teller goroutine
    for {
        select {
        case amount := <-deposits:
            balance += amount
        case balances <- balance:
        }
    }
}

func init() {
    go teller() // start the monitor goroutine
}
</code>```

But I get an error.

```<code>fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.main()
        /Users/kyounghwan.choi/go/main.go:48 +0xd6

goroutine 49 [select]:
bank.teller()
        /usr/local/go/src/bank/bank.go:14 +0x85
created by bank.init.0
        /usr/local/go/src/bank/bank.go:23 +0x25
exit status 2
</code>```

am i missing something?
what's the problem?

答:
Change the following code blocks,

```<code>for i := 0; i < 10; i++ {
    go func() {
        bank.Deposit(1)
        done <- true
    }()
}
</code>```

into

```<code>go func() {
    for i := 0; i < 10; i++ {
        bank.Deposit(1)
        done <- true
    }

    close(done)
}()
</code>```

Note: you need to explicitly close the channel.

Body:
I am studying goroutines and channels. I wrote a practice code to figure out the concurrency problem of goroutine and solve it. Deposit() is called 10 times, passing a bool to the done channel. After that, this is the code that resolves the concurrency while receiving done.

I am getting an error when I run the following code:

package main

import (
    "bank"
    "fmt"
    "log"
    "time"
)

func main() {
    start := time.Now()

    done := make(chan bool)

    // Alice
    for i := 0; i < 10; i++ {
        go func() {
            bank.Deposit(1)
            done <- true
        }()
    }

    // Wait for both transactions.
    for flag := range done {
        if !flag {
            panic("error")
        }
    }

    fmt.Printf("Balance = %d\n", bank.Balance())
    defer log.Printf("[time] Elipsed Time: %s", time.Since(start))
}

package bank

var deposits = make(chan int) // send amount to deposit
var balances = make(chan int) // receive balance

func Deposit(amount int) { deposits <- amount }
func Balance() int       { return <-balances }

func teller() {
    var balance int // balance is confined to teller goroutine
    for {
        select {
        case amount := <-deposits:
            balance += amount
        case balances <- balance:
        }
    }
}

func init() {
    go teller() // start the monitor goroutine
}

But I get an error.

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.main()
        /Users/kyounghwan.choi/go/main.go:48 +0xd6

goroutine 49 [select]:
bank.teller()
        /usr/local/go/src/bank/bank.go:14 +0x85
created by bank.init.0
        /usr/local/go/src/bank/bank.go:23 +0x25
exit status 2

am i missing something?
what's the problem?

Body:
Change the following code blocks,

for i := 0; i < 10; i++ {
    go func() {
        bank.Deposit(1)
        done <- true
    }()
}

into

go func() {
    for i := 0; i < 10; i++ {
        bank.Deposit(1)
        done <- true
    }

    close(done)
}()

Note: you need to explicitly close the channel.


问:
Populate Datagridview price chart
I want to populate my DataGridView (dgvMain) with Bitcoin price I get using webrequest API.

The Price example response from request: 36.560 should be populated in the row1 and 4th column (column(3))

My Code:

```<code> Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False
    getPriceBTC()
    InitializeDataGridView()

End Sub

 Private Sub InitializeDataGridView()

    ' Set the column header style.
    Dim columnHeaderStyle As New DataGridViewCellStyle()

    'columnHeaderStyle.BackColor = Color.Beige
    columnHeaderStyle.Font = New Font("arial", 10, FontStyle.Bold)
    dgvMain.ColumnHeadersDefaultCellStyle = columnHeaderStyle

    ' Set the column header names.
    dgvMain.ColumnCount = 11

    dgvMain.Columns(0).Name = "#"
    dgvMain.Columns(0).Width = 50
    dgvMain.Columns(1).Name = "ID"
    dgvMain.Columns(2).Name = "Coin"
    dgvMain.Columns(3).Name = "Price (EUR)"
    dgvMain.Columns(4).Name = "Last 1h"
    dgvMain.Columns(5).Name = "Last 24h"
    dgvMain.Columns(6).Name = "Last 7d"
    dgvMain.Columns(7).Name = "24h Volume"
    dgvMain.Columns(8).Name = "M. Capital"
    dgvMain.Columns(9).Name = "If Higher"
    dgvMain.Columns(10).Name = "If Lower"

    ' Populate the rows.
    Dim row1() As String = {"", "BTC", "BitCoin", "", "", " ", "", "", "", "", ""}
    Dim row2() As String = {"", "ETH", "Ethereum", "", "", "", "", "", "", "", ""}
    Dim row3() As String = {"", "ADA", "Cardano", "", "", "", "", "", "", "", ""}
    Dim row4() As String = {"", "GLMR", "Moonbeam", "", "", "", "", "", "", "", ""}
    Dim row5() As String = {"", "ELON", "Dogelon Mars", "", "", "", "", "", "", "", ""}
    Dim row6() As String = {"", "MBOX", "Mobox", "", "", "", "", "", "", "", ""}
    Dim row7() As String = {"", "BLOK", "Bloktopia", "", "", "", "", "", "", "", ""}
    Dim row8() As String = {"", "STARL", "Starlink", "", "", "", "", "", "", "", ""}
    Dim row9() As String = {"", "OOKI", "Ooki Protocol", "", "", "", "", "", "", "", ""}
    Dim row10() As String = {"", "Floki", "Floki Inu", "", "", "", "", "", "", "", ""}
    Dim row11() As String = {"", "EGC", "EverGrow Coin", "", "", "", "", "", "", "", ""}
    Dim row12() As String = {"", "SQUID", "Squid Game", "", "", "", "", "", "", "", ""}
    Dim row13() As String = {"", "HOT", "Holo", "", "", "", "", "", "", "", ""}
    Dim row14() As String = {"", "ATLAS", "Star Atlas", "", "", "", "", "", "", "", ""}
    Dim row15() As String = {"", "ZODI", "Zodium", "", "", "", "", "", "", "", ""}
    Dim row16() As String = {"", "VML", "Meta Land", "", "", "", "", "", "", "", ""}
    Dim row17() As String = {"", "SNN", "SeChain", "", "", "", "", "", "", "", ""}

    Dim rows() As Object = {row1, row2, row3, row4, row5, row6, row7, row8, row9, row10, row11, row12, row13, row14, row15, row16, row17}

    Dim rowArray As String()
    For Each rowArray In rows
        dgvMain.Rows.Add(rowArray)
    Next rowArray

    Dim chk As New DataGridViewCheckBoxColumn()
    dgvMain.Columns.Add(chk)
    chk.HeaderText = "Enable"
    chk.Name = "chk"
    chk.Width = 70
End Sub

Public Sub getPriceBTC()
Try
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
    ServicePointManager.Expect100Continue = True
    'Dim _price As String = txtCryptoPrice.Text

    Dim _url As String = "https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=EUR"
    Dim _req As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(_url)
    _req.Proxy = Nothing
    _req.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.81 Safari/537.36"

    Dim _resp As System.Net.HttpWebResponse = _req.GetResponse
    Dim streamReader As System.IO.StreamReader = New System.IO.StreamReader(_resp.GetResponseStream())
    Dim API_source As String = streamReader.ReadToEnd
    Dim _Fprice = API_source.ToLower.ToString
    Dim _priceF = _Fprice.Substring(7)
    Dim jsonprice As String = _priceF.Replace("}", "")
  Dim row As DataGridViewRow = Nothing
        For Each item As DataGridViewRow In dgvMain.Rows
            row = item
            row.Cells(3).Value = jsonprice
        Next
    _runningThreads.Remove(Thread.CurrentThread)
Catch ex As Exception

End Try

End Sub
</code>```

I added piece of CODE after I edited but it shows now in all CELLS
the btc price so how DO I add it only to the first row?
row.Cells(3).Value = jsonprice

答:
heheheh I google it :p

```<code> dgvMain.Rows(0).Cells(3).Value = jsonprice
</code>```

yeees!

Title: Populate Datagridview price chart

Body:
I want to populate my DataGridView (dgvMain) with Bitcoin price I get using webrequest API.

The Price example response from request: 36.560 should be populated in the row1 and 4th column (column(3))

My Code:

 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False
    getPriceBTC()
    InitializeDataGridView()

End Sub

 Private Sub InitializeDataGridView()

    ' Set the column header style.
    Dim columnHeaderStyle As New DataGridViewCellStyle()

    'columnHeaderStyle.BackColor = Color.Beige
    columnHeaderStyle.Font = New Font("arial", 10, FontStyle.Bold)
    dgvMain.ColumnHeadersDefaultCellStyle = columnHeaderStyle

    ' Set the column header names.
    dgvMain.ColumnCount = 11

    dgvMain.Columns(0).Name = "#"
    dgvMain.Columns(0).Width = 50
    dgvMain.Columns(1).Name = "ID"
    dgvMain.Columns(2).Name = "Coin"
    dgvMain.Columns(3).Name = "Price (EUR)"
    dgvMain.Columns(4).Name = "Last 1h"
    dgvMain.Columns(5).Name = "Last 24h"
    dgvMain.Columns(6).Name = "Last 7d"
    dgvMain.Columns(7).Name = "24h Volume"
    dgvMain.Columns(8).Name = "M. Capital"
    dgvMain.Columns(9).Name = "If Higher"
    dgvMain.Columns(10).Name = "If Lower"

    ' Populate the rows.
    Dim row1() As String = {"", "BTC", "BitCoin", "", "", " ", "", "", "", "", ""}
    Dim row2() As String = {"", "ETH", "Ethereum", "", "", "", "", "", "", "", ""}
    Dim row3() As String = {"", "ADA", "Cardano", "", "", "", "", "", "", "", ""}
    Dim row4() As String = {"", "GLMR", "Moonbeam", "", "", "", "", "", "", "", ""}
    Dim row5() As String = {"", "ELON", "Dogelon Mars", "", "", "", "", "", "", "", ""}
    Dim row6() As String = {"", "MBOX", "Mobox", "", "", "", "", "", "", "", ""}
    Dim row7() As String = {"", "BLOK", "Bloktopia", "", "", "", "", "", "", "", ""}
    Dim row8() As String = {"", "STARL", "Starlink", "", "", "", "", "", "", "", ""}
    Dim row9() As String = {"", "OOKI", "Ooki Protocol", "", "", "", "", "", "", "", ""}
    Dim row10() As String = {"", "Floki", "Floki Inu", "", "", "", "", "", "", "", ""}
    Dim row11() As String = {"", "EGC", "EverGrow Coin", "", "", "", "", "", "", "", ""}
    Dim row12() As String = {"", "SQUID", "Squid Game", "", "", "", "", "", "", "", ""}
    Dim row13() As String = {"", "HOT", "Holo", "", "", "", "", "", "", "", ""}
    Dim row14() As String = {"", "ATLAS", "Star Atlas", "", "", "", "", "", "", "", ""}
    Dim row15() As String = {"", "ZODI", "Zodium", "", "", "", "", "", "", "", ""}
    Dim row16() As String = {"", "VML", "Meta Land", "", "", "", "", "", "", "", ""}
    Dim row17() As String = {"", "SNN", "SeChain", "", "", "", "", "", "", "", ""}

    Dim rows() As Object = {row1, row2, row3, row4, row5, row6, row7, row8, row9, row10, row11, row12, row13, row14, row15, row16, row17}

    Dim rowArray As String()
    For Each rowArray In rows
        dgvMain.Rows.Add(rowArray)
    Next rowArray

    Dim chk As New DataGridViewCheckBoxColumn()
    dgvMain.Columns.Add(chk)
    chk.HeaderText = "Enable"
    chk.Name = "chk"
    chk.Width = 70
End Sub

Public Sub getPriceBTC()
Try
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
    ServicePointManager.Expect100Continue = True
    'Dim _price As String = txtCryptoPrice.Text

    Dim _url As String = "https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=EUR"
    Dim _req As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(_url)
    _req.Proxy = Nothing
    _req.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.81 Safari/537.36"

    Dim _resp As System.Net.HttpWebResponse = _req.GetResponse
    Dim streamReader As System.IO.StreamReader = New System.IO.StreamReader(_resp.GetResponseStream())
    Dim API_source As String = streamReader.ReadToEnd
    Dim _Fprice = API_source.ToLower.ToString
    Dim _priceF = _Fprice.Substring(7)
    Dim jsonprice As String = _priceF.Replace("}", "")
  Dim row As DataGridViewRow = Nothing
        For Each item As DataGridViewRow In dgvMain.Rows
            row = item
            row.Cells(3).Value = jsonprice
        Next
    _runningThreads.Remove(Thread.CurrentThread)
Catch ex As Exception

End Try

End Sub

I added piece of CODE after I edited but it shows now in all CELLS
the btc price so how DO I add it only to the first row?
row.Cells(3).Value = jsonprice

Body:
heheheh I google it :p

 dgvMain.Rows(0).Cells(3).Value = jsonprice

yeees!


问:
How to remove error made when adding exit button?
```<code>from tkinter import*
import sqlite3
class login:
    def __init__(self,root):
        self.root=root
        self.root.geometry("250x250")
        self.root.title("Login")
        self.root.resizable(False,False)

        self.var_username=StringVar()   ##variables
        self.var_password=StringVar()

        username=Label(self.root,text="Username",font=("Bahnschrift SemiBold",15),bg="white",fg="black").place(x=15,y=20)
        username=Entry(self.root,textvariable=self.var_username,font=("Bahnschrift SemiBold",15),bg="white",fg="black").place(x=125,y=20,width=115)

        password=Label(self.root,text="Password ",font=("Bahnschrift SemiBold",15),bg="white",fg="black").place(x=15,y=60)
        password=Entry(self.root,textvariable=self.var_password,font=("Bahnschrift SemiBold",15),bg="white",fg="black").place(x=125,y=60,width=115)

        _exit=Button(self.root,text="exit",command=self.destroy,font=("Bahnschrift SemiBold",15),bg="green",fg="white",cursor="hand2").place(x=125,y=100,width=55,height=28)

if __name__ == "__main__":
root=Tk()
obj=login(root)
root.mainloop()
</code>```

it comes up with a attribute error and im not to sure how to fix it because it works in other pieces of code.

答:
You might want to change the button command from self.destroy to self.root.destroy.

Button(self.root,
    text="exit",
    command=self.root.destroy,
    font=("Bahnschrift SemiBold",15),
    bg="green",
    fg="white",
    cursor="hand2").place(x=125, y=100, width=55, height=28)
```

As a side note, doing label = Label(root, ...).place(x=...) does not do anything (for any widget). The value of label will be stored as None and you wont be able to reference that later to change its properties. If this is the goal, then simply: Label(root, ...).place(x=...) would work. Otherwise, you'll have to create widgets in one line, and place them in the next lline

PS: It is a recommended practice to also include the error faced in order for ease of diagnosing. Please do refer How to ask for asking further questions.

Body:
from tkinter import*
import sqlite3
class login:
    def __init__(self,root):
        self.root=root
        self.root.geometry("250x250")
        self.root.title("Login")
        self.root.resizable(False,False)

        self.var_username=StringVar()   ##variables
        self.var_password=StringVar()

        username=Label(self.root,text="Username",font=("Bahnschrift SemiBold",15),bg="white",fg="black").place(x=15,y=20)
        username=Entry(self.root,textvariable=self.var_username,font=("Bahnschrift SemiBold",15),bg="white",fg="black").place(x=125,y=20,width=115)

        password=Label(self.root,text="Password ",font=("Bahnschrift SemiBold",15),bg="white",fg="black").place(x=15,y=60)
        password=Entry(self.root,textvariable=self.var_password,font=("Bahnschrift SemiBold",15),bg="white",fg="black").place(x=125,y=60,width=115)

        _exit=Button(self.root,text="exit",command=self.destroy,font=("Bahnschrift SemiBold",15),bg="green",fg="white",cursor="hand2").place(x=125,y=100,width=55,height=28)

if __name__ == "__main__":
root=Tk()
obj=login(root)
root.mainloop()

it comes up with a attribute error and im not to sure how to fix it because it works in other pieces of code.

Body:
You might want to change the button command from self.destroy to self.root.destroy.

Button(self.root,
    text="exit",
    command=self.root.destroy,
    font=("Bahnschrift SemiBold",15),
    bg="green",
    fg="white",
    cursor="hand2").place(x=125, y=100, width=55, height=28)

As a side note, doing label = Label(root, ...).place(x=...) does not do anything (for any widget). The value of label will be stored as None and you wont be able to reference that later to change its properties. If this is the goal, then simply: Label(root, ...).place(x=...) would work. Otherwise, you'll have to create widgets in one line, and place them in the next lline

PS: It is a recommended practice to also include the error faced in order for ease of diagnosing. Please do refer How to ask for asking further questions.


问:
What happens when a Kafka Broker runs out of space before the configured Retention time/bytes?
I understand that most systems should have monitoring to make sure that this doesn't happen (and that we should set the retention policies properly), but am just curious what happens if the Kafka Broker does indeed run out of disk space (for example, if we set retention time to 30 days, but the Broker runs out of disk space by the 1st day)?

In a single Broker scenario, does the Broker simply stop receiving any new messages and return an exception to the Producer? Or does it delete old message to make space for the new ones?

In a multi Broker scenario, assuming we have Broker A (leader of the partition but has not more disk space) and Broker B (follower of the partition and still has disk space), will leadership move to Broker B? What happens when both Brokers run out of space? Does it also return an exception to the Producer?

答:
Assuming the main data directory is not on a separate volume, the OS processes themselves will start locking up because there's no free space left on the device.

Otherwise, if the log directories are isolated to Kafka, you can expect any producer acks to stop working. I'm not sure if a specific error message is returned to clients, though. From what I remember, the brokers just stop responding to Kafka client requests and we had to SSH to them, stop kafka services, and manually clean up files rather than waiting for retention policies. No, the brokers don't preempt old data in favor of new records


问:
React protected route not redirecting to children when authorisation finished
I'm trying to put in a layer of authentication in my protected routes and I've been doing this using the following:

```<code>function ProtectedRoute ({ children }) {
    const { user } = useContext(AuthContext);

    return user.isVerifying ? (
        <p>Is loading...</p>
    ) : user.verified ? children : <Navigate to="/login" />;
}

export default ProtectedRoute;
</code>```

My user context is initialised with the following information:

```<code>{
    "user": null,
    "verified": false,
    "isVerifying": false
}
</code>```

At the moment, the user authorisation state is checked by a function (authUser), inside of my AuthContext.Provider, that at the moment runs on every render of my components (shown below). This is an asynchronous function that makes an API call to check to see if the user JWT token stored in localStorage is valid.

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

const AuthContext = createContext();

function AuthProvider({children}) {
    const [user, setUser] = useState({
        "user": null,
        "verified": false,
        "isVerifying": true
    });

    async function authUser() {
        const userLocal = localStorage.getItem('user');

        if (userLocal) {
            const userLocalJSON = JSON.parse(userLocal);
            const verifyResponse = await verifyToken(userLocalJSON);

            if (verifyResponse) {
                setUser({"user": userLocalJSON, "verified": true, "isVerifying": false});
            } else {
                setUser({"user": userLocalJSON, "verified": false, "isVerifying": false});
            }
        }
    }

    async function verifyToken(userJSON) {
        try {
            setUser({"user": null, "verified": false, "isVerifying": true});

            // Make API call

            if (response.status === 200) {
                return true;
            } else {
                return false;
            }
        } catch (e) {
            return false;
        }
    }

    useEffect(() => {
        authUser();
    }, [])

    return (
        <AuthContext.Provider value={{user, authUser}}>
            {children}
        </AuthContext.Provider>
    )
}

export default AuthContext;
export { AuthProvider };
</code>```

Upon validating the token, the user context is then updated to verified = true with the information about the user. During this process, the user context isVerifying = true (an equivalent to isLoading) and gets set back to false once the API call is complete.

Now there are a few problems with this:

On every re-render of the DOM, the context information is set back to its defaults. Is there a way around this so that useEffect() only fires upon localStorage changes? I've tried implenting the following solution, which adds a listener to localStorage and then triggers the useEffect when that changes. I could not get this to fire upon localStorage changes. Maybe I did something wrong (see below)?

```<code> useEffect(() => {
   window.addEventListener('storage', authUser)

   return () => {
     window.removeEventListener('storage', authUser)
   }
 }, [])
</code>```

Because the initial isVerifying = false and the switch to true doesn't occur before the DOM is rendered, the protected route navigates to the login page. Even after the user context is finally set, it remains on the login page. The loading page is never displayed and instead there is an instant redirection to the login page. Unfortunately, I can't set isVerifying = true initially as non-logged in users get stuck on the loading page.

Any suggestions would be really helpful.

答:
To solve question 2:

Your ternary isn't quite doing what you want. It's kind of like saying "if user.isVerifying or !user.verified, navigate". That's not what we want.

Embedded ternaries can be tricky and I usually try to avoid them if I can. Since this component is so small, you don't need to do this with ternaries at all actually. I think this should work:

Set isVerifying to start out true. Then:

```<code>function ProtectedRoute ({ children }) {
    const { user } = useContext(AuthContext);

    if (user.isVerifying) {
        return <p>Is loading...</p>
    }

    if (user.verified === false) {
        return <Navigate to="/login" />
    }

    return children

}

export default ProtectedRoute;
</code>```

EDIT: You also need to update the verification state in authUser. Noticed how you are only updating the loading state if userLocal is truthy. Best bet is to start out loading, and always call setUser at the end. This isn't the only way to do it but I think it should work:

    async function authUser() {
        setUser(currentState => {...currentState, isVerifying: true})
        const userLocal = localStorage.getItem('user');

        if (!userLocal) {
            setUser({
                user: null,
                verified: false,
                isVerifying: false,
            })
        }

        const userLocalJSON = JSON.parse(userLocal);
        const verifyResponse = await verifyToken(userLocalJSON);
        setUser({
            user: userLocalJSON,
            verified: verifyResponse,
            isVerifying: false,
        })
    }
```

Body:
I'm trying to put in a layer of authentication in my protected routes and I've been doing this using the following:

function ProtectedRoute ({ children }) {
    const { user } = useContext(AuthContext);

    return user.isVerifying ? (

Is loading...

    ) : user.verified ? children : <Navigate to="/login" />;
}

export default ProtectedRoute;

My user context is initialised with the following information:

{
    "user": null,
    "verified": false,
    "isVerifying": false
}

At the moment, the user authorisation state is checked by a function (authUser), inside of my AuthContext.Provider, that at the moment runs on every render of my components (shown below). This is an asynchronous function that makes an API call to check to see if the user JWT token stored in localStorage is valid.

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

const AuthContext = createContext();

function AuthProvider({children}) {
    const [user, setUser] = useState({
        "user": null,
        "verified": false,
        "isVerifying": true
    });

    async function authUser() {
        const userLocal = localStorage.getItem('user');

        if (userLocal) {
            const userLocalJSON = JSON.parse(userLocal);
            const verifyResponse = await verifyToken(userLocalJSON);

            if (verifyResponse) {
                setUser({"user": userLocalJSON, "verified": true, "isVerifying": false});
            } else {
                setUser({"user": userLocalJSON, "verified": false, "isVerifying": false});
            }
        }
    }

    async function verifyToken(userJSON) {
        try {
            setUser({"user": null, "verified": false, "isVerifying": true});

            // Make API call

            if (response.status === 200) {
                return true;
            } else {
                return false;
            }
        } catch (e) {
            return false;
        }
    }

    useEffect(() => {
        authUser();
    }, [])

    return (
        <AuthContext.Provider value={{user, authUser}}>
            {children}
        </AuthContext.Provider>
    )
}

export default AuthContext;
export { AuthProvider };

Upon validating the token, the user context is then updated to verified = true with the information about the user. During this process, the user context isVerifying = true (an equivalent to isLoading) and gets set back to false once the API call is complete.

Now there are a few problems with this:

On every re-render of the DOM, the context information is set back to its defaults. Is there a way around this so that useEffect() only fires upon localStorage changes? I've tried implenting the following solution, which adds a listener to localStorage and then triggers the useEffect when that changes. I could not get this to fire upon localStorage changes. Maybe I did something wrong (see below)?

 useEffect(() => {
   window.addEventListener('storage', authUser)

   return () => {
     window.removeEventListener('storage', authUser)
   }
 }, [])

Because the initial isVerifying = false and the switch to true doesn't occur before the DOM is rendered, the protected route navigates to the login page. Even after the user context is finally set, it remains on the login page. The loading page is never displayed and instead there is an instant redirection to the login page. Unfortunately, I can't set isVerifying = true initially as non-logged in users get stuck on the loading page.

Any suggestions would be really helpful.

Body:
To solve question 2:

Your ternary isn't quite doing what you want. It's kind of like saying "if user.isVerifying or !user.verified, navigate". That's not what we want.

Embedded ternaries can be tricky and I usually try to avoid them if I can. Since this component is so small, you don't need to do this with ternaries at all actually. I think this should work:

Set isVerifying to start out true. Then:

function ProtectedRoute ({ children }) {
    const { user } = useContext(AuthContext);

    if (user.isVerifying) {
        return <p>Is loading...</p>
    }

    if (user.verified === false) {
        return <Navigate to="/login" />
    }

    return children

}

export default ProtectedRoute;

EDIT: You also need to update the verification state in authUser. Noticed how you are only updating the loading state if userLocal is truthy. Best bet is to start out loading, and always call setUser at the end. This isn't the only way to do it but I think it should work:

    async function authUser() {
        setUser(currentState => {...currentState, isVerifying: true})
        const userLocal = localStorage.getItem('user');

        if (!userLocal) {
            setUser({
                user: null,
                verified: false,
                isVerifying: false,
            })
        }

        const userLocalJSON = JSON.parse(userLocal);
        const verifyResponse = await verifyToken(userLocalJSON);
        setUser({
            user: userLocalJSON,
            verified: verifyResponse,
            isVerifying: false,
        })
    }