问:
User logged out of firebase server when different page loads
I'm new to firebase, and I can't figure out how to keep the user logged in after going to a different page.  I'm able to successfully log in and post user data to the console on the log in page, but when I go to a different page and try to get the user information using firebase.auth().currentUser.  I initially had it immediately redirect to another page after the log in was completed, and turned it off to see if I was leaving the page before the information was relayed to the server, but that did not fix it.  I also tried to manually set the persistence to no avail.  I've looked around here and haven't found anything that fixes the problem.

Here is my sign in method (which is basically the same thing as what's on firebase docs), which is called when the sign in button on the form is clicked:

```<code>function signIn(){
    //getting credential input from form
    var email = document.getElementById('email').value;
    var password = document.getElementById('password').value;
    console.log(email, password)
    //calling firebase to sign in user
    firebase.auth().signInWithEmailAndPassword(email, password)
    .then(cred => {
        //confirmation that user signed in
        console.log("signed in");
    }).catch(function(error) {
        var errorCode = error.code;
        var errorMsg = error.message;
        if(errorCode === 'auth/wrong-password') {
            alert('Wrong Password');
        }
        else {
            alert(errorMsg);
        }
        console.log(error);
    });
};
</code>```

答:
if I'm wrong, the others will correct me. As far as I know, when you log in with a user, even if you switch between pages, the information about that user is permanent . In other words, only the information that the user has added, updated and deleted will be displayed on your page. The user variable and other user information must be displayed in "signout".

```<code>// Think of it as a login page. assume that the user is redirected to a page after being logged in.
firebase.auth().signInWithEmailAndPassword(email, password)
    .then(() => {
            window.location.href = "index.html"; // let this be the page where user information should be displayed.
     })
</code>```

So You also need a listener that handles login and logout status. This is where you can redirect users if they have successfully logged in.

```<code>firebase.auth().onAuthStateChanged(user => {
  if(user) {
    // this is where you can listen to user changes in index html and make your operations related to user here.

firebase.auth().signOut() //  in this section you can do the logout function. Their information will be displayed until the user makes the logout. It continues until a new user logs in.
   .then(() => {
window.location.href = "login.html"
}
});
</code>```

Body:
I'm new to firebase, and I can't figure out how to keep the user logged in after going to a different page.  I'm able to successfully log in and post user data to the console on the log in page, but when I go to a different page and try to get the user information using firebase.auth().currentUser.  I initially had it immediately redirect to another page after the log in was completed, and turned it off to see if I was leaving the page before the information was relayed to the server, but that did not fix it.  I also tried to manually set the persistence to no avail.  I've looked around here and haven't found anything that fixes the problem.

Here is my sign in method (which is basically the same thing as what's on firebase docs), which is called when the sign in button on the form is clicked:

function signIn(){
    //getting credential input from form
    var email = document.getElementById('email').value;
    var password = document.getElementById('password').value;
    console.log(email, password)
    //calling firebase to sign in user
    firebase.auth().signInWithEmailAndPassword(email, password)
    .then(cred => {
        //confirmation that user signed in
        console.log("signed in");
    }).catch(function(error) {
        var errorCode = error.code;
        var errorMsg = error.message;
        if(errorCode === 'auth/wrong-password') {
            alert('Wrong Password');
        }
        else {
            alert(errorMsg);
        }
        console.log(error);
    });
};

Body:
if I'm wrong, the others will correct me. As far as I know, when you log in with a user, even if you switch between pages, the information about that user is permanent . In other words, only the information that the user has added, updated and deleted will be displayed on your page. The user variable and other user information must be displayed in "signout".

// Think of it as a login page. assume that the user is redirected to a page after being logged in.
firebase.auth().signInWithEmailAndPassword(email, password)
    .then(() => {
            window.location.href = "index.html"; // let this be the page where user information should be displayed.
     })

So You also need a listener that handles login and logout status. This is where you can redirect users if they have successfully logged in.

firebase.auth().onAuthStateChanged(user => {
  if(user) {
    // this is where you can listen to user changes in index html and make your operations related to user here.

firebase.auth().signOut() //  in this section you can do the logout function. Their information will be displayed until the user makes the logout. It continues until a new user logs in.
   .then(() => {
window.location.href = "login.html"
}
});


来源: stackexchange

问:
Postman in circleci - Error calling workflow: 'workflow'
Trying to run simple postman API calls but getting

```<code>Error calling workflow: 'workflow'
</code>```

My .circleci/config.yml is

```<code>$ cat .circleci/config.yml
version: 2.1
orbs:
  newman: postman/newman@0.0.2
jobs:
  newman-collection-run:
    executor: newman/postman-newman-docker
    steps:
      - checkout
      - newman/newman-run:
          collection: ./collection.json
</code>```

collection.json is at the root of the project and is the export from postman.

I am using the example from

https://circleci.com/orbs/registry/orb/postman/newman

which shows:

The "workflow" reference comes from the original example on the circleci site (not with newman) when I start building on this branch and I've replaced the config file contents in the branch and pushed it so not sure why this reference is coming up ?

Here is that original screen:

which I change to be:

and

答:
If you read the line of the error you left out (see the build), you can see why there's an error calling the workflow:

```<code># Error calling workflow: 'workflow'
# Cannot find a definition for job named build
</code>```

This requirement is documented in the config file reference (emphasis mine):

If you are not using workflows, the jobs map must contain a job
  named build. This build job is the default entry-point for a run
  that is triggered by a push to your VCS provider. It is possible to
  then specify additional jobs and run them using the CircleCI API.

But why is it looking for a job named build in a workflow named workflow? Because if you don't supply a workflow explicitly, CircleCI uses the following default:

workflows:
  version: 2
  workflow:
    jobs:
    - build
```

<p>You can see this by using CircleCI's Local CLI to run <code>circleci config process .circleci/config.yml</code> on the fixed version in Danny's answer.</p>

<p>This suggests another solution to the problem; rather than renaming the job, <strong>supply the workflow</strong>:</p>

<pre class="lang-yaml prettyprint-override"><code>version: 2.1
orbs:
  newman: postman/newman@0.0.2
jobs:
  newman-collection-run:
    executor: newman/postman-newman-docker
    steps:
      - checkout
      - newman/newman-run:
          collection: ./collection.json
workflows:
  version: 2
  workflow:
    jobs:
    - newman-collection-run
</code>```

As a side note, while looking to see if I could figure what message you saw on the original failing build, this is what I was met with:

```<code>* 37737f0 - (HEAD -> master, origin/master, origin/HEAD) config (22 hours ago) <Michael Durrant>
* e04efa0 - config (22 hours ago) <Michael Durrant>
*   e640e4e - merge into master (26 hours ago) <Michael Durrant>
|\
| * cc16160 - config (27 hours ago) <Michael Durrant>
| * 13e0ad5 - config (28 hours ago) <Michael Durrant>
| * e4df02c - config (28 hours ago) <Michael Durrant>
| * b287102 - config (28 hours ago) <Michael Durrant>
| * 14bd61c - config (28 hours ago) <Michael Durrant>
| * 0f81d84 - config (28 hours ago) <Michael Durrant>
| * ccd06b6 - config (28 hours ago) <Michael Durrant>
| * 2b909f3 - config (28 hours ago) <Michael Durrant>
| * 4b15bca - config (28 hours ago) <Michael Durrant>
| * 240c591 - config (28 hours ago) <Michael Durrant>
| * 50096a9 - config (28 hours ago) <Michael Durrant>
| * ad9fe60 - config (28 hours ago) <Michael Durrant>
| * 7c19205 - config (28 hours ago) <Michael Durrant>
| * 3c0a3b9 - config (28 hours ago) <Michael Durrant>
| * 2d1954e - config (29 hours ago) <Michael Durrant>
| * 4e1f087 - config (29 hours ago) <Michael Durrant>
| * 9413b68 - config (29 hours ago) <Michael Durrant>
| * 942d493 - config (29 hours ago) <Michael Durrant>
| * e8412b8 - config (29 hours ago) <Michael Durrant>
| * c136702 - Add .circleci/config.yml (30 hours ago) <Michael Durrant>
| * 2203710 - Add .circleci/config.yml (30 hours ago) <Michael Durrant>
| * 94a084e - Add .circleci/config.yml (30 hours ago) <Michael Durrant>
| * ec40356 - Add .circleci/config.yml (30 hours ago) <Michael Durrant>
| * 6964057 - Add .circleci/config.yml (30 hours ago) <Michael Durrant>
* | 4e5c9d1 - coinfig (30 hours ago) <Michael Durrant>
* | cbf49fd - workflow name (30 hours ago) <Michael Durrant>
* | 6245ae1 - workflow name (30 hours ago) <Michael Durrant>
* | fdf52b5 - workflow name (30 hours ago) <Michael Durrant>
* | 0c4c455 - workflow name (30 hours ago) <Michael Durrant>
|/
* 7c31fb6 - update circleci config (30 hours ago) <Michael Durrant>
</code>```

This isn't a healthy way to work with git; if you're not going to give your future self enough context to understand what is changing, I would recommending squashing out all the redundant commits when you bring the changes into master.

Note you can get the error messages for basic config file failures locally with the CLI by running circleci config validate, which saves the loop of pushing all of those commits that can't work.

ContentLicense: CC BY-SA 4.0

Body:
Trying to run simple postman API calls but getting

Error calling workflow: 'workflow'

My .circleci/config.yml is

$ cat .circleci/config.yml
version: 2.1
orbs:
  newman: postman/newman@0.0.2
jobs:
  newman-collection-run:
    executor: newman/postman-newman-docker
    steps:
      - checkout
      - newman/newman-run:
          collection: ./collection.json

collection.json is at the root of the project and is the export from postman.

I am using the example from

https://circleci.com/orbs/registry/orb/postman/newman

which shows:

The "workflow" reference comes from the original example on the circleci site (not with newman) when I start building on this branch and I've replaced the config file contents in the branch and pushed it so not sure why this reference is coming up ?

Here is that original screen:

which I change to be:

and

Body:
If you read the line of the error you left out (see the build), you can see why there's an error calling the workflow:

# Error calling workflow: 'workflow'
# Cannot find a definition for job named build

This requirement is documented in the config file reference (emphasis mine):

If you are not using workflows, the jobs map must contain a job
  named build. This build job is the default entry-point for a run
  that is triggered by a push to your VCS provider. It is possible to
  then specify additional jobs and run them using the CircleCI API.

But why is it looking for a job named build in a workflow named workflow? Because if you don't supply a workflow explicitly, CircleCI uses the following default:

workflows:
  version: 2
  workflow:
    jobs:
    - build

You can see this by using CircleCI's Local CLI to run circleci config process .circleci/config.yml on the fixed version in Danny's answer.

This suggests another solution to the problem; rather than renaming the job, supply the workflow:

version: 2.1
orbs:
  newman: postman/newman@0.0.2
jobs:
  newman-collection-run:
    executor: newman/postman-newman-docker
    steps:
      - checkout
      - newman/newman-run:
          collection: ./collection.json
workflows:
  version: 2
  workflow:
    jobs:
    - newman-collection-run

As a side note, while looking to see if I could figure what message you saw on the original failing build, this is what I was met with:

* 37737f0 - (HEAD -> master, origin/master, origin/HEAD) config (22 hours ago) <Michael Durrant>
* e04efa0 - config (22 hours ago) <Michael Durrant>
*   e640e4e - merge into master (26 hours ago) <Michael Durrant>
|\
| * cc16160 - config (27 hours ago) <Michael Durrant>
| * 13e0ad5 - config (28 hours ago) <Michael Durrant>
| * e4df02c - config (28 hours ago) <Michael Durrant>
| * b287102 - config (28 hours ago) <Michael Durrant>
| * 14bd61c - config (28 hours ago) <Michael Durrant>
| * 0f81d84 - config (28 hours ago) <Michael Durrant>
| * ccd06b6 - config (28 hours ago) <Michael Durrant>
| * 2b909f3 - config (28 hours ago) <Michael Durrant>
| * 4b15bca - config (28 hours ago) <Michael Durrant>
| * 240c591 - config (28 hours ago) <Michael Durrant>
| * 50096a9 - config (28 hours ago) <Michael Durrant>
| * ad9fe60 - config (28 hours ago) <Michael Durrant>
| * 7c19205 - config (28 hours ago) <Michael Durrant>
| * 3c0a3b9 - config (28 hours ago) <Michael Durrant>
| * 2d1954e - config (29 hours ago) <Michael Durrant>
| * 4e1f087 - config (29 hours ago) <Michael Durrant>
| * 9413b68 - config (29 hours ago) <Michael Durrant>
| * 942d493 - config (29 hours ago) <Michael Durrant>
| * e8412b8 - config (29 hours ago) <Michael Durrant>
| * c136702 - Add .circleci/config.yml (30 hours ago) <Michael Durrant>
| * 2203710 - Add .circleci/config.yml (30 hours ago) <Michael Durrant>
| * 94a084e - Add .circleci/config.yml (30 hours ago) <Michael Durrant>
| * ec40356 - Add .circleci/config.yml (30 hours ago) <Michael Durrant>
| * 6964057 - Add .circleci/config.yml (30 hours ago) <Michael Durrant>
* | 4e5c9d1 - coinfig (30 hours ago) <Michael Durrant>
* | cbf49fd - workflow name (30 hours ago) <Michael Durrant>
* | 6245ae1 - workflow name (30 hours ago) <Michael Durrant>
* | fdf52b5 - workflow name (30 hours ago) <Michael Durrant>
* | 0c4c455 - workflow name (30 hours ago) <Michael Durrant>
|/
* 7c31fb6 - update circleci config (30 hours ago) <Michael Durrant>

This isn't a healthy way to work with git; if you're not going to give your future self enough context to understand what is changing, I would recommending squashing out all the redundant commits when you bring the changes into master.

Note you can get the error messages for basic config file failures locally with the CLI by running circleci config validate, which saves the loop of pushing all of those commits that can't work.


问:
Big Oh! algorithms running in O(4^N)
For algorithms running in

```<code>O(16^N)
</code>```

If we triple the size, the time is multiplied by what number??

答:
The time complexity of the algorithm represents the growth in run-time of the algorithm with respect to the growth in input size. So, if our input size increases by 3 times, that means we have now new value for our input size.

Hence, time complexity of the algorithm still remains same. i.e O(4^N)

Title: Big Oh! algorithms running in O(4^N)

Body:
For algorithms running in

O(16^N)

If we triple the size, the time is multiplied by what number??


问:
Conditional sum on multiple pandas groups, each defined by a set of overlapping column values
I'm trying to perform a conditional sum on groups of rows defined by a list of arbitrary column values. By conditional sum, I mean sum values in one column only if the value in a second column is above a threshold. There can be overlap among the groups and the number of elements in each group can be different.

For example, given the following dataframe:

data = {
   'id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
   'counter': [10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
   'output': [5, 10, 15, 20, 25, 35, 20, 15, 10, 5]
}
df = pd.DataFrame(data)
```
```>>> df
   id  counter  output
0   1       10       5
1   2        9      10
2   3        8      15
3   4        7      20
4   5        6      25
5   6        5      35
6   7        4      20
7   8        3      15
8   9        2      10
9  10        1       5
```
<p>And the following inputs (I'm flexible if we need to change their format):</p>
<pre class="lang-py prettyprint-override"><code>group_ids = {'Group A': [1, 2, 3, 4], 'Group B': [6, 7, 8, 9], 'Group C': [4, 5, 6]}
output_threshold = 12
</code>```

I would like to generate the following new dataframe, which is the sum of counter for each group defined by the list of group_ids only if output exceeds the specified output_threshold. Bonus points if I can add the title to each of these groups:

```<code>title    sum
Group A   15
Group B   12
Group C   18
</code>```

答:
The following is a solution to the question in this post, except for the fact that the id groups CANNOT be overlapping.

You may want to create an inverse_group dictionary, map the id and groupby:

inverse_groups={x:k for k,v in group_ids.items() for x in v}

(df[df['output']>output_threshold]
   .groupby(df['id'].map(inverse_groups))
   .counter.sum()
)
```
```Output:

id
Group A     8
Group B     7
Group C    18
Name: counter, dtype: int64
```

Full credit goes to @QuangHoang. This was his first reply to my question, which he completely re-wrote to satisfy the overlapping id condition.

Body:
I'm trying to perform a conditional sum on groups of rows defined by a list of arbitrary column values. By conditional sum, I mean sum values in one column only if the value in a second column is above a threshold. There can be overlap among the groups and the number of elements in each group can be different.

For example, given the following dataframe:

data = {
   'id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
   'counter': [10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
   'output': [5, 10, 15, 20, 25, 35, 20, 15, 10, 5]
}
df = pd.DataFrame(data)

>>> df
   id  counter  output
0   1       10       5
1   2        9      10
2   3        8      15
3   4        7      20
4   5        6      25
5   6        5      35
6   7        4      20
7   8        3      15
8   9        2      10
9  10        1       5

And the following inputs (I'm flexible if we need to change their format):

group_ids = {'Group A': [1, 2, 3, 4], 'Group B': [6, 7, 8, 9], 'Group C': [4, 5, 6]}
output_threshold = 12

I would like to generate the following new dataframe, which is the sum of counter for each group defined by the list of group_ids only if output exceeds the specified output_threshold. Bonus points if I can add the title to each of these groups:

title    sum
Group A   15
Group B   12
Group C   18

Body:
The following is a solution to the question in this post, except for the fact that the id groups CANNOT be overlapping.

You may want to create an inverse_group dictionary, map the id and groupby:

inverse_groups={x:k for k,v in group_ids.items() for x in v}

(df[df['output']>output_threshold]
   .groupby(df['id'].map(inverse_groups))
   .counter.sum()
)

Output:

id
Group A     8
Group B     7
Group C    18
Name: counter, dtype: int64

Full credit goes to @QuangHoang. This was his first reply to my question, which he completely re-wrote to satisfy the overlapping id condition.


问:
we have to free up the memory while deleting a node in a linked list in c but we do not have to do the same in java,Why?
in case of c we have to do free(data) while deleting a node to free up the memory space occupied by the node manually but in case of java we do not have to do the same.Why and what happens??</p>

答:
when you remove the reference to the node will be eligible for the GC to free the memory
, For more information, you can read Java Garbage collection basic Oracle doc</p>


问:
How to do Left Void?
I am trying to understand https://hackage.haskell.org/package/base-4.14.0.0/docs/Data-Void.html and having the following example:

```<code>let x :: Either Void Int; x = Left Void
</code>```

The code does not get compiled. How to make it run?

答: Since it is impossible to ever create a value of type Void, every value of type Either Void Int must have a Right constructor (or else a bottom in its Left constructor, which is not very useful). e.g., Right 1 would be a valid value of this type.

Title: How to do Left Void?

Body:
I am trying to understand https://hackage.haskell.org/package/base-4.14.0.0/docs/Data-Void.html and having the following example:

let x :: Either Void Int; x = Left Void

The code does not get compiled. How to make it run?


问:
Yank in visual (Vim) mode in zsh does not copy to clipboard in ordert to paste with Ctrl + d in other applications
I recently moved from bash to zsh and use vim keybindings in zsh.

When I highlight a string in visual and yank it with y, I can then paste it inside of zsh without problem. However when I try to paste that same string outside of zsh (with the command Ctrl + d) it does not work. Instead the last copied item with Ctrl + c is copied there.

Is there an additional command to write in the .zshrc?

答:
By default zsh yanks to its own internal registers. Luckily, like in Vim, it's fairly simple yank to the system clipboard.

```<code># vi mode
bindkey -v

# Yank to the system clipboard
function vi-yank-xclip {
    zle vi-yank
   echo "$CUTBUFFER" | pbcopy -i
}

zle -N vi-yank-xclip
bindkey -M vicmd 'y' vi-yank-xclip

</code>```

Replace pbcopy with the method of your system, for example xclip if you're on Linux.

Further reading and a couple alternatives at:

https://unix.stackexchange.com/questions/25765/pasting-from-clipboard-to-vi-enabled-zsh-or-bash-shell

How do I yank into the system register from v-imode?

(Which this question is a duplicate of.)

Body:
By default zsh yanks to its own internal registers. Luckily, like in Vim, it's fairly simple yank to the system clipboard.

# vi mode
bindkey -v

# Yank to the system clipboard
function vi-yank-xclip {
    zle vi-yank
   echo "$CUTBUFFER" | pbcopy -i
}

zle -N vi-yank-xclip
bindkey -M vicmd 'y' vi-yank-xclip

Replace pbcopy with the method of your system, for example xclip if you're on Linux.

Further reading and a couple alternatives at:

https://unix.stackexchange.com/questions/25765/pasting-from-clipboard-to-vi-enabled-zsh-or-bash-shell

How do I yank into the system register from v-imode?

(Which this question is a duplicate of.)


问:
Trying to create javascript out put loop for various tasks
I am trying to use javascript to create tasks with a counter.  The script will lookup task entries and then create depending on what is within the DB.  For example -

task 1 [timer 1]

task 2 [timer 2]

task 3 [timer 3]

Currently my output is like so

task 1 [timer 3]

task 2 [timer 3]

task 3 [timer 3]

My code is as follows -

```<code>{% if tasks %}

    {% for task in tasks %}

        <button class="button";>Complete!</button><p style="display: inline-block;font-weight: bold; color: red;">{{ task.task_name }}
            </p>
        <p></p>
        <p id='{{ task.id }}'; style="text-align: right;padding-right: 60px"></p>
        <p> <script>
                var countDownDate = new DateTime('{{ task.task_due }}').getTime();

                var x = setInterval(function() {

            var now = new Date().getTime();

            var distance = countDownDate - now;

            var days = Math.floor(distance / (1000 * 60 * 60 * 24));
            var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            var seconds = Math.floor((distance % (1000 * 60)) / 1000);

            document.getElementById('{{ task.id }}').innerHTML = days + "d " + hours + "h "
            + minutes + "m " + seconds + "s ";

            if (distance < 0) {
            clearInterval(x);
            document.getElementById('{{ task.id }}').innerHTML = "EXPIRED";
            }
                }, 1000);
            </script>
        </p>
        <p></p>
</code>```

I appreciate any help, thanks

答:
A few things to point out:

Setting all these vars in the body of the document means they're all scoped to the global window object, which means each loop overwrites the same variable. This is why you're seeing the results of timer3 in all three slots.

(Minor issue) You've got extraneous semicolons in a few places in your HTML. No need for semicolons in HTML tags, unless they're inside the quotes of an attribute that accepts them (such as the style="" attribute).

(Minor issue) Be consistent with quote marks. A good general style principle is "double quotes" for HTML attributes, 'single quotes' for strings in Javascript.

You're creating duplicate javascript code for every iteration of your for task in tasks loop. You should instead think of that loop as a place to trigger the start of timers and display the results of timers, but that shouldn't be where all that timer-creation code lives.

To fix (4), you'll want to make a reusable function out of the timer-creating code. This is a good test case to think about what function arguments you need to pass to a timer-creating function. In looking over your code, I see that you're using task.id and task.task_due in the code that creates the timer. Looks like we would just need to pass those two values to a createTimer() function.

Try something like this:

{% if tasks %}
  {% for task in tasks %}
    <button class="button">Complete!</button>

      {{ task.task_name }}

  {% endfor %}
{% endif %}
```

Body:
I am trying to use javascript to create tasks with a counter.  The script will lookup task entries and then create depending on what is within the DB.  For example -

task 1 [timer 1]

task 2 [timer 2]

task 3 [timer 3]

Currently my output is like so

task 1 [timer 3]

task 2 [timer 3]

task 3 [timer 3]

My code is as follows -

{% if tasks %}

    {% for task in tasks %}

        <button class="button";>Complete!</button>
{{ task.task_name }}

I appreciate any help, thanks

Body:
A few things to point out:

Setting all these vars in the body of the document means they're all scoped to the global window object, which means each loop overwrites the same variable. This is why you're seeing the results of timer3 in all three slots.

(Minor issue) You've got extraneous semicolons in a few places in your HTML. No need for semicolons in HTML tags, unless they're inside the quotes of an attribute that accepts them (such as the style="" attribute).

(Minor issue) Be consistent with quote marks. A good general style principle is "double quotes" for HTML attributes, 'single quotes' for strings in Javascript.

You're creating duplicate javascript code for every iteration of your for task in tasks loop. You should instead think of that loop as a place to trigger the start of timers and display the results of timers, but that shouldn't be where all that timer-creation code lives.

To fix (4), you'll want to make a reusable function out of the timer-creating code. This is a good test case to think about what function arguments you need to pass to a timer-creating function. In looking over your code, I see that you're using task.id and task.task_due in the code that creates the timer. Looks like we would just need to pass those two values to a createTimer() function.

Try something like this:

<script>
  function createTimer(taskId, taskDue) {
    // just look this element up once for this timer
    var timerElement = document.getElementById(taskId);

    var countDownDate = new DateTime(taskDue).getTime();

    var timer = setInterval(function() {
      var now = new Date().getTime();
      var distance = countDownDate - now;

      if (distance < 0) {
        clearInterval(timer);
        timerElement.innerHTML = "EXPIRED";
      } else {
        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

        var timerDisplay = `${days}d ${hours}h ${minutes}m ${seconds}s`;
        timerElement.innerHTML = timerDisplay;
      }
    }, 1000);
  }
</script>

{% if tasks %}
  {% for task in tasks %}
    <button class="button">Complete!</button>

    <p style="display:inline-block; font-weight:bold; color:red;">
      {{ task.task_name }}
    </p>

    <p id="{{ task.id }}" style="text-align:right; padding-right:60px"></p>

    <!-- call the function to start this timer -->
    <script>createTimer('{{ task.id }}', '{{ task.task_due }}')</script>
  {% endfor %}
{% endif %}


答:
The point of the Void type is that it has no inhabitants (other than "bottom" values like exceptions and infinite loops). You could write

```<code>x, y, z :: Either Void Int
x = undefined
y = Left $ error "Whoops"
z = Left $ let q = q in q
</code>```

but all of these violate the essential concept of Void.

The only "legitimate" values of type Either Void Int are of the form Right i, where i :: Int.

Indeed, you can write the following:

```<code>unEither :: Either Void a -> a
unEither (Left v) = absurd v
unEither (Right a) = a
</code>```

Title: How to do Left Void?

Body:
The point of the Void type is that it has no inhabitants (other than "bottom" values like exceptions and infinite loops). You could write

x, y, z :: Either Void Int
x = undefined
y = Left $ error "Whoops"
z = Left $ let q = q in q

but all of these violate the essential concept of Void.

The only "legitimate" values of type Either Void Int are of the form Right i, where i :: Int.

Indeed, you can write the following:

unEither :: Either Void a -> a
unEither (Left v) = absurd v
unEither (Right a) = a


问:
Need to convert a date 09/01/2009 to a CHAR TYPE FORMAT
I need to convert a date 09/01/2009 to a CHAR TYPE FORMAT. The result should have 6 digits.

I knew the TO_CHAR function does it,but its not working for me.

The Date is given as 03/06/08

```<code>SELECT TO_CHAR(030608, 'DD MONTH,YYYY')
 FROM dual;
</code>```

This gives errors-syntax mainly.

It is Oracle database and I have to get the STRING. For example a number like -'200901'

答:
Try the following:

```<code>Input      Desired output  How to get there
030608     '03/06/2008'    TO_CHAR(030608, 'DD/MM/YYYY')
'030608'   '03/06/2008'    TO_CHAR(TO_DATE('030608', 'DDMMYY'), 'DD/MM/YYYY')
</code>```

Share and enjoy.

ContentLicense: CC BY-SA 3.0

Body:
I need to convert a date 09/01/2009 to a CHAR TYPE FORMAT. The result should have 6 digits.

I knew the TO_CHAR function does it,but its not working for me.

The Date is given as 03/06/08

SELECT TO_CHAR(030608, 'DD MONTH,YYYY')
 FROM dual;

This gives errors-syntax mainly.

It is Oracle database and I have to get the STRING. For example a number like -'200901'

Body:
Try the following:

Input      Desired output  How to get there
030608     '03/06/2008'    TO_CHAR(030608, 'DD/MM/YYYY')
'030608'   '03/06/2008'    TO_CHAR(TO_DATE('030608', 'DDMMYY'), 'DD/MM/YYYY')

Share and enjoy.


问:
Group results of joined table in sql
I have a users table and profile_visits table

I am trying to group visitors in profile_visits table

I tried

```<code>SELECT users.ID, COUNT(profile_visits.profile_id) AS b_count
FROM users
INNER JOIN profile_visits on profile_visits.profile_id = users.ID
GROUP BY users.ID
HAVING COUNT(profile_visits.profile_id) > 1
ORDER BY users.ID ASC
</code>```

With this, I can get total visitor numbers but I can't group the visitors

Any idea?

答:
from what i understand you dont need user table at all</p>

```<code>SELECT profile_id, COUNT(profile_visits.user_id) AS b_count
FROM profile_visits
HAVING b_count > 1
ORDER BY profile_id ASC
</code>```

Title: Group results of joined table in sql

Body:
I have a users table and profile_visits table

I am trying to group visitors in profile_visits table

I tried

SELECT users.ID, COUNT(profile_visits.profile_id) AS b_count
FROM users
INNER JOIN profile_visits on profile_visits.profile_id = users.ID
GROUP BY users.ID
HAVING COUNT(profile_visits.profile_id) > 1
ORDER BY users.ID ASC

With this, I can get total visitor numbers but I can't group the visitors

Any idea?

Body:
from what i understand you dont need user table at all

SELECT profile_id, COUNT(profile_visits.user_id) AS b_count
FROM profile_visits
HAVING b_count > 1
ORDER BY profile_id ASC


问:
Creating file with Bash scripting for loop and if test

Problem Statement
  Find files using bash script
  In this section, you are going to write a script named findJane.sh within the scripts directory.

This script should catch all "jane" lines and store them in another text file called oldFiles.txt. You will complete the script using the command we practiced in earlier sections. Don't worry, we'll guide you throughout the whole process.

Navigate to /scripts directory and create a new file named findJane.sh.

Mycode

```<code>
#!/bin/bash

>oldFiles.txt

files=$(grep  " jane " ../data/list.txt | cut -d ' ' -f 3)

for i in $files:do

  do if test -e ~/data/"$i"; then
     echo "$i" >> OldFiles.txt;
  else
     echo "File doesn't exist"; fi
done

</code>```

output now
file does not exist
file does not exist
file does not exist
it should not print nothing
and cat oldFiles.txt should return all those files with name 'jane

Where i am coding wrong

Guide
  Create the text file oldFiles.txt and make sure it's empty. This oldFiles.txt file should save files with username "jane".

Now, search for all lines that contain the name "jane" and save the file names into a variable. Let's call this variable files, we will refer to it with that name later in the lab.

Since none of the files present in the file list.txt are available in the file system, check if file names present in files variable are actually present in the file system. To do this, we'll use the test command that we practiced in the previous section.

Now, iterate over the files variable and add a test expression within the loop. If the item within the files variable passes the test, add/append it to the file oldFiles.txt.

答:
you have just some typos. this is "working" code for your example

```<code>#!/bin/bash

>oldFiles.txt

files=$(grep " jane " ../data/list.txt | cut -d ' ' -f 3)

for i in $files; do

  if test -e ~/data/"$i"; then
    echo "$i" >> OldFiles.txt;
  else
    echo "File doesn't exist"; fi
done
</code>```

however, this works only if list.txt doesn't contain any spaces except as delimiters between (at least) three columns

it won't work for Jane because it doesn't match jane

it won't work when there are more spaces like jane   example.doc

it won't work for file names containing spaces like best movies.txt

it makes less sense to show how to do it right because the concept of list.txt is bad choice

Body:
Problem Statement
  Find files using bash script
  In this section, you are going to write a script named findJane.sh within the scripts directory.

This script should catch all "jane" lines and store them in another text file called oldFiles.txt. You will complete the script using the command we practiced in earlier sections. Don't worry, we'll guide you throughout the whole process.

Navigate to /scripts directory and create a new file named findJane.sh.

Mycode

#!/bin/bash

>oldFiles.txt

files=$(grep  " jane " ../data/list.txt | cut -d ' ' -f 3)

for i in $files:do

  do if test -e ~/data/"$i"; then
     echo "$i" >> OldFiles.txt;
  else
     echo "File doesn't exist"; fi
done

output now
file does not exist
file does not exist
file does not exist
it should not print nothing
and cat oldFiles.txt should return all those files with name 'jane

Where i am coding wrong

Guide
  Create the text file oldFiles.txt and make sure it's empty. This oldFiles.txt file should save files with username "jane".

Now, search for all lines that contain the name "jane" and save the file names into a variable. Let's call this variable files, we will refer to it with that name later in the lab.

Since none of the files present in the file list.txt are available in the file system, check if file names present in files variable are actually present in the file system. To do this, we'll use the test command that we practiced in the previous section.

Now, iterate over the files variable and add a test expression within the loop. If the item within the files variable passes the test, add/append it to the file oldFiles.txt.

Body:
you have just some typos. this is "working" code for your example

#!/bin/bash

>oldFiles.txt

files=$(grep " jane " ../data/list.txt | cut -d ' ' -f 3)

for i in $files; do

  if test -e ~/data/"$i"; then
    echo "$i" >> OldFiles.txt;
  else
    echo "File doesn't exist"; fi
done

however, this works only if list.txt doesn't contain any spaces except as delimiters between (at least) three columns

it won't work for Jane because it doesn't match jane

it won't work when there are more spaces like jane   example.doc

it won't work for file names containing spaces like best movies.txt

it makes less sense to show how to do it right because the concept of list.txt is bad choice


问:
Making nested API calls using RxJS based on a condition using iif operator resulting in Maximum call stack size exceeded
I am trying to use a conditional rxjs operator. I am checking if the data is stored in the local storage, return that, if not, make 2 HTTP calls to get the required data and return it.

Here's my code:

```<code>// making nested API calls
    loggedInUserDetails$ = this._getPoid().pipe(
      concatMap((userData: any) => this._userData(userData)),
      map((userDetails: any) => userDetails.legalName.nameLastFirst),
      tap((user: string) => this._storage.saveUserInStorage(user)),
      catchError(() => of('some dummy name')),
   );

  storedUserData$ = of(this._storage.getUserFromStorage());

  loggedInUsername$ = of(this._storage.getUserFromStorage()).pipe(
    mergeMap((username: string) =>
      iif(
        () => Boolean(username),
        this.storedUserData$,
        this.loggedInUserDetails$,
      ),
    ),
    tap(console.log),
  );

 loggedInUsername$.subscribe(data => console.log(data));
</code>```

The above code returns Maximum call stack size exceeded

Observable.js:54 RangeError: Maximum call stack size exceeded
      at MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/OuterSubscriber.js.OuterSubscriber.notifyError
  (OuterSubscriber.js:12)
      at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/InnerSubscriber.js.InnerSubscriber._error (InnerSubscriber.js:18)
      at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error
  (Subscriber.js:59)
      at TapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/tap.js.TapSubscriber._error
  (tap.js:61)
      at TapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error
  (Subscriber.js:59)
      at

答:
I wouldn't say mergeMap is the appropriate operator in this scenario. You aren't looking to merge the observables, but instead switch it to another. Try with switchMap operator.

loggedInUsername$ = of(this._storage.getUserFromStorage()).pipe(
  switchMap((username: string) =>
    iif(
      () => Boolean(username),
      this.storedUserData$,
      this.loggedInUserDetails$,
    ),
  ),
  tap(console.log),
);
```

Body:
I am trying to use a conditional rxjs operator. I am checking if the data is stored in the local storage, return that, if not, make 2 HTTP calls to get the required data and return it.

Here's my code:

// making nested API calls
    loggedInUserDetails$ = this._getPoid().pipe(
      concatMap((userData: any) => this._userData(userData)),
      map((userDetails: any) => userDetails.legalName.nameLastFirst),
      tap((user: string) => this._storage.saveUserInStorage(user)),
      catchError(() => of('some dummy name')),
   );

  storedUserData$ = of(this._storage.getUserFromStorage());

  loggedInUsername$ = of(this._storage.getUserFromStorage()).pipe(
    mergeMap((username: string) =>
      iif(
        () => Boolean(username),
        this.storedUserData$,
        this.loggedInUserDetails$,
      ),
    ),
    tap(console.log),
  );

 loggedInUsername$.subscribe(data => console.log(data));

The above code returns Maximum call stack size exceeded

Observable.js:54 RangeError: Maximum call stack size exceeded
      at MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/OuterSubscriber.js.OuterSubscriber.notifyError
  (OuterSubscriber.js:12)
      at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/InnerSubscriber.js.InnerSubscriber._error (InnerSubscriber.js:18)
      at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error
  (Subscriber.js:59)
      at TapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/tap.js.TapSubscriber._error
  (tap.js:61)
      at TapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error
  (Subscriber.js:59)
      at


问:
Can't write data to a file. All System.IO methods doesn't work. Xamarin.Forms
I am making a simple iOS app using a Xamarin.Forms. I use SQLite through Mono.Data.Sqlite library. I need to insert data in database through INSERT command and writing data to a text file. All files (text files, .db-file, images) I have stored to Resources directory in iOS project.
When I try to writing data into a text file or INSERT into my database the program does nothing. Data isn't inserted/written. And no exception was thrown. For example:

```<code>public partial class SomePage : ContentPage
{
    public SomePage()
    {
        InitializeComponent();

        using (StreamWriter sw = new StreamWriter("some_file.txt"))
        {
            sw.WriteLine("some data");
        }
    }
}
</code>```

The data wasn't written and the file is still empty.

I use macOS Catalina 10.15.4 and Visual Studio for Mac 8.6.1

I have searched for this problem but nothing can solve this problem. Wait for your answers! Thanks!

答:
Thanks @Jason, he showed me right way :) So the solution is to copy a files that attached in Resources at app startup to a writeable folder, like a Documents folder in iOS Application Sandbox. So we can use a Environment class to reach this folder.

```<code>public partial class SomePage : ContentPage
{
    public SomePage()
    {
        string filepath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "some_file.txt");
        File.Copy("some_file.txt", filepath); // From Resource folder to Documents
        File.WriteAllText(filepath, "Some text");
    }
}
</code>```

Body:
I am making a simple iOS app using a Xamarin.Forms. I use SQLite through Mono.Data.Sqlite library. I need to insert data in database through INSERT command and writing data to a text file. All files (text files, .db-file, images) I have stored to Resources directory in iOS project.
When I try to writing data into a text file or INSERT into my database the program does nothing. Data isn't inserted/written. And no exception was thrown. For example:

public partial class SomePage : ContentPage
{
    public SomePage()
    {
        InitializeComponent();

        using (StreamWriter sw = new StreamWriter("some_file.txt"))
        {
            sw.WriteLine("some data");
        }
    }
}

The data wasn't written and the file is still empty.

I use macOS Catalina 10.15.4 and Visual Studio for Mac 8.6.1

I have searched for this problem but nothing can solve this problem. Wait for your answers! Thanks!

Body:
Thanks @Jason, he showed me right way :) So the solution is to copy a files that attached in Resources at app startup to a writeable folder, like a Documents folder in iOS Application Sandbox. So we can use a Environment class to reach this folder.

public partial class SomePage : ContentPage
{
    public SomePage()
    {
        string filepath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "some_file.txt");
        File.Copy("some_file.txt", filepath); // From Resource folder to Documents
        File.WriteAllText(filepath, "Some text");
    }
}


问:
pandas style set_table_styles for columns/index does not work with to_excel
Consider this dummy DataFrame below:

```<code>df = pd.DataFrame(np.random.rand(15).reshape(5,3), columns='x y z'.split())

# df
          x         y         z
0  0.725005  0.318429  0.918186
1  0.883890  0.993736  0.795322
2  0.687472  0.328307  0.108520
3  0.608381  0.193478  0.469421
4  0.598708  0.276778  0.433235
</code>```

Assume the below simple pandas styling applied:

```<code>style = df.style \
    .set_table_styles([{'selector': 'th', 'props': [('background-color', 'orange')]}]) \
    .applymap(lambda x: 'color: red' if x >.5 else 'color: blue')
</code>```

The style.render() seem to confirm the styling has applied for th and td (snippet below):

```<code><style  type="text/css" >
    #T_8b7f1124_a115_11ea_8cf8_48452026764f th {
          background-color: orange;
    }    #T_8b7f1124_a115_11ea_8cf8_48452026764frow0_col0 {
            color:  red;
        }    #T_8b7f1124_a115_11ea_8cf8_48452026764frow0_col1 {
            color:  blue;
        } ...
</code>```

Exporting this as an html displays all the colours as expected.  However when I apply to_excel, only the elemental styling is picked up.  The headers/index remains default colours:

```<code>style.to_excel(r'somefile.xlsx')
</code>```

I tried both xlsxwriter and openpyxl as engine, both exhibit the same behaviour.

I searched a few questions on set_table_styles and Styler.to_excel, but all seem to be concerned about the individual elements, didn't seem to address the combination thereof.  Tried searching issue log on github as well, haven't ran into a match so far.

Anybody had luck getting set_table_styles and Styler.to_excel to work together?

答:
This seems to be a bug that still exists in the current version (1.0.3).  I have raised a bug in their repo: https://github.com/pandas-dev/pandas/issues/34438

Will try to update this when it gets resolved...

Body:
Consider this dummy DataFrame below:

df = pd.DataFrame(np.random.rand(15).reshape(5,3), columns='x y z'.split())

# df
          x         y         z
0  0.725005  0.318429  0.918186
1  0.883890  0.993736  0.795322
2  0.687472  0.328307  0.108520
3  0.608381  0.193478  0.469421
4  0.598708  0.276778  0.433235

Assume the below simple pandas styling applied:

style = df.style \
    .set_table_styles([{'selector': 'th', 'props': [('background-color', 'orange')]}]) \
    .applymap(lambda x: 'color: red' if x >.5 else 'color: blue')

The style.render() seem to confirm the styling has applied for th and td (snippet below):


问:
Calculate percentage aggregating counts in SQL
I have a SQL Server table called AccessLog that is inserted into every time a user clicks "Log In" on my website. The important fields are UserID, BrowserName and Date. The intent is to get an idea of which browsers are used the most to access the site.

Here is a sample data set:

```<code>| UserID | BrowserName | Date  |
|--------|-------------|-------|
| 1      | Chrome      | 05/28 |
| 1      | Chrome      | 05/29 |
| 2      | Firefox     | 05/29 |
| 1      | Chrome      | 05/30 |
| 3      | Firefox     | 05/31 |

</code>```

This is the SQL code I use (found here):

SELECT BrowserName
    ,(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER ()) pct
    ,COUNT(*) ct
FROM AccessLog
GROUP BY BrowserName

```

<p>These are the results I get with that query:</p>

```| BrowserName | pct  | ct |
|-------------|------|----|
| Chrome      | 60.0 | 3  |
| Firefox     | 40.0 | 2  |
```

<p>But these are the results I want:</p>

```| BrowserName | pct  | ct |
|-------------|------|----|
| Chrome      | 33.3 | 1  |
| Firefox     | 66.6 | 2  |
```

How can I modify my query to count each distinct UserID and BrowserName pair once, to not artificially inflate the counts?

答:
You can try the following by creating a cte. Here is the demo.

```<code>with total_users as
(
    select
      BrowserName,
      count(distinct UserId) as total_users
    from myTable
    group by
      BrowserName
)
select
    BrowserName,
    round((total_users * 100.0)/sum(total_users) over (), 1) as pct,
    total_users as ct
from total_users
</code>```

Output:

```<code>| browsername | pct   | ct  |
| ----------- | ----- | --- |
| Chrome      | 33.3  | 1   |
| Firefox     | 66.6  | 2   |
</code>```

Body:
I have a SQL Server table called AccessLog that is inserted into every time a user clicks "Log In" on my website. The important fields are UserID, BrowserName and Date. The intent is to get an idea of which browsers are used the most to access the site.

Here is a sample data set:

| UserID | BrowserName | Date  |
|--------|-------------|-------|
| 1      | Chrome      | 05/28 |
| 1      | Chrome      | 05/29 |
| 2      | Firefox     | 05/29 |
| 1      | Chrome      | 05/30 |
| 3      | Firefox     | 05/31 |

This is the SQL code I use (found here):

SELECT BrowserName
    ,(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER ()) pct
    ,COUNT(*) ct
FROM AccessLog
GROUP BY BrowserName

These are the results I get with that query:

| BrowserName | pct  | ct |
|-------------|------|----|
| Chrome      | 60.0 | 3  |
| Firefox     | 40.0 | 2  |

But these are the results I want:

| BrowserName | pct  | ct |
|-------------|------|----|
| Chrome      | 33.3 | 1  |
| Firefox     | 66.6 | 2  |

How can I modify my query to count each distinct UserID and BrowserName pair once, to not artificially inflate the counts?

Body:
You can try the following by creating a cte. Here is the demo.

with total_users as
(
    select
      BrowserName,
      count(distinct UserId) as total_users
    from myTable
    group by
      BrowserName
)
select
    BrowserName,
    round((total_users * 100.0)/sum(total_users) over (), 1) as pct,
    total_users as ct
from total_users

Output:

| browsername | pct   | ct  |
| ----------- | ----- | --- |
| Chrome      | 33.3  | 1   |
| Firefox     | 66.6  | 2   |


问:
How do I combine the top n rows with a summary function the remaining rows in R
I wonder if there is an easy way to do the following, perhaps using dplyr:

The data in R built-in dataset "women" is:

```<code>    height  weight
1   58  115
2   59  117
3   60  120
4   61  123
5   62  126
6   63  129
7   64  132
8   65  135
9   66  139
10  67  142
11  68  146
12  69  150
13  70  154
14  71  159
15  72  164
</code>```

I need a function that would give me, for instance, the first 5 rows combined with the average of the remaining rows, like this:

```<code>    height  weight
1   58  115
2   59  117
3   60  120
4   61  123
5   62  126
6   67.5    145   # average of the remaining 10 rows
</code>```

答:
We can create a grouping variable based on row number and then do the mean across

```<code>library(dplyr)
women %>%
   group_by(group =  case_when(row_number() <=5 ~ row_number())) %>%
   summarise(across(everything(), ~ round(mean(.)))) %>%
   select(-group)
# A tibble: 6 x 2
#  height weight
#*  <dbl>  <dbl>
#1     58    115
#2     59    117
#3     60    120
#4     61    123
#5     62    126
#6     68    145
</code>```

Or with bind_rows

```<code>women %>%
    slice(seq_len(5)) %>%
    bind_rows(women %>%
                 slice(-(1:5)) %>%
                 summarise(across(everything(), mean)))
</code>```

Or another option is base R

```<code>rbind(women[1:5,], round(colMeans(women[-(1:5),])))
</code>```

Body:
I wonder if there is an easy way to do the following, perhaps using dplyr:

The data in R built-in dataset "women" is:

    height  weight
1   58  115
2   59  117
3   60  120
4   61  123
5   62  126
6   63  129
7   64  132
8   65  135
9   66  139
10  67  142
11  68  146
12  69  150
13  70  154
14  71  159
15  72  164

I need a function that would give me, for instance, the first 5 rows combined with the average of the remaining rows, like this:

    height  weight
1   58  115
2   59  117
3   60  120
4   61  123
5   62  126
6   67.5    145   # average of the remaining 10 rows

Body:
We can create a grouping variable based on row number and then do the mean across

library(dplyr)
women %>%
   group_by(group =  case_when(row_number() <=5 ~ row_number())) %>%
   summarise(across(everything(), ~ round(mean(.)))) %>%
   select(-group)
# A tibble: 6 x 2
#  height weight
#*  <dbl>  <dbl>
#1     58    115
#2     59    117
#3     60    120
#4     61    123
#5     62    126
#6     68    145

Or with bind_rows

women %>%
    slice(seq_len(5)) %>%
    bind_rows(women %>%
                 slice(-(1:5)) %>%
                 summarise(across(everything(), mean)))

Or another option is base R

rbind(women[1:5,], round(colMeans(women[-(1:5),])))


问:
How to make a rectangle's height the same height of a VStack
I have a swift view that consists of a HStack with a rectangle and a Vstack of text inside. I want to make the height of the rectangle the same as the height of the Vstack. I have already tried looking through many other questions here on StackOverflow but didn't find an answer. Can anyone help me do that?

Here is my code:

```<code>struct TodoView: View {
    @State var todos = ["feed the dog", "take the dog out for a walk", "make coffee"]
    @State var height: CGFloat = 45
    var body: some View {
                HStack{
                    RoundedRectangle(cornerRadius: 2)
                        .frame(width: 1)
                        .foregroundColor(Color("lightGray"))
                        .padding()
                    VStack{

                        Text("Todo")
                            .font(.title)
                        ForEach(todos, id: \.self){ todo in
                            Text(todo)
                        }
                    }

                    Spacer()
        }
    }
}
</code>```

答:
You need to know the GeometryReader and PreferenceKey to make this possible.</p>

```<code>struct SiblingHeightKey: PreferenceKey {
    static var defaultValue: CGSize? {
        nil
    }

    static func reduce(value: inout CGSize?, nextValue: () -> CGSize?) {
        value = value ?? nextValue()
    }
}

struct TodoView: View {
    @State var vStackSize: CGSize? = nil
    @State var todos = ["feed the dog", "take the dog out for a walk", "make coffee"]
    @State var height: CGFloat = 45
    var body: some View {
                HStack{
                    RoundedRectangle(cornerRadius: 2)
                        .foregroundColor(.gray)
                        .frame(width: self.vStackSize?.width, height: self.vStackSize?.height)
                    VStack{

                        Text("Todo")
                            .font(.title)
                        ForEach(todos, id: \.self){ todo in
                            Text(todo)
                        }
                    }.background(
                        GeometryReader { proxy in
                            Color.clear.preference(key: SiblingHeightKey.self, value: proxy.size)
                        }
                    )

                    Spacer()
                }.onPreferenceChange(SiblingHeightKey.self) {
                    self.vStackSize = $0
        }
    }
}
</code>```

Body:
I have a swift view that consists of a HStack with a rectangle and a Vstack of text inside. I want to make the height of the rectangle the same as the height of the Vstack. I have already tried looking through many other questions here on StackOverflow but didn't find an answer. Can anyone help me do that?

Here is my code:

struct TodoView: View {
    @State var todos = ["feed the dog", "take the dog out for a walk", "make coffee"]
    @State var height: CGFloat = 45
    var body: some View {
                HStack{
                    RoundedRectangle(cornerRadius: 2)
                        .frame(width: 1)
                        .foregroundColor(Color("lightGray"))
                        .padding()
                    VStack{

                        Text("Todo")
                            .font(.title)
                        ForEach(todos, id: \.self){ todo in
                            Text(todo)
                        }
                    }

                    Spacer()
        }
    }
}

Body:
You need to know the GeometryReader and PreferenceKey to make this possible.

struct SiblingHeightKey: PreferenceKey {
    static var defaultValue: CGSize? {
        nil
    }

    static func reduce(value: inout CGSize?, nextValue: () -> CGSize?) {
        value = value ?? nextValue()
    }
}

struct TodoView: View {
    @State var vStackSize: CGSize? = nil
    @State var todos = ["feed the dog", "take the dog out for a walk", "make coffee"]
    @State var height: CGFloat = 45
    var body: some View {
                HStack{
                    RoundedRectangle(cornerRadius: 2)
                        .foregroundColor(.gray)
                        .frame(width: self.vStackSize?.width, height: self.vStackSize?.height)
                    VStack{

                        Text("Todo")
                            .font(.title)
                        ForEach(todos, id: \.self){ todo in
                            Text(todo)
                        }
                    }.background(
                        GeometryReader { proxy in
                            Color.clear.preference(key: SiblingHeightKey.self, value: proxy.size)
                        }
                    )

                    Spacer()
                }.onPreferenceChange(SiblingHeightKey.self) {
                    self.vStackSize = $0
        }
    }
}


问:
ASP.NET CORE 3.1 JQuery Pass Parameter to .load('@Url.Action Issue
Razor page works well, except for passing the id to the controller. I can get the partial view to refresh the divAppInfo just fine. I am having problems with the "$("#divAppInfo").load('@Url.Action( "and passing a parameter to it.

```<code><div class="form-group">
    <label class="col-md-2 control-label">App</label>
    <div class="col-md-10">
        <div class="input-group">
        <select id="formApp" name="formApp" class="form-control" asp-items="@appSelectList" onchange="GetAppInfo()"></select>
    </div>
</div>
</code>```

```<code><div id="divAppInfo"></div>

<script>
function GetAppInfo() {
    var s = $("#formApp option:selected").text();
    $("#divAppInfo").load('@Url.Action("GetApplicationInfo", "B2BPortal", new { area = "B2BPortal"})?id='+s);
}
</script>
</code>```

My Controller shows

```<code>    [HttpGet]
    public async Task<IActionResult> GetApplicationInfo(int id)
</code>```

答:
```<code>Changed:
var s = $("#formApp option:selected").text();

To:
var s = $('#formApp').val();
</code>```

Body:
Razor page works well, except for passing the id to the controller. I can get the partial view to refresh the divAppInfo just fine. I am having problems with the "$("#divAppInfo").load('@Url.Action( "and passing a parameter to it.

    App

        <select id="formApp" name="formApp" class="form-control" asp-items="@appSelectList" onchange="GetAppInfo()"></select>

My Controller shows

    [HttpGet]
    public async Task<IActionResult> GetApplicationInfo(int id)


问:
Not giving value when I use inside for loop {{product.i.product_name}} but works fine when {{product.0.product_name}}
Here is my model:

```<code>class Product(models.Model):
product_id = models.AutoField
product_name = models.CharField(max_length=200)
description = models.CharField(max_length=600)
pub_date = models.DateField()
image = models.ImageField(upload_to="home/images")
</code>```

the views.py:

```<code>def home(request):
products = Product.objects.all()
n = len(products)
params = {'product': products, 'range': range(n)}
return render(request,'home/home.html',params)
</code>```

and the HTML for loop part is:

```<code>{% for i in range %}

    <div class="col-md-6 col-lg-4 text-center mt-4 ">
         <div class="card" style="width: 18rem;">
            <img src="..." class="card-img-top" alt="...">
            <div class="card-body">
              <h5 class="card-title">{{product.i.product_name}}</h5>
              <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
              <a href="#" class="btn btn-primary">Go somewhere</a>
            </div>
          </div>
    </div>
    {% endfor %}
</code>```

the problem is when I am typing {{product.i.product_name}} it is not giving the product name but it is working when I am giving value instead of I like {{product.0.product_name}}.
I am not understanding what is the problem.

答:
If you use product.i then, you are looking up a property on product whose name is i. Here, i is a name, like any other property name and is not the variable i.

Fortunately there is a simple way to fix this issue. You can actually loop through the queryset products without using the indexes. All you need to do is:

```<code>{% for p in product %}
     <h5 class="card-title">{{p.product_name}}</h5>
{% endfor %}
</code>```

(I have missed out the additional HTML just to make the answer clearer, but you can add that back in).

I would actually change the name of product in your params to products, then you can write the following:

```<code>{% for product in products %}
     <h5 class="card-title">{{product.product_name}}</h5>
{% endfor %}
</code>```

(which is just a little easier to read).

I hope this helps :)

EDIT: In answer to question in comments:

The reason that this 'works' when you do product.0 is that 0 is a value not a property name, so it is looking up the first (zeroith) element in the queryset. But because 0 doesn't change on each iteration of the loop, you are getting the same value every time, not a different one (as you have observed).

Body:
Here is my model:

class Product(models.Model):
product_id = models.AutoField
product_name = models.CharField(max_length=200)
description = models.CharField(max_length=600)
pub_date = models.DateField()
image = models.ImageField(upload_to="home/images")

the views.py:

def home(request):
products = Product.objects.all()
n = len(products)
params = {'product': products, 'range': range(n)}
return render(request,'home/home.html',params)

and the HTML for loop part is:

{% for i in range %}

{{product.i.product_name}}

Some quick example text to build on the card title and make up the bulk of the card's content.

              Go somewhere

    {% endfor %}

the problem is when I am typing {{product.i.product_name}} it is not giving the product name but it is working when I am giving value instead of I like {{product.0.product_name}}.
I am not understanding what is the problem.

Body:
If you use product.i then, you are looking up a property on product whose name is i. Here, i is a name, like any other property name and is not the variable i.

Fortunately there is a simple way to fix this issue. You can actually loop through the queryset products without using the indexes. All you need to do is:

{% for p in product %}
     <h5 class="card-title">{{p.product_name}}</h5>
{% endfor %}

(I have missed out the additional HTML just to make the answer clearer, but you can add that back in).

I would actually change the name of product in your params to products, then you can write the following:

{% for product in products %}
     <h5 class="card-title">{{product.product_name}}</h5>
{% endfor %}

(which is just a little easier to read).

I hope this helps :)

EDIT: In answer to question in comments:

The reason that this 'works' when you do product.0 is that 0 is a value not a property name, so it is looking up the first (zeroith) element in the queryset. But because 0 doesn't change on each iteration of the loop, you are getting the same value every time, not a different one (as you have observed).


问:
SurfaceView display size is half for portrait
I have created simple android application to test the camera functionality. When I set the display orientation to 'portrait', it open the camera in half of the screen on version 2.1. my requirement is to open the camera on full screen.</p>

答:
Android 2.1 supports a Camera SurfaceView for landscape mode ONLY.

If you want to use in portrait mode, you will have to either:

(a) Rotate your icons and set up the UI in landscape mode (so that the UI looks as if it was set up for portrait mode) keeping the display orientation as landscape.

or

(b) Use portrait mode in Android 2.2, and then use setDisplayOrientation to correct the display. This function is available in Android 2.2 and above only.


答:
You should count profile_visits.user_id rather than profile_visits.profile_id. And then use the DISTINCT modifier so you only count a visitor once, to get the number of unique visitors.

```<code>SELECT users.ID, COUNT(DISTINCT profile_visits.user_id) AS b_count
FROM users
INNER JOIN profile_visits on profile_visits.profile_id = users.ID
GROUP BY users.ID
HAVING b_count > 1
ORDER BY users.ID ASC
</code>```

Title: Group results of joined table in sql

Body:
I have a users table and profile_visits table

I am trying to group visitors in profile_visits table

I tried

SELECT users.ID, COUNT(profile_visits.profile_id) AS b_count
FROM users
INNER JOIN profile_visits on profile_visits.profile_id = users.ID
GROUP BY users.ID
HAVING COUNT(profile_visits.profile_id) > 1
ORDER BY users.ID ASC

With this, I can get total visitor numbers but I can't group the visitors

Any idea?

Body:
You should count profile_visits.user_id rather than profile_visits.profile_id. And then use the DISTINCT modifier so you only count a visitor once, to get the number of unique visitors.

SELECT users.ID, COUNT(DISTINCT profile_visits.user_id) AS b_count
FROM users
INNER JOIN profile_visits on profile_visits.profile_id = users.ID
GROUP BY users.ID
HAVING b_count > 1
ORDER BY users.ID ASC


问:
ICommand is not executed in WPF application
I have a WPF application with a button which I bind to MessageCommand. In order to make it simple, the app only has a button which should display a messagebox. However, when I click the button, nothing happens. I am following the instructions of CodeProject but I do not know what I am missing despite the wealth of questions and answers about this topic.

The XAML file:

```<code><Window x:Class="CommandTestProject.MainWindow"
        ...
        xmlns:local="clr-namespace:CommandTestProject"
        xmlns:vw="clr-namespace:CommandTestProject.ViewModel"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <vw:ViewModelMsg/>
    </Window.DataContext>
    <Grid>
        <Button Content="Click"
                Command="{Binding Path=MessageCommand}"/>
    </Grid>
</Window>
</code>```

The ViewModel class:

```<code>using CommandTestProject.Commands;
using System;
using System.Windows;
using System.Windows.Input;

namespace CommandTestProject.ViewModel
{
    public class ViewModelMsg
    {
        private ShowMessage showMsg;
        public ViewModelMsg()
        {
            showMsg = new ShowMessage(this);
        }

        internal ICommand MessageCommand
        {
            get
            {
                return showMsg;
            }
        }
        internal void Message()
        {
            MessageBox.Show("This is a test command!");
        }
    }
}

</code>```

The ShowMessage class:

```<code>using CommandTestProject.ViewModel;
using System;
using System.Windows.Input;

namespace CommandTestProject.Commands
{
    public class ShowMessage : ICommand
    {
        private ViewModelMsg viewModel;
        public event EventHandler CanExecuteChanged;
        public ShowMessage(ViewModelMsg vm)
        {
            viewModel = vm;
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(object parameter)
        {
            viewModel.Message();
        }
    }
}

</code>```

答: In your view model, change internal ICommand MessageCommand to public ICommand MessageCommand and it will work.  Binding to internal properties won't work because binding is resolved by a binding engine which is in a separate assembly (PresentationFramework.dll)

Body:
I have a WPF application with a button which I bind to MessageCommand. In order to make it simple, the app only has a button which should display a messagebox. However, when I click the button, nothing happens. I am following the instructions of CodeProject but I do not know what I am missing despite the wealth of questions and answers about this topic.

The XAML file:

<Window x:Class="CommandTestProject.MainWindow"
        ...
        xmlns:local="clr-namespace:CommandTestProject"
        xmlns:vw="clr-namespace:CommandTestProject.ViewModel"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <vw:ViewModelMsg/>
    </Window.DataContext>
    <Grid>
        <Button Content="Click"
                Command="{Binding Path=MessageCommand}"/>
    </Grid>
</Window>

The ViewModel class:

using CommandTestProject.Commands;
using System;
using System.Windows;
using System.Windows.Input;

namespace CommandTestProject.ViewModel
{
    public class ViewModelMsg
    {
        private ShowMessage showMsg;
        public ViewModelMsg()
        {
            showMsg = new ShowMessage(this);
        }

        internal ICommand MessageCommand
        {
            get
            {
                return showMsg;
            }
        }
        internal void Message()
        {
            MessageBox.Show("This is a test command!");
        }
    }
}

The ShowMessage class:

using CommandTestProject.ViewModel;
using System;
using System.Windows.Input;

namespace CommandTestProject.Commands
{
    public class ShowMessage : ICommand
    {
        private ViewModelMsg viewModel;
        public event EventHandler CanExecuteChanged;
        public ShowMessage(ViewModelMsg vm)
        {
            viewModel = vm;
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(object parameter)
        {
            viewModel.Message();
        }
    }
}


问:
KeyError when trying to access a value in Tweepy response
i'm new to parsing json files and despite trying for hours I can't find a way to do access the value I want in the json object. Here is my code:

```<code># Access a tweet id and get the tweet info, then save to a txt file
tweet_id = df_tae['tweet_id'][0]
tweet = api.get_status(tweet_id, tweet_mode='extended')
with open('tweet_json_test.txt', "a") as outfile:
   json.dump(tweet._json, outfile)

# Later on, open the file and try to extract the 'media_url' address
with open('tweet_json_test.txt') as json_file:
    image = json.load(json_file)
</code>```

I've copied an extract of "image" at the bottom of the post

Then when I call:

```<code>image['id']
</code>```

I get: 892420643555336193, which is great :-)

But when I call:

```<code>image['media']
</code>```

I get the following error

```<code>KeyError                                  Traceback (most recent call last)
<ipython-input-849-665e447555a9> in <module>
----> 1 image['media']

KeyError: 'media'
</code>```

How do I access the media_url string? I've tried everything I can find and think of, after hours messing around with it. I know I can get this using the tweepy API but want to be able to extract it from the json.txt later down the line.

```<code># The image file looks like this (extract only for brevity):
{'created_at': 'Tue Aug 01 16:23:56 +0000 2017',
 'id': 892420643555336193,
 'id_str': '892420643555336193',
 'full_text': "This is Phineas. He's a mystical boy. Only ever appears in the hole of a donut. 13/10",
 'truncated': False,
 'display_text_range': [0, 85],
 'entities': {'hashtags': [],
  'symbols': [],
  'user_mentions': [],
  'urls': [],
  'media': [{'id': 892420639486877696,
    'id_str': '892420639486877696',
    'indices': [86, 109],
    'media_url': 'http://pbs.twimg.com/media/DGKD1-bXoAAIAUK.jpg',
    'media_url_https': 'https://pbs.twimg.com/media/DGKD1-bXoAAIAUK.jpg',
    'url': 'https......',
    'display_url': '.....',
    'expanded_url': 'https://twitter.com/dog_rates/status/892420643555336193/photo/1',
    'type': 'photo',
    'sizes': {'thumb': {'w': 150, 'h': 150, 'resize': 'crop'},
     'medium': {'w': 540, 'h': 528, 'resize': 'fit'},
     'small': {'w': 540, 'h': 528, 'resize': 'fit'},
     'large': {'w': 540, 'h': 528, 'resize': 'fit'}}}]},
</code>```

答:
As pointed out in np8's answer, I find it useful when debugging something like this to use pretty print. it's part of the standard library/modules, so not outside import/download.

simply,

from pprint import pprint
# ...
pprint(mydict)
# or
pprint(mylist)
```

<p>It usually does a good job.</p>

<h2>Your code</h2>

<p>It sounds like you want to extract out all of the <code>media_url</code>s from the twitter responses.
Looking at the structure of the <code>image</code> dict, we can see...</p>

<pre class="lang-py prettyprint-override"><code>{'created_at': 'Tue Aug 01 16:23:56 +0000 2017',
 'display_text_range': [0, 85],
 'entities': {'hashtags': [],
              'media': [{'display_url': '.....',
                         'expanded_url': 'https://twitter.com/dog_rates/status/892420643555336193/photo/1',
                         'id': 892420639486877696,
                         'id_str': '892420639486877696',
                         'indices': [...],
                         'media_url': 'http://pbs.twimg.com/media/DGKD1-bXoAAIAUK.jpg',
                         'media_url_https': 'https://pbs.twimg.com/media/DGKD1-bXoAAIAUK.jpg',
                         'sizes': {...},
                         'type': 'photo',
                         'url': 'https......'}],
              'symbols': [],
              'urls': [],
              'user_mentions': []},
 'full_text': "This is Phineas. He's a mystical boy. Only ever appears in the "
              'hole of a donut. 13/10',
 'id': 892420643555336193,
 'id_str': '892420643555336193',
 'truncated': False}
</code>```

it is a dict with an entities key that has a value of a dict with a media key that has a value of a list of dicts that has a media_url key. So to access those media_urls, we'll have to dive down through the structure to get them out.

Accessing one:

first_media_url = image['entities']['media'][0]['media_url']
```

<p>Getting all of the <code>media_url</code>s from that one tweet into a list:</p>

<pre class="lang-py prettyprint-override"><code>media_urls = [media['media_url'] for media in image['entities']['media']]
</code>```

(Bonus) Getting all media_urls from all images assuming images are in a list:

all_media_urls = [
    media['media_url']
    for image in images
    for media in image['entities']['media']
]
```

And remember, when working with something like tweepy, to always check the documentation, as they might layout the structure really well. Additionally, anything that has been successfully loads'd by the json module is now just a normal dict that you can interact with, nothing special.

Hope this helps!

Body:
i'm new to parsing json files and despite trying for hours I can't find a way to do access the value I want in the json object. Here is my code:

# Access a tweet id and get the tweet info, then save to a txt file
tweet_id = df_tae['tweet_id'][0]
tweet = api.get_status(tweet_id, tweet_mode='extended')
with open('tweet_json_test.txt', "a") as outfile:
   json.dump(tweet._json, outfile)

# Later on, open the file and try to extract the 'media_url' address
with open('tweet_json_test.txt') as json_file:
    image = json.load(json_file)

I've copied an extract of "image" at the bottom of the post

Then when I call:

image['id']

I get: 892420643555336193, which is great :-)

But when I call:

image['media']

I get the following error

KeyError                                  Traceback (most recent call last)
<ipython-input-849-665e447555a9> in <module>
----> 1 image['media']

KeyError: 'media'

How do I access the media_url string? I've tried everything I can find and think of, after hours messing around with it. I know I can get this using the tweepy API but want to be able to extract it from the json.txt later down the line.

# The image file looks like this (extract only for brevity):
{'created_at': 'Tue Aug 01 16:23:56 +0000 2017',
 'id': 892420643555336193,
 'id_str': '892420643555336193',
 'full_text': "This is Phineas. He's a mystical boy. Only ever appears in the hole of a donut. 13/10",
 'truncated': False,
 'display_text_range': [0, 85],
 'entities': {'hashtags': [],
  'symbols': [],
  'user_mentions': [],
  'urls': [],
  'media': [{'id': 892420639486877696,
    'id_str': '892420639486877696',
    'indices': [86, 109],
    'media_url': 'http://pbs.twimg.com/media/DGKD1-bXoAAIAUK.jpg',
    'media_url_https': 'https://pbs.twimg.com/media/DGKD1-bXoAAIAUK.jpg',
    'url': 'https......',
    'display_url': '.....',
    'expanded_url': 'https://twitter.com/dog_rates/status/892420643555336193/photo/1',
    'type': 'photo',
    'sizes': {'thumb': {'w': 150, 'h': 150, 'resize': 'crop'},
     'medium': {'w': 540, 'h': 528, 'resize': 'fit'},
     'small': {'w': 540, 'h': 528, 'resize': 'fit'},
     'large': {'w': 540, 'h': 528, 'resize': 'fit'}}}]},

Body:
As pointed out in np8's answer, I find it useful when debugging something like this to use pretty print. it's part of the standard library/modules, so not outside import/download.

simply,

from pprint import pprint
# ...
pprint(mydict)
# or
pprint(mylist)

It usually does a good job.

Your code

It sounds like you want to extract out all of the media_urls from the twitter responses.
Looking at the structure of the image dict, we can see...

{'created_at': 'Tue Aug 01 16:23:56 +0000 2017',
 'display_text_range': [0, 85],
 'entities': {'hashtags': [],
              'media': [{'display_url': '.....',
                         'expanded_url': 'https://twitter.com/dog_rates/status/892420643555336193/photo/1',
                         'id': 892420639486877696,
                         'id_str': '892420639486877696',
                         'indices': [...],
                         'media_url': 'http://pbs.twimg.com/media/DGKD1-bXoAAIAUK.jpg',
                         'media_url_https': 'https://pbs.twimg.com/media/DGKD1-bXoAAIAUK.jpg',
                         'sizes': {...},
                         'type': 'photo',
                         'url': 'https......'}],
              'symbols': [],
              'urls': [],
              'user_mentions': []},
 'full_text': "This is Phineas. He's a mystical boy. Only ever appears in the "
              'hole of a donut. 13/10',
 'id': 892420643555336193,
 'id_str': '892420643555336193',
 'truncated': False}

it is a dict with an entities key that has a value of a dict with a media key that has a value of a list of dicts that has a media_url key. So to access those media_urls, we'll have to dive down through the structure to get them out.

Accessing one:

first_media_url = image['entities']['media'][0]['media_url']

Getting all of the media_urls from that one tweet into a list:

media_urls = [media['media_url'] for media in image['entities']['media']]

(Bonus) Getting all media_urls from all images assuming images are in a list:

all_media_urls = [
    media['media_url']
    for image in images
    for media in image['entities']['media']
]

And remember, when working with something like tweepy, to always check the documentation, as they might layout the structure really well. Additionally, anything that has been successfully loads'd by the json module is now just a normal dict that you can interact with, nothing special.

Hope this helps!


问:
React component - onClick and nothing happens, why is that?
I created the following class. Everything seems correct according to documentation and examples, but the onClick event doesn't happen. Why is that?

```<code>import React from 'react'
import Champion from './Champion'

class Champions extends React.Component {

    constructor() {
        super()
        this.state = {
            champions: []
        }
    }

    componentDidMount() {
        var req1 = new Request('http://localhost:8080/api/champions')
        fetch(req1, {
            method: 'GET'
        })
            .then(response => response.json())
            .then(data => {
                var championsArr = []
                for (const champ of data) {
                    championsArr.push(champ)
                }
                this.setState({ champions: championsArr })
            })
    }

    handleClick(itemId) {
        console.log(itemId)
    }

    render() {
        const items = this.state.champions.map(item => <Champion onClick={() => this.handleClick.bind(this, item.id)} key={item.id} id={item.id} championName={item.name} />)

        return (
            <div className="tab-pane fade show active all-objects" id="pills-champions" role="tabpanel" aria-labelledby="pills-champions-tab">
                { items }
            </div>
        )
    }
}

export default Champions
</code>```

I also tried onClick={this.handleClick.bind(this, item.id)} but it does nothing as well.

Edit: Here is the code for the Champion component (removed the class definition and exports):

```<code>    render() {
        return (
            <button className="card" style={{ width: "8rem" }}>
                <img src="https://picsum.photos/126/126" className="card-img-top" alt=""></img>
                <div className="card-body">
                    <p className="card-text">id: {this.props.id}. name: {this.props.championName}</p>
                </div>
            </button>
        )
    }
</code>```

答:
You don't need to double bind the function. You can either put it inside a scoped arrow function, or you can call .bind on it.

Choose either one of the following

const items = this.state.champions.map(item => <Champion onClick={() => this.handleClick(item.id)} key={item.id} id={item.id} championName={item.name} />)
```

<pre class="lang-js prettyprint-override"><code>const items = this.state.champions.map(item => <Champion onClick={this.handleClick.bind(this, item.id)} key={item.id} id={item.id} championName={item.name} />)
</code>```

You could also just use the built-in event

handleClick(event) {
  debugger
}
```

<p>Sadly you don't want to use a console.log statement here because the event will expire and React will clean it up, losing you access to the memory. With a debugger statement, you can at least inspect the memory and explore, but it should show that by using the built-in event, you should still be able to access the data you've scoped to the even target. Just don't forget to bind it with either an arrow function(binds to the scope of creation) or by calling <code>.bind()</code></p>

<p>Next, we need to find your render on your Champion component and actually bind the function to the DOM itself an we'll place it right on the button.</p>

<pre class="lang-js prettyprint-override"><code>
<button className="card" style={{ width: "8rem" }} onClick={this.props.onClick}>
</code>```

Remember that with a custom component, for an onClick to propagate to the DOM to be bound, you must attach it to something that eventually renders to the DOM. Custom components don't do that automatically as they're expecting you to link that logic, and rightfully so. onClick on a custom class is just a variable.

Body:
I created the following class. Everything seems correct according to documentation and examples, but the onClick event doesn't happen. Why is that?

import React from 'react'
import Champion from './Champion'

class Champions extends React.Component {

    constructor() {
        super()
        this.state = {
            champions: []
        }
    }

    componentDidMount() {
        var req1 = new Request('http://localhost:8080/api/champions')
        fetch(req1, {
            method: 'GET'
        })
            .then(response => response.json())
            .then(data => {
                var championsArr = []
                for (const champ of data) {
                    championsArr.push(champ)
                }
                this.setState({ champions: championsArr })
            })
    }

    handleClick(itemId) {
        console.log(itemId)
    }

    render() {
        const items = this.state.champions.map(item => <Champion onClick={() => this.handleClick.bind(this, item.id)} key={item.id} id={item.id} championName={item.name} />)

        return (

                { items }

        )
    }
}

export default Champions

I also tried onClick={this.handleClick.bind(this, item.id)} but it does nothing as well.

Edit: Here is the code for the Champion component (removed the class definition and exports):

    render() {
        return (
            <button className="card" style={{ width: "8rem" }}>

id: {this.props.id}. name: {this.props.championName}

            </button>
        )
    }

Body:
You don't need to double bind the function. You can either put it inside a scoped arrow function, or you can call .bind on it.

Choose either one of the following

const items = this.state.champions.map(item => <Champion onClick={() => this.handleClick(item.id)} key={item.id} id={item.id} championName={item.name} />)

const items = this.state.champions.map(item => <Champion onClick={this.handleClick.bind(this, item.id)} key={item.id} id={item.id} championName={item.name} />)

You could also just use the built-in event

handleClick(event) {
  debugger
}

Sadly you don't want to use a console.log statement here because the event will expire and React will clean it up, losing you access to the memory. With a debugger statement, you can at least inspect the memory and explore, but it should show that by using the built-in event, you should still be able to access the data you've scoped to the even target. Just don't forget to bind it with either an arrow function(binds to the scope of creation) or by calling .bind()

Next, we need to find your render on your Champion component and actually bind the function to the DOM itself an we'll place it right on the button.

<button className="card" style={{ width: "8rem" }} onClick={this.props.onClick}>

Remember that with a custom component, for an onClick to propagate to the DOM to be bound, you must attach it to something that eventually renders to the DOM. Custom components don't do that automatically as they're expecting you to link that logic, and rightfully so. onClick on a custom class is just a variable.


问:
add 2 classpath in 1 command line
I have problems to compile this, im trying to add 2 classpath but it fail

```<code>javac -cp C:\xampp\tomcat\lib\servlet-api.jar : C:\xampp\tomcat\webapps\examen\WEB-INF\classes ErabiltzaileKontuaEzabatuServlet.java
</code>```

in the first i add the .jar, and the second is for the classes inside that folder.

答:
The first thing to notice is the space around : that should not exist. The other thing is the classpath separator. Judging by the C:\ you are using Windows, so the path separator is a semicolon (;) instead of a colon (:).

The following should do:

```<code>javac -cp C:\xampp\tomcat\lib\servlet-api.jar;C:\xampp\tomcat\webapps\examen\WEB-INF\classes ErabiltzaileKontuaEzabatuServlet.java
</code>```

Title: add 2 classpath in 1 command line

Body:
I have problems to compile this, im trying to add 2 classpath but it fail

javac -cp C:\xampp\tomcat\lib\servlet-api.jar : C:\xampp\tomcat\webapps\examen\WEB-INF\classes ErabiltzaileKontuaEzabatuServlet.java

in the first i add the .jar, and the second is for the classes inside that folder.

Body:
The first thing to notice is the space around : that should not exist. The other thing is the classpath separator. Judging by the C:\ you are using Windows, so the path separator is a semicolon (;) instead of a colon (:).

The following should do:

javac -cp C:\xampp\tomcat\lib\servlet-api.jar;C:\xampp\tomcat\webapps\examen\WEB-INF\classes ErabiltzaileKontuaEzabatuServlet.java


问:
Are methods that modify reference type parameters bad?
I've seen methods like this:

```<code>public void Foo(List<string> list)
{
    list.Add("Bar");
}
</code>```

Is this good practice to modify parameters in a method?

Wouldn't this be better?

```<code>public List<string> Foo(List<string> list)
{
    // Edit
    List<string> newlist = new List<string>(list);
    newlist.Add("Bar");
    return newlist;
}
</code>```

It just feels like the first example has unexpected side effects.

答:
You're doing the exact same thing in both methods, just one of them is returning the same list.

It really depends on what you're doing, in my opinion.  Just make sure your documentation is clear on what is going on.  Write pre-conditions and post-conditions if you're into that sort of thing.

OwnerDisplayName: Jonathan Parker

ContentLicense: CC BY-SA 2.5

Body:
I've seen methods like this:

public void Foo(List<string> list)
{
    list.Add("Bar");
}

Is this good practice to modify parameters in a method?

Wouldn't this be better?

public List<string> Foo(List<string> list)
{
    // Edit
    List<string> newlist = new List<string>(list);
    newlist.Add("Bar");
    return newlist;
}

It just feels like the first example has unexpected side effects.

LastEditorDisplayName: Jonathan Parker

OwnerDisplayName: Stuart B


问:
Flex progress loading disappear?
It looks like strange occurrence - te progressbar whcih shows the progress of loading the flex application all of the sudden disappear.

What could cause this issue?

答:
Seems like you were right @J_A_X and @alxx - it came back when i clean the history and temp files and etc ...
It was very strange occurance...

Thank you.

Title: Flex progress loading disappear?


问:
Array.prototype is overriden
The problem is my code is working under the assumption that the Array prototype object will not get modified by 1st party, 3rd party, or browser extension code. This is a dangerous assumption that cannot be made in JavaScript and it caused an avoidable CSO. How do I go about bulletproofing the code to prevent it from breaking in this circumstance?</p>

答:
It is the nature of the Javascript. If you want to ensure that something is not overriden you must test expected behavior before using it. Let say you are using Array.prototype.push. Check its behavior, if it is not works like expected throw error.</p>

```<code>var arr = [1, 2];
arr.push(3);
if (arr[2] !== 3) {
   throw "Push function is overriden!";
}
</code>```

Title: Array.prototype is overriden

Body:
It is the nature of the Javascript. If you want to ensure that something is not overriden you must test expected behavior before using it. Let say you are using Array.prototype.push. Check its behavior, if it is not works like expected throw error.

var arr = [1, 2];
arr.push(3);
if (arr[2] !== 3) {
   throw "Push function is overriden!";
}


问:
Inserting multiple documents in mongo ignore if key exists continue_on_error=True not working
if my db is similar as given below:

/* 1 */ {
      "_id" : 1.0,
      "imagename" : "pen1",
      "qty" : 21.0 }

/* 2 */ {
      "_id" : 2.0,
      "imagename" : "pen",
      "qty" : 20.0 }

/* 3 */ {
      "_id" : 3.0,
      "imagename" : "eraser",
      "qty" : 25.0 }

and i have to insert following documents which contains a duplicate key which i have to skip usually it can be done through continue_on_error=True but its not working

```<code>db.products.insert(
    [{ _id:1,imagename: "pen1", qty: 21 },
     { _id:2,imagename: "pen", qty: 20 },
     { _id:3,imagename: "eraser", qty: 25 }]
)
</code>```

using insert_many getting  batch op errors occurred

using insert_many(data,ordered=False) facing same issue batch op errors occurred

using insert getting duplicate key error collection

using insert(data,continue_on_error=True) getting same issue duplicate key error collection

```<code>using : pymongo Version: 3.9.0,
MongoDB shell version v3.6.3
</code>```

答:
insert() is deprecated so shouldn't be used. As such continue_on_error is no longer a thing.

Use insert_many() with the ordered=False parameter, and wrap the command in a try...except to ignore any duplicate key errors. Any duplicate entries will be skipped and any new records will be inserted. Try this example:

```<code>from pymongo import MongoClient
from pymongo.errors import BulkWriteError

db = MongoClient()['mydatabase']

try:
    db.products.insert_many(
        [{ '_id': 1 ,'imagename': 'pen1', 'qty': 21 },
         { '_id': 2 ,'imagename': 'pen', 'qty': 20 },
         { '_id': 3 ,'imagename': 'eraser', 'qty': 25 }], ordered=False)
except BulkWriteError as e:
    pass
</code>```

Body:
if my db is similar as given below:

/* 1 */ {
      "_id" : 1.0,
      "imagename" : "pen1",
      "qty" : 21.0 }

/* 2 */ {
      "_id" : 2.0,
      "imagename" : "pen",
      "qty" : 20.0 }

/* 3 */ {
      "_id" : 3.0,
      "imagename" : "eraser",
      "qty" : 25.0 }

and i have to insert following documents which contains a duplicate key which i have to skip usually it can be done through continue_on_error=True but its not working

db.products.insert(
    [{ _id:1,imagename: "pen1", qty: 21 },
     { _id:2,imagename: "pen", qty: 20 },
     { _id:3,imagename: "eraser", qty: 25 }]
)

using insert_many getting  batch op errors occurred

using insert_many(data,ordered=False) facing same issue batch op errors occurred

using insert getting duplicate key error collection

using insert(data,continue_on_error=True) getting same issue duplicate key error collection

using : pymongo Version: 3.9.0,
MongoDB shell version v3.6.3

Body:
insert() is deprecated so shouldn't be used. As such continue_on_error is no longer a thing.

Use insert_many() with the ordered=False parameter, and wrap the command in a try...except to ignore any duplicate key errors. Any duplicate entries will be skipped and any new records will be inserted. Try this example:

from pymongo import MongoClient
from pymongo.errors import BulkWriteError

db = MongoClient()['mydatabase']

try:
    db.products.insert_many(
        [{ '_id': 1 ,'imagename': 'pen1', 'qty': 21 },
         { '_id': 2 ,'imagename': 'pen', 'qty': 20 },
         { '_id': 3 ,'imagename': 'eraser', 'qty': 25 }], ordered=False)
except BulkWriteError as e:
    pass