问:
How to access sqlite database files in remote server(ubuntu) using python script in local computer
I am aware that SQLite works well for an embedded system but I am trying to set up a database system with different types of database such as MySQL, through API and SQLite.

The problem is that SQLite data files are stored in Ubuntu server and I want to connect remotely by using its ssh path from a user's computer.

I have tried to connect with paramiko which was successful to execute general command like 'ifconfig'. However, when I execute SQLite command, it didn't work.

```<code>import paramiko

cmd = 'ifconfig'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(remote_ip, username =username, password=pw, port=port)
(stdin, stdout, stderr) = ssh.exec_command(cmd)
</code>```

Is there any way to directly write an ssh path to connect?

The example Code is below:

```<code>import sqlite3
conn = sqlite3.connect('example.db')
</code>```

答:
I just figured this out using Paramiko smashing together a few suggestions from places.  It feels a little hacky, but I have a basic need to do some bulk checks on several things in a Python script, one of which is checking for a value in the sqlite3 db on several servers.  This works for me:</p>

```<code>import paramiko
from paramiko import SSHClient

ssh = SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host=hostname, username='username', password='password')
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('sqlite3 /path/to/yourdb.sqlite3 "select * from table;"')
stdout=ssh_stdout.readlines()
print(stdout)
</code>```

Body:
I am aware that SQLite works well for an embedded system but I am trying to set up a database system with different types of database such as MySQL, through API and SQLite.

The problem is that SQLite data files are stored in Ubuntu server and I want to connect remotely by using its ssh path from a user's computer.

I have tried to connect with paramiko which was successful to execute general command like 'ifconfig'. However, when I execute SQLite command, it didn't work.

import paramiko

cmd = 'ifconfig'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(remote_ip, username =username, password=pw, port=port)
(stdin, stdout, stderr) = ssh.exec_command(cmd)

Is there any way to directly write an ssh path to connect?

The example Code is below:

import sqlite3
conn = sqlite3.connect('example.db')

Body:
I just figured this out using Paramiko smashing together a few suggestions from places.  It feels a little hacky, but I have a basic need to do some bulk checks on several things in a Python script, one of which is checking for a value in the sqlite3 db on several servers.  This works for me:

import paramiko
from paramiko import SSHClient

ssh = SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host=hostname, username='username', password='password')
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('sqlite3 /path/to/yourdb.sqlite3 "select * from table;"')
stdout=ssh_stdout.readlines()
print(stdout)


来源: stackexchange

问:
How to output to txt (Programming in Python with Processing 3)
I'm currently working on a project and a part of the project is to output something to the project directory in a sepereate .txt file, I have completed that but I have a problem, everything works GREAT but I don't want to create a new file every single time but I want to have everything and all records stored in only one file and that they just keep adding up, can someone help me?

Here's a part of the code I've came up with, don't bother about the "%d" etc. I just need help with output :

```<code>output = createWriter("rekordi.txt")
            output.print("Tvoj zadnji rekord je " + str(millis()/1000-sekunde) + " sekund || ob " + str(datum.strftime("%I:" + "%M" + " %p" + " na " + "%d." + "%b"))) # Write the date to the file
            output.flush()# Writes the remaining data to the file
            output.close()# Finishes the file
</code>```

答:
What you want to do is open a file in append mode. This will create it if it doesn't exist, and will append to it instead of overwriting it if it does already exist. Something like this should do what you want:

```<code>my_file_path = 'output_record.txt'
with open(my_file_path, 'a') as outfile:
    outfile.write(<output data here in string format> + '\n') # \n for newline
</code>```

The with ... is a context manager block, which means that the file will automatically be closed when that code block exits. And the 'a' second argument to open specifies append mode.

Hope that helps, Happy Coding (and happy Friday)!

ContentLicense: CC BY-SA 4.0

Body:
I'm currently working on a project and a part of the project is to output something to the project directory in a sepereate .txt file, I have completed that but I have a problem, everything works GREAT but I don't want to create a new file every single time but I want to have everything and all records stored in only one file and that they just keep adding up, can someone help me?

Here's a part of the code I've came up with, don't bother about the "%d" etc. I just need help with output :

output = createWriter("rekordi.txt")
            output.print("Tvoj zadnji rekord je " + str(millis()/1000-sekunde) + " sekund || ob " + str(datum.strftime("%I:" + "%M" + " %p" + " na " + "%d." + "%b"))) # Write the date to the file
            output.flush()# Writes the remaining data to the file
            output.close()# Finishes the file

Body:
What you want to do is open a file in append mode. This will create it if it doesn't exist, and will append to it instead of overwriting it if it does already exist. Something like this should do what you want:

my_file_path = 'output_record.txt'
with open(my_file_path, 'a') as outfile:
    outfile.write(<output data here in string format> + '\n') # \n for newline

The with ... is a context manager block, which means that the file will automatically be closed when that code block exits. And the 'a' second argument to open specifies append mode.

Hope that helps, Happy Coding (and happy Friday)!


问:
How can i read this type of json objects in a my sql table

I have this type of json data in a mysql table. how can i read them

[
    {
        "price": "1000",
        "itemcode": "1",
        "itemname": "Break Pads",
        "quantity": "1"
    },
    {
        "price": "800",
        "itemcode": "3",
        "itemname": "Break Oil",
        "quantity": "1"
    }
]
```

答:
In MySQL 5.7, where JSON_TABLE() is not available, a typical solution uses a table of numbers.

```<code>select
    d.*,
    json_unquote(json_extract(
        d.items,
        concat('$[', n.i, '].price')
    )) price,
    json_unquote(json_extract(
        d.items,
        concat('$[', n.i, '].itemcode')
    )) itemcode,
    json_unquote(json_extract(
        d.items,
        concat('$[', n.i, '].itemname')
    )) itemname,
    json_unquote(json_extract(
        d.items,
        concat('$[', n.i, '].quantity')
    )) quantity
from deals d
inner join (
    select 0 i
    union all select 1
    union all select 2
    union all select 3
) n
    on n.i < json_length(d.items)
</code>```

This would handle up to 4 objects per array. If you need more, you can extend the subquery with more union alls.

Body:
In MySQL 5.7, where JSON_TABLE() is not available, a typical solution uses a table of numbers.

select
    d.*,
    json_unquote(json_extract(
        d.items,
        concat('$[', n.i, '].price')
    )) price,
    json_unquote(json_extract(
        d.items,
        concat('$[', n.i, '].itemcode')
    )) itemcode,
    json_unquote(json_extract(
        d.items,
        concat('$[', n.i, '].itemname')
    )) itemname,
    json_unquote(json_extract(
        d.items,
        concat('$[', n.i, '].quantity')
    )) quantity
from deals d
inner join (
    select 0 i
    union all select 1
    union all select 2
    union all select 3
) n
    on n.i < json_length(d.items)

This would handle up to 4 objects per array. If you need more, you can extend the subquery with more union alls.


问:
/usr/bin/ld: undefined reference to static library
I got the following cmake file:

```<code>cmake_minimum_required(VERSION 3.17)
project(blsbench2)

set(CMAKE_CXX_STANDARD 14)
set(SOURCE_FILES main.cpp)

INCLUDE_DIRECTORIES(../../Documents/projects/bls-signatures/src)
LINK_DIRECTORIES(../../Documents/projects/bls-signatures/build/src)
LINK_DIRECTORIES(../../Documents/projects/bls-signatures/build/object_blstmp)

INCLUDE_DIRECTORIES(/usr/local/include/relic/)
LINK_DIRECTORIES(/usr/local/lib/)

add_executable(blsbench2 ${SOURCE_FILES})

TARGET_LINK_LIBRARIES(blsbench2 bls relic)
</code>```

And the following program

```<code>#include <iostream>
#include <bls.hpp>

using namespace bls;
using namespace std;

int main()
{
    std::cout << "Hello, World!" << std::endl;

    uint8_t seed[] = {0, 50, 6, 244, 24, 199, 1, 25, 52, 88, 192,
                      19, 18, 12, 89, 6, 220, 18, 102, 58, 209,
                      82, 12, 62, 89, 110, 182, 9, 44, 20, 254, 22};

    PrivateKey sk = PrivateKey::FromSeed(seed, sizeof(seed));
    PublicKey pk = sk.GetPublicKey();

    uint8_t msg[] = {100, 2, 254, 88, 90, 45, 23};

    Signature sig = sk.Sign(msg, sizeof(msg));

    return 0;
}
</code>```

I'm working with CLion and the setup above allows me to include the library and use function auto completion.

The problem arises when I try to start running the program.

```<code>/usr/bin/ld: CMakeFiles/blsbench2.dir/main.cpp.o: in function `main':
/home/ray/CLionProjects/blsbench2/main.cpp:16: undefined reference to `bls::PrivateKey::FromSeed(unsigned char const*, unsigned long)'
/usr/bin/ld: /home/ray/CLionProjects/blsbench2/main.cpp:17: undefined reference to `bls::PrivateKey::GetPublicKey() const'
/usr/bin/ld: /home/ray/CLionProjects/blsbench2/main.cpp:21: undefined reference to `bls::PrivateKey::Sign(unsigned char const*, unsigned long) const'
/usr/bin/ld: /home/ray/CLionProjects/blsbench2/main.cpp:16: undefined reference to `bls::PrivateKey::~PrivateKey()'
/usr/bin/ld: /home/ray/CLionProjects/blsbench2/main.cpp:16: undefined reference to `bls::PrivateKey::~PrivateKey()'
/usr/bin/ld: CMakeFiles/blsbench2.dir/main.cpp.o: in function `bls::Signature::~Signature()':
/home/ray/CLionProjects/blsbench2/../../Documents/projects/bls-signatures/src/signature.hpp:101: undefined reference to `bls::AggregationInfo::~AggregationInfo()'
collect2: error: ld returned 1 exit status
</code>```

I searched a bit on the internet and it said at a few places that this is due to the lack of .so files (might be mistaken here). However, the library builds a .a file which should be enough.

答:
As another user in the answers pointed out I went after the library maintainers.

The main problem was that they were
a) Running a heavily modified version of relic.
b) Spread it over 2 folders.

The solution:

a) As antoine pointed out including blstmp instead of bls
b) Including relic_s instead of relic
c) Including relic from the correct directories.

```<code>INCLUDE_DIRECTORIES(../../Documents/projects/bls-signatures/src)
LINK_DIRECTORIES(../../Documents/projects/bls-signatures/build/src)

LINK_DIRECTORIES(../../Documents/projects/bls-signatures/build/contrib/relic/lib)
INCLUDE_DIRECTORIES(../../Documents/projects/bls-signatures/build/contrib/relic/include)
INCLUDE_DIRECTORIES(../../Documents/projects/bls-signatures/contrib/relic/include)

add_executable(blsbench2 ${SOURCE_FILES})

TARGET_LINK_LIBRARIES(blsbench2 blstmp relic_s)
</code>```

Body:
I got the following cmake file:

cmake_minimum_required(VERSION 3.17)
project(blsbench2)

set(CMAKE_CXX_STANDARD 14)
set(SOURCE_FILES main.cpp)

INCLUDE_DIRECTORIES(../../Documents/projects/bls-signatures/src)
LINK_DIRECTORIES(../../Documents/projects/bls-signatures/build/src)
LINK_DIRECTORIES(../../Documents/projects/bls-signatures/build/object_blstmp)

INCLUDE_DIRECTORIES(/usr/local/include/relic/)
LINK_DIRECTORIES(/usr/local/lib/)

add_executable(blsbench2 ${SOURCE_FILES})

TARGET_LINK_LIBRARIES(blsbench2 bls relic)

And the following program

#include <iostream>
#include <bls.hpp>

using namespace bls;
using namespace std;

int main()
{
    std::cout << "Hello, World!" << std::endl;

    uint8_t seed[] = {0, 50, 6, 244, 24, 199, 1, 25, 52, 88, 192,
                      19, 18, 12, 89, 6, 220, 18, 102, 58, 209,
                      82, 12, 62, 89, 110, 182, 9, 44, 20, 254, 22};

    PrivateKey sk = PrivateKey::FromSeed(seed, sizeof(seed));
    PublicKey pk = sk.GetPublicKey();

    uint8_t msg[] = {100, 2, 254, 88, 90, 45, 23};

    Signature sig = sk.Sign(msg, sizeof(msg));

    return 0;
}

I'm working with CLion and the setup above allows me to include the library and use function auto completion.

The problem arises when I try to start running the program.

/usr/bin/ld: CMakeFiles/blsbench2.dir/main.cpp.o: in function `main':
/home/ray/CLionProjects/blsbench2/main.cpp:16: undefined reference to `bls::PrivateKey::FromSeed(unsigned char const*, unsigned long)'
/usr/bin/ld: /home/ray/CLionProjects/blsbench2/main.cpp:17: undefined reference to `bls::PrivateKey::GetPublicKey() const'
/usr/bin/ld: /home/ray/CLionProjects/blsbench2/main.cpp:21: undefined reference to `bls::PrivateKey::Sign(unsigned char const*, unsigned long) const'
/usr/bin/ld: /home/ray/CLionProjects/blsbench2/main.cpp:16: undefined reference to `bls::PrivateKey::~PrivateKey()'
/usr/bin/ld: /home/ray/CLionProjects/blsbench2/main.cpp:16: undefined reference to `bls::PrivateKey::~PrivateKey()'
/usr/bin/ld: CMakeFiles/blsbench2.dir/main.cpp.o: in function `bls::Signature::~Signature()':
/home/ray/CLionProjects/blsbench2/../../Documents/projects/bls-signatures/src/signature.hpp:101: undefined reference to `bls::AggregationInfo::~AggregationInfo()'
collect2: error: ld returned 1 exit status

I searched a bit on the internet and it said at a few places that this is due to the lack of .so files (might be mistaken here). However, the library builds a .a file which should be enough.

Body:
As another user in the answers pointed out I went after the library maintainers.

The main problem was that they were
a) Running a heavily modified version of relic.
b) Spread it over 2 folders.

The solution:

a) As antoine pointed out including blstmp instead of bls
b) Including relic_s instead of relic
c) Including relic from the correct directories.

INCLUDE_DIRECTORIES(../../Documents/projects/bls-signatures/src)
LINK_DIRECTORIES(../../Documents/projects/bls-signatures/build/src)

LINK_DIRECTORIES(../../Documents/projects/bls-signatures/build/contrib/relic/lib)
INCLUDE_DIRECTORIES(../../Documents/projects/bls-signatures/build/contrib/relic/include)
INCLUDE_DIRECTORIES(../../Documents/projects/bls-signatures/contrib/relic/include)

add_executable(blsbench2 ${SOURCE_FILES})

TARGET_LINK_LIBRARIES(blsbench2 blstmp relic_s)


问:
Comparing Given String To An Array sub property
I'm building an array of players which will be added to when solver is not found within the name properties inside players

```<code>let players = []

let solver = 'Any Name Given'

// This if statement is the issue : How to check the name properties and compare to solver
// If the solver's name is already in players : add +1 point
if(players.includes(solver)){

   // Give The Player +1 point

   return console.log('Player Exists')

 } else {

   // Add The newPlayer to players with a starting point
   let newPlayer = [name = solver, points = 1]
   players.push(newPlayer)

}

</code>```

How do I compare solver inside name of players. I've tried players[name] and players.name with no luck

答:
In your else, you should be having:

```<code>const newPlayer = {name: solver, points: 1};
</code>```

i.e. an object, rather than an array. So that you have players array which will always have player objects

Now, since what you have is an array of objects, you need to use something like some to find whether an object matching your condition exists or not:

The if condition can be replaced by:

```<code>if (players.some(player => player.name === solver))
</code>```

I just saw that you want to increase the points of the found player by 1. In that case you should be using find instead of some so that you can access the found player and update its points property. So do this:

```<code>const player = players.find(player => player.name === solver);

if (player) {
    player.points++;
} else {
    const newPlayer = {name: solver, points: 1};
    players.push(newPlayer)
}

</code>```

Body:
I'm building an array of players which will be added to when solver is not found within the name properties inside players

let players = []

let solver = 'Any Name Given'

// This if statement is the issue : How to check the name properties and compare to solver
// If the solver's name is already in players : add +1 point
if(players.includes(solver)){

   // Give The Player +1 point

   return console.log('Player Exists')

 } else {

   // Add The newPlayer to players with a starting point
   let newPlayer = [name = solver, points = 1]
   players.push(newPlayer)

}

How do I compare solver inside name of players. I've tried players[name] and players.name with no luck

Body:
In your else, you should be having:

const newPlayer = {name: solver, points: 1};

i.e. an object, rather than an array. So that you have players array which will always have player objects

Now, since what you have is an array of objects, you need to use something like some to find whether an object matching your condition exists or not:

The if condition can be replaced by:

if (players.some(player => player.name === solver))

I just saw that you want to increase the points of the found player by 1. In that case you should be using find instead of some so that you can access the found player and update its points property. So do this:

const player = players.find(player => player.name === solver);

if (player) {
    player.points++;
} else {
    const newPlayer = {name: solver, points: 1};
    players.push(newPlayer)
}


问:
Printing number of rows in Laravel
I am trying to print number of rows in Laravel from MySQL but i get this error:
htmlspecialchars() expects parameter 1 to be string, object given (View: C:\wamp64\www\kont\resources\views\profile.blade.php)

I have two function inside my model. First function returns information about user from one table and another function counts number of friends for that user from another table. Please view my code below:

HomeController.php

```<code>public function profile(Request $request,$id){
        $model = new UserModel();
 $podaciIzBaze = $model->userdata($id);
 $data = array();
 $data['dt'] = $podaciIzBaze;

$model2 = new UserModel();
 $podaciIzBaze2 = $model2->countfriends($id);

 $data['dt2'] = $podaciIzBaze2;

         return view('profile',$data);

    }
</code>```

UserModel.php

```<code>  class UserModel extends Model
    {
        //
        public function userdata($id){
            $query = DB::select("SELECT first_name,last_name,email,website,birth_date FROM users where id = $id");
            return $query;
        }

        public function countfriends($id){

            $query=DB::SELECT("SELECT count(user_id) from user_friend where user_id = $id");
            return $query;

        }
</code>```

profile.blade.php

```<code> @foreach($dt as $d)
                                 <tr>
                                    <td>Ime:</td>
                                    <td>{{ $d->first_name }}</td>
                                 </tr>
                                 <tr>
                                    <td>Prezime</td>
                                    <td>{{ $d->last_name }}</td>
                                 </tr>
                                 <tr>
                                    <td>Datum Rodjenja</td>
                                    <td>{{ $d->birth_date }}</td>
                                 </tr>
                                 <tr>
                                 <tr>
                                    <td>Pol</td>
                                    <td>Musko</td>
                                 </tr>
                                 <tr>
                                    <td>Email</td>
                                    <td><a href="mailto:info@support.com">{{ $d->email }}</a></td>
                                 </tr>
                                 <td>Website</td>
                                 <td>
                                   {{ $d->website }}
                                 </td>
                                 </tr>
                                     @endforeach

                       @foreach($dt2 as $d2)
                     Number of friends: {{ $d }}
                     @endforeach
</code>```

答:
The DB::select returns an array of results.  You should use

```<code>$data['dt'] = $podaciIzBaze[0];
</code>```

However, a more elegant way of doing this is as follows:

```<code>$data['dt'] = UserModel::find($id);
</code>```

The find method returns the first row of the model in which the primary key equals $id

Title: Printing number of rows in Laravel

Body:
I am trying to print number of rows in Laravel from MySQL but i get this error:
htmlspecialchars() expects parameter 1 to be string, object given (View: C:\wamp64\www\kont\resources\views\profile.blade.php)

I have two function inside my model. First function returns information about user from one table and another function counts number of friends for that user from another table. Please view my code below:

HomeController.php

public function profile(Request $request,$id){
        $model = new UserModel();
 $podaciIzBaze = $model->userdata($id);
 $data = array();
 $data['dt'] = $podaciIzBaze;

$model2 = new UserModel();
 $podaciIzBaze2 = $model2->countfriends($id);

 $data['dt2'] = $podaciIzBaze2;

         return view('profile',$data);

    }

UserModel.php

  class UserModel extends Model
    {
        //
        public function userdata($id){
            $query = DB::select("SELECT first_name,last_name,email,website,birth_date FROM users where id = $id");
            return $query;
        }

        public function countfriends($id){

            $query=DB::SELECT("SELECT count(user_id) from user_friend where user_id = $id");
            return $query;

        }

profile.blade.php

 @foreach($dt as $d)

                                    Ime:
                                    {{ $d->first_name }}

                                    Prezime
                                    {{ $d->last_name }}

                                    Datum Rodjenja
                                    {{ $d->birth_date }}

                                    Pol
                                    Musko

                                    Email
                                    {{ $d->email }}

                                 Website

                                   {{ $d->website }}

                                     @endforeach

                       @foreach($dt2 as $d2)
                     Number of friends: {{ $d }}
                     @endforeach

Body:
The DB::select returns an array of results.  You should use

$data['dt'] = $podaciIzBaze[0];

However, a more elegant way of doing this is as follows:

$data['dt'] = UserModel::find($id);

The find method returns the first row of the model in which the primary key equals $id


问:
Javascript: Flatten each array item containing nested object
I need to flatten an array where each item contains a nested object, as below:

```<code>[
  {
    a: "x",
    b: { b1: "x1", b2: "x2"}
  },
  {
    a: "y",
    b: { b1: "y1", b2: "y2"}
  }
]
</code>```

to

```<code>[
  {
    a: "x",
    b1: "x1",
    b2: "x2"
  },
  {
    a: "y",
    b1: "y1",
    b2: "y2"
  }
]
</code>```

This here is the closest to what I'm looking for https://stackoverflow.com/a/33037683/4217097
However, I'm not sure how to use that solution for an array, as it only return the last item of the array when I tried applying it.

答:
You can do something like:

const source = [
  {
    a: "x",
    b: { b1: "x1", b2: "x2"}
  },
  {
    a: "y",
    b: { b1: "y1", b2: "y2"}
  }
]

const transformed = source.map(item => ({ ...item.b, a: item.a }));

console.log(transformed)```

Map your source to a new object by grabbing a and spreading b into it.

Body:
I need to flatten an array where each item contains a nested object, as below:

[
  {
    a: "x",
    b: { b1: "x1", b2: "x2"}
  },
  {
    a: "y",
    b: { b1: "y1", b2: "y2"}
  }
]

to

[
  {
    a: "x",
    b1: "x1",
    b2: "x2"
  },
  {
    a: "y",
    b1: "y1",
    b2: "y2"
  }
]

This here is the closest to what I'm looking for https://stackoverflow.com/a/33037683/4217097
However, I'm not sure how to use that solution for an array, as it only return the last item of the array when I tried applying it.

Body:
You can do something like:

const source = [
  {
    a: "x",
    b: { b1: "x1", b2: "x2"}
  },
  {
    a: "y",
    b: { b1: "y1", b2: "y2"}
  }
]

const transformed = source.map(item => ({ ...item.b, a: item.a }));

console.log(transformed)

Map your source to a new object by grabbing a and spreading b into it.


问:
Authentication for .NET Core Razor Pages application doesn't work for views without an "/Identity" route while using .AddIdentityServerJwt()
Using the .NET Core 3.1 framework, I'm trying to configure a web platform with the following setup:

A Razor Pages application, that acts as the landing page for the platform with features/pages such as advertising the platform, cookie consent, privacy policy, contacts, and the pages that come with Identity (e.g., login, register, manage account).

Authentication for the Razor Pages application is performed in the standard Identity way.

An Angular SPA, that is only accessible after the user is logged in.

OIDC configuration with Identity Server in order to add authentication and authorisation to the Angular SPA.

All of these three components (Razor Pages + Angular + Identity Server) are bundled into one single .NET Core web project. I have also scaffolded Identity so that I am able to customise the look and behaviour of the pages.

I was able to almost configure the application the way I want it, by basically mixing the code of the startup templates of the Razor Pages option (with user accounts stored locally) and the Angular template option (with user accounts stored locally) and with a bit of trial and error and investigation.

The current status of my application is:

The user logs in in the Razor Pages application.

The login is successful and the email is displayed on the navigation bar.

When we navigate to the SPA, my Angular app tries to silently login and is successful:

localhost:5001/Dashboard (Angular SPA home route)

If we navigate to a part of the Razor Pages application that does not have the /Identity route (which is only used for the pages that come with Identity) the cookies appear to no longer contain the right information and I have no session in those routes. This means that, for example, if I am using the SignInManager.IsSignedIn(User) to only display a navigation option to an Administration page that is protected with an options.Conventions.AuthorizePage($"/Administration"), if I am in a URL that has the Identity route, the navigation tab will be displayed, otherwise it will not be displayed:

localhost:5001/Identity/Account/Login

localhost:5001 (Razor Pages application home route)

However, even though the Administration navigation tab is being displayed when I am on a URL that has the /Identity route, if I click on it I will get a 401 unauthorised error, because the Administration page is not preceded by the /Identity route:

localhost:5001/Administration

I have managed to trace the problem to the the AddIdentityServerJwt(). Without this, the login for the Razor Pages application works as intended, but I am obviously unable to use authentication and authorisation with the Angular application afterwards.

I went to check the source code for that method and it turns out that it creates a new IdentityServerJwtPolicySchemeForwardSelector that forwards the JWT policy scheme to the DefaultIdentityUIPathPrefix which, as you might have guessed it, contains only the value "/Identity".

I have configured my Startup class in the following way:

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });
    services
        .AddDbContext<ApplicationDbContext>(optionsBuilder =>
        {
            DatabaseProviderFactory
                    .CreateDatabaseProvider(configuration, optionsBuilder);
        });
    services
        .AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddRoles<IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>();
    services
        .AddIdentityServer()
        .AddApiAuthorization<IdentityUser, ApplicationDbContext>();
    services
        .AddAuthentication()
        .AddIdentityServerJwt();
    services
        .AddControllersWithViews();
    services
            .AddRazorPages()
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.AuthorizePage($"/Administration");
            });
    services
        .AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/dist";
        });

    services.AddTransient<IEmailSender, EmailSenderService>();
    services.Configure<AuthMessageSenderOptions>(configuration);

    services.AddTransient<IProfileService, ProfileService>();
}

public void Configure(IApplicationBuilder applicationBuilder, IWebHostEnvironment webHostEnvironment)
{
    SeedData.SeedDatabase(applicationBuilder, configuration);

    if (webHostEnvironment.IsDevelopment())
    {
        applicationBuilder.UseDeveloperExceptionPage();
        applicationBuilder.UseDatabaseErrorPage();
    }
    else
    {
        applicationBuilder.UseExceptionHandler("/Error");
        applicationBuilder.UseHsts();
    }

    applicationBuilder.UseHttpsRedirection();
    applicationBuilder.UseStaticFiles();
    applicationBuilder.UseCookiePolicy();

    if (!webHostEnvironment.IsDevelopment())
    {
        applicationBuilder.UseSpaStaticFiles();
    }

    applicationBuilder.UseRouting();

    applicationBuilder.UseAuthentication();
    applicationBuilder.UseIdentityServer();
    applicationBuilder.UseAuthorization();
    applicationBuilder.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller}/{action=Index}/{id?}");
        endpoints.MapRazorPages();
    });

    applicationBuilder.UseSpa(spa =>
    {
        spa.Options.SourcePath = "ClientApp";

        if (webHostEnvironment.IsDevelopment())
        {
            if (bool.Parse(configuration["DevelopmentConfigurations:UseProxyToSpaDevelopmentServer"]))
            {
                spa.UseProxyToSpaDevelopmentServer(configuration["DevelopmentConfigurations:ProxyToSpaDevelopmentServerAddress"]);
            }
            else
            {
                spa.UseAngularCliServer(npmScript: configuration["DevelopmentConfigurations:AngularCliServerNpmScript"]);
            }
        }
    });
}
```

How can I configure my application so that the session is available across my entire application and not just on URLs that have the "/Identity" route while maintaining both authentication and authorisation for the Razor Pages application and the Angular application?

答:
I had the same problem and solved it by adding my own PolicyScheme that decides which type of authentication should be used based on the request path. All my razor pages have a path starting with "/Identity" or "/Server" and all other requests should use JWT.

I set this up in ConfigureServices using the collowing coding:

```<code>// Add authentication using JWT and add a policy scheme to decide which type of authentication should be used
services.AddAuthentication()
    .AddIdentityServerJwt()
    .AddPolicyScheme("ApplicationDefinedAuthentication", null, options =>
    {
        options.ForwardDefaultSelector = (context) =>
        {
            if (context.Request.Path.StartsWithSegments(new PathString("/Identity"), StringComparison.OrdinalIgnoreCase) ||
                context.Request.Path.StartsWithSegments(new PathString("/Server"), StringComparison.OrdinalIgnoreCase))
                return IdentityConstants.ApplicationScheme;
            else
                return IdentityServerJwtConstants.IdentityServerJwtBearerScheme;
        };
    });

// Use own policy scheme instead of default policy scheme that was set in method AddIdentityServerJwt
services.Configure<AuthenticationOptions>(options => options.DefaultScheme = "ApplicationDefinedAuthentication");
</code>```

Body:
Using the .NET Core 3.1 framework, I'm trying to configure a web platform with the following setup:

A Razor Pages application, that acts as the landing page for the platform with features/pages such as advertising the platform, cookie consent, privacy policy, contacts, and the pages that come with Identity (e.g., login, register, manage account).

Authentication for the Razor Pages application is performed in the standard Identity way.

An Angular SPA, that is only accessible after the user is logged in.

OIDC configuration with Identity Server in order to add authentication and authorisation to the Angular SPA.

All of these three components (Razor Pages + Angular + Identity Server) are bundled into one single .NET Core web project. I have also scaffolded Identity so that I am able to customise the look and behaviour of the pages.

I was able to almost configure the application the way I want it, by basically mixing the code of the startup templates of the Razor Pages option (with user accounts stored locally) and the Angular template option (with user accounts stored locally) and with a bit of trial and error and investigation.

The current status of my application is:

The user logs in in the Razor Pages application.

The login is successful and the email is displayed on the navigation bar.

When we navigate to the SPA, my Angular app tries to silently login and is successful:

localhost:5001/Dashboard (Angular SPA home route)

If we navigate to a part of the Razor Pages application that does not have the /Identity route (which is only used for the pages that come with Identity) the cookies appear to no longer contain the right information and I have no session in those routes. This means that, for example, if I am using the SignInManager.IsSignedIn(User) to only display a navigation option to an Administration page that is protected with an options.Conventions.AuthorizePage($"/Administration"), if I am in a URL that has the Identity route, the navigation tab will be displayed, otherwise it will not be displayed:

localhost:5001/Identity/Account/Login

localhost:5001 (Razor Pages application home route)

However, even though the Administration navigation tab is being displayed when I am on a URL that has the /Identity route, if I click on it I will get a 401 unauthorised error, because the Administration page is not preceded by the /Identity route:

localhost:5001/Administration

I have managed to trace the problem to the the AddIdentityServerJwt(). Without this, the login for the Razor Pages application works as intended, but I am obviously unable to use authentication and authorisation with the Angular application afterwards.

I went to check the source code for that method and it turns out that it creates a new IdentityServerJwtPolicySchemeForwardSelector that forwards the JWT policy scheme to the DefaultIdentityUIPathPrefix which, as you might have guessed it, contains only the value "/Identity".

I have configured my Startup class in the following way:

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });
    services
        .AddDbContext<ApplicationDbContext>(optionsBuilder =>
        {
            DatabaseProviderFactory
                    .CreateDatabaseProvider(configuration, optionsBuilder);
        });
    services
        .AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddRoles<IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>();
    services
        .AddIdentityServer()
        .AddApiAuthorization<IdentityUser, ApplicationDbContext>();
    services
        .AddAuthentication()
        .AddIdentityServerJwt();
    services
        .AddControllersWithViews();
    services
            .AddRazorPages()
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.AuthorizePage($"/Administration");
            });
    services
        .AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/dist";
        });

    services.AddTransient<IEmailSender, EmailSenderService>();
    services.Configure<AuthMessageSenderOptions>(configuration);

    services.AddTransient<IProfileService, ProfileService>();
}

public void Configure(IApplicationBuilder applicationBuilder, IWebHostEnvironment webHostEnvironment)
{
    SeedData.SeedDatabase(applicationBuilder, configuration);

    if (webHostEnvironment.IsDevelopment())
    {
        applicationBuilder.UseDeveloperExceptionPage();
        applicationBuilder.UseDatabaseErrorPage();
    }
    else
    {
        applicationBuilder.UseExceptionHandler("/Error");
        applicationBuilder.UseHsts();
    }

    applicationBuilder.UseHttpsRedirection();
    applicationBuilder.UseStaticFiles();
    applicationBuilder.UseCookiePolicy();

    if (!webHostEnvironment.IsDevelopment())
    {
        applicationBuilder.UseSpaStaticFiles();
    }

    applicationBuilder.UseRouting();

    applicationBuilder.UseAuthentication();
    applicationBuilder.UseIdentityServer();
    applicationBuilder.UseAuthorization();
    applicationBuilder.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller}/{action=Index}/{id?}");
        endpoints.MapRazorPages();
    });

    applicationBuilder.UseSpa(spa =>
    {
        spa.Options.SourcePath = "ClientApp";

        if (webHostEnvironment.IsDevelopment())
        {
            if (bool.Parse(configuration["DevelopmentConfigurations:UseProxyToSpaDevelopmentServer"]))
            {
                spa.UseProxyToSpaDevelopmentServer(configuration["DevelopmentConfigurations:ProxyToSpaDevelopmentServerAddress"]);
            }
            else
            {
                spa.UseAngularCliServer(npmScript: configuration["DevelopmentConfigurations:AngularCliServerNpmScript"]);
            }
        }
    });
}

How can I configure my application so that the session is available across my entire application and not just on URLs that have the "/Identity" route while maintaining both authentication and authorisation for the Razor Pages application and the Angular application?

Body:
I had the same problem and solved it by adding my own PolicyScheme that decides which type of authentication should be used based on the request path. All my razor pages have a path starting with "/Identity" or "/Server" and all other requests should use JWT.

I set this up in ConfigureServices using the collowing coding:

// Add authentication using JWT and add a policy scheme to decide which type of authentication should be used
services.AddAuthentication()
    .AddIdentityServerJwt()
    .AddPolicyScheme("ApplicationDefinedAuthentication", null, options =>
    {
        options.ForwardDefaultSelector = (context) =>
        {
            if (context.Request.Path.StartsWithSegments(new PathString("/Identity"), StringComparison.OrdinalIgnoreCase) ||
                context.Request.Path.StartsWithSegments(new PathString("/Server"), StringComparison.OrdinalIgnoreCase))
                return IdentityConstants.ApplicationScheme;
            else
                return IdentityServerJwtConstants.IdentityServerJwtBearerScheme;
        };
    });

// Use own policy scheme instead of default policy scheme that was set in method AddIdentityServerJwt
services.Configure<AuthenticationOptions>(options => options.DefaultScheme = "ApplicationDefinedAuthentication");


问:
Flitered noise signal fft
I wanted to create two random noise signals sampled 2.5G sa/s in frequency range 200kHz - 20Mhz, time of signal 5us and calculate fft of it but I have a problem with fft. Thank you for help, the code is</p>

```<code>import numpy as np
import matplotlib.pyplot as plot
from scipy import signal
from scipy import fft
import pandas as pd

   t = np.arange(0, 5e-6, 4e-10)

   s1 = 1e-8*np.random.normal(0, 1, 12500)
   s2 = 1e-8*np.random.normal(0, 1, 12500)
   sos1 = signal.butter(N=10, Wn=[200000, 20000000], btype='band', fs=2.5e9, output='sos')
   sos2 = signal.butter(N=10, Wn=[200000, 20000000], btype='band', fs=2.5e9, output='sos')

   fs1 = signal.sosfilt(sos1, s1)
   fs2 = signal.sosfilt(sos2, s2)

f1 = abs(fs1.fft())
f2 = abs(fs2.fft())
ax1 = plot.subplot(311)
plot.plot(t, fs1, t, fs2)
#ax1.set_xlim([0, 5e-6])
plot.xlabel('Time (s)')
plot.ylabel('Current (A)')
ax2 = plot.subplot(312)
plot.plot(f1, f2)
plot.xlabel('Frequency (Hz)')
plot.ylabel('Current (A)')

plot.show()
</code>```

答:
I had to do some changes to your code in order to run it. The main one was to change fs1.fft() to fft.fft().

Another issue is the 'fft.fftshift()' method that you should be aware of. You can calculate the frequency vector by hand, but this is somewhat tedious because of the order of the elements in the resulting fft vector. The result of the fft has a peculiar frequency arrangement. From the scipy.fft.fft() documentation:

The frequency term f=k/n is found at y[k]. At y[n/2] we reach the Nyquist frequency and wrap around to the negative-frequency terms. So, for an 8-point transform, the frequencies of the result are [0, 1, 2, 3, -4, -3, -2, -1]. To rearrange the fft output so that the zero-frequency component is centered, like [-4, -3, -2, -1, 0, 1, 2, 3], use fftshift.

So, the easiest way is to use scipy.fft.fftfreq() to let scipy do the calculation for you. If you want to plot it in a natural way, then you should call scipy.fft.fftshift() to shift the zero Hz frequency to the center of the array.

Also, as you are using real signals, for efficiency reasons you might consider using the real number version of the fft algorithm scipy.fft.rfft(). The output does not include the negative frequencies, since for real input arrays the output of the full algorithm is always symmetric.

Please see the code below.

```<code>import matplotlib
matplotlib.use('Qt5Agg')

import numpy as np
import matplotlib.pyplot as plot
from scipy import signal
from scipy import fft
import pandas as pd

sampling_freq_Hz = 2.5e9
sampling_period_s = 1 / sampling_freq_Hz
signal_duration_s = 5.0e-6
wanted_number_of_points = signal_duration_s / sampling_period_s
f_low_Hz = 200.0e3
f_high_Hz = 20.0e6
msg = f'''
Sampling frequency: {sampling_freq_Hz} Hz
Sampling period: {sampling_period_s} s
Signal duration: {signal_duration_s} s
Wanted number of points: {wanted_number_of_points}
Lower frequency limit {f_low_Hz}
Upper frequency limit: {f_high_Hz}
'''
print(msg)

# Time axis
time_s = np.arange(0, signal_duration_s, sampling_period_s)
real_number_of_points = time_s.size
print(f'Real number of points: {real_number_of_points}')

# Normal(0,sigma^2) distributed random noise
sigma_2 = 1.0e-8
s1 = np.random.normal(0, sigma_2, real_number_of_points)
s2 = np.random.normal(0, sigma_2, real_number_of_points)

# Since both filters are equal, you only need one
sos1 = signal.butter(N=10, Wn=[f_low_Hz, f_high_Hz], btype='band', fs=sampling_freq_Hz, output='sos')
#sos2 = signal.butter(N=10, Wn=[f_low_Hz, f_high_Hz], btype='band', fs=sampling_freq_Hz, output='sos')

# Do the actual filtering
filtered_signal_1 = signal.sosfilt(sos1, s1)
filtered_signal_2 = signal.sosfilt(sos1, s2)

# Absolute value
f_1 = abs(fft.fft(filtered_signal_1))
f_2 = abs(fft.fft(filtered_signal_2))
freqs_Hz = fft.fftfreq(time_s.size, sampling_period_s)

# Shift the FFT for understandable plotting
f_1_shift = fft.fftshift(f_1)
f_2_shift = fft.fftshift(f_2)
freqs_Hz_shift = fft.fftshift(freqs_Hz)

# Plot
ax1 = plot.subplot(311)
ax1.plot(time_s, filtered_signal_1, time_s, filtered_signal_2)
#ax1.set_xlim([0, 5e-6])
ax1.set_xlabel('Time (s)')
ax1.set_ylabel('Current (A)')

ax2 = plot.subplot(313)
ax2.plot(freqs_Hz_shift, f_1_shift, freqs_Hz_shift, f_2_shift)
ax2.set_xlabel('Frequency (Hz)')
ax2.set_ylabel('Current (A)')

plot.show()
</code>```

Title: Flitered noise signal fft

Body:
I wanted to create two random noise signals sampled 2.5G sa/s in frequency range 200kHz - 20Mhz, time of signal 5us and calculate fft of it but I have a problem with fft. Thank you for help, the code is

import numpy as np
import matplotlib.pyplot as plot
from scipy import signal
from scipy import fft
import pandas as pd

   t = np.arange(0, 5e-6, 4e-10)

   s1 = 1e-8*np.random.normal(0, 1, 12500)
   s2 = 1e-8*np.random.normal(0, 1, 12500)
   sos1 = signal.butter(N=10, Wn=[200000, 20000000], btype='band', fs=2.5e9, output='sos')
   sos2 = signal.butter(N=10, Wn=[200000, 20000000], btype='band', fs=2.5e9, output='sos')

   fs1 = signal.sosfilt(sos1, s1)
   fs2 = signal.sosfilt(sos2, s2)

f1 = abs(fs1.fft())
f2 = abs(fs2.fft())
ax1 = plot.subplot(311)
plot.plot(t, fs1, t, fs2)
#ax1.set_xlim([0, 5e-6])
plot.xlabel('Time (s)')
plot.ylabel('Current (A)')
ax2 = plot.subplot(312)
plot.plot(f1, f2)
plot.xlabel('Frequency (Hz)')
plot.ylabel('Current (A)')

plot.show()

Body:
I had to do some changes to your code in order to run it. The main one was to change fs1.fft() to fft.fft().

Another issue is the 'fft.fftshift()' method that you should be aware of. You can calculate the frequency vector by hand, but this is somewhat tedious because of the order of the elements in the resulting fft vector. The result of the fft has a peculiar frequency arrangement. From the scipy.fft.fft() documentation:

The frequency term f=k/n is found at y[k]. At y[n/2] we reach the Nyquist frequency and wrap around to the negative-frequency terms. So, for an 8-point transform, the frequencies of the result are [0, 1, 2, 3, -4, -3, -2, -1]. To rearrange the fft output so that the zero-frequency component is centered, like [-4, -3, -2, -1, 0, 1, 2, 3], use fftshift.

So, the easiest way is to use scipy.fft.fftfreq() to let scipy do the calculation for you. If you want to plot it in a natural way, then you should call scipy.fft.fftshift() to shift the zero Hz frequency to the center of the array.

Also, as you are using real signals, for efficiency reasons you might consider using the real number version of the fft algorithm scipy.fft.rfft(). The output does not include the negative frequencies, since for real input arrays the output of the full algorithm is always symmetric.

Please see the code below.

import matplotlib
matplotlib.use('Qt5Agg')

import numpy as np
import matplotlib.pyplot as plot
from scipy import signal
from scipy import fft
import pandas as pd

sampling_freq_Hz = 2.5e9
sampling_period_s = 1 / sampling_freq_Hz
signal_duration_s = 5.0e-6
wanted_number_of_points = signal_duration_s / sampling_period_s
f_low_Hz = 200.0e3
f_high_Hz = 20.0e6
msg = f'''
Sampling frequency: {sampling_freq_Hz} Hz
Sampling period: {sampling_period_s} s
Signal duration: {signal_duration_s} s
Wanted number of points: {wanted_number_of_points}
Lower frequency limit {f_low_Hz}
Upper frequency limit: {f_high_Hz}
'''
print(msg)

# Time axis
time_s = np.arange(0, signal_duration_s, sampling_period_s)
real_number_of_points = time_s.size
print(f'Real number of points: {real_number_of_points}')

# Normal(0,sigma^2) distributed random noise
sigma_2 = 1.0e-8
s1 = np.random.normal(0, sigma_2, real_number_of_points)
s2 = np.random.normal(0, sigma_2, real_number_of_points)

# Since both filters are equal, you only need one
sos1 = signal.butter(N=10, Wn=[f_low_Hz, f_high_Hz], btype='band', fs=sampling_freq_Hz, output='sos')
#sos2 = signal.butter(N=10, Wn=[f_low_Hz, f_high_Hz], btype='band', fs=sampling_freq_Hz, output='sos')

# Do the actual filtering
filtered_signal_1 = signal.sosfilt(sos1, s1)
filtered_signal_2 = signal.sosfilt(sos1, s2)

# Absolute value
f_1 = abs(fft.fft(filtered_signal_1))
f_2 = abs(fft.fft(filtered_signal_2))
freqs_Hz = fft.fftfreq(time_s.size, sampling_period_s)

# Shift the FFT for understandable plotting
f_1_shift = fft.fftshift(f_1)
f_2_shift = fft.fftshift(f_2)
freqs_Hz_shift = fft.fftshift(freqs_Hz)

# Plot
ax1 = plot.subplot(311)
ax1.plot(time_s, filtered_signal_1, time_s, filtered_signal_2)
#ax1.set_xlim([0, 5e-6])
ax1.set_xlabel('Time (s)')
ax1.set_ylabel('Current (A)')

ax2 = plot.subplot(313)
ax2.plot(freqs_Hz_shift, f_1_shift, freqs_Hz_shift, f_2_shift)
ax2.set_xlabel('Frequency (Hz)')
ax2.set_ylabel('Current (A)')

plot.show()


问:
When I create a new project in the latest version of android studio for 2020, it shows me this error
This is the error I get</p>

```<code>   Gradle sync failed: Could not load wrapper properties from 'C:\Users\k1\AndroidStudioProjects\Fixerror\gradle\wrapper\gradle-wrapper.properties'.
                    No value with key 'distributionUrl' specified in wrapper properties file 'C:\Users\k1\AndroidStudioProjects\Fixerror\gradle\wrapper\gradle-wrapper.properties'.
                    Consult IDE log for more details (Help | Show Log) (96 ms)
</code>```

答:
Check in your gradle-wrapper.properties there should be a value for distributionUrl for example

```<code>#Wed May 27 16:03:33 BST 2020
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip
</code>```

EDIT

You can file the file here

Body:
This is the error I get

   Gradle sync failed: Could not load wrapper properties from 'C:\Users\k1\AndroidStudioProjects\Fixerror\gradle\wrapper\gradle-wrapper.properties'.
                    No value with key 'distributionUrl' specified in wrapper properties file 'C:\Users\k1\AndroidStudioProjects\Fixerror\gradle\wrapper\gradle-wrapper.properties'.
                    Consult IDE log for more details (Help | Show Log) (96 ms)

Body:
Check in your gradle-wrapper.properties there should be a value for distributionUrl for example

#Wed May 27 16:03:33 BST 2020
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip

EDIT

You can file the file here


问:
Dependency Injection in every aspect of a spring app?
I am taking a look into Spring as a web framework, however I am needing a bit of help getting my head around DI.

The concept of objects getting constructed in the container on run time is such a new concept.

I am just wondering how this will reflect in a big application, would I have some modules doing work that are more highly coupled or should every object be initialised at runtime?

It all seems a little intensive to me, I mean say for example I have a CSV file data mining application that removes the data per row - each rows data is encapsulated in one of my own CSVRow objects for processing or whatever. These objects are instantiated whenever an Excel file maybe uploaded to the server. I don't know how many I will need to create?

I seem to be getting a bit lost, any clarity, an overview or some guidance would be much appreciated.

Thanks in advance!

答: I think of Spring as a way to create "singletons". When I want to guarantee there's only one instance of a class in the application, use Spring to create it. But, instead of being a traditional singleton with a static INSTANCE field or similar, it's a POJO with whatever constructors / setters you need. Spring creates the instance at runtime for you and makes sure that creation only happens once.

ContentLicense: CC BY-SA 3.0


问:
Is a python appengine app with no firestore security rules insecure?
I have a Google App Engine Standard Environment application written in Python 3, using Flask as the framework, and firestore in native mode as the database. All of the database calls are done in the App Engine code, hidden behind Flask end points/views/handlers.  Client browsers do not execute any javascript that directly call the firestore database. Client side javascript is basically 'dumb' code used for cosmetics.  The only time client side javascript does "anything" is when a user creates a new account or logs in using the firebase auth ui.

Having said so, I noticed that some online resources mention that it is absolutely necessary to secure the firestore database since anything that is not disallowed by security rules are basically allowed (i.e. the firestore database is insecure by default), however, I suspect that this is only the case for apps that have thick clients (i.e. the client side code or javascript is in charge of doing the heavy lifting of querying and writing to firestore).

So my question is, is writing these security rules necessary only for mobile/web clients and not for firestore databases accessed only by server side code? Or is it necessary for all firestore projects to define these security rules? If so, then I would appreciate any pointers as to where to find reasonable default security rules to start securing my firestore database.

I am including a caricature of my flask main.py file for reference.

# main.py

from google.cloud import firestore

from mylibrary import function_that_fetches_user_data
from mylibrary2 import function_that_writes_user_content

def validate_cookie(protected_function):
    def wrapper(*args, **kwargs):
        # handle cookie validation
        # run protected function
    return wrapper

# The dashboard is meant to display user data and user content to the user.
# It is not meant to be seen by other users.
@app.route("/user_dashboard")
@validate_cookie
def dashboard():
    user_id = get_uid_from_cookie
    firestore_client = firestore.Client()
    user_data = function_that_fetches_user_data(user_id, firestore_client)
    return render_template('dashboard.html', user_data)

# The write function creates user content that should only be accessible to the author
# and the system/app.
@app.route("/write_user_content")
@validate_cookie
def write_user_content():
    user_id = get_uid_from_cookie
    firestore_client = firestore.Client()
    result = function_that_writes_user_content(user_id, firestore_client)
    return render_template('success.html', result)
```

答:
Security rules are only necessary to control access coming from web and mobile clients.  Backend SDK accessing Firestore actually bypass security rules altogether, so writing any rules at all won't change the behavior of your backend code at all.

If you simply do not directly access the database from web or mobile, then you can set the security rules to reject all access, and that's fine.

```<code>match /{document=**} {
  allow read, write: if false;
}
</code>```

Body:
Security rules are only necessary to control access coming from web and mobile clients.  Backend SDK accessing Firestore actually bypass security rules altogether, so writing any rules at all won't change the behavior of your backend code at all.

If you simply do not directly access the database from web or mobile, then you can set the security rules to reject all access, and that's fine.

match /{document=**} {
  allow read, write: if false;
}


问:
Regex - how to exclude 4 digit number from wider numeric pattern
Really tried to browse and search if this specific question has been posted previously, so I hope I'm not asking an obvious one here.

My problem: I have a regex expression, with few different possible criteria for pattern matching separated by pipes. I'm OK with all of them except one, where I basically want to:

Find any expression which would be number between 4 and 6 digits (regardless of position in the string)

Exclude from this pattern expressions which would relate to years in this century (so starting with 20 and followed by two digits)

So for example, I would like to match: 4149, 20259, 202046, but would like to exclude 2019 as it will refer to a year and not the code I'm searching for.

Currently, I tried applying this one (only last part of the expression): |\d{4,6}?!20\d{2}) , but it's not working properly. I know that the expressions preceeding pipe are fine and was able to notice that \d{4,6} stops to work once I add the "exclusion" in this case, so I assume I'm not using the ?! properly. Could I ask you for an advice on this one?

Edit: Solved! Thank you very much for immediate answers (I was really positively surprised how fast there were few alternative solutions). Sorry I had to pick just one, all of others would be adjustable and viable for my needs, I just found this one most appealing and tailored for my needs.

答:
This should work:

```<code>[013-9][1-9]\d{2}|\d{5,6}
</code>```

Match all 4 digit sequences, except the ones starting with 20, and all 5 or 6 digit sequences

Body:
This should work:

[013-9][1-9]\d{2}|\d{5,6}

Match all 4 digit sequences, except the ones starting with 20, and all 5 or 6 digit sequences


问:
How to assign scheduled tasks to a specific thread?
Collegues, I have a group of tasks that are scheduled. In spring-boot properties file it looks like:

```<code>group1.task1.run = <execute every first minute>
group1.task2.run = <execute every second minute>

group2.task1.run = <execute every first minute>
group2.task2.run = <execute every second minute>
</code>```

Is it possible to create two different threads (T1 and T2) and assign the first group of scheduled tasks to be executed in T1 thread, and the second group in T2 thread?

I can’t just increase PoolSize in TaskScheduler beacuse after that group1 tasks will be execute in different threads, it is not suitable for business process.

I would be grateful for any advice and help.

答:
As far as I know it's not possible to specify a single thread. However, you can specify the Executor which should be used to schedule your tasks. If you wan't your tasks to be executed in the same thread, just create a thread pool with a single thread in it, like so:

@Configuration
@EnableAsync
@EnableScheduling
public class TempConfig {

    @Scheduled(fixedRate = 1000)
    @Async(value = "threadPool1")
    public void task1() {
        System.out.println("Task1: " + Thread.currentThread());
    }

    @Scheduled(fixedRate = 1000)
    @Async(value = "threadPool2")
    public void task2() {
        System.out.println("Task2: " + Thread.currentThread());
    }

    @Bean
    public Executor threadPool1() {
        return Executors.newFixedThreadPool(1);
    }

    @Bean
    public Executor threadPool2() {
        return Executors.newFixedThreadPool(1);
    }
}
```

<p>Of course, you can alternatively just schedule the tasks yourself:</p>

<pre class="lang-java prettyprint-override"><code>var s1 = Executors.newScheduledThreadPool(1);
var s2 = Executors.newScheduledThreadPool(1);

// schedule tasks of group1
s1.scheduleWithFixedDelay(...);
s1.scheduleWithFixedDelay(...);

// schedule tasks of group2
s2.scheduleWithFixedDelay(...);
s2.scheduleWithFixedDelay(...);
</code>```

Body:
Collegues, I have a group of tasks that are scheduled. In spring-boot properties file it looks like:

group1.task1.run = <execute every first minute>
group1.task2.run = <execute every second minute>

group2.task1.run = <execute every first minute>
group2.task2.run = <execute every second minute>

Is it possible to create two different threads (T1 and T2) and assign the first group of scheduled tasks to be executed in T1 thread, and the second group in T2 thread?

I can’t just increase PoolSize in TaskScheduler beacuse after that group1 tasks will be execute in different threads, it is not suitable for business process.

I would be grateful for any advice and help.

Body:
As far as I know it's not possible to specify a single thread. However, you can specify the Executor which should be used to schedule your tasks. If you wan't your tasks to be executed in the same thread, just create a thread pool with a single thread in it, like so:

@Configuration
@EnableAsync
@EnableScheduling
public class TempConfig {

    @Scheduled(fixedRate = 1000)
    @Async(value = "threadPool1")
    public void task1() {
        System.out.println("Task1: " + Thread.currentThread());
    }

    @Scheduled(fixedRate = 1000)
    @Async(value = "threadPool2")
    public void task2() {
        System.out.println("Task2: " + Thread.currentThread());
    }

    @Bean
    public Executor threadPool1() {
        return Executors.newFixedThreadPool(1);
    }

    @Bean
    public Executor threadPool2() {
        return Executors.newFixedThreadPool(1);
    }
}

Of course, you can alternatively just schedule the tasks yourself:

var s1 = Executors.newScheduledThreadPool(1);
var s2 = Executors.newScheduledThreadPool(1);

// schedule tasks of group1
s1.scheduleWithFixedDelay(...);
s1.scheduleWithFixedDelay(...);

// schedule tasks of group2
s2.scheduleWithFixedDelay(...);
s2.scheduleWithFixedDelay(...);


问:
Azure Cosmos DB Trigger not working after upgrading to 3.6
we had an existing Cosmos DB on version 3.3, which is now upgraded to 3.6 after which Cosmos DB Triggered functions are unable to start with error saying

Exception type  Microsoft.Azure.WebJobs.Host.Indexers.FunctionIndexingException
Exception message   Error indexing method 'GetSomeData' <---
 Cannot create Collection Information for collectionName in database %MongoDbMetadata% with lease leaslineName in database %MongoDbMetadata% :
 Error reading JObject from JsonReader. Path '', line 0, position 0. <--- Error reading JObject from JsonReader. Path '', line 0, position 0.

答:
This may be because the endpoint for your Cosmos account is different for MongoDB 3.6 versus 3.2. Try using this URI for your Cosmos account in your Azure Function.

[account-name].mongo.cosmos.azure.com

Hope this helps.


问:
How can I get "permutations with repetitions/replacement" from a list (Cartesian product of a list with itself)?
Suppose I have a list die_faces = [1, 2, 3, 4, 5, 6]. I want to generate all 36 possible results for rolling two dice: (1, 1), (1, 2), (2, 1) etc. If I try using permutations from the itertools standard library:

```<code>>>> import itertools
>>> die_faces = [1, 2, 3, 4, 5, 6]
>>> list(itertools.permutations(die_faces, 2))
[(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 1), (2, 3), (2, 4), (2, 5), (2, 6), (3, 1), (3, 2), (3, 4), (3, 5), (3, 6), (4, 1), (4, 2), (4, 3), (4, 5), (4, 6), (5, 1), (5, 2), (5, 3), (5, 4), (5, 6), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5)]
</code>```

there are only 30 results, missing the ones where the same number comes up on both dice. It seems that it only generates permutations without repetitions. How can I fix this?

答:
I think I found a solution using only lambdas, map and reduce.

```<code>product_function = lambda n: reduce(lambda x, y: x+y, map(lambda i: list(map(lambda j: (i, j), np.arange(n))), np.arange(n)), [])
</code>```

Essentially I'm mapping a first lambda function that given a row, iterates the columnns

```<code>list(map(lambda j: (i, j), np.arange(n)))
</code>```

then this is used as the output of a new lambda function

```<code>lambda i:list(map(lambda j: (i, j), np.arange(n)))
</code>```

which is mapped across all the possible rows

```<code>map(lambda i: list(map(lambda j: (i, j), np.arange(n))), np.arange(m))
</code>```

and then we reduce all the resulting lists into one.

even better

Can also use two different numbers.

```<code>prod= lambda n, m: reduce(lambda x, y: x+y, map(lambda i: list(map(lambda j: (i, j), np.arange(m))), np.arange(n)), [])
</code>```

Body:
Suppose I have a list die_faces = [1, 2, 3, 4, 5, 6]. I want to generate all 36 possible results for rolling two dice: (1, 1), (1, 2), (2, 1) etc. If I try using permutations from the itertools standard library:

>>> import itertools
>>> die_faces = [1, 2, 3, 4, 5, 6]
>>> list(itertools.permutations(die_faces, 2))
[(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 1), (2, 3), (2, 4), (2, 5), (2, 6), (3, 1), (3, 2), (3, 4), (3, 5), (3, 6), (4, 1), (4, 2), (4, 3), (4, 5), (4, 6), (5, 1), (5, 2), (5, 3), (5, 4), (5, 6), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5)]

there are only 30 results, missing the ones where the same number comes up on both dice. It seems that it only generates permutations without repetitions. How can I fix this?

Body:
I think I found a solution using only lambdas, map and reduce.

product_function = lambda n: reduce(lambda x, y: x+y, map(lambda i: list(map(lambda j: (i, j), np.arange(n))), np.arange(n)), [])

Essentially I'm mapping a first lambda function that given a row, iterates the columnns

list(map(lambda j: (i, j), np.arange(n)))

then this is used as the output of a new lambda function

lambda i:list(map(lambda j: (i, j), np.arange(n)))

which is mapped across all the possible rows

map(lambda i: list(map(lambda j: (i, j), np.arange(n))), np.arange(m))

and then we reduce all the resulting lists into one.

even better

Can also use two different numbers.

prod= lambda n, m: reduce(lambda x, y: x+y, map(lambda i: list(map(lambda j: (i, j), np.arange(m))), np.arange(n)), [])


问:
Select text within terminal output using VIM
Let's say I have the following output in my terminal window now:

```<code>1. vsud@vsud:~$ pwd
2. /home/vsud
3. vsud@vsud:~$ echo "Hello, world!"
4. Hello, world!
</code>```

I want to copy to clipboard the 1st and 2nd lines.

```<code>vsud@vsud:~$ pwd
/home/vsud
</code>```

With mouse - I can do that by selecting those 2 lines and pressing Ctrl + Shift + C.
But can I enter into VIM mode somehow and work with that whole output in my terminal as with pure text - so to copy 2 lines I will need to type just "H2yy" ?
Do I need to install some specific Terminal Emulator for that?

Now I'm using terminal emulator which is built in XFCE.

答:
You can pipe the output to vim using view -. For example:

ls -la | view -
```

This opens a vim instance in read-only mode which can read from stdin

Body:
Let's say I have the following output in my terminal window now:

1. vsud@vsud:~$ pwd
2. /home/vsud
3. vsud@vsud:~$ echo "Hello, world!"
4. Hello, world!

I want to copy to clipboard the 1st and 2nd lines.

vsud@vsud:~$ pwd
/home/vsud

With mouse - I can do that by selecting those 2 lines and pressing Ctrl + Shift + C.
But can I enter into VIM mode somehow and work with that whole output in my terminal as with pure text - so to copy 2 lines I will need to type just "H2yy" ?
Do I need to install some specific Terminal Emulator for that?

Now I'm using terminal emulator which is built in XFCE.

Body:
You can pipe the output to vim using view -. For example:

ls -la | view -

This opens a vim instance in read-only mode which can read from stdin


问:
How to attach a weapon to players hand and implement dynamic aiming?
I wanted the weapon to be pointing in the direction of wherever the mouse is,[![This is my player texture][1]][1]

what i want is, if a weapon is in players hand, than the weapon along with the hand, being in perfect sync with the body points in the direction where ever the mouse is

I have no idea how to implement this mechanism, please help

答: First off it completely depends on how the character is rigged. Are you using Spriter or something to that effect to produce a 2d skeletal animation rig? If so then the IK from that should take care of a weapon if you just attach it to the handbone. If not then simple trig is going to be your friend. Get the angle of the mouse to the center of the character or character's hand and then cos with be your X position for the weapon and sin will be your Y position.</p>


问:
mongodb-charts ssl data source PRIVATE KEY error
I'm trying to connect to an SSL protected Mongo DB instance running a service from a local MongoDB-charts deployment. I got a local Mongo running as metadata DB, and MongoDB-charts running from a local container following instructions on:

https://docs.mongodb.com/charts/19.12/installation/

But when I want to connect to a Mongo DB instance running a service and protected with SSL using a certificate I get the following error:

I've copied the certificate within the container. I know it is being picked up because If I rename the filename, MongoDB-charts complains that the cert file doesn't exist.

I'm able to connect to the MongoDB service from Mongo shell, and from MongoDB-compass using the same credentials and same certificate, therefore that information is correct. I figure it has to be something missing on the container but I cannot find a solution.

¿Any tips?

答:
I was provided with the solution in my company internal forum.

I had that error ...

"Because it’s a CA file, not a Key file - with the option you’re
  selecting, it’s looking for a certificate and a key"

Solution: Use tlsCAFile instead of sslclientcertificatekeyfile in the Mongo URI.

Example:

```<code>mongodb://user:password@host0,host2/dbname?authSource=admin&replicaSet=replset&ssl=true&sslclientcertificatekeyfile=/mongodb-charts/volumes/db-certs/cert.pem
</code>```

Body:
I was provided with the solution in my company internal forum.

I had that error ...

"Because it’s a CA file, not a Key file - with the option you’re
  selecting, it’s looking for a certificate and a key"

Solution: Use tlsCAFile instead of sslclientcertificatekeyfile in the Mongo URI.

Example:

mongodb://user:password@host0,host2/dbname?authSource=admin&replicaSet=replset&ssl=true&sslclientcertificatekeyfile=/mongodb-charts/volumes/db-certs/cert.pem


问:
Data frame and text mining
```<code>library(stringr)
data<-data.frame(id=c(1,2,3),
          text=c("This is (2020) text; mining exercise (1999)","Text analysis (1975) is; bit confusing (2012)","Hint (1998) on; this text (2007) analysis?"))

a <- b <- list()
mm <- data.frame(a=NA,b=NA)
for(i in 1:length(data$text)){
   a[[i]] <- lengths(strsplit(as.character(data$text[i]),";"))
   b[[i]] <- str_count(data$text[i], "\\(19[0-9]{2}\\)|\\(20[0-9]{2}\\)")
}
</code>```

Output I'm getting:

```<code># mm
    a     b
1  NA     NA
</code>```

Why I'm not getting the corresponding values for each row of the data frame mm? The code has nor error.

Expected output:

```<code># mm
   a   b
1  2   2
2  2   2
3  2   2
</code>```

答:
After your loop completes, you have two lists, a and b with your expected output:

```<code>a
[[1]]
[1] 2

[[2]]
[1] 2

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

But you never assign these values to your data.frame:

```<code>mm <- data.frame(a=unlist(a),b=unlist(b))
mm
  a b
1 2 2
2 2 2
3 2 2
</code>```

Title: Data frame and text mining

Body:
library(stringr)
data<-data.frame(id=c(1,2,3),
          text=c("This is (2020) text; mining exercise (1999)","Text analysis (1975) is; bit confusing (2012)","Hint (1998) on; this text (2007) analysis?"))

a <- b <- list()
mm <- data.frame(a=NA,b=NA)
for(i in 1:length(data$text)){
   a[[i]] <- lengths(strsplit(as.character(data$text[i]),";"))
   b[[i]] <- str_count(data$text[i], "\\(19[0-9]{2}\\)|\\(20[0-9]{2}\\)")
}

Output I'm getting:

# mm
    a     b
1  NA     NA

Why I'm not getting the corresponding values for each row of the data frame mm? The code has nor error.

Expected output:

# mm
   a   b
1  2   2
2  2   2
3  2   2

Body:
After your loop completes, you have two lists, a and b with your expected output:

a
[[1]]
[1] 2

[[2]]
[1] 2

[[3]]
[1] 2

But you never assign these values to your data.frame:

mm <- data.frame(a=unlist(a),b=unlist(b))
mm
  a b
1 2 2
2 2 2
3 2 2


问:
NodeJS - https - TypeError [ERR_INVALID_HTTP_TOKEN]: Header name must be a valid HTTP token ["Accept"]
I have a NodeJS code that uses https module as: https.request(options, (res) => {...... where options is an object like

```<code>const options = {
    hostname: SERVICE_HOSTNAME,
    path: BASE_PATH,
    method: 'GET',
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        ApplicationId,
        Authorization
    }
  };
</code>```

My problems start when I add Accept header. I getting an error:

```<code>TypeError [ERR_INVALID_HTTP_TOKEN]: Header name must be a valid HTTP token ["Accept"]
    at ClientRequest.setHeader (_http_outgoing.js:472:3)
    at new ClientRequest (_http_client.js:203:14)
    at Object.request (https.js:289:10)
</code>```

How Accept header would be invalid?

答:
Now this is crazy, but you have an extra character in your "Accept" string.
If you run

console.log('Accept'.charCodeAt(6)) // prints 8203
```

(You have to run it with your copy of "Accept" from your question, which I assume is copy-pasted from elsewhere)

Unicode 8203 is zero width space, hence it's not visible to us humans :)

By the way, initially i've discovered the character by copy-pasting into Node REPL and noticing a "square" in console output after getting the error.

I've then tried copy-pasting your code into my IntelliJ editor, and was pleasantly surprised to see this warning:

Body:
I have a NodeJS code that uses https module as: https.request(options, (res) => {...... where options is an object like

const options = {
    hostname: SERVICE_HOSTNAME,
    path: BASE_PATH,
    method: 'GET',
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        ApplicationId,
        Authorization
    }
  };

My problems start when I add Accept header. I getting an error:

TypeError [ERR_INVALID_HTTP_TOKEN]: Header name must be a valid HTTP token ["Accept"]
    at ClientRequest.setHeader (_http_outgoing.js:472:3)
    at new ClientRequest (_http_client.js:203:14)
    at Object.request (https.js:289:10)

How Accept header would be invalid?

Body:
Now this is crazy, but you have an extra character in your "Accept" string.
If you run

console.log('Accept'.charCodeAt(6)) // prints 8203

(You have to run it with your copy of "Accept" from your question, which I assume is copy-pasted from elsewhere)

Unicode 8203 is zero width space, hence it's not visible to us humans :)

By the way, initially i've discovered the character by copy-pasting into Node REPL and noticing a "square" in console output after getting the error.

I've then tried copy-pasting your code into my IntelliJ editor, and was pleasantly surprised to see this warning:


问:
Remove country code from phone number?
Below is the code I am currently using to format phone numbers for databasing. However iOS is putting a +1 or 1 (country code) before it in autofills. How can I remove the 1 before the phone number?

So...

+12223334444 should be 2223334444

12223334444 should be 2223334444

```<code>preg_replace('/\D/', '', ($phone));
</code>```

Title: Remove country code from phone number?

Body:
Below is the code I am currently using to format phone numbers for databasing. However iOS is putting a +1 or 1 (country code) before it in autofills. How can I remove the 1 before the phone number?

So...

+12223334444 should be 2223334444

12223334444 should be 2223334444

preg_replace('/\D/', '', ($phone));

Body:
It cleans phone number & strips (, ), -, +
returns just last 10 digit numeric phone number

Examples:

1234567890 => +11234567890
1234567890 => :+112:34567890
1234567890 => Phone :+1-123-456-7890
1234567890 => Phone :+1-(123)-(456)-(7890)
1234567890 => +1-(123)-(456)-(7890)
1234567890 => +1-123-456-7890

Sample test code:

$dirty_phone = ["+11234567890", ":+112:34567890", "Phone :+1-123-456-7890",  "Home :(+1)-(123)-(456)-(7890)", "+1-(123)-(456)-(7890)", "+1-123-456-7890"];

foreach ($dirty_phone as $key => $phone_no) {
    $cleaned_phone = clean_phone_number($phone_no);
    echo "{$cleaned_phone} => {$phone_no}<br>";
}

function clean_phone_number($phone_no){
    return substr( preg_replace('/^\+?1|\|1|\D/', '', $phone_no), -10);
}


问:
Printing number of rows in Laravel
I am trying to print number of rows in Laravel from MySQL but i get this error:
htmlspecialchars() expects parameter 1 to be string, object given (View: C:\wamp64\www\kont\resources\views\profile.blade.php)

I have two function inside my model. First function returns information about user from one table and another function counts number of friends for that user from another table. Please view my code below:

HomeController.php

```<code>public function profile(Request $request,$id){
        $model = new UserModel();
 $podaciIzBaze = $model->userdata($id);
 $data = array();
 $data['dt'] = $podaciIzBaze;

$model2 = new UserModel();
 $podaciIzBaze2 = $model2->countfriends($id);

 $data['dt2'] = $podaciIzBaze2;

         return view('profile',$data);

    }
</code>```

UserModel.php

```<code>  class UserModel extends Model
    {
        //
        public function userdata($id){
            $query = DB::select("SELECT first_name,last_name,email,website,birth_date FROM users where id = $id");
            return $query;
        }

        public function countfriends($id){

            $query=DB::SELECT("SELECT count(user_id) from user_friend where user_id = $id");
            return $query;

        }
</code>```

profile.blade.php

```<code> @foreach($dt as $d)
                                 <tr>
                                    <td>Ime:</td>
                                    <td>{{ $d->first_name }}</td>
                                 </tr>
                                 <tr>
                                    <td>Prezime</td>
                                    <td>{{ $d->last_name }}</td>
                                 </tr>
                                 <tr>
                                    <td>Datum Rodjenja</td>
                                    <td>{{ $d->birth_date }}</td>
                                 </tr>
                                 <tr>
                                 <tr>
                                    <td>Pol</td>
                                    <td>Musko</td>
                                 </tr>
                                 <tr>
                                    <td>Email</td>
                                    <td><a href="mailto:info@support.com">{{ $d->email }}</a></td>
                                 </tr>
                                 <td>Website</td>
                                 <td>
                                   {{ $d->website }}
                                 </td>
                                 </tr>
                                     @endforeach

                       @foreach($dt2 as $d2)
                     Number of friends: {{ $d }}
                     @endforeach
</code>```

答:
Number of friends: {{ $d }} should be Number of friends: {{ $d2 }}

I suggest the following changes to your code:

Rename UserModel to just User

Add Friend model

Add eloquent relation of one to many between User model and Friend model

Rename table name user_friend to user_friends - this way you can utilise laravel's magic

dt and dt2 are not descriptive - I have no idea what they represent, I would suggest renaming them to:
dt -> userData
dt2 -> totalFriends

```<code>public function profile(User $user){
    $userData = $user->only([
        'first_name',
        'last_name',
        'email',
        'website',
        'birth_date',
    ]);

    return view('profile', [
        'userData' => $userData,
        'totalFriends' => $user->friends->count(),
    ]);

}
</code>```

Blade file would then look similar to:

```<code> <tr>
    <td>Ime:</td>
    <td>{{ $userData->first_name }}</td>
 </tr>
 <tr>
    <td>Prezime</td>
    <td>{{ $userData->last_name }}</td>
 </tr>
 <tr>
    <td>Datum Rodjenja</td>
    <td>{{ $userData->birth_date }}</td>
 </tr>
 <tr>
 <tr>
    <td>Pol</td>
    <td>Musko</td>
 </tr>
 <tr>
    <td>Email</td>
    <td><a href="mailto:info@support.com">{{ $userData->email }}</a></td>
 </tr>
 <td>Website</td>
     <td>
       {{ $userData->website }}
     </td>
 </tr>

 Number of friends: {{ $totalFiends }}
</code>```

Title: Printing number of rows in Laravel

Body:
I am trying to print number of rows in Laravel from MySQL but i get this error:
htmlspecialchars() expects parameter 1 to be string, object given (View: C:\wamp64\www\kont\resources\views\profile.blade.php)

I have two function inside my model. First function returns information about user from one table and another function counts number of friends for that user from another table. Please view my code below:

HomeController.php

public function profile(Request $request,$id){
        $model = new UserModel();
 $podaciIzBaze = $model->userdata($id);
 $data = array();
 $data['dt'] = $podaciIzBaze;

$model2 = new UserModel();
 $podaciIzBaze2 = $model2->countfriends($id);

 $data['dt2'] = $podaciIzBaze2;

         return view('profile',$data);

    }

UserModel.php

  class UserModel extends Model
    {
        //
        public function userdata($id){
            $query = DB::select("SELECT first_name,last_name,email,website,birth_date FROM users where id = $id");
            return $query;
        }

        public function countfriends($id){

            $query=DB::SELECT("SELECT count(user_id) from user_friend where user_id = $id");
            return $query;

        }

profile.blade.php

 @foreach($dt as $d)

                                    Ime:
                                    {{ $d->first_name }}

                                    Prezime
                                    {{ $d->last_name }}

                                    Datum Rodjenja
                                    {{ $d->birth_date }}

                                    Pol
                                    Musko

                                    Email
                                    {{ $d->email }}

                                 Website

                                   {{ $d->website }}

                                     @endforeach

                       @foreach($dt2 as $d2)
                     Number of friends: {{ $d }}
                     @endforeach

Body:
Number of friends: {{ $d }} should be Number of friends: {{ $d2 }}

I suggest the following changes to your code:

Rename UserModel to just User

Add Friend model

Add eloquent relation of one to many between User model and Friend model

Rename table name user_friend to user_friends - this way you can utilise laravel's magic

dt and dt2 are not descriptive - I have no idea what they represent, I would suggest renaming them to:
dt -> userData
dt2 -> totalFriends

public function profile(User $user){
    $userData = $user->only([
        'first_name',
        'last_name',
        'email',
        'website',
        'birth_date',
    ]);

    return view('profile', [
        'userData' => $userData,
        'totalFriends' => $user->friends->count(),
    ]);

}

Blade file would then look similar to:

 <tr>
    <td>Ime:</td>
    <td>{{ $userData->first_name }}</td>
 </tr>
 <tr>
    <td>Prezime</td>
    <td>{{ $userData->last_name }}</td>
 </tr>
 <tr>
    <td>Datum Rodjenja</td>
    <td>{{ $userData->birth_date }}</td>
 </tr>
 <tr>
 <tr>
    <td>Pol</td>
    <td>Musko</td>
 </tr>
 <tr>
    <td>Email</td>
    <td><a href="mailto:info@support.com">{{ $userData->email }}</a></td>
 </tr>
 <td>Website</td>
     <td>
       {{ $userData->website }}
     </td>
 </tr>

 Number of friends: {{ $totalFiends }}


问:
Spring Boot Startup Slow After Upgrade
I just recently upgraded one of my teams Spring Boot applications from 2.1.3-RELEASE to now be 2.3.0-RELEASE, well as upgrading Hibernate versions from 5.3.6.Final to be 5.4.15.Final.

Everything went fine, however now when the application starts on the server, it takes anywhere from 800-900 seconds to start (roughly 15 minutes) when it used to only take about 30 seconds.

Something important to note, when running on localhost, with both 2.1.3 and 2.3.0, application startup was the same, about 12-15 seconds.

The slow startup issue is only encountered when deployed to the server.

I am certain the issue lies with the new version of Spring Boot, as i switched to SpringBoot 2.1.3 and left Hibernate as 5.4.15, and the startup was fast.

So, is there something that has changed in recent SpringBoot releases where I have to set a property to disable certain checks or something?

Most articles and posts I have seen said the issue was with Hibernate and to set this property spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false but i did that and it had no effect.

UPDATE:

I tried the property spring.main.lazy-initialization=true but it had no effect on startup performance.

UPDATE 2:

I downgraded from 2.3.0 to 2.2.7 which resulted in an average of 170 second startup time, vs an average of 800 second startup times with 2.3.0. A roughly 3 minute startup time is still terrible, but, with a difference of 12 minutes with no change other than versions, I wonder if its just too ambitious to be on the latest version of Spring Boot.

Still very curious if anyone has some suggestions of why we would have gone from a 30 second start time with 2.1.3 to a 3 minute start time with 2.2.7.

Was there a major changed introduced between 2.1.x and 2.2.x?

LAST UPDATE

I tried version 2.2.5 which resulted in no decrease in startup performance from 2.1.3. If anything startup performance has increased. So, this leads me to believe something has changed under the hood with versions 2.2.6 and higher.

I am going to stick with 2.2.5, but am still hoping for an answer if anyone out there has attempted to use these most recent versions of Spring Boot.

答:
I've hit the same issue trying to upgrade from spring boot 2.2.6 to 2.3.0.
I observe slower application start time when running spring boot app on server or in docker container and don't see the problem with local runs both on win and mac.

Out of curiosity I took spring-petclinic and tried to run it docker.
That's the start up times I get with it.

With Spring Boot 2.3.0

```<code>2020-05-29 15:33:28.957  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 22.723 seconds (JVM running for 24.397)
2020-05-29 15:41:08.278  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 22.955 seconds (JVM running for 24.641)
2020-05-29 15:42:20.741  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 24.847 seconds (JVM running for 26.534)
2020-05-29 15:43:28.472  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 24.645 seconds (JVM running for 26.294)
2020-05-29 15:43:58.152  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 23.931 seconds (JVM running for 25.609)
2020-05-29 15:44:30.186  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 24.708 seconds (JVM running for 26.608)
</code>```

With Spring Boot 2.2.6

```<code>2020-05-29 15:40:25.829  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 19.062 seconds (JVM running for 20.474)
2020-05-29 15:41:35.797  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 18.18 seconds (JVM running for 19.582)
2020-05-29 15:48:36.693  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 18.648 seconds (JVM running for 20.067)
2020-05-29 15:49:00.379  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 18.548 seconds (JVM running for 19.978)
2020-05-29 15:49:23.282  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 18.808 seconds (JVM running for 20.218)
2020-05-29 15:49:47.100  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 19.862 seconds (JVM running for 21.285)
2020-05-29 15:50:08.247  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 16.599 seconds (JVM running for 17.916)
</code>```

I wonder what has changed in that area...

Surprisingly spring boot 2.3.1 looks better, almost the same as 2.2.x:

```<code>2020-06-19 21:16:18.935  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 18.886 seconds (JVM running for 20.552)
2020-06-19 21:16:43.461  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 18.637 seconds (JVM running for 20.091)
2020-06-19 21:17:07.226  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 18.526 seconds (JVM running for 20.007)
2020-06-19 21:17:30.172  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 19.694 seconds (JVM running for 21.209)
2020-06-19 21:17:57.662  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 20.348 seconds (JVM running for 21.85)
</code>```

I suggest to give 2.3.1 a try.

Title: Spring Boot Startup Slow After Upgrade

Body:
I've hit the same issue trying to upgrade from spring boot 2.2.6 to 2.3.0.
I observe slower application start time when running spring boot app on server or in docker container and don't see the problem with local runs both on win and mac.

Out of curiosity I took spring-petclinic and tried to run it docker.
That's the start up times I get with it.

With Spring Boot 2.3.0

2020-05-29 15:33:28.957  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 22.723 seconds (JVM running for 24.397)
2020-05-29 15:41:08.278  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 22.955 seconds (JVM running for 24.641)
2020-05-29 15:42:20.741  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 24.847 seconds (JVM running for 26.534)
2020-05-29 15:43:28.472  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 24.645 seconds (JVM running for 26.294)
2020-05-29 15:43:58.152  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 23.931 seconds (JVM running for 25.609)
2020-05-29 15:44:30.186  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 24.708 seconds (JVM running for 26.608)

With Spring Boot 2.2.6

2020-05-29 15:40:25.829  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 19.062 seconds (JVM running for 20.474)
2020-05-29 15:41:35.797  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 18.18 seconds (JVM running for 19.582)
2020-05-29 15:48:36.693  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 18.648 seconds (JVM running for 20.067)
2020-05-29 15:49:00.379  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 18.548 seconds (JVM running for 19.978)
2020-05-29 15:49:23.282  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 18.808 seconds (JVM running for 20.218)
2020-05-29 15:49:47.100  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 19.862 seconds (JVM running for 21.285)
2020-05-29 15:50:08.247  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 16.599 seconds (JVM running for 17.916)

I wonder what has changed in that area...

Surprisingly spring boot 2.3.1 looks better, almost the same as 2.2.x:

2020-06-19 21:16:18.935  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 18.886 seconds (JVM running for 20.552)
2020-06-19 21:16:43.461  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 18.637 seconds (JVM running for 20.091)
2020-06-19 21:17:07.226  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 18.526 seconds (JVM running for 20.007)
2020-06-19 21:17:30.172  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 19.694 seconds (JVM running for 21.209)
2020-06-19 21:17:57.662  INFO 1 --- [           main] o.s.s.petclinic.PetClinicApplication     : Started PetClinicApplication in 20.348 seconds (JVM running for 21.85)

I suggest to give 2.3.1 a try.


问:
Load pdf file from url
I have this url from server
https://xxxx.pdf20200529". How can I load it as pdf in my flutter app?

I use this plugin, but nothing happened.

Code

```<code>OpenFile.open(value);  // value is https://xxxx.pdf20200529
</code>```

Edit

```<code> generatePDF(dynamic value) async {
    final filename = value.substring(value.lastIndexOf("/") + 1);
    var request = await HttpClient().getUrl(Uri.parse(value));
    var response = await request.close();
    var bytes = await consolidateHttpClientResponseBytes(response);
    String dir = (await getApplicationDocumentsDirectory()).path;
    File file = new File('$dir/$filename');
    await file.writeAsBytes(bytes);
    OpenFile.open(file.path);
  }
</code>```

答:
Have you tried url_launcher 5.4.10

As far as I know it opens pdfs as well.

Title: Load pdf file from url

Body:
I have this url from server
https://xxxx.pdf20200529". How can I load it as pdf in my flutter app?

I use this plugin, but nothing happened.

Code

OpenFile.open(value);  // value is https://xxxx.pdf20200529

Edit

 generatePDF(dynamic value) async {
    final filename = value.substring(value.lastIndexOf("/") + 1);
    var request = await HttpClient().getUrl(Uri.parse(value));
    var response = await request.close();
    var bytes = await consolidateHttpClientResponseBytes(response);
    String dir = (await getApplicationDocumentsDirectory()).path;
    File file = new File('$dir/$filename');
    await file.writeAsBytes(bytes);
    OpenFile.open(file.path);
  }


问:
How to remove last line in a text file in R?
Im reading a text file containing data with "problematic" line. The last line that starts with *NOTE has to be removed (number of rows in the text file is not always the same):

```<code>ColumnA ColumnB ColumnC
A2  17  14
B2  20  -1
C2  21  36

*NOTE: -1 = data do not exist
</code>```

This is my line to read the text file (i have to select text file since its location not constant:

```<code>my_data <- read.delim(file.choose(), header = TRUE, sep = "", quote = "",
                      dec = ".", fill = TRUE, comment.char = "")
</code>```

I have tried :

```<code>my_data[- grep("*NOTE:", my_data$ColumnA),]
</code>```

But it does not seem to work.
Any simple solutions to this?

答:
There is another way to handle this, which is to write a short function that takes the regexes that you want to filter out. You can feed it the file name, but if this is missing it will give you the file dialogue:

read_broken <- function(file_path, filter_out = "^[*]NOTE:")
{
  if(missing(file_path)) file_path <- file.choose()
  x <- suppressWarnings(readLines(file_path))
  x <- x[nzchar(x)]
  x <- x[!apply(sapply(filter_out, grepl, x), 1, any)]
  read.delim(text = x, header = TRUE, sep = "", quote = "", dec = ".", fill = TRUE)
}
```

<p>So you can do:</p>

```read_broken("myfile.txt")
#>   ColumnA ColumnB ColumnC
#> 1      A2      17      14
#> 2      B2      20      -1
#> 3      C2      21      36
```

<p>Or</p>

```read_broken("myfile.txt", filter_out = c("^[*]NOTE:", "A2"))
#>   ColumnA ColumnB ColumnC
#> 1      B2      20      -1
#> 2      C2      21      36
```

Body:
Im reading a text file containing data with "problematic" line. The last line that starts with *NOTE has to be removed (number of rows in the text file is not always the same):

ColumnA ColumnB ColumnC
A2  17  14
B2  20  -1
C2  21  36

*NOTE: -1 = data do not exist

This is my line to read the text file (i have to select text file since its location not constant:

my_data <- read.delim(file.choose(), header = TRUE, sep = "", quote = "",
                      dec = ".", fill = TRUE, comment.char = "")

I have tried :

my_data[- grep("*NOTE:", my_data$ColumnA),]

But it does not seem to work.
Any simple solutions to this?

Body:
There is another way to handle this, which is to write a short function that takes the regexes that you want to filter out. You can feed it the file name, but if this is missing it will give you the file dialogue:

read_broken <- function(file_path, filter_out = "^[*]NOTE:")
{
  if(missing(file_path)) file_path <- file.choose()
  x <- suppressWarnings(readLines(file_path))
  x <- x[nzchar(x)]
  x <- x[!apply(sapply(filter_out, grepl, x), 1, any)]
  read.delim(text = x, header = TRUE, sep = "", quote = "", dec = ".", fill = TRUE)
}

So you can do:

read_broken("myfile.txt")
#>   ColumnA ColumnB ColumnC
#> 1      A2      17      14
#> 2      B2      20      -1
#> 3      C2      21      36

Or

read_broken("myfile.txt", filter_out = c("^[*]NOTE:", "A2"))
#>   ColumnA ColumnB ColumnC
#> 1      B2      20      -1
#> 2      C2      21      36


问:
Is it 'PowerApps' or 'Power Apps'?
I am sometimes engaged in content writing and I don't understand the differencce between PowerApps and Power Apps. I see most writers using 'PowerApps' while Microsoft uses 'Power Apps'. Which word is contextually correct?</p>

答: It used to be "PowerApps", but it was rebranded to "Power Apps" (with space) earlier this year (probably some marketing decision, I don't know). You'll likely see PowerApps (no space) in all old references, and possible for quite some time until the new name gets to people's minds.</p>

Title: Is it 'PowerApps' or 'Power Apps'?