问:
Trying to run LibreOffice (soffice) as a systemctl service fails
I'm trying to get LibreOffice (more specifically, soffice) to run as a service on an Ubuntu server (20.04.3), but I've just not been able to make it work. It's the first time I'm trying to set up a custom service, so the likelihood that it's just configured wrong is very high.

Basically, I want to keep soffice running in headless mode, listening in a socket. The command I use for it is:

```<code>/usr/bin/soffice --headless --accept='socket,host=127.0.0.1,port=8100;urp;' --nofirststartwizard
</code>```

From all I can see, this command seems to be working. No output whatsoever when I run it manually, and it blocks the terminal, supposedly waiting for incoming connections.

So, to run it as a service, I created the following soffice.service file on /etc/systemd/system:

```<code>[Unit]
Description=LibreOffice service
After=syslog.target

[Service]
ExecStart=soffice "--headless --accept='socket,host=127.0.0.1,port=8100;urp;' --nofirststartwizard"
Restart=always
KillSignal=SIGQUIT
Type=simple
StandardError=syslog
User=www-data

[Install]
WantedBy=multi-user.target
</code>```

After enabling and starting it, I get the following on systemctl status soffice:

```<code>● soffice.service - LibreOffice service
     Loaded: loaded (/etc/systemd/system/soffice.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Sun 2022-02-06 17:18:40 WET; 4s ago
    Process: 24786 ExecStart=/usr/bin/soffice --headless --accept='socket,host=127.0.0.1,port=8100;urp;' --nofirststartwizard (code=exited, status=1/FAILURE)
   Main PID: 24786 (code=exited, status=1/FAILURE)
</code>```

I'm guessing the issue is on the ExecStart directive, but despite reading the documentation – which is hard to follow for me, since I only use linux to keep my webserver running – I just couldn't figure out what was wrong. Any help would be much appreciated.

答: Apparently, it was the double quotes on the ExecStart that were causing trouble. I'll test everything and edit this answer once I'm sure it's working.</p>

Body:
I'm trying to get LibreOffice (more specifically, soffice) to run as a service on an Ubuntu server (20.04.3), but I've just not been able to make it work. It's the first time I'm trying to set up a custom service, so the likelihood that it's just configured wrong is very high.

Basically, I want to keep soffice running in headless mode, listening in a socket. The command I use for it is:

/usr/bin/soffice --headless --accept='socket,host=127.0.0.1,port=8100;urp;' --nofirststartwizard

From all I can see, this command seems to be working. No output whatsoever when I run it manually, and it blocks the terminal, supposedly waiting for incoming connections.

So, to run it as a service, I created the following soffice.service file on /etc/systemd/system:

[Unit]
Description=LibreOffice service
After=syslog.target

[Service]
ExecStart=soffice "--headless --accept='socket,host=127.0.0.1,port=8100;urp;' --nofirststartwizard"
Restart=always
KillSignal=SIGQUIT
Type=simple
StandardError=syslog
User=www-data

[Install]
WantedBy=multi-user.target

After enabling and starting it, I get the following on systemctl status soffice:

● soffice.service - LibreOffice service
     Loaded: loaded (/etc/systemd/system/soffice.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Sun 2022-02-06 17:18:40 WET; 4s ago
    Process: 24786 ExecStart=/usr/bin/soffice --headless --accept='socket,host=127.0.0.1,port=8100;urp;' --nofirststartwizard (code=exited, status=1/FAILURE)
   Main PID: 24786 (code=exited, status=1/FAILURE)

I'm guessing the issue is on the ExecStart directive, but despite reading the documentation – which is hard to follow for me, since I only use linux to keep my webserver running – I just couldn't figure out what was wrong. Any help would be much appreciated.


来源: stackexchange

问:
Xamarin iOS code signing key not found in keychain
I'm trying to debug my Xamarin.Forms application on a physical iPhone, from my windows machine.

I have a Mac connected, and an iPhone connected to that Mac

I have an Apple developer certificate

I have the device linked to my developer account

I set up automatic provisioning using Visual Studio (17.0.5)

I downloaded the generated certificate, and installed it:

On the Mac in the System keychain and Login keychain

On my windows machine running Visual Studio

When I try to deploy my application in Debug|iPhone, I get the following error:

iOS code signing key 'Apple Development: John Doe (5L4565FZ2L)' not found in keychain.

More details from the build output in Visual Studio:

```<code>2>Using "DetectSigningIdentity" task from assembly "C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Xamarin\iOS\..\iOS\Xamarin.iOS.Tasks.dll".
2>Task "DetectSigningIdentity"
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9039262+01:00 - Started
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9039262+01:00 - Initializing
2>  [xma]: Trying to get a Build Connection for Session '6b535ab5f3c9b550fa521b36f236660807d516f929527c4e1cb2a3ecca9ec40d': Xamarin.Messaging.Build.Client.BuildConnection.6b535ab5f3c9b550fa521b36f236660807d516f929527c4e1cb2a3ecca9ec40d, Lifetime: AppDomain
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9039262+01:00 - Initialized
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9039262+01:00 - There's no available inputs to copy to the Mac
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9039262+01:00 - Serializing intputs
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9079268+01:00 - Executing
2>  [xma]: Starting remote task execution for 'Writeful.Mobile.iOS': Xamarin.iOS.Tasks.DetectSigningIdentity
2>  [xma]: Sending Request Xamarin.Messaging.Build.Contracts.ExecuteTaskMessage to topic xvs/build/execute-task/Writeful.Mobile.iOS/6b535ab002fDetectSigningIdentity
2>  [xma]: Received Response of Xamarin.Messaging.Build.Contracts.ExecuteTaskMessage to topic build6b535ab5f3c9b550fa521b36f236660807d516f929527c4e1cb2a3ecca9ec40d47080johndoe/+/xvs/build/execute-task/Writeful.Mobile.iOS/6b535ab002fDetectSigningIdentity
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9499278+01:00 - Logging messages
2>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Xamarin\iOS\Xamarin.Shared.targets(1566,3): error : iOS code signing key 'Apple Development: John Doe (5L4565FZ2L)' not found in keychain.
2>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Xamarin\iOS\Xamarin.Shared.targets(1566,3): error :
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9499278+01:00 - Finished
2>Done executing task "DetectSigningIdentity" -- FAILED.
2>Done building target "_DetectSigningIdentity" in project "Writeful.Mobile.iOS.csproj" -- FAILED.
2>
2>Build FAILED.
2>
2>"C:\Users\johndoe\source\repos\johndoe\writeful-app\Writeful.Mobile.iOS\Writeful.Mobile.iOS.csproj" (Build;BuiltProjectOutputGroup;BuiltProjectOutputGroupDependencies;DebugSymbolsProjectOutputGroup;DebugSymbolsProjectOutputGroupDependencies;DocumentationProjectOutputGroup;DocumentationProjectOutputGroupDependencies;SatelliteDllsProjectOutputGroup;SatelliteDllsProjectOutputGroupDependencies;SGenFilesOutputGroup;SGenFilesOutputGroupDependencies target) (1) ->
2>(_DetectSigningIdentity target) ->
2>  C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Xamarin\iOS\Xamarin.Shared.targets(1566,3): error : iOS code signing key 'Apple Development: John Doe (5L4565FZ2L)' not found in keychain.
2>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Xamarin\iOS\Xamarin.Shared.targets(1566,3): error :
2>
2>    0 Warning(s)
2>    1 Error(s)
2>
2>Time Elapsed 00:00:01.23
========== Build: 1 succeeded, 1 failed, 21 up-to-date, 0 skipped ==========
========== Deploy: 0 succeeded, 0 failed, 0 skipped ==========

</code>```

I'm not sure which device is missing the signing key, but I assume it is the iPhone, since I installed the certificate on the Mac.

If this is the issue, how can I transfer the certificate to the iPhone? I already tried by deploying an empty app from Xcode on the Mac to the iPhone, but that didn't work.

答:
it might be VS issue. Please refer this official Link where issue is fixed.
Please make sure you're using latest version. Check Here</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to debug my Xamarin.Forms application on a physical iPhone, from my windows machine.

I have a Mac connected, and an iPhone connected to that Mac

I have an Apple developer certificate

I have the device linked to my developer account

I set up automatic provisioning using Visual Studio (17.0.5)

I downloaded the generated certificate, and installed it:

On the Mac in the System keychain and Login keychain

On my windows machine running Visual Studio

When I try to deploy my application in Debug|iPhone, I get the following error:

iOS code signing key 'Apple Development: John Doe (5L4565FZ2L)' not found in keychain.

More details from the build output in Visual Studio:

2>Using "DetectSigningIdentity" task from assembly "C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Xamarin\iOS\..\iOS\Xamarin.iOS.Tasks.dll".
2>Task "DetectSigningIdentity"
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9039262+01:00 - Started
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9039262+01:00 - Initializing
2>  [xma]: Trying to get a Build Connection for Session '6b535ab5f3c9b550fa521b36f236660807d516f929527c4e1cb2a3ecca9ec40d': Xamarin.Messaging.Build.Client.BuildConnection.6b535ab5f3c9b550fa521b36f236660807d516f929527c4e1cb2a3ecca9ec40d, Lifetime: AppDomain
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9039262+01:00 - Initialized
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9039262+01:00 - There's no available inputs to copy to the Mac
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9039262+01:00 - Serializing intputs
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9079268+01:00 - Executing
2>  [xma]: Starting remote task execution for 'Writeful.Mobile.iOS': Xamarin.iOS.Tasks.DetectSigningIdentity
2>  [xma]: Sending Request Xamarin.Messaging.Build.Contracts.ExecuteTaskMessage to topic xvs/build/execute-task/Writeful.Mobile.iOS/6b535ab002fDetectSigningIdentity
2>  [xma]: Received Response of Xamarin.Messaging.Build.Contracts.ExecuteTaskMessage to topic build6b535ab5f3c9b550fa521b36f236660807d516f929527c4e1cb2a3ecca9ec40d47080johndoe/+/xvs/build/execute-task/Writeful.Mobile.iOS/6b535ab002fDetectSigningIdentity
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9499278+01:00 - Logging messages
2>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Xamarin\iOS\Xamarin.Shared.targets(1566,3): error : iOS code signing key 'Apple Development: John Doe (5L4565FZ2L)' not found in keychain.
2>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Xamarin\iOS\Xamarin.Shared.targets(1566,3): error :
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9499278+01:00 - Finished
2>Done executing task "DetectSigningIdentity" -- FAILED.
2>Done building target "_DetectSigningIdentity" in project "Writeful.Mobile.iOS.csproj" -- FAILED.
2>
2>Build FAILED.
2>
2>"C:\Users\johndoe\source\repos\johndoe\writeful-app\Writeful.Mobile.iOS\Writeful.Mobile.iOS.csproj" (Build;BuiltProjectOutputGroup;BuiltProjectOutputGroupDependencies;DebugSymbolsProjectOutputGroup;DebugSymbolsProjectOutputGroupDependencies;DocumentationProjectOutputGroup;DocumentationProjectOutputGroupDependencies;SatelliteDllsProjectOutputGroup;SatelliteDllsProjectOutputGroupDependencies;SGenFilesOutputGroup;SGenFilesOutputGroupDependencies target) (1) ->
2>(_DetectSigningIdentity target) ->
2>  C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Xamarin\iOS\Xamarin.Shared.targets(1566,3): error : iOS code signing key 'Apple Development: John Doe (5L4565FZ2L)' not found in keychain.
2>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Xamarin\iOS\Xamarin.Shared.targets(1566,3): error :
2>
2>    0 Warning(s)
2>    1 Error(s)
2>
2>Time Elapsed 00:00:01.23
========== Build: 1 succeeded, 1 failed, 21 up-to-date, 0 skipped ==========
========== Deploy: 0 succeeded, 0 failed, 0 skipped ==========

I'm not sure which device is missing the signing key, but I assume it is the iPhone, since I installed the certificate on the Mac.

If this is the issue, how can I transfer the certificate to the iPhone? I already tried by deploying an empty app from Xcode on the Mac to the iPhone, but that didn't work.


问:
Why does my code keep printing the first data in the array?
```<code>i = 0
one_adult = [20.00,30.00]
one_child = [12.00,18.00]
one_senior = [16.00,24.00]
family_ticket = [60.00,90.00]
groups_of_six = [15.00,22.50]
lion_feeding = 2.50
penguin_feeding = 2.00
evening_barbecue = 5.00

Ticket_Type = ["one_adult",one_adult[i],"one_child",one_child[i],"one_senior",one_senior[i],"family_ticket",family_ticket[i],"groups_of_six",groups_of_six[i]]

Attractions_1day = ["lion_feeding",lion_feeding,"penguin_feeding",penguin_feeding]
Attractions_2day = ["lion_feeding",lion_feeding,"penguin_feeding",penguin_feeding,"evening_barbecue",evening_barbecue]

option = input("are you buying tickets for one day? (yes or no)")
if option == "yes" :
  print()
  print("These are ticket types available for one day tickets and their prices $")
  print()
  print(Ticket_Type)
  print()
  print("These are the attractions available for one day tickets and their prices $")
  print()
  print(Attractions_1day)
elif option == "no" :
  i = i + 1
  print()
  print("These are ticket types available for two day tickets and their prices $")
  print()
  print(Ticket_Type)
  print()
  print("These are the attractions available for two day tickets and their prices $")
  print()
  print(Attractions_2day)
</code>```

Why does it keep printing the data when i = 0 and not the data when i = 1?
It is supposed to print one_adult, 30 not one_adult 20 etc
The program is supposed to display the options available for people to buy tickets (1 day / 2 day)

答:
Check your code properly, You have specified i=0 and and in every place in the Ticket_type array you have put one_adult[i] which is just the first element of the array i.e "20".
You haven't increased the value of i after every iteration. like you have to put loops to increase the value so that other elements of the array is printed.

To solve your problem do this

```<code>["one_adult",one_adult[0],"one_child",one_child[1],"one_senior",one_senior[2],"family_ticket",family_ticket[3],"groups_of_six",groups_of_six[4]]
</code>```

Reply if this was helpful or you want better explanation.

Body:
i = 0
one_adult = [20.00,30.00]
one_child = [12.00,18.00]
one_senior = [16.00,24.00]
family_ticket = [60.00,90.00]
groups_of_six = [15.00,22.50]
lion_feeding = 2.50
penguin_feeding = 2.00
evening_barbecue = 5.00

Ticket_Type = ["one_adult",one_adult[i],"one_child",one_child[i],"one_senior",one_senior[i],"family_ticket",family_ticket[i],"groups_of_six",groups_of_six[i]]

Attractions_1day = ["lion_feeding",lion_feeding,"penguin_feeding",penguin_feeding]
Attractions_2day = ["lion_feeding",lion_feeding,"penguin_feeding",penguin_feeding,"evening_barbecue",evening_barbecue]

option = input("are you buying tickets for one day? (yes or no)")
if option == "yes" :
  print()
  print("These are ticket types available for one day tickets and their prices $")
  print()
  print(Ticket_Type)
  print()
  print("These are the attractions available for one day tickets and their prices $")
  print()
  print(Attractions_1day)
elif option == "no" :
  i = i + 1
  print()
  print("These are ticket types available for two day tickets and their prices $")
  print()
  print(Ticket_Type)
  print()
  print("These are the attractions available for two day tickets and their prices $")
  print()
  print(Attractions_2day)

Why does it keep printing the data when i = 0 and not the data when i = 1?
It is supposed to print one_adult, 30 not one_adult 20 etc
The program is supposed to display the options available for people to buy tickets (1 day / 2 day)

Body:
Check your code properly, You have specified i=0 and and in every place in the Ticket_type array you have put one_adult[i] which is just the first element of the array i.e "20".
You haven't increased the value of i after every iteration. like you have to put loops to increase the value so that other elements of the array is printed.

To solve your problem do this

["one_adult",one_adult[0],"one_child",one_child[1],"one_senior",one_senior[2],"family_ticket",family_ticket[3],"groups_of_six",groups_of_six[4]]

Reply if this was helpful or you want better explanation.


问:
My program returns 4 instead of expected value 40
```<code>#include <stdio.h>

int value(int *a);

int main(){
    int num = 4;
    value(&num);
    printf("value of number is = %d", num);
    return 0;
}

int value(int *a){
    int c = (*a)*10;
    return c;
}
</code>```

In this code, I transfer the address in function but it does not change, Why?

答:
You have 2 ways of having a function change data outside it: you can pass a variable by reference and update it, or you can return a value and use that. You are mixing half of each method instead. I reordered the code to make my commentary clearer.

```<code>#include <stdio.h>

int value(int *a);

// here you are passing by reference, good
int value(int *a){
    int c = (*a)*10; // but you don't change a
    return c;  // instead you return a new value
}

int main(){
    int num = 4;
    value(&num); // but here you ignore the new value.
    printf("value of number is = %d", num);
    return 0;
}
</code>```

to make reference way work, you need:

```<code>#include <stdio.h>

void value(int *a);

int main(){
    int num = 4;
    value(&num);
    printf("value of number is = %d", num);
    return 0;
}

void value(int *a){
    *a = (*a)*10; // change the value that a points at
    // no need to return anything
}
</code>```

or to make the return way work:

```<code>#include <stdio.h>
// no need to pass by reference
int value(int a);

int main(){
    int num = 4;
    num = value(num); // use value return by function
    printf("value of number is = %d", num);
    return 0;
}

int value(int a){
    int c = a * 10;
    return c;
}
</code>```

Body:
#include <stdio.h>

int value(int *a);

int main(){
    int num = 4;
    value(&num);
    printf("value of number is = %d", num);
    return 0;
}

int value(int *a){
    int c = (*a)*10;
    return c;
}

In this code, I transfer the address in function but it does not change, Why?

Body:
You have 2 ways of having a function change data outside it: you can pass a variable by reference and update it, or you can return a value and use that. You are mixing half of each method instead. I reordered the code to make my commentary clearer.

#include <stdio.h>

int value(int *a);

// here you are passing by reference, good
int value(int *a){
    int c = (*a)*10; // but you don't change a
    return c;  // instead you return a new value
}

int main(){
    int num = 4;
    value(&num); // but here you ignore the new value.
    printf("value of number is = %d", num);
    return 0;
}

to make reference way work, you need:

#include <stdio.h>

void value(int *a);

int main(){
    int num = 4;
    value(&num);
    printf("value of number is = %d", num);
    return 0;
}

void value(int *a){
    *a = (*a)*10; // change the value that a points at
    // no need to return anything
}

or to make the return way work:

#include <stdio.h>
// no need to pass by reference
int value(int a);

int main(){
    int num = 4;
    num = value(num); // use value return by function
    printf("value of number is = %d", num);
    return 0;
}

int value(int a){
    int c = a * 10;
    return c;
}


问:
Extract Microsoft Graph Chart Object from Excel file
I need to extract Microsoft Graph Chart that is embedded in Ms Excel files externally and save it to MySQL database. The data I need is the value in the datasheet that made up the chart. (It appears when you double click the chart). I have tried to use PHP Excel library, but it can only access the data in the cells, not embedded object's data.

I am open to use any tool, PHP, PERL, Python, Java or anything as long as I can get the job done.

Sample excel file that contain the embedded Ms Graph Chart : http://www.sendspace.com/file/8rd1jg

Any information/thoughts will be much appreciated!

答:
Just to clarify, I doubt it's a Microsoft Graph object in the Excel workbook. Microsoft Graph was the applet used by PowerPoint and Word to insert charts in Office 2003 and earlier.

So if you have to hunt in Google for help, you'll find more information, which is more relevant, if you search for Excel Chart, rather than Microsoft Graph.

ContentLicense: CC BY-SA 3.0


问:
postgres r2dbc gives ssl error but connects using jpa
r2dbc config:

```<code>spring:
  profiles: default   r2dbc:
  url: r2dbc:postgresql://testserver.dev.net:1234/test?ssl=true&sslmode=require
  username: test
  password: test
  connection_timeout: 20000
</code>```

jpa config:

```<code>spring:
profiles: default
  datasource:
    url: jdbc:postgresql://testserver.dev.net:1234/test?ssl=true&sslmode=require
    username: test
    password: test
    hikari:
        connectionTimeout: 20000
        maximumPoolSize: 5
</code>```

The jpa connection works fine and returns the results, r2dbc fails to connect to the server sighting unable to find valid certificate

Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

with r2dbc and ssl off it says pg_hba.conf does not have entry for the host. Why does it only asks for certificate with r2dbc config.

dependencies with r2dbc:

```<code><dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-r2dbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency> <dependency>
        <groupId>io.r2dbc</groupId>
        <artifactId>r2dbc-postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
</code>```

with jpa I am using spring web starter and jpa starter, both are spring version 2.4.1.
I am stuck with this, cant find a reason for this error. Any solutions are welcome.

答:
If you have all the certificates, here is the configuration you can use, It worked for me. Make sure the certificates are in resources folder & they should be only in pem format.</p>
```<code>spring:
  config:
    activate:
      on-profile: dev
  r2dbc:
    url: r2dbc:pool:postgresql://<DB_HOST>:<DB_PORT>/<DB_NAME>
    username: <DB_USER>
    password: <DB_PASSWORD>
    properties:
      ssl: true
      sslMode: VERIFY_CA
      sslRootCert: root.pem
      sslCert: server.pem
      sslKey: key.pem
</code>```

Body:
r2dbc config:

spring:
  profiles: default   r2dbc:
  url: r2dbc:postgresql://testserver.dev.net:1234/test?ssl=true&sslmode=require
  username: test
  password: test
  connection_timeout: 20000

jpa config:

spring:
profiles: default
  datasource:
    url: jdbc:postgresql://testserver.dev.net:1234/test?ssl=true&sslmode=require
    username: test
    password: test
    hikari:
        connectionTimeout: 20000
        maximumPoolSize: 5

The jpa connection works fine and returns the results, r2dbc fails to connect to the server sighting unable to find valid certificate

Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

with r2dbc and ssl off it says pg_hba.conf does not have entry for the host. Why does it only asks for certificate with r2dbc config.

dependencies with r2dbc:

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-r2dbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency> <dependency>
        <groupId>io.r2dbc</groupId>
        <artifactId>r2dbc-postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>

with jpa I am using spring web starter and jpa starter, both are spring version 2.4.1.
I am stuck with this, cant find a reason for this error. Any solutions are welcome.

Body:
If you have all the certificates, here is the configuration you can use, It worked for me. Make sure the certificates are in resources folder & they should be only in pem format.

spring:
  config:
    activate:
      on-profile: dev
  r2dbc:
    url: r2dbc:pool:postgresql://<DB_HOST>:<DB_PORT>/<DB_NAME>
    username: <DB_USER>
    password: <DB_PASSWORD>
    properties:
      ssl: true
      sslMode: VERIFY_CA
      sslRootCert: root.pem
      sslCert: server.pem
      sslKey: key.pem


问:
Not working Godady CA certs using Plug in certificates and key into the cluster in the ISTIO
I have started working on istio implementation and able to see some progress. Have got few doubts and I see myself missing something in the documentation....

Currently, I am using a gateway, virtual service, destination rules, authorization services for 2 deployments and I am able to see the graph with mTLS enabled in the kiali dashboard. and it's all working fine.

As I have to use now GoDaddy CA certs, gone through the documentation regarding "Plug in certificates and key into the cluster", looks like during the fresh installation of the istio it's picking custom CA certs but with below errors

```<code>2022-02-03T16:23:31.337162Z info    initializing mesh networks from mesh config watcher
2022-02-03T16:23:31.337167Z info    initializing mesh handlers
2022-02-03T16:23:31.337178Z info    creating CA and initializing public key
2022-02-03T16:23:31.337214Z info    Use local CA certificate
Error: failed to create discovery service: failed to create CA: failed to create an istiod CA: certificate is not authorized to sign other certificates
2022-02-03T16:23:31.338090Z error   failed to create discovery service: failed to create CA: failed to create an istiod CA: certificate is not authorized to sign other certificates
</code>```

I am a bit stuck in this and exploring for any other approaches if I have to look into anything if I am missing.

Can you please advise with some of the inputs regarding this.

答:
If I am understanding you correctly you are talking about this page and trying to issue certs on behalf of GoDaddy. This will not work (unless you are the owner of GoDaddy..)

You most likely do not need this setup unless perhaps you are running two clusters.

If using AWS you would normally have an ALB connected to your Istio Gateway (NodePort) via HTTPS.  Let Istio use self signed certs.

Body:
I have started working on istio implementation and able to see some progress. Have got few doubts and I see myself missing something in the documentation....

Currently, I am using a gateway, virtual service, destination rules, authorization services for 2 deployments and I am able to see the graph with mTLS enabled in the kiali dashboard. and it's all working fine.

As I have to use now GoDaddy CA certs, gone through the documentation regarding "Plug in certificates and key into the cluster", looks like during the fresh installation of the istio it's picking custom CA certs but with below errors

2022-02-03T16:23:31.337162Z info    initializing mesh networks from mesh config watcher
2022-02-03T16:23:31.337167Z info    initializing mesh handlers
2022-02-03T16:23:31.337178Z info    creating CA and initializing public key
2022-02-03T16:23:31.337214Z info    Use local CA certificate
Error: failed to create discovery service: failed to create CA: failed to create an istiod CA: certificate is not authorized to sign other certificates
2022-02-03T16:23:31.338090Z error   failed to create discovery service: failed to create CA: failed to create an istiod CA: certificate is not authorized to sign other certificates

I am a bit stuck in this and exploring for any other approaches if I have to look into anything if I am missing.

Can you please advise with some of the inputs regarding this.


问:
How do I save a timestamp to a mysql database?
I have a table in mysql for people's posts. But I'd like to be able to get the time the post was made? How do I do it? Any help will be appreciated. The language I'm using is PHP and I'm using prepared statements.
Is it as simple as specifying a column in the database with the datatype TIMESTAMP? And how do I read a timestamp and convert it to a date?</p>

答:
When specifying a column in the database, Use datetime and as default, select current time

If you want to use this data, just extract from database and use date('y/m/d', strtotime($time));


问:
Show/Hide Html sections on button click
I have 3 sections of code in the same page, in those 3 sections I have submit buttons.
Initially 1st section should be visible, 2nd and 3rd sections are hidden. On button click from 1st section, 2nd section should become visible and hide 1st and 3rd sections. On button click from 2nd section, 1st and 2nd sections should be hidden and 3rd section should be visible.
Can someone please help?</p>

答:
Try this code

$(document).ready(function(){
    $('.section:not(:first-child)').hide();

    $(".section button").click(function(){
        $('.section').hide();

        if( $(this).closest('.section').is(':last-child') ){
            $(this).closest('.section').siblings().first().show();
        }else{
            $(this).closest('.section').next().show();
        }
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
    <section class="section">
        <div>
            <h2>Section 1</h2>
            <p>Ut ex consequat enim ullamco in do do proident ut sint adipisicing mollit do tempor.</p>
        </div>
        <button>Button 1</button>
    </section>
    <section class="section">
        <div>
            <h2>Section 2</h2>
            <p>Veniam occaecat aliquip do irure incididunt consectetur aliquip do sit aute non duis mollit sed consequat.</p>
        </div>
        <button>Button 2</button>
    </section>
    <section class="section">
        <div>
            <h2>Section 3</h2>
            <p>Sit anim ea eiusmod nulla ut laboris minim consectetur labore anim mollit id excepteur.</p>
        </div>
        <button>Button 3</button>
    </section>
</div></code>```

Title: Show/Hide Html sections on button click

Body:
Try this code

$(document).ready(function(){
    $('.section:not(:first-child)').hide();

    $(".section button").click(function(){
        $('.section').hide();

        if( $(this).closest('.section').is(':last-child') ){
            $(this).closest('.section').siblings().first().show();
        }else{
            $(this).closest('.section').next().show();
        }
    });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
    <section class="section">
        <div>
            <h2>Section 1</h2>
            <p>Ut ex consequat enim ullamco in do do proident ut sint adipisicing mollit do tempor.</p>
        </div>
        <button>Button 1</button>
    </section>
    <section class="section">
        <div>
            <h2>Section 2</h2>
            <p>Veniam occaecat aliquip do irure incididunt consectetur aliquip do sit aute non duis mollit sed consequat.</p>
        </div>
        <button>Button 2</button>
    </section>
    <section class="section">
        <div>
            <h2>Section 3</h2>
            <p>Sit anim ea eiusmod nulla ut laboris minim consectetur labore anim mollit id excepteur.</p>
        </div>
        <button>Button 3</button>
    </section>
</div>


答:
Move the line:

```<code>Ticket_Type = ["one_adult",one_adult[i],"one_child",one_child[i],"one_senior",one_senior[i],"family_ticket",family_ticket[i],"groups_of_six",groups_of_six[i]]
</code>```

to if and elif clause

```<code>if option == "yes" :
//Here
  Ticket_Type = ["one_adult",one_adult[i],"one_child",one_child[i],"one_senior",one_senior[i],"family_ticket",family_ticket[i],"groups_of_six",groups_of_six[i]]
  print()
  print("These are ticket types available for one day tickets and their prices $")
  print()
  print(Ticket_Type)
  print()
  print("These are the attractions available for one day tickets and their prices $")
  print()
  print(Attractions_1day)
elif option == "no" :
  i = i + 1
//And here.
  Ticket_Type = ["one_adult",one_adult[i],"one_child",one_child[i],"one_senior",one_senior[i],"family_ticket",family_ticket[i],"groups_of_six",groups_of_six[i]]
  print()
  print("These are ticket types available for two day tickets and their prices $")
  print()
  print(Ticket_Type)
  print()
  print("These are the attractions available for two day tickets and their prices $")
  print()
  print(Attractions_2day)
</code>```

Title: Why does my code keep printing the first data in the array?

Body:
Move the line:

Ticket_Type = ["one_adult",one_adult[i],"one_child",one_child[i],"one_senior",one_senior[i],"family_ticket",family_ticket[i],"groups_of_six",groups_of_six[i]]

to if and elif clause

if option == "yes" :
//Here
  Ticket_Type = ["one_adult",one_adult[i],"one_child",one_child[i],"one_senior",one_senior[i],"family_ticket",family_ticket[i],"groups_of_six",groups_of_six[i]]
  print()
  print("These are ticket types available for one day tickets and their prices $")
  print()
  print(Ticket_Type)
  print()
  print("These are the attractions available for one day tickets and their prices $")
  print()
  print(Attractions_1day)
elif option == "no" :
  i = i + 1
//And here.
  Ticket_Type = ["one_adult",one_adult[i],"one_child",one_child[i],"one_senior",one_senior[i],"family_ticket",family_ticket[i],"groups_of_six",groups_of_six[i]]
  print()
  print("These are ticket types available for two day tickets and their prices $")
  print()
  print(Ticket_Type)
  print()
  print("These are the attractions available for two day tickets and their prices $")
  print()
  print(Attractions_2day)


问:
How to extract the maximum value key from an array?
[1]: https://i.stack.imgur.com/szHJJ.png [2]: https://i.stack.imgur.com/8Oic4.png
There is an array, you need to pull the maximum value and its key from it. Each number from the array has its own key, and I need to pull exactly the one that is associated with the maximum number. With the help of regularity, I pulled out the numbers and through jsr 223, the sampler found the maximum number. Now the question is: how to extract the key of exactly the maximum number? Don't kick, a week since I started studying jmeter after lr, so I'm suffering. And the text was translated into English through a translator.

The key itself from part of the array (what needs to be pulled): dUUyTlFoUmhQMmExbCtFZ2VCY09uQT09LS1FK3lZbzJlakFUeEJoNlhCV3poRzV3PT0=--4814f46102fd5ecaf9f440be0a8925644927b3d0 described above the way to find the maximum number, in my case
the number 69, now i need to somehow find the key to the maximum number and then apply it in the request.

Part of the array:

```<code>dUUyTlFoUmhQMmExbCtFZ2VCY09uQT09LS1FK3lZbzJlakFUeEJoNlhCV3poRzV3PT0=--4814f46102fd5ecaf9f440be0a8925644927b3d0" /><label class="collection_radio_buttons" for="challenger_order_selected_duuytlfoumhqmmexbctfz2vcy09uqt09ls1fk3lzbzjlakfueejonlhcv3porzv3pt0--4814f46102fd5ecaf9f440be0a8925644927b3d0">69</label></span></div>```
```

答:
You already have the value and even highlighted it in blue, just iterate through existing JMeter Variables values, get the match number and get the key which corresponds to the match number.

Example code:

```<code>for (int i = 1; i < (vars.get('maxValue_matchNr') as int); i++) {
    if (vars.get('maxValue_' + i + '_g2').equals(vars.get('maxValue_max'))) {
        vars.put('maxKey_max', vars.get('maxValue_' + i + '_g1'))
        break;
    }
}
</code>```

You should be able to refer the extracted value as ${maxKey_max} where required.

Also using "regularity" for getting the values from HTML might not be the best idea, maybe it worth considering using CSS Selector Extractor instead?

Body:
[1]: https://i.stack.imgur.com/szHJJ.png [2]: https://i.stack.imgur.com/8Oic4.png
There is an array, you need to pull the maximum value and its key from it. Each number from the array has its own key, and I need to pull exactly the one that is associated with the maximum number. With the help of regularity, I pulled out the numbers and through jsr 223, the sampler found the maximum number. Now the question is: how to extract the key of exactly the maximum number? Don't kick, a week since I started studying jmeter after lr, so I'm suffering. And the text was translated into English through a translator.

The key itself from part of the array (what needs to be pulled): dUUyTlFoUmhQMmExbCtFZ2VCY09uQT09LS1FK3lZbzJlakFUeEJoNlhCV3poRzV3PT0=--4814f46102fd5ecaf9f440be0a8925644927b3d0 described above the way to find the maximum number, in my case
the number 69, now i need to somehow find the key to the maximum number and then apply it in the request.

Part of the array:

dUUyTlFoUmhQMmExbCtFZ2VCY09uQT09LS1FK3lZbzJlakFUeEJoNlhCV3poRzV3PT0=--4814f46102fd5ecaf9f440be0a8925644927b3d0" />69
```

Body:
You already have the value and even highlighted it in blue, just iterate through existing JMeter Variables values, get the match number and get the key which corresponds to the match number.

Example code:

for (int i = 1; i < (vars.get('maxValue_matchNr') as int); i++) {
    if (vars.get('maxValue_' + i + '_g2').equals(vars.get('maxValue_max'))) {
        vars.put('maxKey_max', vars.get('maxValue_' + i + '_g1'))
        break;
    }
}

You should be able to refer the extracted value as ${maxKey_max} where required.

Also using "regularity" for getting the values from HTML might not be the best idea, maybe it worth considering using CSS Selector Extractor instead?


问:
Show DisclosureGroup view based on state
I'm fairly new to SwiftUI, and I'm having trouble wrapping my head around the following issue I ran into. I have a button which toggles a state property, and I'd like to display a DisclosureGroup when the button's state is toggle on. For some reason, I can display any sort of view with my code below, with the exception of a DisclosureGroup:

```<code>@Binding var showing : Bool
@Binding var revealDetails : Bool

var body: some View {

    if showing {

        VStack {
            DisclosureGroup("Monday", isExpanded: $revealDetails){
                    Text("7PM - 10PM").frame(height: 100)
                }
            .frame(width: 150)
                .buttonStyle(PlainButtonStyle()).accentColor(.black)

        }
    }

}
</code>```

}

The above code does not work when I present in my ContentView, however, the strange thing is, if I add some sort of empty view above the DisclosureGroup, it does work. So for now, I'm including a Text("") inside the VStack. Any thoughts on why this is?

答:
I think you're not passing correct values to your bindings, i can tell you clearly after seeing your code in ContentView as you haven't attached it in the question but you can copy paste below code and customise it depending on your needs.

ContentView

```<code>import SwiftUI

struct ContentView: View {

    // MARK: - PROPERTIES

    @State private var showDiscloureGroup = false
    @State private var showDetails = false

    // MARK: - BODY

    var body: some View {
        VStack{
            Toggle("Show Disclosure Group", isOn: $showDiscloureGroup)
            Toggle("Show Details", isOn: $showDetails)

            MyDiscloureGroup(showing: $showDiscloureGroup, revealDetails: $showDetails)
        }//: VSTACK
        .padding()
    }
}

// MARK: - PREVIEW
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

MyDiscloureGroupView

```<code>import SwiftUI

struct MyDiscloureGroupView: View {

    @Binding var showing : Bool
    @Binding var revealDetails : Bool

    var body: some View {
        if showing {
            VStack {
                DisclosureGroup("Monday", isExpanded: $revealDetails){
                        Text("7PM - 10PM").frame(height: 100)
                    }
                .frame(width: 150)
                    .buttonStyle(PlainButtonStyle()).accentColor(.black)
            }
        }
    }
}

struct MyDiscloureGroup_Previews: PreviewProvider {
    static var previews: some View {
        MyDiscloureGroupView(showing: .constant(true), revealDetails: .constant(true))
    }
}
</code>```

Body:
I'm fairly new to SwiftUI, and I'm having trouble wrapping my head around the following issue I ran into. I have a button which toggles a state property, and I'd like to display a DisclosureGroup when the button's state is toggle on. For some reason, I can display any sort of view with my code below, with the exception of a DisclosureGroup:

@Binding var showing : Bool
@Binding var revealDetails : Bool

var body: some View {

    if showing {

        VStack {
            DisclosureGroup("Monday", isExpanded: $revealDetails){
                    Text("7PM - 10PM").frame(height: 100)
                }
            .frame(width: 150)
                .buttonStyle(PlainButtonStyle()).accentColor(.black)

        }
    }

}

}

The above code does not work when I present in my ContentView, however, the strange thing is, if I add some sort of empty view above the DisclosureGroup, it does work. So for now, I'm including a Text("") inside the VStack. Any thoughts on why this is?

Body:
I think you're not passing correct values to your bindings, i can tell you clearly after seeing your code in ContentView as you haven't attached it in the question but you can copy paste below code and customise it depending on your needs.

ContentView

import SwiftUI

struct ContentView: View {

    // MARK: - PROPERTIES

    @State private var showDiscloureGroup = false
    @State private var showDetails = false

    // MARK: - BODY

    var body: some View {
        VStack{
            Toggle("Show Disclosure Group", isOn: $showDiscloureGroup)
            Toggle("Show Details", isOn: $showDetails)

            MyDiscloureGroup(showing: $showDiscloureGroup, revealDetails: $showDetails)
        }//: VSTACK
        .padding()
    }
}

// MARK: - PREVIEW
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

MyDiscloureGroupView

import SwiftUI

struct MyDiscloureGroupView: View {

    @Binding var showing : Bool
    @Binding var revealDetails : Bool

    var body: some View {
        if showing {
            VStack {
                DisclosureGroup("Monday", isExpanded: $revealDetails){
                        Text("7PM - 10PM").frame(height: 100)
                    }
                .frame(width: 150)
                    .buttonStyle(PlainButtonStyle()).accentColor(.black)
            }
        }
    }
}

struct MyDiscloureGroup_Previews: PreviewProvider {
    static var previews: some View {
        MyDiscloureGroupView(showing: .constant(true), revealDetails: .constant(true))
    }
}


问:
Return PDF to WebPage from ASHX
I have a web page with a "download" link on it.

Using jQuery I do an Ajax Get to a ASHX file.

In the ASHX I get the Stream of the file.  I then convert the stream to a byte array and return the byte array back to the calling html page;

jQuery

```<code>$(".DownloadConvertedPDF").click(function () {
  var bookId = $(this).attr("bookId");

  $.get('/UserControls/download.ashx?format=pdf&bookId=' + bookId, {}, function (data) { });

});
</code>```

C#

```<code>context.Response.ContentType = "Application/pdf";
Stream fileStream = publishBookManager.GetFile(documentId);
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
  int read;
  while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
  {
    ms.Write(buffer, 0, read);
  }
}

context.Response.OutputStream.Write(buffer, 0, buffer.Length);
</code>```

I don't get an error but also the PDF doesn't display on screen.

Ideally I'd like the pdf returned and the jQuery to launch the pdf in a seperate tab within the browser.

How can I make this happen or what am I doing wrong?

答:
Try this (do not use .get):

```<code>window.open('/UserControls/download.ashx?format=pdf&bookId=' + bookId, "pdfViewer");
</code>```

To prevent the "File does not begin with '%PDF" error, use Response.BinaryWrite:

```<code>context.Response.Clear();
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.ContentType = "application/pdf";

Stream fileStream = publishBookManager.GetFile(documentId);
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
  int read;
  while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
  {
    ms.Write(buffer, 0, read);
  }
}

context.Response.BinaryWrite(data);
context.Response.Flush();
</code>```

Title: Return PDF to WebPage from ASHX

Body:
I have a web page with a "download" link on it.

Using jQuery I do an Ajax Get to a ASHX file.

In the ASHX I get the Stream of the file.  I then convert the stream to a byte array and return the byte array back to the calling html page;

jQuery

$(".DownloadConvertedPDF").click(function () {
  var bookId = $(this).attr("bookId");

  $.get('/UserControls/download.ashx?format=pdf&bookId=' + bookId, {}, function (data) { });

});

C#

context.Response.ContentType = "Application/pdf";
Stream fileStream = publishBookManager.GetFile(documentId);
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
  int read;
  while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
  {
    ms.Write(buffer, 0, read);
  }
}

context.Response.OutputStream.Write(buffer, 0, buffer.Length);

I don't get an error but also the PDF doesn't display on screen.

Ideally I'd like the pdf returned and the jQuery to launch the pdf in a seperate tab within the browser.

How can I make this happen or what am I doing wrong?

Body:
Try this (do not use .get):

window.open('/UserControls/download.ashx?format=pdf&bookId=' + bookId, "pdfViewer");

To prevent the "File does not begin with '%PDF" error, use Response.BinaryWrite:

context.Response.Clear();
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.ContentType = "application/pdf";

Stream fileStream = publishBookManager.GetFile(documentId);
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
  int read;
  while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
  {
    ms.Write(buffer, 0, read);
  }
}

context.Response.BinaryWrite(data);
context.Response.Flush();


问:
Move zoom controls in Leaflet for R Shiny
I have a Shiny application with multiple leaflet maps. I'd like to move the zoom in/out controls from the top left side of the map to the top right, and I'm not sure how to do this - I'm pretty sure it's by calling options = leafletOptions() inside leaflet()/leafletProxy(), but I'm unsure of the exact syntax.

Minimum reproducible example:

```<code>library(shiny)
library(leaflet)

ui <- fluidPage(

  leafletOutput("output1")
)

server <- function(input, output) {
  output$output1 <- renderLeaflet({
    leaflet() %>%
      addProviderTiles(providers$Esri.WorldImagery)
  })

}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

答:
See this example:

```<code>library(shiny)
library(leaflet)
library(htmlwidgets)

ui <- fluidPage(
  leafletOutput("output1")
)

server <- function(input, output) {
  output$output1 <- renderLeaflet({
    leaflet(options = leafletOptions(zoomControl = FALSE)) %>%
      addProviderTiles(providers$Esri.WorldImagery) %>%
      onRender(
        "function(el, x) {
          L.control.zoom({position:'topright'}).addTo(this);
        }")
  })
}

shinyApp(ui = ui, server = server)
</code>```

The code references this: https://markusdumke.github.io/articles/2017/11/customize-leaflet-map-in-r-with-html-css-and-javascript/

Body:
I have a Shiny application with multiple leaflet maps. I'd like to move the zoom in/out controls from the top left side of the map to the top right, and I'm not sure how to do this - I'm pretty sure it's by calling options = leafletOptions() inside leaflet()/leafletProxy(), but I'm unsure of the exact syntax.

Minimum reproducible example:

library(shiny)
library(leaflet)

ui <- fluidPage(

  leafletOutput("output1")
)

server <- function(input, output) {
  output$output1 <- renderLeaflet({
    leaflet() %>%
      addProviderTiles(providers$Esri.WorldImagery)
  })

}

# Run the application
shinyApp(ui = ui, server = server)

Body:
See this example:

library(shiny)
library(leaflet)
library(htmlwidgets)

ui <- fluidPage(
  leafletOutput("output1")
)

server <- function(input, output) {
  output$output1 <- renderLeaflet({
    leaflet(options = leafletOptions(zoomControl = FALSE)) %>%
      addProviderTiles(providers$Esri.WorldImagery) %>%
      onRender(
        "function(el, x) {
          L.control.zoom({position:'topright'}).addTo(this);
        }")
  })
}

shinyApp(ui = ui, server = server)

The code references this: https://markusdumke.github.io/articles/2017/11/customize-leaflet-map-in-r-with-html-css-and-javascript/


问:
How do I change tab size in Vim?
Every time I add a selector in CSS and I press Enter to define the properties it ends up like this:

#selector {
        property: value;
}
```

<p>(8-space tabs)</p>

<p>How can I configure Vim to make it like this:</p>

<pre class="lang-css prettyprint-override"><code>#selector {
    property: value;
}
</code>```

(4-space tabs)

答:
in vim command mode, write:

```<code>:set ts=X
</code>```

where X is your new desired space length

Title: How do I change tab size in Vim?

Body:
Every time I add a selector in CSS and I press Enter to define the properties it ends up like this:

#selector {
        property: value;
}

(8-space tabs)

How can I configure Vim to make it like this:

#selector {
    property: value;
}

(4-space tabs)

Body:
in vim command mode, write:

:set ts=X

where X is your new desired space length


答: If the column is NOT NULL with DEFAULT CURRENT_TIMESTAMP you don't need to mention the column in the INSERT.</p>

Title: How do I save a timestamp to a mysql database?

Body:
I have a table in mysql for people's posts. But I'd like to be able to get the time the post was made? How do I do it? Any help will be appreciated. The language I'm using is PHP and I'm using prepared statements.
Is it as simple as specifying a column in the database with the datatype TIMESTAMP? And how do I read a timestamp and convert it to a date?


问:
We made it reliable. What's next? Usability?
I'm working in a small development group. We are building and improving our product.

Half a year ago we couldn't think about higher characteristics, such as usability, because we had so many problems with our product. Many bugs, high technical debt, low performance and other problems kept us from being able to focus on usability.

With time we've improved our process substantially. What we've done:

Real Agile iterations

Continuous integration

Testing(unit-tests, functional Smoke tests, performance)

Code quality is 'good'

Painless deployment process

So we are now producing stable, reliable releases. The following quote (paraphrased) describes our current situation:

first - make it work; after that, make it reliable; after that, make it usable

We are geeks, so we can't 'make' a great UI by ourselves.
So what should we do? What direction can you recommend?
Maybe we should hire Usability experts part-time or full-time?
How can we explain the importance of Usability to our stakeholders?
How do we convince them that this is useful?

答: What do your users want ? They're probably the people best placed to identify requirements.</p>

OwnerDisplayName: Fedyashev Nikita

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Gortok

OwnerDisplayName: Brian Agnew


问:
Angular 12, set variable from function
I'm developing a little tool where I need to populate a variable on component creation.
I've declared variable here:

```<code>export class HomeComponent implements OnInit {
myVar: any
</code>```

and try to set its value here:

```<code>  ngOnInit(): void {
    setInterval(() => this.myFunction(5), 3000);
  }

  myFunction(arg: number): void {
    this.data.forEach(function (this: HomeComponent, element: any) {
      if (element.id === number) {
        this.myVar = element.id;
      }
    });
  }
</code>```

but no value was passed and I get this error:
"ERROR TypeError: this is undefined"

Any idea?
Thank you in advice!

答:
Arrow functions do not have their own 'this'. Arrow functions establish "this" based on the scope the Arrow function is defined within.

Try to change the code like below by just sending the myFunction as reference

```<code>setInterval(myFunction, 3000);
</code>```

Title: Angular 12, set variable from function

Body:
I'm developing a little tool where I need to populate a variable on component creation.
I've declared variable here:

export class HomeComponent implements OnInit {
myVar: any

and try to set its value here:

  ngOnInit(): void {
    setInterval(() => this.myFunction(5), 3000);
  }

  myFunction(arg: number): void {
    this.data.forEach(function (this: HomeComponent, element: any) {
      if (element.id === number) {
        this.myVar = element.id;
      }
    });
  }

but no value was passed and I get this error:
"ERROR TypeError: this is undefined"

Any idea?
Thank you in advice!

Body:
Arrow functions do not have their own 'this'. Arrow functions establish "this" based on the scope the Arrow function is defined within.

Try to change the code like below by just sending the myFunction as reference

setInterval(myFunction, 3000);


问:
Bootstrapping a compiler: why?
I understand how a language can bootstrap itself, but I haven't been able to find much reference on why you should consider bootstrapping.

The intuitive answer is that the language you're writing offers utilities that are not found in the "base" language of the compiler, and the language's features are relatively well-suited for a compiler.

For instance, it would make sense to bootstrap a C++ compiler -- it could potentially be much easier to maintain the compiler when OOP is properly used, as opposed to using plain C.

On the other hand, MATLAB certainly makes matrix math a lot easier than plain C, but I can't see any apparent benefits from writing a MATLAB compiler/interpreter in MATLAB -- it seems like it would become less maintainable.  A similar view could be applied to the R programming language.  Or a pretty extreme example would be bootstrapping Whitespace, which is written in Haskell -- definitely a massive superset of Whitespace.

Is the only reason for bootstrapping to take advantage of the new language's features?  I know there's also the "because we can" reason, but that's not what I'm looking for :)

答: Bootstrapping is expected from a general purpose programming language .

Title: Bootstrapping a compiler: why?


问:
How to change Identity validation properties
I created an Identity project, using .net core 3 version. I generated a Migrations file, and Startup.cs with some configuration.

```<code>public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();
            services.AddControllersWithViews();
            services.AddRazorPages();
        }
</code>```

But how to modify the rules for creating passwords during registration?
enter image description here

答:
Here is a completed custom validation demo, you can select the parts you need to change:

1.Create UserLoginDto.cs class and set validation for email, password and create UserRegistrationDto.cs class to register and set validation for all properties

```<code> public class UserRegistrationDto
    {
        [Required(ErrorMessage = "Name is required")]
        [StringLength(100)]
        public string Name { get; set; }

        [EmailAddress(ErrorMessage = "Invalid email address")]
        [Required(ErrorMessage = "Email is required")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Password is required")]
        [RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$",
         ErrorMessage = "Characters are not allowed.")]

        public string Password { get; set; }

        [Required(ErrorMessage = "Confirm password is required")]

        [Compare("Password", ErrorMessage = "The Password and Confirm Password do not match.")]
        public string ConfirmPassword { get; set; }

        public string PhoneNumber { get; set; }
    }

 public class UserLoginDto
    {
        [Required(ErrorMessage = "Email is required")]
        [EmailAddress(ErrorMessage = "Invalid email address")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Password is required")]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Display(Name = "Remember me")]
        public bool RememberMe { get; set; }
    }
</code>```

2.Inject the UserManager and SignInManager identity classes into their constructors.

```<code> public class AccountController : Controller
    {
        private readonly UserManager<IdentityUser> userManager;
        private readonly SignInManager<IdentityUser> signInManager;
        public AccountController(UserManager<IdentityUser> userManager,
            SignInManager<IdentityUser> signInManager)
        {
            this.userManager = userManager;
            this.signInManager = signInManager;
        }
</code>```

3.Create a register and login method like this

```<code>     public class AccountController : Controller
        {
            private readonly UserManager<IdentityUser> userManager;
            private readonly SignInManager<IdentityUser> signInManager;
            public AccountController(UserManager<IdentityUser> userManager,
                SignInManager<IdentityUser> signInManager)
            {
                this.userManager = userManager;
                this.signInManager = signInManager;
            }

            [HttpGet, AllowAnonymous]
            public IActionResult Register()
            {
                UserRegistrationDto model = new UserRegistrationDto();
                return View(model);
            }

            [HttpPost, AllowAnonymous]
            public async Task<IActionResult> Register(UserRegistrationDto request)
            {
                if (ModelState.IsValid)
                {
                    var userCheck = await userManager.FindByEmailAsync(request.Email);
                    if (userCheck == null)
                    {
                        var user = new IdentityUser
                        {
                            UserName = request.Email,
                            NormalizedUserName = request.Email,
                            Email = request.Email,
                            PhoneNumber = request.PhoneNumber,
                            EmailConfirmed = true,
                            PhoneNumberConfirmed = true,
                        };
                        var result = await userManager.CreateAsync(user, request.Password);
                        if (result.Succeeded)
                        {
                            return RedirectToAction("Login");
                        }
                        else
                        {
                            if (result.Errors.Count() > 0)
                            {
                                foreach (var error in result.Errors)
                                {
                                    ModelState.AddModelError("message", error.Description);
                                }
                            }
                            return View(request);
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("message", "Email already exists.");
                        return View(request);
                    }
                }
                return View(request);

            }

            [HttpGet]
            [AllowAnonymous]
            public IActionResult Login()
            {
                UserLoginDto model = new UserLoginDto();
                return View(model);
            }

            [HttpPost]
            [AllowAnonymous]
            public async Task<IActionResult> Login(UserLoginDto model)
            {
                if (ModelState.IsValid)
                {
                    var user = await userManager.FindByEmailAsync(model.Email);
                    if (user != null && !user.EmailConfirmed)
                    {
                        ModelState.AddModelError("message", "Email not confirmed yet");
                        return View(model);

                    }
                    if (await userManager.CheckPasswordAsync(user, model.Password) == false)
                    {
                        ModelState.AddModelError("message", "Invalid credentials");
                        return View(model);

                    }

                    var result = await signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, true);

                    if (result.Succeeded)
                    {
                        await userManager.AddClaimAsync(user, new Claim("UserRole", "Admin"));
                        return RedirectToAction("Dashboard");
                    }
                    else if (result.IsLockedOut)
                    {
                        return View("AccountLocked");
                    }
                    else
                    {
                        ModelState.AddModelError("message", "Invalid login attempt");
                        return View(model);
                    }
                    }
                    return View(model);
                }
 [Authorize]
        public IActionResult Dashboard()
        {
            return View();
        }
        public async Task<IActionResult> Logout()
        {
            await signInManager.SignOutAsync();
            return RedirectToAction("login", "account");
        }
</code>```

4.Create the Register.cshtml view

```<code>@model UserRegistrationDto
@{
    ViewData["Title"] = "Register";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container">
    <h1>Register</h1>
    @Html.ValidationSummary()
    <form asp-action="Register" asp-controller="Account" method="post">

        <div class="registerdiv">
            <div class="form-group col-sm-12">
                <label asp-for="@Model.Name" class="col-lg-3 control-label"></label>
                <br>
                <div class="col-lg-9">
                    @Html.TextBoxFor(m => m.Name, new { placeholder = "First Name", @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.Name)
                </div>
            </div>

            <div class="form-group col-sm-12">
                <label asp-for="@Model.Email" class="col-lg-3 control-label"></label>
                <br>
                <div class="col-lg-9">
                    @Html.TextBoxFor(m => m.Email, new { placeholder = "Email", @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.Email)
                </div>
            </div>

            <div class="form-group col-sm-12">
                <label asp-for="@Model.PhoneNumber" class="col-lg-3 control-label"></label>
                <br>
                <div class="col-lg-9">
                    @Html.TextBoxFor(m => m.PhoneNumber, new { placeholder = "Phone Number", @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.PhoneNumber)
                </div>
            </div>

            <div class="form-group col-sm-12">
                <label asp-for="@Model.Password" class="col-lg-3 control-label"></label>
                <br>
                <div class="col-lg-9">
                    @Html.TextBoxFor(m => m.Password, new { placeholder = "Password", @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.Password)
                </div>
            </div>

            <div class="form-group col-sm-12">
                <label asp-for="@Model.ConfirmPassword" class="col-lg-3 control-label"></label>
                <br>
                <div class="col-lg-9">

                    @Html.PasswordFor(m => m.ConfirmPassword, new { placeholder = "Confirm Password", @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.ConfirmPassword)
                </div>
            </div>

            <div class="form-group">
                <div class="col-sm-12 btn-submit">
                    <button type="submit" class="btn btn-success">Sign Up</button>

                </div>
            </div>
        </div>
    </form>
</div>
<style>
    .validation-summary-errors,.field-validation-error {
        color: red;
    }
</style>
</code>```

5.Create the Login.cshmt view

```<code>@model UserLoginDto
@{
    ViewData["Title"] = "Login";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="container">
    <h1>Login</h1>
    @Html.ValidationSummary()
    <form asp-action="Login" asp-controller="Account" method="post">

        <div class="logindiv">

            <div class="form-group col-sm-12">
                <label asp-for="@Model.Email" class="col-lg-3 control-label"></label>
                <br>
                <div class="col-lg-9">
                    @Html.TextBoxFor(m => m.Email, new { placeholder = "Email", @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.Email)
                </div>
            </div>

            <div class="form-group col-sm-12">
                <label asp-for="@Model.Password" class="col-lg-3 control-label"></label>
                <br>
                <div class="col-lg-9">
                    @Html.PasswordFor(m => m.Password, new { placeholder = "Password", @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.Password)
                </div>
            </div>

            <div class="form-group">
                <div class="col-sm-12 btn-submit">
                    <button type="submit" class="btn btn-success">Login</button>
                    <a asp-action="Register" asp-controller="account">Don't have an account?Click to Register</a>

                </div>
            </div>
        </div>
    </form>
</div>
</code>```

6.Create a partial view of _LoginPartial.cshmtl, display the login user name, and the logout button will appear after logging in to the website

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - WebApplication221</title>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
    <header>
        <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
            <div class="container">
                <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">WebApplication221</a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                        aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
                    <partial name="_LoginPartial" />
                    <ul class="navbar-nav flex-grow-1">
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
    </header>
    <div class="container">
        <main role="main" class="pb-3">
            @RenderBody()
        </main>
    </div>

    <footer class="border-top footer text-muted">
        <div class="container">
            © 2022 - WebApplication221 - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
        </div>
    </footer>
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>
    @RenderSection("Scripts", required: false)
</body>
</html>
</code>```

7.Set the custom redirect URL path from ConfigureServices in the Startup.cs class.

```<code> public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath = $"/account/login";
                options.LogoutPath = $"/account/logout";
                options.AccessDeniedPath = $"/account/accessDenied";
            });

            services.AddControllersWithViews();
            services.AddRazorPages();
        }
</code>```

8.Result：

Body:
I created an Identity project, using .net core 3 version. I generated a Migrations file, and Startup.cs with some configuration.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();
            services.AddControllersWithViews();
            services.AddRazorPages();
        }

But how to modify the rules for creating passwords during registration?
enter image description here

Body:
Here is a completed custom validation demo, you can select the parts you need to change:

1.Create UserLoginDto.cs class and set validation for email, password and create UserRegistrationDto.cs class to register and set validation for all properties

 public class UserRegistrationDto
    {
        [Required(ErrorMessage = "Name is required")]
        [StringLength(100)]
        public string Name { get; set; }

        [EmailAddress(ErrorMessage = "Invalid email address")]
        [Required(ErrorMessage = "Email is required")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Password is required")]
        [RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$",
         ErrorMessage = "Characters are not allowed.")]

        public string Password { get; set; }

        [Required(ErrorMessage = "Confirm password is required")]

        [Compare("Password", ErrorMessage = "The Password and Confirm Password do not match.")]
        public string ConfirmPassword { get; set; }

        public string PhoneNumber { get; set; }
    }

 public class UserLoginDto
    {
        [Required(ErrorMessage = "Email is required")]
        [EmailAddress(ErrorMessage = "Invalid email address")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Password is required")]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Display(Name = "Remember me")]
        public bool RememberMe { get; set; }
    }

2.Inject the UserManager and SignInManager identity classes into their constructors.

 public class AccountController : Controller
    {
        private readonly UserManager<IdentityUser> userManager;
        private readonly SignInManager<IdentityUser> signInManager;
        public AccountController(UserManager<IdentityUser> userManager,
            SignInManager<IdentityUser> signInManager)
        {
            this.userManager = userManager;
            this.signInManager = signInManager;
        }

3.Create a register and login method like this

     public class AccountController : Controller
        {
            private readonly UserManager<IdentityUser> userManager;
            private readonly SignInManager<IdentityUser> signInManager;
            public AccountController(UserManager<IdentityUser> userManager,
                SignInManager<IdentityUser> signInManager)
            {
                this.userManager = userManager;
                this.signInManager = signInManager;
            }

            [HttpGet, AllowAnonymous]
            public IActionResult Register()
            {
                UserRegistrationDto model = new UserRegistrationDto();
                return View(model);
            }

            [HttpPost, AllowAnonymous]
            public async Task<IActionResult> Register(UserRegistrationDto request)
            {
                if (ModelState.IsValid)
                {
                    var userCheck = await userManager.FindByEmailAsync(request.Email);
                    if (userCheck == null)
                    {
                        var user = new IdentityUser
                        {
                            UserName = request.Email,
                            NormalizedUserName = request.Email,
                            Email = request.Email,
                            PhoneNumber = request.PhoneNumber,
                            EmailConfirmed = true,
                            PhoneNumberConfirmed = true,
                        };
                        var result = await userManager.CreateAsync(user, request.Password);
                        if (result.Succeeded)
                        {
                            return RedirectToAction("Login");
                        }
                        else
                        {
                            if (result.Errors.Count() > 0)
                            {
                                foreach (var error in result.Errors)
                                {
                                    ModelState.AddModelError("message", error.Description);
                                }
                            }
                            return View(request);
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("message", "Email already exists.");
                        return View(request);
                    }
                }
                return View(request);

            }

            [HttpGet]
            [AllowAnonymous]
            public IActionResult Login()
            {
                UserLoginDto model = new UserLoginDto();
                return View(model);
            }

            [HttpPost]
            [AllowAnonymous]
            public async Task<IActionResult> Login(UserLoginDto model)
            {
                if (ModelState.IsValid)
                {
                    var user = await userManager.FindByEmailAsync(model.Email);
                    if (user != null && !user.EmailConfirmed)
                    {
                        ModelState.AddModelError("message", "Email not confirmed yet");
                        return View(model);

                    }
                    if (await userManager.CheckPasswordAsync(user, model.Password) == false)
                    {
                        ModelState.AddModelError("message", "Invalid credentials");
                        return View(model);

                    }

                    var result = await signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, true);

                    if (result.Succeeded)
                    {
                        await userManager.AddClaimAsync(user, new Claim("UserRole", "Admin"));
                        return RedirectToAction("Dashboard");
                    }
                    else if (result.IsLockedOut)
                    {
                        return View("AccountLocked");
                    }
                    else
                    {
                        ModelState.AddModelError("message", "Invalid login attempt");
                        return View(model);
                    }
                    }
                    return View(model);
                }
 [Authorize]
        public IActionResult Dashboard()
        {
            return View();
        }
        public async Task<IActionResult> Logout()
        {
            await signInManager.SignOutAsync();
            return RedirectToAction("login", "account");
        }

4.Create the Register.cshtml view

@model UserRegistrationDto
@{
    ViewData["Title"] = "Register";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container">
    <h1>Register</h1>
    @Html.ValidationSummary()
    <form asp-action="Register" asp-controller="Account" method="post">

        <div class="registerdiv">
            <div class="form-group col-sm-12">
                <label asp-for="@Model.Name" class="col-lg-3 control-label"></label>
                <br>
                <div class="col-lg-9">
                    @Html.TextBoxFor(m => m.Name, new { placeholder = "First Name", @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.Name)
                </div>
            </div>

            <div class="form-group col-sm-12">
                <label asp-for="@Model.Email" class="col-lg-3 control-label"></label>
                <br>
                <div class="col-lg-9">
                    @Html.TextBoxFor(m => m.Email, new { placeholder = "Email", @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.Email)
                </div>
            </div>

            <div class="form-group col-sm-12">
                <label asp-for="@Model.PhoneNumber" class="col-lg-3 control-label"></label>
                <br>
                <div class="col-lg-9">
                    @Html.TextBoxFor(m => m.PhoneNumber, new { placeholder = "Phone Number", @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.PhoneNumber)
                </div>
            </div>

            <div class="form-group col-sm-12">
                <label asp-for="@Model.Password" class="col-lg-3 control-label"></label>
                <br>
                <div class="col-lg-9">
                    @Html.TextBoxFor(m => m.Password, new { placeholder = "Password", @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.Password)
                </div>
            </div>

            <div class="form-group col-sm-12">
                <label asp-for="@Model.ConfirmPassword" class="col-lg-3 control-label"></label>
                <br>
                <div class="col-lg-9">

                    @Html.PasswordFor(m => m.ConfirmPassword, new { placeholder = "Confirm Password", @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.ConfirmPassword)
                </div>
            </div>

            <div class="form-group">
                <div class="col-sm-12 btn-submit">
                    <button type="submit" class="btn btn-success">Sign Up</button>

                </div>
            </div>
        </div>
    </form>
</div>
<style>
    .validation-summary-errors,.field-validation-error {
        color: red;
    }
</style>

5.Create the Login.cshmt view

@model UserLoginDto
@{
    ViewData["Title"] = "Login";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="container">
    <h1>Login</h1>
    @Html.ValidationSummary()
    <form asp-action="Login" asp-controller="Account" method="post">

        <div class="logindiv">

            <div class="form-group col-sm-12">
                <label asp-for="@Model.Email" class="col-lg-3 control-label"></label>
                <br>
                <div class="col-lg-9">
                    @Html.TextBoxFor(m => m.Email, new { placeholder = "Email", @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.Email)
                </div>
            </div>

            <div class="form-group col-sm-12">
                <label asp-for="@Model.Password" class="col-lg-3 control-label"></label>
                <br>
                <div class="col-lg-9">
                    @Html.PasswordFor(m => m.Password, new { placeholder = "Password", @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.Password)
                </div>
            </div>

            <div class="form-group">
                <div class="col-sm-12 btn-submit">
                    <button type="submit" class="btn btn-success">Login</button>
                    <a asp-action="Register" asp-controller="account">Don't have an account?Click to Register</a>

                </div>
            </div>
        </div>
    </form>
</div>

6.Create a partial view of _LoginPartial.cshmtl, display the login user name, and the logout button will appear after logging in to the website

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - WebApplication221</title>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
    <header>
        <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
            <div class="container">
                <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">WebApplication221</a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                        aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
                    <partial name="_LoginPartial" />
                    <ul class="navbar-nav flex-grow-1">
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
    </header>
    <div class="container">
        <main role="main" class="pb-3">
            @RenderBody()
        </main>
    </div>

    <footer class="border-top footer text-muted">
        <div class="container">
            &copy; 2022 - WebApplication221 - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
        </div>
    </footer>
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>
    @RenderSection("Scripts", required: false)
</body>
</html>

7.Set the custom redirect URL path from ConfigureServices in the Startup.cs class.

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath = $"/account/login";
                options.LogoutPath = $"/account/logout";
                options.AccessDeniedPath = $"/account/accessDenied";
            });

            services.AddControllersWithViews();
            services.AddRazorPages();
        }

8.Result：


问:
Generate n coordinates via console input in Python
```<code>enter code here

ref = (x,y)

print(ref)
print(ref[0])
print(ref[1])

n = int(input("Enter the number of points in the race"))
points = []

for i in range(1,n+1):

    m =  int(input("Enter x coordinate for number {0}:"
         .format(i)))
    n =  int(input("Enter y coordinate for number {0}: "
         .format(i)))
    k = (m,n)
    points.append(k)
    print(points)
</code>```

So this is a code to get an number of coordinate points .
But there has to be a better way.
Can anyone suggest a more advanced style of getting this code

答:
This will directly read the elements and put it into list using map and list functions.

// input: 2 3

ele_list = list(map(int, input("enter elements with space separated:").split()))

Output:
[2,3]

Body:
enter code here

ref = (x,y)

print(ref)
print(ref[0])
print(ref[1])

n = int(input("Enter the number of points in the race"))
points = []

for i in range(1,n+1):

    m =  int(input("Enter x coordinate for number {0}:"
         .format(i)))
    n =  int(input("Enter y coordinate for number {0}: "
         .format(i)))
    k = (m,n)
    points.append(k)
    print(points)

So this is a code to get an number of coordinate points .
But there has to be a better way.
Can anyone suggest a more advanced style of getting this code


问:
Need help identifying right XPath
I'm trying to scrape all of the table from this website : https://qmjhldraft.rinknet.com/results.htm?year=2018

When the XPath is a simple td (like the names for example), I can scrape the table with the simple xpath being something like this :

```<code>players = driver.find_elements_by_xpath('//tr[@rnid]/td[4]')
</code>```

And I can scrape the players name using this code :

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

PATH = 'C:\Program Files (x86)\chromedriver.exe'
driver = webdriver.Chrome(PATH)
driver.get('https://qmjhldraft.rinknet.com/results.htm?year=2018')

try:
    elements = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, "//tr[@rnid]/td[1]"))
    )
finally:
    players = driver.find_elements_by_xpath('//tr[@rnid]/td[4]')

for player in players[:5]:
    pl = player.text
    print(pl)
</code>```

But when I get to the "Height" section, I can't find the write XPath. I guess this has to do with the td having a class, "ht-itemVisibility1", changing the way to scrape it, I've tried a few different ways to scrape it, like :

```<code>('//tr/td[@class="ht-itemVisibility1"][1]')
('//tr/td[@class="ht-itemVisibility1"][5]')
('//tr[@rnid]/td[5]')
</code>```

to no avail. Can someone enlighten me on the way to capature this XPath with td class? Thanks a lot.

答:
Try this

```<code>from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get('https://qmjhldraft.rinknet.com/results.htm?year=2018')

try:
    elements = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, "//tr[@rnid]/td[1]"))
    )
finally:
    players = driver.find_elements_by_xpath('//tr[@rnid]/td[4]')

for player in players[:5]:
    pl = player.text
    print(pl)

players_height = driver.find_elements_by_xpath('//tr/td[@class="ht-itemVisibility1"][1]')

for player in players_height[:5]:
    pl = player.text
    print(pl)

players_last_team = driver.find_elements_by_xpath('//tr/td[@class="ht-itemVisibility1"][5]')

for player in players_last_team[:5]:
    pl = player.text
    print(pl)

</code>```

don't know why it wasn't working for you but it's working fine with me.

Results:

Title: Need help identifying right XPath

Body:
I'm trying to scrape all of the table from this website : https://qmjhldraft.rinknet.com/results.htm?year=2018

When the XPath is a simple td (like the names for example), I can scrape the table with the simple xpath being something like this :

players = driver.find_elements_by_xpath('//tr[@rnid]/td[4]')

And I can scrape the players name using this code :

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

PATH = 'C:\Program Files (x86)\chromedriver.exe'
driver = webdriver.Chrome(PATH)
driver.get('https://qmjhldraft.rinknet.com/results.htm?year=2018')

try:
    elements = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, "//tr[@rnid]/td[1]"))
    )
finally:
    players = driver.find_elements_by_xpath('//tr[@rnid]/td[4]')

for player in players[:5]:
    pl = player.text
    print(pl)

But when I get to the "Height" section, I can't find the write XPath. I guess this has to do with the td having a class, "ht-itemVisibility1", changing the way to scrape it, I've tried a few different ways to scrape it, like :

('//tr/td[@class="ht-itemVisibility1"][1]')
('//tr/td[@class="ht-itemVisibility1"][5]')
('//tr[@rnid]/td[5]')

to no avail. Can someone enlighten me on the way to capature this XPath with td class? Thanks a lot.

Body:
Try this

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get('https://qmjhldraft.rinknet.com/results.htm?year=2018')

try:
    elements = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, "//tr[@rnid]/td[1]"))
    )
finally:
    players = driver.find_elements_by_xpath('//tr[@rnid]/td[4]')

for player in players[:5]:
    pl = player.text
    print(pl)

players_height = driver.find_elements_by_xpath('//tr/td[@class="ht-itemVisibility1"][1]')

for player in players_height[:5]:
    pl = player.text
    print(pl)

players_last_team = driver.find_elements_by_xpath('//tr/td[@class="ht-itemVisibility1"][5]')

for player in players_last_team[:5]:
    pl = player.text
    print(pl)

don't know why it wasn't working for you but it's working fine with me.

Results: