问:
python DataFrame comparison using == operator
I have two python dataframes of same structure and same number of rows
when I perform '==' operation on them they gives wrong answers

df1:

```<code>      0     61561899
      1     56598947
      2     52231204
      3     10069030
      4     19900179
      5     52892001
      6     50015534
      7     10071207
      8     55455545
      9     10075649
      10    52050196
 Name: spn, dtype: object
</code>```

df2:

```<code>  0     61561899
  1     56598947
  2     52231204
  3     10069030
  4     19900179
  5     52892001
  6     50015534
  7     10071207
  8     55455545
  9     10075649
  10    52050196
  Name: spn, dtype: object
</code>```

print df1 == df2

the above python statement gives following output:

```<code>  0     False
  1     False
  2     False
  3     False
  4     False
  5     False
  6     False
  7     False
  8     False
  9     False
  10    False
  Name: spn, dtype: bool
</code>```

I dont know what am I missing. I am expecting all true.

Body:
I have two python dataframes of same structure and same number of rows
when I perform '==' operation on them they gives wrong answers

df1:

      0     61561899
      1     56598947
      2     52231204
      3     10069030
      4     19900179
      5     52892001
      6     50015534
      7     10071207
      8     55455545
      9     10075649
      10    52050196
 Name: spn, dtype: object

df2:

  0     61561899
  1     56598947
  2     52231204
  3     10069030
  4     19900179
  5     52892001
  6     50015534
  7     10071207
  8     55455545
  9     10075649
  10    52050196
  Name: spn, dtype: object

print df1 == df2

the above python statement gives following output:

  0     False
  1     False
  2     False
  3     False
  4     False
  5     False
  6     False
  7     False
  8     False
  9     False
  10    False
  Name: spn, dtype: bool

I dont know what am I missing. I am expecting all true.

Body:
Would like to see your code as the comparison gives True values. Here is an example using your data.

import pandas as pd
df1 = pd.DataFrame({'A': [61561899,
       56598947,
       52231204,
       10069030,
       19900179,
       52892001,
       50015534,
       10071207,
       55455545,
       10075649,
       52050196]})

df2 = pd.DataFrame({'A': [61561899,
       56598947,
       52231204,
       10069030,
       19900179,
       52892001,
       50015534,
       10071207,
       55455545,
       10075649,
       52050196]})

print(df1 == df2)

Out[1]:
       A
0   True
1   True
2   True
3   True
4   True
5   True
6   True
7   True
8   True
9   True
10  True

df1.dtypes

Out[2]:
A    int64
dtype: object


来源: stackexchange

问:
How do you use the "Embed in button" action in Xcode 11.0
This is a very general question for everyone who uses Xcode 11. I am trying to find the action that will allow me to use the "Embed in button" if you know of any ways please leave a comment below. I have tried Command + Click & Control + Click and neither work or direct me to the action</p>

答:
Version 11.4.1 of XCode

The option to: Embed in Button isn't available anymore in XCode.

Anyway, you can do this instead:

Click the "+" (Library Button)

Click on "Show the views library" and search for Button

Drag and drop the Button wherever you need it

Cut, Paste your code inside of the brachets

1.
2.
3.
4.

I hope this can help you.

ContentLicense: CC BY-SA 4.0


问:
Creating a C++ object with and without new keyword
Creating an object with new keyword:

```<code>#include <iostream>
#include <string>

using namespace std;

class Person {
  private:
  string name;

  public:
  Person(string name) {
    setName(name);
  }

  string getName() {
    return this->name;
  }

  void setName(string name) {
    this->name = name;
  }
};

int main() {
  Person *person1 = new Person("Rajat");
  Person *person2 = person1;

  person2->setName("Karan");

  cout << person1->getName() << endl;
  cout << person2->getName() << endl;

  return 0;
}
</code>```

Output:

```<code>Karan
Karan
</code>```

Creating an object without new keyword:

```<code>#include <iostream>
#include <string>

using namespace std;

class Person {
  private:
  string name;

  public:
  Person(string name) {
    setName(name);
  }

  string getName() {
    return this->name;
  }

  void setName(string name) {
    this->name = name;
  }
};

int main() {
  Person person1("Rajat");
  Person person2 = person1;

  person2.setName("Karan");

  cout << person1.getName() << endl;
  cout << person2.getName() << endl;

  return 0;
}
</code>```

Output:

```<code>Rajat
Karan
</code>```

I expected the output to be 'Karan Karan' as I thought in Person person2 = person1, person2 refers to the same person1. But it isn't the case.

Can someone please explain what does the line Person person2 = person1 do under the hood? Does it create a totally new object?

答:
In the first snippet, you have two pointers pointing two the same object which is dangerous, hence on using any of the two pointers to make a change you change the same object. Note that you have created only one object.

```<code>Person *person2 = person1;
</code>```

The previous line creates a new pointer pointing to the same object pointed to by the pointer person1

While in the second snippet you have created person2 object which is different from person1 but has the same value for name data member (because you've used the copy ctor) and then you have changed the value of the name of person2, hence two different names.

```<code>Person person2 = person1;
</code>```

The previous line creates a new object using copy actor, hence have the same values for the data members.

Body:
Creating an object with new keyword:

#include <iostream>
#include <string>

using namespace std;

class Person {
  private:
  string name;

  public:
  Person(string name) {
    setName(name);
  }

  string getName() {
    return this->name;
  }

  void setName(string name) {
    this->name = name;
  }
};

int main() {
  Person *person1 = new Person("Rajat");
  Person *person2 = person1;

  person2->setName("Karan");

  cout << person1->getName() << endl;
  cout << person2->getName() << endl;

  return 0;
}

Output:

Karan
Karan

Creating an object without new keyword:

#include <iostream>
#include <string>

using namespace std;

class Person {
  private:
  string name;

  public:
  Person(string name) {
    setName(name);
  }

  string getName() {
    return this->name;
  }

  void setName(string name) {
    this->name = name;
  }
};

int main() {
  Person person1("Rajat");
  Person person2 = person1;

  person2.setName("Karan");

  cout << person1.getName() << endl;
  cout << person2.getName() << endl;

  return 0;
}

Output:

Rajat
Karan

I expected the output to be 'Karan Karan' as I thought in Person person2 = person1, person2 refers to the same person1. But it isn't the case.

Can someone please explain what does the line Person person2 = person1 do under the hood? Does it create a totally new object?

Body:
In the first snippet, you have two pointers pointing two the same object which is dangerous, hence on using any of the two pointers to make a change you change the same object. Note that you have created only one object.

Person *person2 = person1;

The previous line creates a new pointer pointing to the same object pointed to by the pointer person1

While in the second snippet you have created person2 object which is different from person1 but has the same value for name data member (because you've used the copy ctor) and then you have changed the value of the name of person2, hence two different names.

Person person2 = person1;

The previous line creates a new object using copy actor, hence have the same values for the data members.


问:
How to reload page with javascript without sending POST information again
I have a page, to which I POST information via form method="post". I would like to relaod it with JavaScript, but location.reload(true) and location.reload() makes browsers ask if I want to send the POST data again.

I would like to make JavaScript reload the page with GET instead of POST to skip the POST data.

How can I achieve that?

答:
To reload a page without post data using javascript the easiest way I've found is to use an extra form to submit - this works regardless of whether the url is # or anything.

```<code><form name="reloadForm">
    <button type="submit">
        Continue
    </button>
</form>
<script>
    document.reloadForm.submit() ;
</script>
</code>```

That will show a button briefly on screen that the user can click continue on but the script will automatically submit it  - this method sorts out a number of problems - the form is empty so it will not submit any post data (the button isn't named so even that won't submit a value).  It works even if the url is set to #, and finally it gives a backup in case the user has disabled javascript (or the javascript doesn't work for some reason) they've still got a continue button available to click.

ContentLicense: CC BY-SA 3.0

Body:
To reload a page without post data using javascript the easiest way I've found is to use an extra form to submit - this works regardless of whether the url is # or anything.

<form name="reloadForm">
    <button type="submit">
        Continue
    </button>
</form>
<script>
    document.reloadForm.submit() ;
</script>

That will show a button briefly on screen that the user can click continue on but the script will automatically submit it  - this method sorts out a number of problems - the form is empty so it will not submit any post data (the button isn't named so even that won't submit a value).  It works even if the url is set to #, and finally it gives a backup in case the user has disabled javascript (or the javascript doesn't work for some reason) they've still got a continue button available to click.


问:
Unable to connect to server: FATAL: password authentication failed for user "xxxx" FATAL: password authentication failed for user "xxxx"
I'm building a Django app and I'm trying to create a connection from AWS. The password is right and the hostname/address but after connecting it, it says

"Unable to connect to server:  FATAL: password authentication failed for user 'xxxx'"

Here's a screenshot of the error: https://prnt.sc/sqziuq

Other screenshots for another details of the connection:

https://prnt.sc/sqzm9z

https://prnt.sc/sqzlx7

答:
The solution I specified was to reset the password.

This was confirmed to work.


问:
Remove everything after the first whitespace in pandas dataframe
Here is the dataframe:

```<code>     State  RegionName
0    NY     New York
1    CA     Los Angeles
2    IL     Chicago 865
3    PA     Philadelphia Wrin
4    AZ     Phoenix City
</code>```

I want the output to look like this:

```<code>     State   RegionName
0    NY      New
1    CA      Los
2    IL      Chicago
3    PA      Philadelphia
4    AZ      Phoenix
</code>```

How to do it without using for loops ??

答:
You could also str.extract the start of the string but exclude space ^[^\s]+ using regex

```<code>df['RegionName']=df['RegionName'].str.extract('(^[^\s]+)')
</code>```

Body:
Here is the dataframe:

     State  RegionName
0    NY     New York
1    CA     Los Angeles
2    IL     Chicago 865
3    PA     Philadelphia Wrin
4    AZ     Phoenix City

I want the output to look like this:

     State   RegionName
0    NY      New
1    CA      Los
2    IL      Chicago
3    PA      Philadelphia
4    AZ      Phoenix

How to do it without using for loops ??

Body:
You could also str.extract the start of the string but exclude space ^[^\s]+ using regex

df['RegionName']=df['RegionName'].str.extract('(^[^\s]+)')


问:
Control flow statements. How many years should pass until goal money
I would like to solve this task, but unfortunately, I stopped at this: Maybe I calculated in int but should in double?

Peter put money in the bank. The bank increases Peter's deposit by a percent every year. Peter wants to know how many years should pass until his deposit in the bank reaches his goal money.

```<code>import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // write your code here
        Scanner myobject = new Scanner(System.in);
        double money = myobject.nextDouble();
        double percent = myobject.nextDouble();
        double goal = myobject.nextDouble();
        int years = -1;
        while (goal >= money) {
            money = money + money * (percent / 100);
            ++years;
        }
        System.out.println(years);
    }
}
</code>```

Test input: 100 15 120

Correct output: 2

Your code output: 1

答:
you should initilize years to 0 instead of -1 :</p>

```<code> int years =0;
</code>```

Body:
I would like to solve this task, but unfortunately, I stopped at this: Maybe I calculated in int but should in double?

Peter put money in the bank. The bank increases Peter's deposit by a percent every year. Peter wants to know how many years should pass until his deposit in the bank reaches his goal money.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // write your code here
        Scanner myobject = new Scanner(System.in);
        double money = myobject.nextDouble();
        double percent = myobject.nextDouble();
        double goal = myobject.nextDouble();
        int years = -1;
        while (goal >= money) {
            money = money + money * (percent / 100);
            ++years;
        }
        System.out.println(years);
    }
}

Test input: 100 15 120

Correct output: 2

Your code output: 1

Body:
you should initilize years to 0 instead of -1 :

 int years =0;


问:
Write a C function to evaluate the series // sin(x) = x-(x3 /3!)+(x5 /5!)-(x7 /7!)+... // up to 10 terms
```<code>#include <stdio.h>
#include<math.h>

int series(float,float);

int main()

{

    float x,n,series_value;
    printf("Enter the value of x: ");
    scanf("%f",&x);
    printf("\nEnter the value of n: ");
    scanf("%f",&n);
    series_value=series(x,n);
    printf("\nValue of series sin (%.2f) is: %f\n",x,series_value);
    return 0;
}

int series(float x,float n)

{

    int i,sum=0,sign=-1;
    int j,fact=1,p=1;
    for (i=1; i<=(2*n)-1; i+=2)
    {
        for (j=1; j<=i; j++)
        {
        p=p*x;
        fact=fact*j;
        }
        sign=-1*sign;
        sum=sum + sign*p/fact;
    }
    return (sum);
}
</code>```

Output:
Enter the value of x: 5

Enter the value of n: 10
(lldb)
and this message
Thread 1: EXC_ARITHMETIC (code=EXC_I386_DIV, subcode=0x0)
![Thread 1 Queue : com.apple.main-thread (serial)
]1

Why is this message coming? and what is wrong in the program as answer is not coming right

答:
There is a few problems with your code. As @PaulHankin said, when fact overflows and becoms zero, you will have a division by zero, and "weird things" happen.

Your factorial and power calculation is also wrong. You are recalculating it in each iteration of the outer loop without reseting fact and p first:

```<code>fact = 1; // You need to reset fact and p to its start value here
p = 1;
for (j=1; j<=i; j++)
  {
    p=p*x;
    fact=fact*j;
  }
</code>```

Your third problem is that for your function calculate the correct value for sin, which is not an integer value, you need to use float, or even better double, when calculating sum. So sum must be declared float, and the division p/fact must use float division. By also declaring p and fact as float, you will solve both the overflow issue, and use the correct division. Naturally your function must also return  a float

```<code>float series(float x,float n)
{
    int i,sign=-1;
    int j,
    float sum = 0;
    float fact = 1;
    float p = 1;
    for (i=1; i<=(2*n)-1; i+=2)
    {
        fact = 1;
        p = 1;
        for (j=1; j<=i; j++)
        {
           p=p*x;
           fact=fact*j;
        }
        sign=-1*sign;
        sum=sum + sign*p/fact;
    }
    return (sum);
}
</code>```

This code still has a minor problem. By having an inner loop, it is slower than necessary. Since this probably is homework, I am not getting rid of that loop for you, just giving you a hint: You don't have to recalculate fact from scratch on each iteration of the outer loop, just try to find out how fact changes from one iteration to the next. The same goes for p.

Body:
#include <stdio.h>
#include<math.h>

int series(float,float);

int main()

{

    float x,n,series_value;
    printf("Enter the value of x: ");
    scanf("%f",&x);
    printf("\nEnter the value of n: ");
    scanf("%f",&n);
    series_value=series(x,n);
    printf("\nValue of series sin (%.2f) is: %f\n",x,series_value);
    return 0;
}

int series(float x,float n)

{

    int i,sum=0,sign=-1;
    int j,fact=1,p=1;
    for (i=1; i<=(2*n)-1; i+=2)
    {
        for (j=1; j<=i; j++)
        {
        p=p*x;
        fact=fact*j;
        }
        sign=-1*sign;
        sum=sum + sign*p/fact;
    }
    return (sum);
}

Output:
Enter the value of x: 5

Enter the value of n: 10
(lldb)
and this message
Thread 1: EXC_ARITHMETIC (code=EXC_I386_DIV, subcode=0x0)
![Thread 1 Queue : com.apple.main-thread (serial)
]1

Why is this message coming? and what is wrong in the program as answer is not coming right

Body:
There is a few problems with your code. As @PaulHankin said, when fact overflows and becoms zero, you will have a division by zero, and "weird things" happen.

Your factorial and power calculation is also wrong. You are recalculating it in each iteration of the outer loop without reseting fact and p first:

fact = 1; // You need to reset fact and p to its start value here
p = 1;
for (j=1; j<=i; j++)
  {
    p=p*x;
    fact=fact*j;
  }

Your third problem is that for your function calculate the correct value for sin, which is not an integer value, you need to use float, or even better double, when calculating sum. So sum must be declared float, and the division p/fact must use float division. By also declaring p and fact as float, you will solve both the overflow issue, and use the correct division. Naturally your function must also return  a float

float series(float x,float n)
{
    int i,sign=-1;
    int j,
    float sum = 0;
    float fact = 1;
    float p = 1;
    for (i=1; i<=(2*n)-1; i+=2)
    {
        fact = 1;
        p = 1;
        for (j=1; j<=i; j++)
        {
           p=p*x;
           fact=fact*j;
        }
        sign=-1*sign;
        sum=sum + sign*p/fact;
    }
    return (sum);
}

This code still has a minor problem. By having an inner loop, it is slower than necessary. Since this probably is homework, I am not getting rid of that loop for you, just giving you a hint: You don't have to recalculate fact from scratch on each iteration of the outer loop, just try to find out how fact changes from one iteration to the next. The same goes for p.


问:
Are Sanctum and Laravel's default auth the same if not used for tokens?
I'm not quite sure about what is meant in the Laravel documentation, so I'm asking to be sure.

We have the default authentication of Laravel on one side and Sanctum on the other.

It is stated that Sanctum can either do Tokens or simply implement auth. :

For this feature, Sanctum does not use tokens of any kind. Instead, Sanctum uses Laravel's built-in cookie based session authentication services. This provides the benefits of CSRF protection, session authentication, as well as protects against leakage of the authentication credentials via XSS. Sanctum will only attempt to authenticate using cookies when the incoming request originates from your own SPA frontend (Vue.js).

Therefor if Tokens are nevers used, Sanctum is basically the same as the default Authentication method, am I correct? Basically, does it implement the default authentication and add tokens if needed on top of that? If so, what is the difference between sanctum and passport since they do the same thing but Sanctum is said to be lightweight. What does that actually mean?

Thanks for reading

答:
Therefore if Tokens are never used, Sanctum is basically the same as the default Authentication method, am I correct?

Yes, under the hood it uses laravel's default auth.

Taking a look at the sanctum guard (below code taken fro github. It was last commited on Apr 11, sanctum 2.x)

```<code><?php

namespace Laravel\Sanctum;

use Illuminate\Contracts\Auth\Factory as AuthFactory;
use Illuminate\Http\Request;

class Guard
{
    /**
     * The authentication factory implementation.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */
    protected $auth;

    /**
     * The number of minutes tokens should be allowed to remain valid.
     *
     * @var int
     */
    protected $expiration;

    /**
     * Create a new guard instance.
     *
     * @param  \Illuminate\Contracts\Auth\Factory  $auth
     * @param  int  $expiration
     * @return void
     */
    public function __construct(AuthFactory $auth, $expiration = null)
    {
        $this->auth = $auth;
        $this->expiration = $expiration;
    }

    /**
     * Retrieve the authenticated user for the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return mixed
     */
    public function __invoke(Request $request)
    {
        if ($user = $this->auth->guard(config('sanctum.guard', 'web'))->user()) {
            return $this->supportsTokens($user)
                        ? $user->withAccessToken(new TransientToken)
                        : $user;
        }

        if ($token = $request->bearerToken()) {
            $model = Sanctum::$personalAccessTokenModel;

            $accessToken = $model::findToken($token);

            if (! $accessToken ||
                ($this->expiration &&
                 $accessToken->created_at->lte(now()->subMinutes($this->expiration)))) {
                return;
            }

            return $this->supportsTokens($accessToken->tokenable) ? $accessToken->tokenable->withAccessToken(
                tap($accessToken->forceFill(['last_used_at' => now()]))->save()
            ) : null;
        }
    }

    /**
     * Determine if the tokenable model supports API tokens.
     *
     * @param  mixed  $tokenable
     * @return bool
     */
    protected function supportsTokens($tokenable = null)
    {
        return $tokenable && in_array(HasApiTokens::class, class_uses_recursive(
            get_class($tokenable)
        ));
    }
}
</code>```

If you check the _invoke() method,

```<code>    if ($user = $this->auth->guard(config('sanctum.guard', 'web'))->user()) {
        return $this->supportsTokens($user)
                    ? $user->withAccessToken(new TransientToken)
                    : $user;
    }
</code>```

the authenticated user is found using

```<code>$user = $this->auth->guard(config('sanctum.guard', 'web'))->user()
</code>```

After checking the sanctum config file, there is no sanctum.guard config currently (it's probably meant for some future version), so sanctum checks with the web guard by default, so it's basically doing the same thing as your default web routes.

But you've misunderstood the use of Sanctum. Sanctum is for API authentication and not for web auth (though it can be used web auth as well). Sanctum's non-token auth is for your SPA's to be able to use the same API as mobile applications ( which use token authentication ) without needing tokens and providing the benefits of csrf and session based auth.

To help you understand better, suppose you have build an API which uses tokens (if it's already using sanctum for tokens, that makes things simpler) for authentication. Now you wish to build an SPA ( which may be build inside the laravel project itself, or a seperate project, on same domain or on different domain ) which will use the same API's, but since this will be built by you, it is a trusted site so you don't want it to use tokens but instead use laravel's default session based auth along with csrf protection while also using the same api routes. The SPA will communicate with the server through ajax. You also want to ensure that only your SPA is allowed to use session based auth and not allow other third party sites to use it.

So this is where Sanctum comes in. You would just need to add the Sanctum middleware to your api route group in app/Http/Kernel.php

```<code>use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;

'api' => [
    EnsureFrontendRequestsAreStateful::class,
    'throttle:60,1',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],
</code>```

Then configure sanctum to allow your SPA's domain and configure cors (check the docs to learn how to do this). Then just add the auth:sanctum middleware to your route and you're done with the serverside setup.

Now these routes will authenticate users if the request has a token or if it is stateful (session cookie).

Now your SPA can communicate with your API without tokens.

To get csrf protection, call the csrf-cookie request first, this will set up a csrf token in your cookies, and axios will automatically attach it to subsequent requests

```<code>axios.get('/sanctum/csrf-cookie').then(response => {
    // Login...
})
</code>```

What is the difference between sanctum and passport since they do the same thing but Sanctum is said to be lightweight.

Well it's just like it says, sanctum is lightweight. This is because Passport provides full Oauth functionality while Sanctum only focuses on creating and managing tokens. To explain Oauth in a simple way, you must have seen those Sign in with Google, Sign in with Facebook, Sign in with Github on different sites, and you can then sign it to those sites using your google/facebook/github account. This is possible because Google, Facebook and Github provide Oauth functionality (just a simple example, not going in to too much detail). For most websites, you don't really need Passport as it provides a lot features that you don't need. For simple api authentication Sanctum is more than enough

Body:
Therefore if Tokens are never used, Sanctum is basically the same as the default Authentication method, am I correct?

Yes, under the hood it uses laravel's default auth.

Taking a look at the sanctum guard (below code taken fro github. It was last commited on Apr 11, sanctum 2.x)

<?php

namespace Laravel\Sanctum;

use Illuminate\Contracts\Auth\Factory as AuthFactory;
use Illuminate\Http\Request;

class Guard
{
    /**
     * The authentication factory implementation.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */
    protected $auth;

    /**
     * The number of minutes tokens should be allowed to remain valid.
     *
     * @var int
     */
    protected $expiration;

    /**
     * Create a new guard instance.
     *
     * @param  \Illuminate\Contracts\Auth\Factory  $auth
     * @param  int  $expiration
     * @return void
     */
    public function __construct(AuthFactory $auth, $expiration = null)
    {
        $this->auth = $auth;
        $this->expiration = $expiration;
    }

    /**
     * Retrieve the authenticated user for the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return mixed
     */
    public function __invoke(Request $request)
    {
        if ($user = $this->auth->guard(config('sanctum.guard', 'web'))->user()) {
            return $this->supportsTokens($user)
                        ? $user->withAccessToken(new TransientToken)
                        : $user;
        }

        if ($token = $request->bearerToken()) {
            $model = Sanctum::$personalAccessTokenModel;

            $accessToken = $model::findToken($token);

            if (! $accessToken ||
                ($this->expiration &&
                 $accessToken->created_at->lte(now()->subMinutes($this->expiration)))) {
                return;
            }

            return $this->supportsTokens($accessToken->tokenable) ? $accessToken->tokenable->withAccessToken(
                tap($accessToken->forceFill(['last_used_at' => now()]))->save()
            ) : null;
        }
    }

    /**
     * Determine if the tokenable model supports API tokens.
     *
     * @param  mixed  $tokenable
     * @return bool
     */
    protected function supportsTokens($tokenable = null)
    {
        return $tokenable && in_array(HasApiTokens::class, class_uses_recursive(
            get_class($tokenable)
        ));
    }
}

If you check the _invoke() method,

    if ($user = $this->auth->guard(config('sanctum.guard', 'web'))->user()) {
        return $this->supportsTokens($user)
                    ? $user->withAccessToken(new TransientToken)
                    : $user;
    }

the authenticated user is found using

$user = $this->auth->guard(config('sanctum.guard', 'web'))->user()

After checking the sanctum config file, there is no sanctum.guard config currently (it's probably meant for some future version), so sanctum checks with the web guard by default, so it's basically doing the same thing as your default web routes.

But you've misunderstood the use of Sanctum. Sanctum is for API authentication and not for web auth (though it can be used web auth as well). Sanctum's non-token auth is for your SPA's to be able to use the same API as mobile applications ( which use token authentication ) without needing tokens and providing the benefits of csrf and session based auth.

To help you understand better, suppose you have build an API which uses tokens (if it's already using sanctum for tokens, that makes things simpler) for authentication. Now you wish to build an SPA ( which may be build inside the laravel project itself, or a seperate project, on same domain or on different domain ) which will use the same API's, but since this will be built by you, it is a trusted site so you don't want it to use tokens but instead use laravel's default session based auth along with csrf protection while also using the same api routes. The SPA will communicate with the server through ajax. You also want to ensure that only your SPA is allowed to use session based auth and not allow other third party sites to use it.

So this is where Sanctum comes in. You would just need to add the Sanctum middleware to your api route group in app/Http/Kernel.php

use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;

'api' => [
    EnsureFrontendRequestsAreStateful::class,
    'throttle:60,1',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

Then configure sanctum to allow your SPA's domain and configure cors (check the docs to learn how to do this). Then just add the auth:sanctum middleware to your route and you're done with the serverside setup.

Now these routes will authenticate users if the request has a token or if it is stateful (session cookie).

Now your SPA can communicate with your API without tokens.

To get csrf protection, call the csrf-cookie request first, this will set up a csrf token in your cookies, and axios will automatically attach it to subsequent requests

axios.get('/sanctum/csrf-cookie').then(response => {
    // Login...
})

What is the difference between sanctum and passport since they do the same thing but Sanctum is said to be lightweight.

Well it's just like it says, sanctum is lightweight. This is because Passport provides full Oauth functionality while Sanctum only focuses on creating and managing tokens. To explain Oauth in a simple way, you must have seen those Sign in with Google, Sign in with Facebook, Sign in with Github on different sites, and you can then sign it to those sites using your google/facebook/github account. This is possible because Google, Facebook and Github provide Oauth functionality (just a simple example, not going in to too much detail). For most websites, you don't really need Passport as it provides a lot features that you don't need. For simple api authentication Sanctum is more than enough


问:
I want to show the Progress Dialog until the data is received from the Firebase Database
I have a login activity, when the user enters the correct credentials I want to toast Welcome Username, but I am getting a null pointer and the app crashes.

Here's the code for your reference:

```<code>mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
        if (task.isSuccessful()) {
            if (Objects.requireNonNull(mAuth.getCurrentUser()).isEmailVerified()) {

                final String uid = mAuth.getCurrentUser().getUid();
                /* This method stores the logged in user data in Prevalent.currentOnlineUser, currentOnlineUser is a reference to User class*/
                saveUserPersonalData(uid);
                loadingBar.dismiss();

                Toast.makeText(LoginActivity.this, "Welcome "+Prevalent.currentOnlineUser.getName(), Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(LoginActivity.this, Home.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
             } else {
                loadingBar.dismiss();
                Toast.makeText(LoginActivity.this, "Please verify your email", Toast.LENGTH_SHORT).show();
             }
        } else {
             loadingBar.dismiss();
             Toast.makeText(LoginActivity.this, Objects.requireNonNull(task.getException()).getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
});
</code>```

Here at the Toast message I get a null pointer exception. I want to wait until the Prevalent.currentOnlineUser.getName() is not null anymore, and then show the Toast.
How can I do it, I've tried using solutions available on stack overflow but none of them has worked.

Here's the code for saveUserPersonalData() method.

```<code>private static void saveUserPersonalData(final String uid) {
    final DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    ref.child("users").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot ds) {
            if (ds.hasChild(uid)){
                Users usersData = ds.child(uid).child("personaldetails").getValue(Users.class);
                Prevalent.currentOnlineUser = usersData;
            }
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
        }
    });
}
</code>```

Any help regarding this would be appreciated. Thanks.

答:
put this code inside the saveUserPersonalData()

```<code>Toast.makeText(LoginActivity.this, "Welcome "+Prevalent.currentOnlineUser.getName(), Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(LoginActivity.this, Home.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
</code>```

inside onDataChange

Body:
I have a login activity, when the user enters the correct credentials I want to toast Welcome Username, but I am getting a null pointer and the app crashes.

Here's the code for your reference:

mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
        if (task.isSuccessful()) {
            if (Objects.requireNonNull(mAuth.getCurrentUser()).isEmailVerified()) {

                final String uid = mAuth.getCurrentUser().getUid();
                /* This method stores the logged in user data in Prevalent.currentOnlineUser, currentOnlineUser is a reference to User class*/
                saveUserPersonalData(uid);
                loadingBar.dismiss();

                Toast.makeText(LoginActivity.this, "Welcome "+Prevalent.currentOnlineUser.getName(), Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(LoginActivity.this, Home.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
             } else {
                loadingBar.dismiss();
                Toast.makeText(LoginActivity.this, "Please verify your email", Toast.LENGTH_SHORT).show();
             }
        } else {
             loadingBar.dismiss();
             Toast.makeText(LoginActivity.this, Objects.requireNonNull(task.getException()).getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
});

Here at the Toast message I get a null pointer exception. I want to wait until the Prevalent.currentOnlineUser.getName() is not null anymore, and then show the Toast.
How can I do it, I've tried using solutions available on stack overflow but none of them has worked.

Here's the code for saveUserPersonalData() method.

private static void saveUserPersonalData(final String uid) {
    final DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
    ref.child("users").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot ds) {
            if (ds.hasChild(uid)){
                Users usersData = ds.child(uid).child("personaldetails").getValue(Users.class);
                Prevalent.currentOnlineUser = usersData;
            }
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
        }
    });
}

Any help regarding this would be appreciated. Thanks.

Body:
put this code inside the saveUserPersonalData()

Toast.makeText(LoginActivity.this, "Welcome "+Prevalent.currentOnlineUser.getName(), Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(LoginActivity.this, Home.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);

inside onDataChange


问:
How to count the amount of triggers in jQuery
I have this code for a WordPress plugin:

```<code>jQuery( function( $ ) {
    $('.wpcf7-field-groups').on('wpcf7-field-groups/change', function() {
        var $groups = $(this).find('.group-index');

        // Set index each time user adds a new field on front-end
        $groups.each(function() {
            $(this).text($groups.index(this) + 1);
        } );
});
</code>```

Which dynamically sets a "number" each time a user adds a row. So like this:

```<code><span class="group-index">1</span>
<span class="group-index">2</span>
<span class="group-index">3</span>
.... etc
</code>```

But what I would like is to do is to use the row "count" as a variable. What I tried:

```<code>counter = $groups.index(this) + 1);
console.log(counter)
</code>```

But then the output each time the user fires the button is this:

```<code>1

1
2

1
2
3
</code>```

What I want to see is this:

```<code>1
2
3
</code>```

How can I modify my code to do this?

答:
Replace your

```<code>$groups.each(function() {
         $(this).text($groups.index(this) + 1);
     });
</code>```

with

```<code>$groups.last().text($groups.length);
</code>```

So that instead of changing the numbers of all elements, you're just updating the last one.

Body:
I have this code for a WordPress plugin:

jQuery( function( $ ) {
    $('.wpcf7-field-groups').on('wpcf7-field-groups/change', function() {
        var $groups = $(this).find('.group-index');

        // Set index each time user adds a new field on front-end
        $groups.each(function() {
            $(this).text($groups.index(this) + 1);
        } );
});

Which dynamically sets a "number" each time a user adds a row. So like this:

1
2
3
.... etc

But what I would like is to do is to use the row "count" as a variable. What I tried:

counter = $groups.index(this) + 1);
console.log(counter)

But then the output each time the user fires the button is this:

1

1
2

1
2
3

What I want to see is this:

1
2
3

How can I modify my code to do this?

Body:
Replace your

$groups.each(function() {
         $(this).text($groups.index(this) + 1);
     });

with

$groups.last().text($groups.length);

So that instead of changing the numbers of all elements, you're just updating the last one.


问:
How to select specific range of data column with C#
I am trying to display several data, but I cannot select the column that I want. My code will produce all of the column data values. I have 9 columns in data table (zero-based), and I just want to get the data from column 3 till column 9. Grateful for any kind of insight!</p>

```<code>foreach (DataColumn column in dt.Columns)
    {
        int i = dt.Columns.IndexOf(column);
        int colCount = dt.Columns.Count;

        for (i = 3; i < colCount; i++)
            {
                html.Append("<div class='col col-" + column.Ordinal + "' data-label='" + column.ColumnName + "'>");
                html.Append(row[column.ColumnName]);
                html.Append("</div>");
            }
    }
</code>```

答:
Check the snippet

```<code>        for (int i = 3; i < dt.Columns.Count; i++)
        {
            var column = dt.Columns[i];
            // more code
        }
</code>```

Using LINQ you can achieve the same

```<code>        //This requires namespace using System.Linq;
        foreach (var column in dt.Columns.OfType<DataColumn>().Skip(3))
        {
            // more code
        }
</code>```

Body:
I am trying to display several data, but I cannot select the column that I want. My code will produce all of the column data values. I have 9 columns in data table (zero-based), and I just want to get the data from column 3 till column 9. Grateful for any kind of insight!

foreach (DataColumn column in dt.Columns)
    {
        int i = dt.Columns.IndexOf(column);
        int colCount = dt.Columns.Count;

        for (i = 3; i < colCount; i++)
            {
                html.Append("
");
                html.Append(row[column.ColumnName]);
                html.Append("
");
            }
    }

Body:
Check the snippet

        for (int i = 3; i < dt.Columns.Count; i++)
        {
            var column = dt.Columns[i];
            // more code
        }

Using LINQ you can achieve the same

        //This requires namespace using System.Linq;
        foreach (var column in dt.Columns.OfType<DataColumn>().Skip(3))
        {
            // more code
        }


问:
How to plot the random forest tree corresponding to best parameter
Python: 3.6

Windows: 10

I have few question regarding Random Forest and problem at hand:

I am using Gridsearch to run regression problem using Random Forest. I want to plot the tree corresponding to best fit parameter that gridsearch has found out. Here is the code.

```<code>    from sklearn.model_selection import train_test_split
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=55)

    # Use the random grid to search for best hyperparameters
    # First create the base model to tune
    rf = RandomForestRegressor()
    # Random search of parameters, using 3 fold cross validation,
    # search across 100 different combinations, and use all available cores
    rf_random = RandomizedSearchCV(estimator = rf, param_distributions = random_grid, n_iter = 50, cv = 5, verbose=2, random_state=56, n_jobs = -1)
    # Fit the random search model
    rf_random.fit(X_train, y_train)

    rf_random.best_params_
</code>```

The best parameter came out to be is:

```<code>    {'n_estimators': 1000,
     'min_samples_split': 5,
     'min_samples_leaf': 1,
     'max_features': 'auto',
     'max_depth': 5,
     'bootstrap': True}
</code>```

How can I plot this tree using above parameter?

My dependent variable y lies in range [0,1] (continuous) and all predictor variables are either binary or categorical. Which algorithm in general can work well fot this input and output feature space. I tried with Random Forest. (Didn't give that good result). Note here y   variable is a kind of ratio therefore its between 0 and 1. Example: Expense on food/Total Expense

The above data is skewed that means the dependent or y variable has value=1 in 60% of data and somewhere between 0 and 1 in rest of data. like 0.66, 0.87 so on.

Since my data has only binary {0,1} and categorical variables {A,B,C}. Do I need to convert it into one-hot encoding variable for using random forest?

答:
Allow me to take a step back before answering your questions.

Ideally one should drill down further on the best_params_ of RandomizedSearchCV output through GridSearchCV. RandomizedSearchCV will go over your parameters without trying out all the possible options. Then once you have the best_params_ of RandomizedSearchCV, we can investigate all the possible options across a more narrower range.

You did not include random_grid parameters in your code input, but I would expect you to do a GridSearchCV like this:

```<code># Create the parameter grid based on the results of RandomizedSearchCV
param_grid = {
    'max_depth': [4, 5, 6],
    'min_samples_leaf': [1, 2],
    'min_samples_split': [4, 5, 6],
    'n_estimators': [990, 1000, 1010]
}
# Fit the grid search model
grid_search = GridSearchCV(estimator = rf, param_grid = param_grid,
                          cv = 5, n_jobs = -1, verbose = 2, random_state=56)
</code>```

What the above will do is to go through all the possible combinations of parameters in the param_grid and give you the best parameter.

Now coming to your questions:

Random forests are a combination of multiple trees - so you do not have only 1 tree that you can plot. What you can instead do is to plot 1 or more the individual trees used by the random forests. This can be achieved by the plot_tree function. Have a read of the documentation and this SO question to understand it more.

Did you try a simple linear regression first?

This would impact what kind of accuracy metrics you would utilize to assess your model's fit/accuracy. Precision, recall & F1 scores come to mind when dealing with unbalanced/skewed data

Yes, categorical variables need to be converted to dummy variables before fitting a random forest

Body:
Python: 3.6

Windows: 10

I have few question regarding Random Forest and problem at hand:

I am using Gridsearch to run regression problem using Random Forest. I want to plot the tree corresponding to best fit parameter that gridsearch has found out. Here is the code.

    from sklearn.model_selection import train_test_split
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=55)

    # Use the random grid to search for best hyperparameters
    # First create the base model to tune
    rf = RandomForestRegressor()
    # Random search of parameters, using 3 fold cross validation,
    # search across 100 different combinations, and use all available cores
    rf_random = RandomizedSearchCV(estimator = rf, param_distributions = random_grid, n_iter = 50, cv = 5, verbose=2, random_state=56, n_jobs = -1)
    # Fit the random search model
    rf_random.fit(X_train, y_train)

    rf_random.best_params_

The best parameter came out to be is:

    {'n_estimators': 1000,
     'min_samples_split': 5,
     'min_samples_leaf': 1,
     'max_features': 'auto',
     'max_depth': 5,
     'bootstrap': True}

How can I plot this tree using above parameter?

My dependent variable y lies in range [0,1] (continuous) and all predictor variables are either binary or categorical. Which algorithm in general can work well fot this input and output feature space. I tried with Random Forest. (Didn't give that good result). Note here y   variable is a kind of ratio therefore its between 0 and 1. Example: Expense on food/Total Expense

The above data is skewed that means the dependent or y variable has value=1 in 60% of data and somewhere between 0 and 1 in rest of data. like 0.66, 0.87 so on.

Since my data has only binary {0,1} and categorical variables {A,B,C}. Do I need to convert it into one-hot encoding variable for using random forest?

Body:
Allow me to take a step back before answering your questions.

Ideally one should drill down further on the best_params_ of RandomizedSearchCV output through GridSearchCV. RandomizedSearchCV will go over your parameters without trying out all the possible options. Then once you have the best_params_ of RandomizedSearchCV, we can investigate all the possible options across a more narrower range.

You did not include random_grid parameters in your code input, but I would expect you to do a GridSearchCV like this:

# Create the parameter grid based on the results of RandomizedSearchCV
param_grid = {
    'max_depth': [4, 5, 6],
    'min_samples_leaf': [1, 2],
    'min_samples_split': [4, 5, 6],
    'n_estimators': [990, 1000, 1010]
}
# Fit the grid search model
grid_search = GridSearchCV(estimator = rf, param_grid = param_grid,
                          cv = 5, n_jobs = -1, verbose = 2, random_state=56)

What the above will do is to go through all the possible combinations of parameters in the param_grid and give you the best parameter.

Now coming to your questions:

Random forests are a combination of multiple trees - so you do not have only 1 tree that you can plot. What you can instead do is to plot 1 or more the individual trees used by the random forests. This can be achieved by the plot_tree function. Have a read of the documentation and this SO question to understand it more.

Did you try a simple linear regression first?

This would impact what kind of accuracy metrics you would utilize to assess your model's fit/accuracy. Precision, recall & F1 scores come to mind when dealing with unbalanced/skewed data

Yes, categorical variables need to be converted to dummy variables before fitting a random forest


答:
In the first case, you have pointers to Person which actually pointing to the same dynamically allocated object. Two pointers but there are no two separate objects. Therefore, changing the name will affect both.

In the second one, you do copy initialization and has created literally two distinct objects here.

```<code>Person person2 = person1;
</code>```

Therefore you have different names after setting them.

Title: Creating a C++ object with and without new keyword

Body:
Creating an object with new keyword:

#include <iostream>
#include <string>

using namespace std;

class Person {
  private:
  string name;

  public:
  Person(string name) {
    setName(name);
  }

  string getName() {
    return this->name;
  }

  void setName(string name) {
    this->name = name;
  }
};

int main() {
  Person *person1 = new Person("Rajat");
  Person *person2 = person1;

  person2->setName("Karan");

  cout << person1->getName() << endl;
  cout << person2->getName() << endl;

  return 0;
}

Output:

Karan
Karan

Creating an object without new keyword:

#include <iostream>
#include <string>

using namespace std;

class Person {
  private:
  string name;

  public:
  Person(string name) {
    setName(name);
  }

  string getName() {
    return this->name;
  }

  void setName(string name) {
    this->name = name;
  }
};

int main() {
  Person person1("Rajat");
  Person person2 = person1;

  person2.setName("Karan");

  cout << person1.getName() << endl;
  cout << person2.getName() << endl;

  return 0;
}

Output:

Rajat
Karan

I expected the output to be 'Karan Karan' as I thought in Person person2 = person1, person2 refers to the same person1. But it isn't the case.

Can someone please explain what does the line Person person2 = person1 do under the hood? Does it create a totally new object?

Body:
In the first case, you have pointers to Person which actually pointing to the same dynamically allocated object. Two pointers but there are no two separate objects. Therefore, changing the name will affect both.

In the second one, you do copy initialization and has created literally two distinct objects here.

Person person2 = person1;

Therefore you have different names after setting them.


问:
Standard practice when navigating pages using BottomNavigationBar in Flutter?
I am trying to understand the standard practice of using the BottomNavigationBar for navigating/rendering in Flutter. I've been looking at examples and have seen multiple ways of doing this.

When a tab is selected do a setstate and render the body.

When a tab is selected use navigator to navigate to a new screen/page while persisting the BottomNavigationBar

Which is the right thing to do or it depends?

答:
It depends on what you want to achieve.

If you render a new page (with navigate) the page will slide in from right or from wherever you want and you can add a back button to go back to the previous page.

If you use setState to render new content the content will just be replaced. Therefore it's a completely different user experience.

With a ButtomNavigationBar I suggest to use setState, to just replace the content. This is the usual behavior of a ButtomNavigationBar


答:
Let's see what's going on in the background.

First case

While using new keyword, new created an object and returned a pointer to that object.

```<code>                           +--------------------------+
       person1 ----------> |    Person Object         |
                           |        name = Rajat      |
                           +--------------------------+
</code>```

You then copied the address to the object in another pointer to object. So basically now both pointers point to the same object.

```<code>                           +--------------------------+
       person1 ----------> |    Person Object         |
                           |        name = Rajat      |
       person2-----------> |                          |
                           +--------------------------+
</code>```

Now, You then changed the value of name using one pointer and changing the value using one pointer changed both person1 and person2.

```<code>person2->setName("Karan")
</code>```

```<code>                               +--------------------------+
           person1 ----------> |    Person Object         |
                               |        name = Karan      |
           person2-----------> |                          |
                               +--------------------------+
</code>```

Is it so??

No! Basically it changed for only the object it points. Hence for one object. In fact, there were never two objects, two objects never got created. It was the same object pointed by two pointers.

In second case

You created an object and that object (not a pointer to the object) and stored in variable person1.

```<code>                           +--------------------------+
                           | Person Object (Person 1) |
                           |        name = Karan      |
                           |                          |
                           +--------------------------+
</code>```

Now, when you assigned person2 = person1, there is something called Copy constructor is involved here.

It creates another object for person2 copying everything in person1 to person2.

```<code>                           +--------------------------+
                           | Person Object (Person1)  |
                           |        name = Rajat      |
                           |                          |
                           +--------------------------+

                           +--------------------------+
                           | Person Object (Person2)  |
                           |        name = Rajat      |
                           |                          |
                           +--------------------------+
</code>```

Hence, here we have two independent objects.

When you changed the value for one, the value got changed for only one, for the ones you actually wanted to change. And another independent object is as it was earlier.

```<code>                           +--------------------------+
                           | Person Object (Person1)  |
                           |        name = Rajat      |
                           |                          |
                           +--------------------------+

                           +--------------------------+
                           | Person Object (Person2)  |
                           |        name = Karan      |
                           |                          |
                           +--------------------------+
</code>```

Body:
Let's see what's going on in the background.

First case

While using new keyword, new created an object and returned a pointer to that object.

                           +--------------------------+
       person1 ----------> |    Person Object         |
                           |        name = Rajat      |
                           +--------------------------+

You then copied the address to the object in another pointer to object. So basically now both pointers point to the same object.

                           +--------------------------+
       person1 ----------> |    Person Object         |
                           |        name = Rajat      |
       person2-----------> |                          |
                           +--------------------------+

Now, You then changed the value of name using one pointer and changing the value using one pointer changed both person1 and person2.

person2->setName("Karan")

                               +--------------------------+
           person1 ----------> |    Person Object         |
                               |        name = Karan      |
           person2-----------> |                          |
                               +--------------------------+

Is it so??

No! Basically it changed for only the object it points. Hence for one object. In fact, there were never two objects, two objects never got created. It was the same object pointed by two pointers.

In second case

You created an object and that object (not a pointer to the object) and stored in variable person1.

                           +--------------------------+
                           | Person Object (Person 1) |
                           |        name = Karan      |
                           |                          |
                           +--------------------------+

Now, when you assigned person2 = person1, there is something called Copy constructor is involved here.

It creates another object for person2 copying everything in person1 to person2.

                           +--------------------------+
                           | Person Object (Person1)  |
                           |        name = Rajat      |
                           |                          |
                           +--------------------------+

                           +--------------------------+
                           | Person Object (Person2)  |
                           |        name = Rajat      |
                           |                          |
                           +--------------------------+

Hence, here we have two independent objects.

When you changed the value for one, the value got changed for only one, for the ones you actually wanted to change. And another independent object is as it was earlier.

                           +--------------------------+
                           | Person Object (Person1)  |
                           |        name = Rajat      |
                           |                          |
                           +--------------------------+

                           +--------------------------+
                           | Person Object (Person2)  |
                           |        name = Karan      |
                           |                          |
                           +--------------------------+


问:
Axios post returns 401 and logs user out, but only on OSX & iOS
I have a Vue app using Vue router and I suddenly started getting a 401 on an axios.post /wp-json/jwt-auth/v1/and it only seems to be happening on OS X and iOS.

Thoughts on where to direct my debug hunt?

The error is:

```<code>{
  "code": "rest_forbidden",
  "message": "Sorry, you are not allowed to do that.",
  "data": {
    "status": 401
  }
}
</code>```

I post, it immediately fails with a 401, but only on Macs.

localClient config:

```<code>import axios from "axios";
import environment from "@/environments/environment";
import state from "../store";
import router from "../router";

const userData = JSON.parse(localStorage.getItem("userData"));

let instance = {};

if (userData) {
  instance = axios.create({
    baseURL: environment.CUSTOM_BASE_URL,
    headers: { Authorization: `Bearer ${userData.token}` }
  });
} else {
  instance = axios.create({
    baseURL: environment.CUSTOM_BASE_URL
  });
}

instance.interceptors.request.use(
  config => {
    state.commit("setNetworkStatus", true);
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  response => {
    state.commit("setNetworkStatus", false);
    return response;
  },
  error => {
    if ([401, 403].includes(error.response.status)) {
      console.log(error);
      state.commit("delUserData");
      router.push("/login");
    }
    return Promise.reject(error);
  }
);

export default {
  get(path) {
    return instance.get(instance.defaults.baseURL + path);
  },
  post(path, params) {
    console.log(instance.defaults.baseURL + path, params);
    return instance.post(instance.defaults.baseURL + path, params);
  },
  put(path, params) {
    return instance.put(instance.defaults.baseURL + path, params);
  },
  delete(path, params) {
    return instance.delete(instance.defaults.baseURL + path, params);
  }
};

</code>```

interceptor request success before response 401 failure:

```<code>interceptor request success=
{url: "https://panel.site.art/wp-json/jwt-auth/v1/site/transfer", method: "post", data: {…}, headers: {…}, baseURL: "https://panel.site.art/wp-json", …}
adapter: ƒ (t)
baseURL: "https://panel.site.art/wp-json"
data: "{"location_id":"rec140ttKVWJCDr8v","items":["recg1W9lQuLLRm8VS"]}"
headers:
Accept: "application/json, text/plain, */*"
Content-Type: "application/json;charset=utf-8"
__proto__: Object
maxContentLength: -1
method: "post"
timeout: 0
transformRequest: [ƒ]
transformResponse: [ƒ]
url: "https://panel.site.art/wp-json/jwt-auth/v1/site/transfer"
validateStatus: ƒ (t)
xsrfCookieName: "XSRF-TOKEN"
xsrfHeaderName: "X-XSRF-TOKEN"
__proto__: Object
</code>```

答:
A classic issue with safari & local-storage, there is a privacy config for safari which allows to disable localStorage (yeah, it is not works by the spec!)

Had the same issue in one of the companies I've worked for. Eventually, we wrote a specific flow for this case, with a product tradeoff.

It is better to save it inside a cookie in the matter explained here ReactJS - watch access token expiration

Body:
I have a Vue app using Vue router and I suddenly started getting a 401 on an axios.post /wp-json/jwt-auth/v1/and it only seems to be happening on OS X and iOS.

Thoughts on where to direct my debug hunt?

The error is:

{
  "code": "rest_forbidden",
  "message": "Sorry, you are not allowed to do that.",
  "data": {
    "status": 401
  }
}

I post, it immediately fails with a 401, but only on Macs.

localClient config:

import axios from "axios";
import environment from "@/environments/environment";
import state from "../store";
import router from "../router";

const userData = JSON.parse(localStorage.getItem("userData"));

let instance = {};

if (userData) {
  instance = axios.create({
    baseURL: environment.CUSTOM_BASE_URL,
    headers: { Authorization: `Bearer ${userData.token}` }
  });
} else {
  instance = axios.create({
    baseURL: environment.CUSTOM_BASE_URL
  });
}

instance.interceptors.request.use(
  config => {
    state.commit("setNetworkStatus", true);
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  response => {
    state.commit("setNetworkStatus", false);
    return response;
  },
  error => {
    if ([401, 403].includes(error.response.status)) {
      console.log(error);
      state.commit("delUserData");
      router.push("/login");
    }
    return Promise.reject(error);
  }
);

export default {
  get(path) {
    return instance.get(instance.defaults.baseURL + path);
  },
  post(path, params) {
    console.log(instance.defaults.baseURL + path, params);
    return instance.post(instance.defaults.baseURL + path, params);
  },
  put(path, params) {
    return instance.put(instance.defaults.baseURL + path, params);
  },
  delete(path, params) {
    return instance.delete(instance.defaults.baseURL + path, params);
  }
};

interceptor request success before response 401 failure:

interceptor request success=
{url: "https://panel.site.art/wp-json/jwt-auth/v1/site/transfer", method: "post", data: {…}, headers: {…}, baseURL: "https://panel.site.art/wp-json", …}
adapter: ƒ (t)
baseURL: "https://panel.site.art/wp-json"
data: "{"location_id":"rec140ttKVWJCDr8v","items":["recg1W9lQuLLRm8VS"]}"
headers:
Accept: "application/json, text/plain, */*"
Content-Type: "application/json;charset=utf-8"
__proto__: Object
maxContentLength: -1
method: "post"
timeout: 0
transformRequest: [ƒ]
transformResponse: [ƒ]
url: "https://panel.site.art/wp-json/jwt-auth/v1/site/transfer"
validateStatus: ƒ (t)
xsrfCookieName: "XSRF-TOKEN"
xsrfHeaderName: "X-XSRF-TOKEN"
__proto__: Object


问:
How to extract text from a html form drop-down options?
Recently I'm building a website where I need data of all car types and models, such an example with the data type is sellanycar.com.

I need all the data from 'Select Make' and corresponding 'Select Model'  dropdowns:

The code of any language is acceptable but javaScript/jQuery or Python is preferable and the data can be of any format e.g. JSON or XLXS, etc.

答:
A) In JS/Node, you can use Pupeteer to scrape pages, and Cheerio, do extract what you want JQuery-style.

B) You could use a scraping tool such as Screaming Frog, to do the same, and set upp XPATH or REGEX extractions. I wrote a small piece on how to set up custom regex extractions, which might help, should you choose this option.


问:
How to change dataframe column names in PySpark?
I come from pandas background and am used to reading data from CSV files into a dataframe and then simply changing the column names to something useful using the simple command:

```<code>df.columns = new_column_name_list
</code>```

However, the same doesn't work in PySpark dataframes created using sqlContext.
The only solution I could figure out to do this easily is the following:

```<code>df = sqlContext.read.format("com.databricks.spark.csv").options(header='false', inferschema='true', delimiter='\t').load("data.txt")
oldSchema = df.schema
for i,k in enumerate(oldSchema.fields):
  k.name = new_column_name_list[i]
df = sqlContext.read.format("com.databricks.spark.csv").options(header='false', delimiter='\t').load("data.txt", schema=oldSchema)
</code>```

This is basically defining the variable twice and inferring the schema first then renaming the column names and then loading the dataframe again with the updated schema.

Is there a better and more efficient way to do this like we do in pandas?

My Spark version is 1.5.0

答:
We can use various approaches to rename the column name.

First, let create a simple DataFrame.

```<code>df = spark.createDataFrame([("x", 1), ("y", 2)],
                                  ["col_1", "col_2"])
</code>```

Now let's try to rename col_1 to col_3. PFB a few approaches to do the same.

```<code># Approach - 1 : using withColumnRenamed function.
df.withColumnRenamed("col_1", "col_3").show()

# Approach - 2 : using alias function.
df.select(df["col_1"].alias("col3"), "col_2").show()

# Approach - 3 : using selectExpr function.
df.selectExpr("col_1 as col_3", "col_2").show()

# Rename all columns
# Approach - 4 : using toDF function. Here you need to pass the list of all columns present in DataFrame.
df.toDF("col_3", "col_2").show()
</code>```

Here is the output.

```<code>+-----+-----+
|col_3|col_2|
+-----+-----+
|    x|    1|
|    y|    2|
+-----+-----+
</code>```

I hope this helps.

Body:
I come from pandas background and am used to reading data from CSV files into a dataframe and then simply changing the column names to something useful using the simple command:

df.columns = new_column_name_list

However, the same doesn't work in PySpark dataframes created using sqlContext.
The only solution I could figure out to do this easily is the following:

df = sqlContext.read.format("com.databricks.spark.csv").options(header='false', inferschema='true', delimiter='\t').load("data.txt")
oldSchema = df.schema
for i,k in enumerate(oldSchema.fields):
  k.name = new_column_name_list[i]
df = sqlContext.read.format("com.databricks.spark.csv").options(header='false', delimiter='\t').load("data.txt", schema=oldSchema)

This is basically defining the variable twice and inferring the schema first then renaming the column names and then loading the dataframe again with the updated schema.

Is there a better and more efficient way to do this like we do in pandas?

My Spark version is 1.5.0

Body:
We can use various approaches to rename the column name.

First, let create a simple DataFrame.

df = spark.createDataFrame([("x", 1), ("y", 2)],
                                  ["col_1", "col_2"])

Now let's try to rename col_1 to col_3. PFB a few approaches to do the same.

# Approach - 1 : using withColumnRenamed function.
df.withColumnRenamed("col_1", "col_3").show()

# Approach - 2 : using alias function.
df.select(df["col_1"].alias("col3"), "col_2").show()

# Approach - 3 : using selectExpr function.
df.selectExpr("col_1 as col_3", "col_2").show()

# Rename all columns
# Approach - 4 : using toDF function. Here you need to pass the list of all columns present in DataFrame.
df.toDF("col_3", "col_2").show()

Here is the output.

+-----+-----+
|col_3|col_2|
+-----+-----+
|    x|    1|
|    y|    2|
+-----+-----+

I hope this helps.


问:
How to make a custom method in JpaRepository from Spring Data JPA?
I'm using JpaRepository from Spring Data JPA to call a MySQL db. I know that I don't need to add metods for findById, save, etc becuse they are implemented by Spring, but I want to add a method: findByAccountNumber() and I don't know how to do that.

I tried to do in this way but it's not working:

```<code>@Repository
public interface AccountRepository extends JpaRepository<Account, Long> {

    Account findByAccountNumber(String accountNumber);
}
</code>```

Account class:

```<code>@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
@Entity
@Table(name = "account")
public class Account {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "accountId")
    private Long accountId;

    @Column(name = "accountNumber")
    private String accountNumber;

    @Column(name = "currentBalance")
    private BigDecimal currentBalance;
}
</code>```

So when I'm calling accountRepository.findByAccountNumber(accountNumber) I receive null.

```<code>CREATE TABLE `account` (
  `accountId` bigint(19) NOT NULL AUTO_INCREMENT,
  `accountNumber` varchar(100) NOT NULL,
  `currentBalance` decimal(10,5) NOT NULL,
  PRIMARY KEY (`accountId`)
)
</code>```

How can I make this method? Thank you!

答:
Maybe you need to add the org.springframework.data.repository.query.Param annotation.</p>

```<code>Account findByAccountNumber(@Param("accountNumber") String accountNumber);
</code>```

Body:
I'm using JpaRepository from Spring Data JPA to call a MySQL db. I know that I don't need to add metods for findById, save, etc becuse they are implemented by Spring, but I want to add a method: findByAccountNumber() and I don't know how to do that.

I tried to do in this way but it's not working:

@Repository
public interface AccountRepository extends JpaRepository<Account, Long> {

    Account findByAccountNumber(String accountNumber);
}

Account class:

@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
@Entity
@Table(name = "account")
public class Account {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "accountId")
    private Long accountId;

    @Column(name = "accountNumber")
    private String accountNumber;

    @Column(name = "currentBalance")
    private BigDecimal currentBalance;
}

So when I'm calling accountRepository.findByAccountNumber(accountNumber) I receive null.

CREATE TABLE `account` (
  `accountId` bigint(19) NOT NULL AUTO_INCREMENT,
  `accountNumber` varchar(100) NOT NULL,
  `currentBalance` decimal(10,5) NOT NULL,
  PRIMARY KEY (`accountId`)
)

How can I make this method? Thank you!

Body:
Maybe you need to add the org.springframework.data.repository.query.Param annotation.

Account findByAccountNumber(@Param("accountNumber") String accountNumber);


问:
Question regarding multi-threaded environment of servlet
If there is a servlet, inside a servlet container such as Websphere. The servlet are executed by some threads. I would like to ask, what does the threads share? How variables are shared between them?

Do they have a local copy of the following variables?

1) private/protected/public final Semaphore permits = new Semaphore(50);

2) private/protected/public final static Semaphore permits = new Semaphore(50);

3) private/protected/public Semaphore permits = new Semaphore(50);

4) private/protected/public static Semaphore permits = new Semaphore(50);

How should I declare the semaphore so that I can use semaphore to control them? I don't want them to have each of them a copy of the semaphore. Thanks.

答:
Servlets must be thread safe. This means your servlets should be "stateless" (unless you really know what you're doing). Essentially, use only local variables - not fields.

If you want to share state, by all means use fields of your servlet, or use classes with static fields and static getters (like the singleton pattern)


问:
vector of strings and transform with C++20 ranges
What is wrong in the following C++20 ranges basic syntax (Ubuntu 20.04, gcc g++ (Ubuntu 10-20200411-0ubuntu1) 10.0.1 20200411 (experimental) [master revision bb87d5cc77d:75961caccb7:f883c46b4877f637e0fa5025b4d6b5c9040ec566]):

```<code>#include <iostream>
#include <vector>
#include <ranges>

[[nodiscard]]
auto f(const std::vector<std::string>& vec) {
   return vec | std::views::transform([] (const std::string &f){
      return f.size(); });
}

int main() {
    const auto v = f({"c", "dddddddd", "aaaa", "bb"});
    for(auto i : v)
        std::cout << i << ' ';
    std::cout << '\n';
    return 0;
}
</code>```

I'd like to take a vector of strings and transform it to the size of each string.

Trying to iterate with C++11 range for-loop is just crashing.
In gdb, I can see that the std:: ranges view is pointing to invalid memory.

Dealing with non string using same constructs as above works fine.

答:
There is nothing wrong with your compiler. Your code has Undefined Behavior. Views are lazy evaluated and require that the underlying container is still alive when you access them. What you have is akin to a dangling reference.

{"c", "dddddddd", "aaaa", "bb"} Here you create a temporary vector which dies at the end of the full expression containing the call to f (a.k.a until the end of the line ;) and so it dies by the time you access v in for(auto i : v). The f.size(); from your lambda is not called until your for range loop. But at this point as I've said you temporary vector with all of its string elements don't exist anymore.

To help mitigate this kind of bug you can prohibit calling f with temporaries:

```<code>auto f(std::vector<std::string>&& vec) = delete;
</code>```

Body:
What is wrong in the following C++20 ranges basic syntax (Ubuntu 20.04, gcc g++ (Ubuntu 10-20200411-0ubuntu1) 10.0.1 20200411 (experimental) [master revision bb87d5cc77d:75961caccb7:f883c46b4877f637e0fa5025b4d6b5c9040ec566]):

#include <iostream>
#include <vector>
#include <ranges>

[[nodiscard]]
auto f(const std::vector<std::string>& vec) {
   return vec | std::views::transform([] (const std::string &f){
      return f.size(); });
}

int main() {
    const auto v = f({"c", "dddddddd", "aaaa", "bb"});
    for(auto i : v)
        std::cout << i << ' ';
    std::cout << '\n';
    return 0;
}

I'd like to take a vector of strings and transform it to the size of each string.

Trying to iterate with C++11 range for-loop is just crashing.
In gdb, I can see that the std:: ranges view is pointing to invalid memory.

Dealing with non string using same constructs as above works fine.

Body:
There is nothing wrong with your compiler. Your code has Undefined Behavior. Views are lazy evaluated and require that the underlying container is still alive when you access them. What you have is akin to a dangling reference.

{"c", "dddddddd", "aaaa", "bb"} Here you create a temporary vector which dies at the end of the full expression containing the call to f (a.k.a until the end of the line ;) and so it dies by the time you access v in for(auto i : v). The f.size(); from your lambda is not called until your for range loop. But at this point as I've said you temporary vector with all of its string elements don't exist anymore.

To help mitigate this kind of bug you can prohibit calling f with temporaries:

auto f(std::vector<std::string>&& vec) = delete;


问:
Combining Array-contains with == in Firebase
I have documents where I have a map field of teacher containing uid and username and in that same document I have a array field of students that contains the student id's now I want to query documents based on both field how can I merge the code below  </p>

```<code>var teacherRef = db.collection('classes')
                   .where("teacher.id", "==", localStorage.getItem("user"))

var studentRef = db.collection('classes')
                   .where("students", "array-contains", localStorage.getItem("user"))
</code>```

答:
You can combine multiple where in a single query :

var classTeacherRef = db.collection('classes')
    .where("teacher.id", "==", localStorage.getItem("user"))
    .where("students", "array-contains", localStorage.getItem("user");
```

Keep in mind that Firebase will ask you to create index for both properties to make it work.

Body:
I have documents where I have a map field of teacher containing uid and username and in that same document I have a array field of students that contains the student id's now I want to query documents based on both field how can I merge the code below

var teacherRef = db.collection('classes')
                   .where("teacher.id", "==", localStorage.getItem("user"))

var studentRef = db.collection('classes')
                   .where("students", "array-contains", localStorage.getItem("user"))

Body:
You can combine multiple where in a single query :

var classTeacherRef = db.collection('classes')
    .where("teacher.id", "==", localStorage.getItem("user"))
    .where("students", "array-contains", localStorage.getItem("user");

Keep in mind that Firebase will ask you to create index for both properties to make it work.


问:
Not able to push docker image into untrusted registry
I have configured Harbor docker registry in GCP compute engine (hostname : harbor ) , as I have not installed any certificate I am able to access the registry through http (port 80) & from client end (within same VPC of harbor registry compute engine) I have configured docker insecure registry as below

```<code>[root@client docker]# cat /etc/docker/daemon.json
{
"insecure-registries" : [
    "harbor:80",
    "<external-ip>:80",
    "10.128.0.20:80"
  ],
  "debug" : true,
  "experimental" : true
}
</code>```

but while I am trying to login into the docker registry I am getting bellow error (it's automatically hitting my registry in port 443 not 80)

```<code>[root@client docker]# docker login -u "####" -p "####" harbor

Error response from daemon: Get https://harbor/v1/users/: dial tcp 10.128.0.20:443: connect: connection refused
</code>```

Could you please help me resolve the issue

答: It seems to pick the wrong port, 443. Try adding a port explicitly: docker login -u "####" -p "####" harbor:80. Note I strongly recommend against using authentication over unencrypted channels (HTTP vs HTTPS). Perhaps docker login is smart enough to refuse to do it.

Body:
I have configured Harbor docker registry in GCP compute engine (hostname : harbor ) , as I have not installed any certificate I am able to access the registry through http (port 80) & from client end (within same VPC of harbor registry compute engine) I have configured docker insecure registry as below

[root@client docker]# cat /etc/docker/daemon.json
{
"insecure-registries" : [
    "harbor:80",
    "<external-ip>:80",
    "10.128.0.20:80"
  ],
  "debug" : true,
  "experimental" : true
}

but while I am trying to login into the docker registry I am getting bellow error (it's automatically hitting my registry in port 443 not 80)

[root@client docker]# docker login -u "####" -p "####" harbor

Error response from daemon: Get https://harbor/v1/users/: dial tcp 10.128.0.20:443: connect: connection refused

Could you please help me resolve the issue


问:
Python3: Length of values does not match length of index
I'm trying to combine pandas to retrieve the values of a number of tables in the fixtures, but on the extraction I'm also willing to include the href tags contained within the tables, however I come across an error:

The code is:

```<code>import numpy as nd
import pandas as pd
import requests
from bs4 import BeautifulSoup

url = 'http://fcf.cat/calendari/1920/futbol-11/infantil-primera-divisio/grup-1'
df = pd.read_html(url, attrs={'class': 'calendaritable'})[0]

print(df)

response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

links = []
for tr in soup.findAll("tr"):
    trs = tr.findAll("td")
    for each in trs:
        try:
            link = each.find('a')['href']
            links.append(link)
        except:
            pass

df['Links'] = links
print (df.to_string())
</code>```

答:
This script will get all information from tables, including the links:

```<code>import requests
import pandas as pd
from bs4 import BeautifulSoup

url = 'http://fcf.cat/calendari/1920/futbol-11/infantil-primera-divisio/grup-1'

soup = BeautifulSoup(requests.get(url).content, 'html.parser')

out = []
for tr in soup.select('.calendaritable tbody tr'):
    t = tr.get_text(strip=True, separator='|').split('|')
    a = tr.select_one('.calendaritablehover a')
    jornada = tr.find_previous('th', {'colspan': '4'}).get_text(strip=True)
    jornada_date = tr.find_previous('th', {'colspan': '3'}).get_text(strip=True)

    if len(t) == 4: # there's result
        out.append({'Team 1': t[0], 'Team 2': t[3], 'Goals 1': t[1], 'Goals 2': t[2], 'Jornada': jornada, 'Jornada date': jornada_date, 'Link': a['href'] if a else ''})
    else:
        out.append({'Team 1': t[0], 'Team 2': t[2], 'Goals 1': '', 'Goals 2': '', 'Jornada': jornada, 'Jornada date': jornada_date, 'Link': a['href'] if a else ''})

df = pd.DataFrame(out)
print(df)

df.to_csv('data.csv')
</code>```

Prints:

```<code>                             Team 1                    Team 2 Goals 1 Goals 2     Jornada Jornada date                                               Link
0                 CATALONIA, U.B.,A            EUROPA, C.E.,B       0       1   Jornada 1   06-10-2019  http://fcf.cat/acta/1920/futbol-11/infantil-pr...
1         FUNDACIO P. CE. JUPITER,A  ESCOLA PIA SARRIÀ S.E.,A       1       0   Jornada 1   06-10-2019  http://fcf.cat/acta/1920/futbol-11/infantil-pr...
2             Pª BARC. CINC COPES,A         MONTAÑESA, C.F.,A       1       0   Jornada 1   06-10-2019  http://fcf.cat/acta/1920/futbol-11/infantil-pr...
3            Pª BARC. BARCINO, CE,A        Pª BARC. ANGUERA,B       0       3   Jornada 1   06-10-2019  http://fcf.cat/acta/1920/futbol-11/infantil-pr...
4              DIAGONAL CLUB ESP.,A          SISTRELLS C.F.,A       8       2   Jornada 1   06-10-2019  http://fcf.cat/acta/1920/futbol-11/infantil-pr...
..                              ...                       ...     ...     ...         ...          ...                                                ...
235            DIAGONAL CLUB ESP.,A        Pª BARC. ANGUERA,B                  Jornada 30   31-05-2020
236               MONTAÑESA, C.F.,A    Pª BARC. BARCINO, CE,A                  Jornada 30   31-05-2020
237           Pª BARC. CINC COPES,A  ESCOLA PIA SARRIÀ S.E.,A                  Jornada 30   31-05-2020
238       FUNDACIO P. CE. JUPITER,A            EUROPA, C.E.,B                  Jornada 30   31-05-2020
239  L'HOSPITALET, CENTRE ESPORTS,B         CATALONIA, U.B.,A                  Jornada 30   31-05-2020

[240 rows x 7 columns]
</code>```

And produces data.csv, screenshot from Libre Office:

Body:
I'm trying to combine pandas to retrieve the values of a number of tables in the fixtures, but on the extraction I'm also willing to include the href tags contained within the tables, however I come across an error:

The code is:

import numpy as nd
import pandas as pd
import requests
from bs4 import BeautifulSoup

url = 'http://fcf.cat/calendari/1920/futbol-11/infantil-primera-divisio/grup-1'
df = pd.read_html(url, attrs={'class': 'calendaritable'})[0]

print(df)

response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

links = []
for tr in soup.findAll("tr"):
    trs = tr.findAll("td")
    for each in trs:
        try:
            link = each.find('a')['href']
            links.append(link)
        except:
            pass

df['Links'] = links
print (df.to_string())

Body:
This script will get all information from tables, including the links:

import requests
import pandas as pd
from bs4 import BeautifulSoup

url = 'http://fcf.cat/calendari/1920/futbol-11/infantil-primera-divisio/grup-1'

soup = BeautifulSoup(requests.get(url).content, 'html.parser')

out = []
for tr in soup.select('.calendaritable tbody tr'):
    t = tr.get_text(strip=True, separator='|').split('|')
    a = tr.select_one('.calendaritablehover a')
    jornada = tr.find_previous('th', {'colspan': '4'}).get_text(strip=True)
    jornada_date = tr.find_previous('th', {'colspan': '3'}).get_text(strip=True)

    if len(t) == 4: # there's result
        out.append({'Team 1': t[0], 'Team 2': t[3], 'Goals 1': t[1], 'Goals 2': t[2], 'Jornada': jornada, 'Jornada date': jornada_date, 'Link': a['href'] if a else ''})
    else:
        out.append({'Team 1': t[0], 'Team 2': t[2], 'Goals 1': '', 'Goals 2': '', 'Jornada': jornada, 'Jornada date': jornada_date, 'Link': a['href'] if a else ''})

df = pd.DataFrame(out)
print(df)

df.to_csv('data.csv')

Prints:

                             Team 1                    Team 2 Goals 1 Goals 2     Jornada Jornada date                                               Link
0                 CATALONIA, U.B.,A            EUROPA, C.E.,B       0       1   Jornada 1   06-10-2019  http://fcf.cat/acta/1920/futbol-11/infantil-pr...
1         FUNDACIO P. CE. JUPITER,A  ESCOLA PIA SARRIÀ S.E.,A       1       0   Jornada 1   06-10-2019  http://fcf.cat/acta/1920/futbol-11/infantil-pr...
2             Pª BARC. CINC COPES,A         MONTAÑESA, C.F.,A       1       0   Jornada 1   06-10-2019  http://fcf.cat/acta/1920/futbol-11/infantil-pr...
3            Pª BARC. BARCINO, CE,A        Pª BARC. ANGUERA,B       0       3   Jornada 1   06-10-2019  http://fcf.cat/acta/1920/futbol-11/infantil-pr...
4              DIAGONAL CLUB ESP.,A          SISTRELLS C.F.,A       8       2   Jornada 1   06-10-2019  http://fcf.cat/acta/1920/futbol-11/infantil-pr...
..                              ...                       ...     ...     ...         ...          ...                                                ...
235            DIAGONAL CLUB ESP.,A        Pª BARC. ANGUERA,B                  Jornada 30   31-05-2020
236               MONTAÑESA, C.F.,A    Pª BARC. BARCINO, CE,A                  Jornada 30   31-05-2020
237           Pª BARC. CINC COPES,A  ESCOLA PIA SARRIÀ S.E.,A                  Jornada 30   31-05-2020
238       FUNDACIO P. CE. JUPITER,A            EUROPA, C.E.,B                  Jornada 30   31-05-2020
239  L'HOSPITALET, CENTRE ESPORTS,B         CATALONIA, U.B.,A                  Jornada 30   31-05-2020

[240 rows x 7 columns]

And produces data.csv, screenshot from Libre Office:


问:
Performance issue when creating a list of 1000 elements in SwiftUI
I have a horizontal scroll view with lists. When scrolling horizontally, how to make the lists to snap to the edges.

```<code>struct RowView: View {
    var post: Post
    var body: some View {
        GeometryReader { geometry in
            VStack {
                Text(self.post.title)
                Text(self.post.description)
            }.frame(width: geometry.size.width, height: 200)
            //.border(Color(#colorLiteral(red: 0.1764705926, green: 0.01176470611, blue: 0.5607843399, alpha: 1)))
            .background(Color(#colorLiteral(red: 0.721568644, green: 0.8862745166, blue: 0.5921568871, alpha: 1)))
            .cornerRadius(10, antialiased: true)
            .padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
        }
    }
}

struct ListView: View {
    var n: Int
    @State var posts = [Post(id: UUID(), title: "1", description: "11"),
                        Post(id: UUID(), title: "2", description: "22"),
                        Post(id: UUID(), title: "3", description: "33")]

    var body: some View {
        GeometryReader { geometry in
            ScrollView {
                ForEach(0..<self.n) { n in
                    RowView(post: self.posts[0])
                    //.border(Color(#colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1)))
                    .frame(width: geometry.size.width, height: 200)
                }
            }
        }
    }
}

struct ContentView: View {
    init() {
        initGlobalStyles()
    }

    func initGlobalStyles() {
        UITableView.appearance().separatorColor = .clear
    }

    var body: some View {
        GeometryReader { geometry in
            NavigationView {
                ScrollView(.horizontal) {
                    HStack {
                        ForEach(0..<3) { _ in
                            ListView(n: 1000)  // crashes
                                .frame(width: geometry.size.width - 60)
                        }
                    }.padding(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 0))
                }
            }
        }
    }
}
</code>```

When I give the value of ListView(n: 1000), the view is crashing. The app launches and a white screen is shown for some time and then I get a black screen.

```<code>2019-10-06 15:52:57.644766+0530 MyApp[12366:732544] [Render] CoreAnimation: Message::send_message() returned 0x1000000e
</code>```

How to fix this? My assumption is that it would be using something like dequeue cells like UITableView, but not sure why it's crashing.

答:
I've created SwiftUI horizontal list which loads views only for visible objects + extra elements as a buffer. Moreover, it exposes the offset parameter as binding so you can follow it or modify it from outside.

You can access source code here HList

Give it a go! This example is prepared in the swift playground.

Example use case

```<code>struct ContentView: View {
    @State public var offset: CGFloat = 0

    var body: some View {
        HList(offset: self.$offset, numberOfItems: 10000, itemWidth: 80) { index in
            Text("\(index)")
        }
    }
}
</code>```

To see content being reused in action you could do something like this

```<code>struct ContentView: View {
    @State public var offset: CGFloat = 0

    var body: some View {
        HList(offset: self.$offset, numberOfItems: 10000, itemWidth: 80) { index in
            Text("\(index)")
        }
        .frame(width: 200, height: 60)
        .border(Color.black, width: 2)
        .clipped()
    }
}
</code>```

If you do remove .clipped() at the end you will see how the extra component is reused while scrolling when it moves out of the frame.

Update

While the above solution is still valid, however, it is a custom component.
With WWDC2020 SwiftUI introduces lazy components such as LazyHStack but keep in mind that:

The stack is “lazy,” in that the stack view doesn’t create items until it needs to render them onscreen.

Meaning, elements are loaded lazy but after that, they are kept in the memory.

My custom HList only refers to visible components. Not the one which already has appeared.

Body:
I have a horizontal scroll view with lists. When scrolling horizontally, how to make the lists to snap to the edges.

struct RowView: View {
    var post: Post
    var body: some View {
        GeometryReader { geometry in
            VStack {
                Text(self.post.title)
                Text(self.post.description)
            }.frame(width: geometry.size.width, height: 200)
            //.border(Color(#colorLiteral(red: 0.1764705926, green: 0.01176470611, blue: 0.5607843399, alpha: 1)))
            .background(Color(#colorLiteral(red: 0.721568644, green: 0.8862745166, blue: 0.5921568871, alpha: 1)))
            .cornerRadius(10, antialiased: true)
            .padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
        }
    }
}

struct ListView: View {
    var n: Int
    @State var posts = [Post(id: UUID(), title: "1", description: "11"),
                        Post(id: UUID(), title: "2", description: "22"),
                        Post(id: UUID(), title: "3", description: "33")]

    var body: some View {
        GeometryReader { geometry in
            ScrollView {
                ForEach(0..<self.n) { n in
                    RowView(post: self.posts[0])
                    //.border(Color(#colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1)))
                    .frame(width: geometry.size.width, height: 200)
                }
            }
        }
    }
}

struct ContentView: View {
    init() {
        initGlobalStyles()
    }

    func initGlobalStyles() {
        UITableView.appearance().separatorColor = .clear
    }

    var body: some View {
        GeometryReader { geometry in
            NavigationView {
                ScrollView(.horizontal) {
                    HStack {
                        ForEach(0..<3) { _ in
                            ListView(n: 1000)  // crashes
                                .frame(width: geometry.size.width - 60)
                        }
                    }.padding(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 0))
                }
            }
        }
    }
}

When I give the value of ListView(n: 1000), the view is crashing. The app launches and a white screen is shown for some time and then I get a black screen.

2019-10-06 15:52:57.644766+0530 MyApp[12366:732544] [Render] CoreAnimation: Message::send_message() returned 0x1000000e

How to fix this? My assumption is that it would be using something like dequeue cells like UITableView, but not sure why it's crashing.

Body:
I've created SwiftUI horizontal list which loads views only for visible objects + extra elements as a buffer. Moreover, it exposes the offset parameter as binding so you can follow it or modify it from outside.

You can access source code here HList

Give it a go! This example is prepared in the swift playground.

Example use case

struct ContentView: View {
    @State public var offset: CGFloat = 0

    var body: some View {
        HList(offset: self.$offset, numberOfItems: 10000, itemWidth: 80) { index in
            Text("\(index)")
        }
    }
}

To see content being reused in action you could do something like this

struct ContentView: View {
    @State public var offset: CGFloat = 0

    var body: some View {
        HList(offset: self.$offset, numberOfItems: 10000, itemWidth: 80) { index in
            Text("\(index)")
        }
        .frame(width: 200, height: 60)
        .border(Color.black, width: 2)
        .clipped()
    }
}

If you do remove .clipped() at the end you will see how the extra component is reused while scrolling when it moves out of the frame.

Update

While the above solution is still valid, however, it is a custom component.
With WWDC2020 SwiftUI introduces lazy components such as LazyHStack but keep in mind that:

The stack is “lazy,” in that the stack view doesn’t create items until it needs to render them onscreen.

Meaning, elements are loaded lazy but after that, they are kept in the memory.

My custom HList only refers to visible components. Not the one which already has appeared.


问:
What are the benefits of using the real image height and width?
What are the benefits to using an images real height and width when rendering HTML?  That is if I have an image that 100x100 pixels but I want to display something that is 95x95 pixels, should I resize the image on the server or can I let the browser handle this?  I'm really looking for a general rule along with the reason.  Thanks.</p>

```<code><img src="image.jpg" style="width: 95px; height: 95px;" alt="an image" />
</code>```

答:
Just re-size the image. Otherwise the full 100X100 image will be loaded (which weighs more than 95x95 - and difference in size gets bigger the more you're trying to scale it with html). So it'll take an unnecessary long time to load an image that will not be displayed in its full size. If you scale them down a lot using html and you have a lot of images on the page - that's a lot of wasted traffic and reduced speed.

The whole width/height thing was used when connection was very slow and everyone used phone lines with ancient modems - that way you could see the proper layout of the page before all images were loaded (and it took a while to see all images after seeing the page with all the text).