问:
Spring boot data + Oracle = batch update of entities not working
I am trying to do a batch/bulk update using the CrudRespositories saveAll method however it seems that it does not work. Generate log :

```<code>2020-05-23 07:06:27.963Z INFO  [nio-8080-exec-1] i.StatisticalLoggingSessionEventListener {} : Session Metrics {
    314694800 nanoseconds spent acquiring 1 JDBC connections;
    0 nanoseconds spent releasing 0 JDBC connections;
    54054998 nanoseconds spent preparing 12 JDBC statements;
    5762126698 nanoseconds spent executing 12 JDBC statements;
    0 nanoseconds spent executing 0 JDBC batches;
</code>```

I think 0 JDBC batches means batch update was not done?

I have configured the following properties for batching :

```<code>spring.jpa.properties.hibernate.jdbc.batch_size=30
spring.jpa.properties.hibernate.order_updates=true
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.batch_versioned_data=true
</code>```

Dependency versions:

```<code>Spring boot : 2.2.5.RELEASE
Oracle : tried on both 11g and 12c
jdbc driver :
<groupId>com.oracle</groupId>
<artifactId>ojdbc8</artifactId>
<version>18.3</version>
</code>```

Let me know what else needs to be done for this to work? If it doesn't work by providing these properties what are other possible solutions?

答:
Make sure to use the official JDBC drivers in your pom.xml </p>

```<code><groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>18.3.0.0</version>
</code>```

Body:
I am trying to do a batch/bulk update using the CrudRespositories saveAll method however it seems that it does not work. Generate log :

2020-05-23 07:06:27.963Z INFO  [nio-8080-exec-1] i.StatisticalLoggingSessionEventListener {} : Session Metrics {
    314694800 nanoseconds spent acquiring 1 JDBC connections;
    0 nanoseconds spent releasing 0 JDBC connections;
    54054998 nanoseconds spent preparing 12 JDBC statements;
    5762126698 nanoseconds spent executing 12 JDBC statements;
    0 nanoseconds spent executing 0 JDBC batches;

I think 0 JDBC batches means batch update was not done?

I have configured the following properties for batching :

spring.jpa.properties.hibernate.jdbc.batch_size=30
spring.jpa.properties.hibernate.order_updates=true
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.batch_versioned_data=true

Dependency versions:

Spring boot : 2.2.5.RELEASE
Oracle : tried on both 11g and 12c
jdbc driver :
<groupId>com.oracle</groupId>
<artifactId>ojdbc8</artifactId>
<version>18.3</version>

Let me know what else needs to be done for this to work? If it doesn't work by providing these properties what are other possible solutions?

Body:
Make sure to use the official JDBC drivers in your pom.xml

<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>18.3.0.0</version>


来源: stackexchange

问:
After installation react-native-vector-icons white screen
Before installation the react-native-vector-icons, The project is work well.
 But ..

When I install the react-native-vector-icons, I can only see the white screen .
It took me two days to solve this problem.
But it doesn't work. I add it like this:

npm install react-native-vector-icons --save

  react-native link

Build success and no error or warnning,I compared with npm website,all of the file was the same,like android/app/build.gradle setting.gradle and so on, but it doesn't work in my android phone.

Thx for any help!I'm almost broke.

答:
You must add below line and run react-native run-android:

Android
Option: With Gradle (recommended)
This method has the advantage of fonts being copied from this module at build time so that the fonts and JS are always in sync, making upgrades painless.

Edit android/app/build.gradle ( NOT android/build.gradle ) and add the following:

```<code>apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You must add below line and run react-native run-android:

Android
Option: With Gradle (recommended)
This method has the advantage of fonts being copied from this module at build time so that the fonts and JS are always in sync, making upgrades painless.

Edit android/app/build.gradle ( NOT android/build.gradle ) and add the following:

apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

ContentLicense: CC BY-SA 4.0


问:
What happens when C# reached its limit to generate Guid.NewGuid() ? How to handle it?
I have a scenario where i need to generate a unique key for which i am using Guid.NewGuid() in C#, and sending this key to the user via an email when user request for it and for next 48Hrs that user will be identified by this unique key. There is no limit for the user to request for this key but only the latest one will be a valid key to identify the user.
My question is when C# reached the limit to generate new key what happens then?. Do i really need to worry about it?</p>

答:
I'll quote this page from the Online Guid Generator

128-bits is big enough and the generation algorithm is unique enough that if 1,000,000,000 GUIDs per second were generated for 1 year the probability of a duplicate would be only 50%. Or if every human on Earth generated 600,000,000 GUIDs there would only be a 50% probability of a duplicate.

You will never need to worry about it.


问:
Angular 8 viewChild returns undefined
I am trying to access the childView instance but it keeps saying the the childView is undefined.

Here is my code for childViews:

```<code>@ViewChild(CreateQuestionnaireComponent,{ read: true, static: false })  private childQuestionnaireDialog:CreateQuestionnaireComponent;
@ViewChild(ProjectNavbarComponent,{ read: true, static: false })  private childProjectNavBar:ProjectNavbarComponent;
@ViewChild(QuestionnaireNodeComponent,{ read: true, static: false }) private childQuestionnaireNode:QuestionnaireNodeComponent;
....

onCreateTerminal() {
        this.childQuestionnaireDialog.generateQuestionnaireDropDownList();
        this.childQuestionnaireDialog.resetFields();
        this._hideQuestionnaireDialog = false;
        this._modalTitle = 'New Terminal';
        this._placeHolderText = 'Terminal Questionnaire Title';
        this._terminal = true;
    }
</code>```

...

It says :this.childQuestionnaireDialog is undefined".

It was working with Angular 7.

As per my new knowledge, the @viewChild takes a flag called static. If we put the flag to true, the parent component tries to get a reference to the childView during its own creation. In other words, we could have an instance of the childView in the onInit() method of the parent Component.Basically a one time access because we won't be able to access in any other methods.

The flag set to false, is basically the new way in ivy renderer.

The problem in my case, neither options are working.

答:
For Angular 7 we won't get the {static: boolean} parameter instead we are getting {read: any} in my case I had a *ngif directive so the reference of the element was not getting by Viewchild(), what I did is I just checked the element is undefined or not in Component.ts

If you need to access it in ngOnInit hook

Here is an example for removing class by Hot listening

@ViewChild('elref', ) elref: ElementRef;

```<code>import { Component, ElementRef, , Renderer2, ViewChild } from'@angular/core';

export class Component implements OnInit {
 @ViewChild('elref', ) elref: ElementRef;
    constructor(private renderer: Renderer2) {}
     ngOnInit() { this.hotlistening(); }
      hotlistening() {
        this.renderer.listen('window', 'click', (e: Event) => {
                if (this.elref !== undefined) { //Here i checked for undefined
                    this.elref.nativeElement.classList.remove('open');
                });
        }
    }
</code>```

Title: Angular 8 viewChild returns undefined

Body:
I am trying to access the childView instance but it keeps saying the the childView is undefined.

Here is my code for childViews:

@ViewChild(CreateQuestionnaireComponent,{ read: true, static: false })  private childQuestionnaireDialog:CreateQuestionnaireComponent;
@ViewChild(ProjectNavbarComponent,{ read: true, static: false })  private childProjectNavBar:ProjectNavbarComponent;
@ViewChild(QuestionnaireNodeComponent,{ read: true, static: false }) private childQuestionnaireNode:QuestionnaireNodeComponent;
....

onCreateTerminal() {
        this.childQuestionnaireDialog.generateQuestionnaireDropDownList();
        this.childQuestionnaireDialog.resetFields();
        this._hideQuestionnaireDialog = false;
        this._modalTitle = 'New Terminal';
        this._placeHolderText = 'Terminal Questionnaire Title';
        this._terminal = true;
    }

...

It says :this.childQuestionnaireDialog is undefined".

It was working with Angular 7.

As per my new knowledge, the @viewChild takes a flag called static. If we put the flag to true, the parent component tries to get a reference to the childView during its own creation. In other words, we could have an instance of the childView in the onInit() method of the parent Component.Basically a one time access because we won't be able to access in any other methods.

The flag set to false, is basically the new way in ivy renderer.

The problem in my case, neither options are working.

Body:
For Angular 7 we won't get the {static: boolean} parameter instead we are getting {read: any} in my case I had a *ngif directive so the reference of the element was not getting by Viewchild(), what I did is I just checked the element is undefined or not in Component.ts

If you need to access it in ngOnInit hook

Here is an example for removing class by Hot listening

@ViewChild('elref', ) elref: ElementRef;

import { Component, ElementRef, , Renderer2, ViewChild } from'@angular/core';

export class Component implements OnInit {
 @ViewChild('elref', ) elref: ElementRef;
    constructor(private renderer: Renderer2) {}
     ngOnInit() { this.hotlistening(); }
      hotlistening() {
        this.renderer.listen('window', 'click', (e: Event) => {
                if (this.elref !== undefined) { //Here i checked for undefined
                    this.elref.nativeElement.classList.remove('open');
                });
        }
    }


问:
How to simulate cable pull for Openstack VM?
we want to simulate a link state down in a Openstack Nova VM.
When we did "openstack port set --disable <port>" VM not sensing it.

Is there any way to bring down a VM port link, But keep the Admin state up?

答:
Basically there seems to be such a feature in Openstack to do this since pike-version:

https://specs.openstack.org/openstack/neutron-specs/specs/pike/port-data-plane-status.html

which add the new CLI-option:

openstack port set [--data-plane-status <ACTIVE/DOWN>] <port>

there are some things necessary to activate this, which a written in the ticket of the feature:

https://bugs.launchpad.net/neutron/+bug/1598081/comments/15

I tried it out on my test-deployment, but there was still a data-connection possible within the subnet. Maybe I've overlooked something or understand something wrong about this feature, but maybe it helps you.

The only other solution I have in mind, would it be to access the compute-node of the VM over ssh and take the tap-device down with ip link set down <TAP_DEVICE>, which represents the interface outside of the VM.


问:
How to nest shortcodes with Hugo ? raw HTML ommitted
I get into troubles with shortcodes in hugo.

To make some text-align:right I made an Align shortcode.

To add some color to the text I made a Color shortcode.

To wrap some content into a cream panel I have a Hint shortcode.

1 2 3 works well separately, but when I'm in a config where some text inside a cream panel needs to be on the right or in color I can't achieve that. By looking the html rendered source I see <--- raw HTML ommitted --->

document.md :

```<code>{{< hint cream >}}
Lorem {{< color red >}}ipsum{{< /color >}} example.
{{< align right >}}John Doe{{< /align >}}
{{< /hint >}}
</code>```

Hint shortcode :

```<code><blockquote class="hint {{ .Get 0 }}">
  {{ .Inner | markdownify }}
</blockquote>
</code>```

Align shortcode :

```<code><p style="text-align:{{.Get 0}}">{{ .Inner }}</p>
</code>```

Color shortcode :

```<code><span style="color:{{.Get 0}}">{{ .Inner | markdownify }}</span>
</code>```

It should results in :

```<code><blockquote class="hint cream">
<p>Lorem <span style="color:red">ipsum</span> example.
<p style="text-align:right">John Doe</p>
</blockquote>
</code>```

But results in:

```<code><blockquote class="hint cream">
<p>Lorem <--- raw HTML ommitted --->ipsum<--- raw HTML ommitted ---> example.
<--- raw HTML ommitted --->
</blockquote>
</code>```

Someone can explain me what is wrong with that ?

答:
I just finally find it out.
If someone needs the answer, in the config.toml file of the site, add

```<code>[markup.goldmark.renderer]
unsafe= true
</code>```

Then it will work.

Body:
I get into troubles with shortcodes in hugo.

To make some text-align:right I made an Align shortcode.

To add some color to the text I made a Color shortcode.

To wrap some content into a cream panel I have a Hint shortcode.

1 2 3 works well separately, but when I'm in a config where some text inside a cream panel needs to be on the right or in color I can't achieve that. By looking the html rendered source I see <--- raw HTML ommitted --->

document.md :

{{< hint cream >}}
Lorem {{< color red >}}ipsum{{< /color >}} example.
{{< align right >}}John Doe{{< /align >}}
{{< /hint >}}

Hint shortcode :

  {{ .Inner | markdownify }}

Align shortcode :

{{ .Inner }}

Color shortcode :

{{ .Inner | markdownify }}

It should results in :

Lorem ipsum example.

John Doe

But results in:

Lorem <--- raw HTML ommitted --->ipsum<--- raw HTML ommitted ---> example.
<--- raw HTML ommitted --->

Someone can explain me what is wrong with that ?

Body:
I just finally find it out.
If someone needs the answer, in the config.toml file of the site, add

[markup.goldmark.renderer]
unsafe= true

Then it will work.


问:
Java Multipleclients - server javafx
I have to create an electronic mail with JavaFX using socket, FXML. I need to create one server and 3 clients that are my three accounts and they must start in parallel. Every client must have an associated thread but my problem is: when I start the first client it works, so the FXML file opens. But when I try to open the second client Intellij shows a pop-up that says to me: Stop And Rerun. In my FXML I have a connect button in which I must choose one of my accounts and then my server says "connect". How can I fix this problem? Opening more than one client? If you don't understand I'll try to be more specific. </p>

```<code>MailClient.java

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class MailClient extends Application {

    @Override
    public void start(Stage stage) {
        try{
            Parent root = FXMLLoader.load(getClass().getResource("FXMLMailClient.fxml"));
            Scene scene = new Scene(root);
            stage.setScene(scene);
            stage.show();

        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        Socket s = new Socket("127.0.0.1", 4445);
        PrintWriter out = new PrintWriter(s.getOutputStream(), true);
        launch(args);
    }
}
</code>```

```<code>Server.java

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    private int port = 4445;
    private ServerSocket s = null;

    private static ArrayList<ServerThread> clients = new ArrayList<>();
    private static ExecutorService pool = Executors.newFixedThreadPool(3);

    public void activate() throws IOException {
        try {
            s = new ServerSocket(port);
            while (true) {
                Socket s1 = s.accept();
                System.out.println("Server connect");
                ServerThread st1 = new ServerThread(s1);
                clients.add(st1);

                pool.execute(st1);
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }finally{
            s.close();
        }

    }

    public static void main(String[] args) throws IOException {
        Server s = new Server();
        s.activate();
    }
}
</code>```

```<code>ServerThread.java

import java.io.IOException;
import java.net.Socket;

class ServerThread implements Runnable {

    private Socket socket = null;

    public ServerThread(Socket socket)  throws IOException {
        this.socket = socket;
    }
    @Override
    public void run() {
        System.out.println("Connected");
        // during the run, the following cases will be handled:
        // write an email, receive an email, delete an email.
    }
}
</code>```

```<code>FXMLMailClientController.java

import java.io.IOException;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;

public class FXMLMailClientController {
    private boolean isConnected = false;

    @FXML
    private void handleConnectAction(ActionEvent event) throws IOException {
        while (!isConnected) {
            System.out.println("Client connect");
            isConnected = true;
        }
    }
}

</code>```

```<code>FXMLMailClient.fxml

<?import java.lang.String?>
<?import javafx.collections.FXCollections?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ChoiceBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane id="AnchorPane" prefHeight="583.0" prefWidth="994.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.FXMLMailClientController">
    <children>
        <Button fx:id="connectClient" layoutX="70.0" layoutY="116.0" mnemonicParsing="false" onAction="#handleConnectAction" prefWidth="85.0" text="Connetti" />
        <Label fx:id="account" layoutX="383.0" layoutY="14.0" prefWidth="344.0" text="" />
        <ChoiceBox fx:id="choiceAccount" layoutY="83.0" prefHeight="25.0" prefWidth="225.0">
            <items>
                <FXCollections fx:factory="observableArrayList">
                    <String fx:value="email1" />
                    <String fx:value="email2" />
                    <String fx:value="email3" />
                </FXCollections>
            </items>
        </ChoiceBox>
    </children>
</AnchorPane>
</code>```

答:
The following MRE demonstrates a sever that supports multiple clients.

JavaFx Application is typically the entry point. It should be used to start this example:

```<code>import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class MailClient extends Application {

    //todo add support to start / stop the server and al clents
    private final static int PORT_NUMBER = 4445;

    @Override
    public void start(Stage stage) {
        try{
            Parent root = FXMLLoader.load(getClass().getResource("FXMLMailClient.fxml"));
            //todo path port number to FXMLMailClientController
            Scene scene = new Scene(root);
            stage.setScene(scene);
            stage.show();

        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        new Server(PORT_NUMBER).activate(); //todo start server ftom gui
        launch(args);
    }
}
</code>```

The Server continuously accepts connections. Every client connected is handled by a separate thread (ServerThread).

The Server simply prints out any message received from a client:

```<code>import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {

    private final ExecutorService pool;
    private final List<ServerThread> clients;
    private final int portNumber;
    private  boolean stop;

    Server(int portNumber) {
        this.portNumber = portNumber;
        pool = Executors.newFixedThreadPool(3);
        clients = new ArrayList<>();
    }

    private void runServer(){

        System.out.println("SERVER: Waiting for client");
        try{
            ServerSocket serverSocket = new ServerSocket(portNumber);
            stop = false;

            while(! stop){//do in loop to support multiple clients
                Socket clientSocket = serverSocket.accept();
                System.out.println("SERVER: client connected");
                ServerThread st1 = new ServerThread(clientSocket);
                pool.execute(st1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void stop(){
        for( ServerThread st : clients) {
            st.stopServerTread();
        }
        stop = true;
        pool.shutdown();
    }

    public void activate(){
        new Thread(()->runServer()).start();
    }
}

class ServerThread extends Thread {

    private Socket socket = null;
    private  boolean stop;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        try{
            stop = false;
            DataInputStream in = new DataInputStream( socket.getInputStream() );
            String fromClient;
            while(!stop){
                if((fromClient = in.readUTF()) != null) {
                    System.out.println("SERVER: recieved message - " + fromClient);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();;
        }
    }

    void stopServerTread(){
        stop = true;
    }
}
</code>```

FXMLMailClient.fxml

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.String?>
<?import javafx.collections.FXCollections?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ChoiceBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>

<AnchorPane id="AnchorPane" prefHeight="300.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/10.0.1"
xmlns:fx="http://javafx.com/fxml/1" fx:controller="tests.FXMLMailClientController">
  <children>
    <Button fx:id="connectClient" layoutX="70.0" layoutY="120.0" mnemonicParsing="false"
                                    onAction="#handleConnectAction" prefWidth="85.0" text="Connetti" />
    <ChoiceBox fx:id="choiceAccount" layoutY="85.0" prefHeight="25.0" prefWidth="225.0">
      <items>
        <FXCollections fx:factory="observableArrayList">
          <String fx:value="email1" />
          <String fx:value="email2" />
          <String fx:value="email3" />
        </FXCollections>
      </items>
    </ChoiceBox>
  </children>
</AnchorPane>
</code>```

The controller constructs a new Client when a button is pressed:

```<code>import java.io.IOException;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.ChoiceBox;

public class FXMLMailClientController {

    private final String hostName = "localhost";
    private final int portNumber = 4445;

    @FXML
    ChoiceBox<String> choiceAccount;

    @FXML
    private void handleConnectAction(ActionEvent event) throws IOException {

        if(choiceAccount.getSelectionModel().getSelectedItem() == null) return;
        new Client(choiceAccount.getSelectionModel().getSelectedItem(), hostName, portNumber).activate();
    }
}
</code>```

The Client keeps sending time-stamped messages to the Server:

```<code>import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

public class Client{

    private final String account, hostName;
    private final  int portNumber;
    private  boolean stop;

    Client(String account, String hostName, int portNumber )  {
        this.account = account;
        this.hostName = hostName;
        this.portNumber = portNumber;
    }

    private void runClient(){
        try {
            stop = false;
            Socket socket = new Socket(hostName, portNumber);
            DataInputStream in = new DataInputStream( socket.getInputStream() );
            DataOutputStream out = new DataOutputStream( socket.getOutputStream() );
            out.writeUTF(getClientMessage());

            while (! stop) {
                TimeUnit.SECONDS.sleep(3);
                out.writeUTF(getClientMessage());
            }

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }

    public void activate(){
        new Thread(()->runClient()).start();
    }

    public void stop(){
        stop = true;
    }

    private String getClientMessage(){
        LocalTime time = LocalTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        return "from client # "+ account + " at "+ time.format(formatter);
    }
}
</code>```

Note that in this simple demo the number of clients is not limited to 3.

Also connecting two clients having the same account is possible.

Title: Java Multipleclients - server javafx

Body:
I have to create an electronic mail with JavaFX using socket, FXML. I need to create one server and 3 clients that are my three accounts and they must start in parallel. Every client must have an associated thread but my problem is: when I start the first client it works, so the FXML file opens. But when I try to open the second client Intellij shows a pop-up that says to me: Stop And Rerun. In my FXML I have a connect button in which I must choose one of my accounts and then my server says "connect". How can I fix this problem? Opening more than one client? If you don't understand I'll try to be more specific.

MailClient.java

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class MailClient extends Application {

    @Override
    public void start(Stage stage) {
        try{
            Parent root = FXMLLoader.load(getClass().getResource("FXMLMailClient.fxml"));
            Scene scene = new Scene(root);
            stage.setScene(scene);
            stage.show();

        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        Socket s = new Socket("127.0.0.1", 4445);
        PrintWriter out = new PrintWriter(s.getOutputStream(), true);
        launch(args);
    }
}

Server.java

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    private int port = 4445;
    private ServerSocket s = null;

    private static ArrayList<ServerThread> clients = new ArrayList<>();
    private static ExecutorService pool = Executors.newFixedThreadPool(3);

    public void activate() throws IOException {
        try {
            s = new ServerSocket(port);
            while (true) {
                Socket s1 = s.accept();
                System.out.println("Server connect");
                ServerThread st1 = new ServerThread(s1);
                clients.add(st1);

                pool.execute(st1);
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }finally{
            s.close();
        }

    }

    public static void main(String[] args) throws IOException {
        Server s = new Server();
        s.activate();
    }
}

ServerThread.java

import java.io.IOException;
import java.net.Socket;

class ServerThread implements Runnable {

    private Socket socket = null;

    public ServerThread(Socket socket)  throws IOException {
        this.socket = socket;
    }
    @Override
    public void run() {
        System.out.println("Connected");
        // during the run, the following cases will be handled:
        // write an email, receive an email, delete an email.
    }
}

FXMLMailClientController.java

import java.io.IOException;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;

public class FXMLMailClientController {
    private boolean isConnected = false;

    @FXML
    private void handleConnectAction(ActionEvent event) throws IOException {
        while (!isConnected) {
            System.out.println("Client connect");
            isConnected = true;
        }
    }
}

FXMLMailClient.fxml

<?import java.lang.String?>
<?import javafx.collections.FXCollections?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ChoiceBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane id="AnchorPane" prefHeight="583.0" prefWidth="994.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.FXMLMailClientController">
    <children>
        <Button fx:id="connectClient" layoutX="70.0" layoutY="116.0" mnemonicParsing="false" onAction="#handleConnectAction" prefWidth="85.0" text="Connetti" />

        <ChoiceBox fx:id="choiceAccount" layoutY="83.0" prefHeight="25.0" prefWidth="225.0">
            <items>
                <FXCollections fx:factory="observableArrayList">
                    <String fx:value="email1" />
                    <String fx:value="email2" />
                    <String fx:value="email3" />
                </FXCollections>
            </items>
        </ChoiceBox>
    </children>
</AnchorPane>

Body:
The following MRE demonstrates a sever that supports multiple clients.

JavaFx Application is typically the entry point. It should be used to start this example:

import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class MailClient extends Application {

    //todo add support to start / stop the server and al clents
    private final static int PORT_NUMBER = 4445;

    @Override
    public void start(Stage stage) {
        try{
            Parent root = FXMLLoader.load(getClass().getResource("FXMLMailClient.fxml"));
            //todo path port number to FXMLMailClientController
            Scene scene = new Scene(root);
            stage.setScene(scene);
            stage.show();

        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        new Server(PORT_NUMBER).activate(); //todo start server ftom gui
        launch(args);
    }
}

The Server continuously accepts connections. Every client connected is handled by a separate thread (ServerThread).

The Server simply prints out any message received from a client:

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {

    private final ExecutorService pool;
    private final List<ServerThread> clients;
    private final int portNumber;
    private  boolean stop;

    Server(int portNumber) {
        this.portNumber = portNumber;
        pool = Executors.newFixedThreadPool(3);
        clients = new ArrayList<>();
    }

    private void runServer(){

        System.out.println("SERVER: Waiting for client");
        try{
            ServerSocket serverSocket = new ServerSocket(portNumber);
            stop = false;

            while(! stop){//do in loop to support multiple clients
                Socket clientSocket = serverSocket.accept();
                System.out.println("SERVER: client connected");
                ServerThread st1 = new ServerThread(clientSocket);
                pool.execute(st1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void stop(){
        for( ServerThread st : clients) {
            st.stopServerTread();
        }
        stop = true;
        pool.shutdown();
    }

    public void activate(){
        new Thread(()->runServer()).start();
    }
}

class ServerThread extends Thread {

    private Socket socket = null;
    private  boolean stop;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        try{
            stop = false;
            DataInputStream in = new DataInputStream( socket.getInputStream() );
            String fromClient;
            while(!stop){
                if((fromClient = in.readUTF()) != null) {
                    System.out.println("SERVER: recieved message - " + fromClient);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();;
        }
    }

    void stopServerTread(){
        stop = true;
    }
}

FXMLMailClient.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.String?>
<?import javafx.collections.FXCollections?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ChoiceBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>

<AnchorPane id="AnchorPane" prefHeight="300.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/10.0.1"
xmlns:fx="http://javafx.com/fxml/1" fx:controller="tests.FXMLMailClientController">
  <children>
    <Button fx:id="connectClient" layoutX="70.0" layoutY="120.0" mnemonicParsing="false"
                                    onAction="#handleConnectAction" prefWidth="85.0" text="Connetti" />
    <ChoiceBox fx:id="choiceAccount" layoutY="85.0" prefHeight="25.0" prefWidth="225.0">
      <items>
        <FXCollections fx:factory="observableArrayList">
          <String fx:value="email1" />
          <String fx:value="email2" />
          <String fx:value="email3" />
        </FXCollections>
      </items>
    </ChoiceBox>
  </children>
</AnchorPane>

The controller constructs a new Client when a button is pressed:

import java.io.IOException;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.ChoiceBox;

public class FXMLMailClientController {

    private final String hostName = "localhost";
    private final int portNumber = 4445;

    @FXML
    ChoiceBox<String> choiceAccount;

    @FXML
    private void handleConnectAction(ActionEvent event) throws IOException {

        if(choiceAccount.getSelectionModel().getSelectedItem() == null) return;
        new Client(choiceAccount.getSelectionModel().getSelectedItem(), hostName, portNumber).activate();
    }
}

The Client keeps sending time-stamped messages to the Server:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

public class Client{

    private final String account, hostName;
    private final  int portNumber;
    private  boolean stop;

    Client(String account, String hostName, int portNumber )  {
        this.account = account;
        this.hostName = hostName;
        this.portNumber = portNumber;
    }

    private void runClient(){
        try {
            stop = false;
            Socket socket = new Socket(hostName, portNumber);
            DataInputStream in = new DataInputStream( socket.getInputStream() );
            DataOutputStream out = new DataOutputStream( socket.getOutputStream() );
            out.writeUTF(getClientMessage());

            while (! stop) {
                TimeUnit.SECONDS.sleep(3);
                out.writeUTF(getClientMessage());
            }

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }

    public void activate(){
        new Thread(()->runClient()).start();
    }

    public void stop(){
        stop = true;
    }

    private String getClientMessage(){
        LocalTime time = LocalTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        return "from client # "+ account + " at "+ time.format(formatter);
    }
}

Note that in this simple demo the number of clients is not limited to 3.

Also connecting two clients having the same account is possible.


问:
GET request returning 404 not found
I have a spring boot application where I am just sending a GET request to fetch some data from a pre populated list.
The list exists inside the controller class. When I am hitting the URL, I am constantly getting 404 error.

Student.java

```<code>package com.SpringBootDemo.entities;

public class Student {

    private Integer studentId;
    private String studentName;

    public Student(Integer studentId, String studentName) {
        super();
        this.studentId = studentId;
        this.studentName = studentName;
    }
    public Integer getStudentId() {
        return studentId;
    }
    public void setStudentId(Integer studentId) {
        this.studentId = studentId;
    }
    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

}

</code>```

StudentController.java

```<code>package com.SpringBootDemo.controller;

import java.util.Arrays;
import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.SpringBootDemo.entities.Student;

@RestController
@RequestMapping("api/v1/students")
public class StudentController {

    private static final List<Student> STUDENTS = Arrays.asList(
            new Student(1,"ABC"),
            new Student(2,"DEF"),
            new Student(3,"HIJ"));

    @GetMapping(path = "{studentId}")
    public Student getStudentById(@PathVariable("studentId")Integer studentId)
    {
        System.out.println("inside the controller");
        return STUDENTS.stream()
                .filter(student -> studentId.equals(student.getStudentId()))
                .findFirst()
                .orElseThrow(()->new IllegalStateException("Student with id "+studentId+" doesn't exist"));

    }

}

</code>```

Application.properties

```<code>spring.datasource.url=jdbc:mysql://localhost:3306/spring_project
spring.datasource.username=root
spring.datasource.password=Pblock@20
server.port = 8081
spring.jpa.show-sql=true
</code>```

My stacktrace

```<code>020-06-01 15:07:29.879  INFO 21012 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 10ms. Found 0 JPA repository interfaces.
2020-06-01 15:07:30.275  INFO 21012 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8081 (http)
2020-06-01 15:07:30.281  INFO 21012 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-06-01 15:07:30.281  INFO 21012 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.35]
</code>```

答:
Your endpoint is wrong. change @GetMapping(path = "{studentId}") to @GetMapping("/{studentId}")</p>

```<code>@RestController
@RequestMapping("api/v1/students")
public class StudentController {

    private static final List<Student> STUDENTS = Arrays.asList(
            new Student(1,"ABC"),
            new Student(2,"DEF"),
            new Student(3,"HIJ"));

    @GetMapping("/{studentId}")
    public Student getStudentById(@PathVariable("studentId")Integer studentId)
    {
        System.out.println("inside the controller");
        return STUDENTS.stream()
                .filter(student -> studentId.equals(student.getStudentId()))
                .findFirst()
                .orElseThrow(()->new IllegalStateException("Student with id "+studentId+" doesn't exist"));

    }

}
</code>```

Title: GET request returning 404 not found

Body:
I have a spring boot application where I am just sending a GET request to fetch some data from a pre populated list.
The list exists inside the controller class. When I am hitting the URL, I am constantly getting 404 error.

Student.java

package com.SpringBootDemo.entities;

public class Student {

    private Integer studentId;
    private String studentName;

    public Student(Integer studentId, String studentName) {
        super();
        this.studentId = studentId;
        this.studentName = studentName;
    }
    public Integer getStudentId() {
        return studentId;
    }
    public void setStudentId(Integer studentId) {
        this.studentId = studentId;
    }
    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

}

StudentController.java

package com.SpringBootDemo.controller;

import java.util.Arrays;
import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.SpringBootDemo.entities.Student;

@RestController
@RequestMapping("api/v1/students")
public class StudentController {

    private static final List<Student> STUDENTS = Arrays.asList(
            new Student(1,"ABC"),
            new Student(2,"DEF"),
            new Student(3,"HIJ"));

    @GetMapping(path = "{studentId}")
    public Student getStudentById(@PathVariable("studentId")Integer studentId)
    {
        System.out.println("inside the controller");
        return STUDENTS.stream()
                .filter(student -> studentId.equals(student.getStudentId()))
                .findFirst()
                .orElseThrow(()->new IllegalStateException("Student with id "+studentId+" doesn't exist"));

    }

}

Application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/spring_project
spring.datasource.username=root
spring.datasource.password=Pblock@20
server.port = 8081
spring.jpa.show-sql=true

My stacktrace

020-06-01 15:07:29.879  INFO 21012 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 10ms. Found 0 JPA repository interfaces.
2020-06-01 15:07:30.275  INFO 21012 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8081 (http)
2020-06-01 15:07:30.281  INFO 21012 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-06-01 15:07:30.281  INFO 21012 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.35]

Body:
Your endpoint is wrong. change @GetMapping(path = "{studentId}") to @GetMapping("/{studentId}")

@RestController
@RequestMapping("api/v1/students")
public class StudentController {

    private static final List<Student> STUDENTS = Arrays.asList(
            new Student(1,"ABC"),
            new Student(2,"DEF"),
            new Student(3,"HIJ"));

    @GetMapping("/{studentId}")
    public Student getStudentById(@PathVariable("studentId")Integer studentId)
    {
        System.out.println("inside the controller");
        return STUDENTS.stream()
                .filter(student -> studentId.equals(student.getStudentId()))
                .findFirst()
                .orElseThrow(()->new IllegalStateException("Student with id "+studentId+" doesn't exist"));

    }

}


问:
Time complexity of copying a Collection of strings to another in Java
I have a couple of questions about how the add function of a Java Collection handles strings. For example, in the below code snippet, I am copying a List of strings to a HashSet. What is the worst-case total time complexity in this case? Is it O(M x N) or O(N), where M is the max length of any string in the list, and N is the total number of strings in the list.

```<code>public HashSet<String> createDict(List<String> wordList) {
   HashSet<String> wordDict = new HashSet<>();
   for(String word : wordList) {
       wordDict.add(word);
   }
   return wordDict;
}
</code>```

Will the time complexity be exactly the same if I use the below code instead of the loop?

```<code>HashSet<String> wordDict = new HashSet<>(wordList);
</code>```

答: HashSet is implemented using HashTable. Which means, it has O(1) insertion and is using hash function to insert an element. In this case, size of the inserted element does not really matter much, and they all are considered to be O(1). So your overall, code has O(N) complexity, where N is the size of your list.

Body:
I have a couple of questions about how the add function of a Java Collection handles strings. For example, in the below code snippet, I am copying a List of strings to a HashSet. What is the worst-case total time complexity in this case? Is it O(M x N) or O(N), where M is the max length of any string in the list, and N is the total number of strings in the list.

public HashSet<String> createDict(List<String> wordList) {
   HashSet<String> wordDict = new HashSet<>();
   for(String word : wordList) {
       wordDict.add(word);
   }
   return wordDict;
}

Will the time complexity be exactly the same if I use the below code instead of the loop?

HashSet<String> wordDict = new HashSet<>(wordList);


答:
Length of Strings has nothing to do with copying elements between collections. In fact, you don't copy Strings themselves but references to them. So the complexity will be O(N).

When it comes to the second question about new HashSet<>(wordList) - this call will be faster than than doing a loop. The reason for that is that in HashSet(Collection) constructor it first checks the size of that collection and starts with initialCapacity based on that. This way it doesn't have to resize the underlying HashMap that often.

For those who are curious and too lazy to search, this is HashSets constructor in question:

```<code>public HashSet(Collection<? extends E> c) {
    map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
    addAll(c);
}
</code>```

And addAll from AbstractCollection:

```<code>public boolean addAll(Collection<? extends E> c) {
    boolean modified = false;
    for (E e : c)
        if (add(e))
            modified = true;
    return modified;
}
</code>```

So if you were to set initialCapacity in your example code you will get the same performance, like so:

```<code>public HashSet<String> createDict(List<String> wordList) {
   int initialCapacity = Math.max((int) (wordList.size()/.75f) + 1, 16);
   HashSet<String> wordDict = new HashSet<>(initialCapacity );
   for(String word : wordList) {
       wordDict.add(word);
   }
   return wordDict;
}
</code>```

Title: Time complexity of copying a Collection of strings to another in Java

Body:
Length of Strings has nothing to do with copying elements between collections. In fact, you don't copy Strings themselves but references to them. So the complexity will be O(N).

When it comes to the second question about new HashSet<>(wordList) - this call will be faster than than doing a loop. The reason for that is that in HashSet(Collection) constructor it first checks the size of that collection and starts with initialCapacity based on that. This way it doesn't have to resize the underlying HashMap that often.

For those who are curious and too lazy to search, this is HashSets constructor in question:

public HashSet(Collection<? extends E> c) {
    map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
    addAll(c);
}

And addAll from AbstractCollection:

public boolean addAll(Collection<? extends E> c) {
    boolean modified = false;
    for (E e : c)
        if (add(e))
            modified = true;
    return modified;
}

So if you were to set initialCapacity in your example code you will get the same performance, like so:

public HashSet<String> createDict(List<String> wordList) {
   int initialCapacity = Math.max((int) (wordList.size()/.75f) + 1, 16);
   HashSet<String> wordDict = new HashSet<>(initialCapacity );
   for(String word : wordList) {
       wordDict.add(word);
   }
   return wordDict;
}


问:
regex for group of square brackets and comma javascript
I'm trying to construct a regular expression which I can use to replace all instances of "],[" with just "," in a string.

I'm stuck on this.

I've been through a number of different combinations - currently trying:

```<code>str.replace(/(\[,\])/, ',');
</code>```

But it's not picking it up and I can't see what's wrong with it - anything obvious I'm doing wrong here?

Thanks

答:
Your square brackets are positioned wrongly, and you don't need the normal brackets.

Let's go in steps:

You want to replace all intances of ],[ so you need to use the following:

```<code>/],[/g
</code>```

The g in the regexp is ensures that all instances  are replaced.

[ and ] are special characters, so you use \ to stop regexp from parsing them:

```<code>/\],\[/g
</code>```

Final Result:

let str = '[myString],[AnotherString]';
str = str.replace(/\],\[/g, ",");
console.log(str);```

Body:
I'm trying to construct a regular expression which I can use to replace all instances of "],[" with just "," in a string.

I'm stuck on this.

I've been through a number of different combinations - currently trying:

str.replace(/(\[,\])/, ',');

But it's not picking it up and I can't see what's wrong with it - anything obvious I'm doing wrong here?

Thanks

Body:
Your square brackets are positioned wrongly, and you don't need the normal brackets.

Let's go in steps:

You want to replace all intances of ],[ so you need to use the following:

/],[/g

The g in the regexp is ensures that all instances  are replaced.

[ and ] are special characters, so you use \ to stop regexp from parsing them:

/\],\[/g

Final Result:

let str = '[myString],[AnotherString]';
str = str.replace(/\],\[/g, ",");
console.log(str);


问:
what is the fastest way to toggle images by class
i have a list of image

```<code><img class="onOff" src="/Content/Images/on.png" />
<img class="onOff" src="/Content/Images/on.png" />
<img class="onOff" src="/Content/Images/on.png" />
<img class="onOff" src="/Content/Images/on.png" />
<img class="onOff" src="/Content/Images/on.png" />
</code>```

and i want to change the source of all of the images (by using the class selector .onOff so each of the above images changes to this:

```<code><img class="onOff" src="/Content/Images/off.png" />
</code>```

what is the most efficient way to changing all of these images through jquery?

答:
This is the easiest way:

```<code>$('.onOff').attr('src', function(src) {
    return src == '/Content/Images/off.png' ? '/Content/Images/on.png' : src;
});
</code>```

Looks like you might be misusing the image tag though. If the images are for design/layout only, then you'd be better to use background-images. What context are you using these in?

Body:
i have a list of image

and i want to change the source of all of the images (by using the class selector .onOff so each of the above images changes to this:

what is the most efficient way to changing all of these images through jquery?

Body:
This is the easiest way:

$('.onOff').attr('src', function(src) {
    return src == '/Content/Images/off.png' ? '/Content/Images/on.png' : src;
});

Looks like you might be misusing the image tag though. If the images are for design/layout only, then you'd be better to use background-images. What context are you using these in?


问:
lottery loop through random numbers in a list find how many counts it took to find it
im very new to python and cant figure out a basic matching game using lottery numbers.

i have 6 numbers. the first 5 numbers are between 1-49 and the last number is 1-7.
i cant seem to loop through where after it checks it, it generates another random number.

edited:

how do i remove duplicates from range(0,4)?

```<code>import random

def lottery(ticket):
    count = 0
    run = True
    while count < 200:
        lottoNum = sorted([random.randint(1,49) for x in range(5)])
        lottoNum.append(random.randint(1,7))

        if lottoNum != ticket:
            count += 1
            print(lottoNum)

        else:
            run = False
            print(lottoNum, count)

lottery([11, 12, 36, 39, 46, 1])
</code>```

答:
```<code>import random

def lottery(ticket):
    """
    Compare lottery ticket against lottery draws and print how many draws have taken place
    to match the ticket.
    """

    count = 0
    run = True

    while run:
        lotto_num = [random.randint(1, 49) for _ in range(6)]
        lotto_num[-1] = random.randint(1, 7)

        if lotto_num != ticket:
            print(f"No match! Your ticket {ticket}, Lottery ticket {lotto_num}")
            count += 1
        else:
            print(f"Match! Your ticket {ticket} lottery ticket {lotto_num}")
            print(f"{count} draws")
            run = False

lottery([11, 12, 36, 39, 46, 1])
</code>```

Body:
im very new to python and cant figure out a basic matching game using lottery numbers.

i have 6 numbers. the first 5 numbers are between 1-49 and the last number is 1-7.
i cant seem to loop through where after it checks it, it generates another random number.

edited:

how do i remove duplicates from range(0,4)?

import random

def lottery(ticket):
    count = 0
    run = True
    while count < 200:
        lottoNum = sorted([random.randint(1,49) for x in range(5)])
        lottoNum.append(random.randint(1,7))

        if lottoNum != ticket:
            count += 1
            print(lottoNum)

        else:
            run = False
            print(lottoNum, count)

lottery([11, 12, 36, 39, 46, 1])


问:
CFHTTP unable to find valid certification path to requested target
I'm looking to scrape data off a website, other https sites work and this was working last week but now fails

```<code><cfhttp url="https://www.cliftoncameras.co.uk/all-brands-and-types-of-used-cameras/"></cfhttp>
</code>```

If I run a dump of cfhttp

Exception: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
  unable to find valid certification path to requested target

I have tried running with the latest JRE version 12 - no change

https://helpx.adobe.com/coldfusion/kb/import-certificates-certificate-stores-coldfusion.html

Reverted back to CF original JRE, downloaded the target SSL certificate and installed it using the keytool - no change

c:\ColdFusion2018\jre\bin\keytool -import -keystore cacerts -alias
  cliftoncameras -file
  c:\ColdFusion2018\jre\lib\security\cliftoncameras.cer

I changed the websocket in the CFAdmin to proxy - no change

I did restart the CF Application Server each time.

What else can I do?

答:
I have also seen this java.security.cert.CertPathBuilderException error before from Java and Coldfusion on sites that load ok in a regular browser, but which still error from cfhttp even after adding the certificate to the CF keystore and restarting.

This happens when the target site server certificate configuration has a trust chain issue - when one or more trust chain paths requires the browser to perform an "extra download" of a certificate. This can be because of a missing intermediate certificate in a single trust chain path, or because there are multiple branches in the trust chain with different fingerprints and one or more certificates from one or more of those branches is not being served.

If you run the target site through an SSL Analyzer like ssllabs.com - eg
https://globalsign.ssllabs.com/analyze.html?d=www.cliftoncameras.co.uk&hideResults=on - you'll see that their intermediate certificate Starfield Secure Certificate Authority - G2 is not being served by their server, which forces the client to do an "extra download" - which won't be a problem for most proper browsers, but the Java client used by cfhttp needs the server to provide pretty much every intermediate and root cert directly. It used to be the same for most mobile OSs up until a few years ago.

So the ideal solution is to contact cliftoncameras and have their server admin install the correct Starfield Intermediate certificate so that it is served correctly.

A possible workaround on your side is to install the Starfield Secure Certificate Authority - G2 intermediate certificate in your CF keystore.

Body:
I'm looking to scrape data off a website, other https sites work and this was working last week but now fails

<cfhttp url="https://www.cliftoncameras.co.uk/all-brands-and-types-of-used-cameras/"></cfhttp>

If I run a dump of cfhttp

Exception: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
  unable to find valid certification path to requested target

I have tried running with the latest JRE version 12 - no change

https://helpx.adobe.com/coldfusion/kb/import-certificates-certificate-stores-coldfusion.html

Reverted back to CF original JRE, downloaded the target SSL certificate and installed it using the keytool - no change

c:\ColdFusion2018\jre\bin\keytool -import -keystore cacerts -alias
  cliftoncameras -file
  c:\ColdFusion2018\jre\lib\security\cliftoncameras.cer

I changed the websocket in the CFAdmin to proxy - no change

I did restart the CF Application Server each time.

What else can I do?


问:
Integrate MongoDB with Django
I currently have a project which is using MySQL. However, I also have some data in a Mongo database that I need to fetch. I know there is a python library called Django, but I think it's changing the backend database to MongoDB. I wonder if there is any way I can fetch data from the MongoDB while the rest of the project is still using MySQL?

答:
Yes, there is a way. You should be running the mongo server in the backend.
You can access it in the views as,

```<code>from pymongo import MongoClient

server="localhost"
port = 27017
#Establish a connection with mongo instance.
conn = MongoClient(server,port)
</code>```

After connecting using the above code, you can normally use mongo commands to make CRUD applications on mongodb data.
For example,

```<code>polls = conn.db_name.collection_name.find({})
</code>```

Title: Integrate MongoDB with Django

Body:
Yes, there is a way. You should be running the mongo server in the backend.
You can access it in the views as,

from pymongo import MongoClient

server="localhost"
port = 27017
#Establish a connection with mongo instance.
conn = MongoClient(server,port)

After connecting using the above code, you can normally use mongo commands to make CRUD applications on mongodb data.
For example,

polls = conn.db_name.collection_name.find({})


问:
rejected by cors when using withCredentials, despiete access-control-allow-credentials and origin are set
I'm using AWS lambdas and cloudfront to serve a SPA.
Now that my lambdas are setting a cookie, I want to include that cookie in the requests I made to the backend (the cookie is HttpOnly and Secure).
Using Axios I set the withCredentials option to true and all my request are now being rejected because CORS.
The web app is being served from the main domain, while the backend lambdas are on the usual lambda weird UUID url. The lambdas are returning the proper headers, as you can see in the screenshot: access-control-allow-origin is set to the domain the web-app is being served from and access-control-allow-credentials is true. The screenshot is from the app without the withCredentials option activated, so it is being triggered from the web-app 100% sure.
Everything is being served over https with a valid certificate (I want to test this also on localhost, but that is a different story)

This is the error I'm getting on the console. One weird thing is that it claims that Access-Control-Allow-Credentials is set to '', which is not true

```<code>Access to XMLHttpRequest at 'https://p3doiszvgg.execute-api.eu-central-1.amazonaws.com/dev/sessions'
from origin 'https://pento.danielo.es' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
</code>```

Is there anything missing?

EDIT:

This are the headers that I'm sending. The problem with this headers is that they are obtained without the withCredentials flag, because if I add such flag the only headers I can see are the provisional headers.

```<code>:authority: p3doiszvgg.execute-api.eu-central-1.amazonaws.com
:method: POST
:path: /dev/sessions
:scheme: https
accept: application/json, text/plain, */*
accept-encoding: gzip, deflate, br
accept-language: en-GB,en;q=0.9,es-ES;q=0.8,es;q=0.7,en-US;q=0.6
authorization: Bearer the.bearer.token
cache-control: no-cache
content-length: 58
content-type: application/json;charset=UTF-8
origin: https://pento.danielo.es
pragma: no-cache
referer: https://pento.danielo.es/
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36
</code>```

Here is a provisional headers screenshot:

The cookie sent by the server looks something like this:

```<code> Set-Cookie: refresh_token=uuid-string-with-letters-numbers; HttpOnly; Secure;
</code>```

答:
Finally I found the problem and a temporary solution (I'm not very happy with it).
The problem was not my lambda response, that was correct and including the required headers, the problem was with the preflight request. Your browser will send a preflight request almost for every CORS request you made, and, while that request was being successful it was missing some headers. This can be very confusing because the request that it is failing is your actual request (that is what the browser flags as failed) but the problem is on the preflight response.

To be fair, the error on the console was already pointing this out:

```<code>Response to preflight request doesn't pass access control check
</code>```

But it is abit buried, easy to miss and the documentation about it is sparse.

The way I fixed it is by adding some extra props to the CORS definition of my serverless template:

```<code>  authEcho:
    handler: src/users/me.handler
    events:
      - http:
          path: me
          method: get
          cors:
            origin: https://frontend.domain.es
            allowCredentials: true # <-- this is the key part
</code>```

It is not clear on the serverless documentation, but those will be merged with the final response, so you don't need to specify everything or all the headers. The only thing I don't like is that I have to hardcode the origin, while on the actual labmda responses I can calculate it dynamically.

Body:
I'm using AWS lambdas and cloudfront to serve a SPA.
Now that my lambdas are setting a cookie, I want to include that cookie in the requests I made to the backend (the cookie is HttpOnly and Secure).
Using Axios I set the withCredentials option to true and all my request are now being rejected because CORS.
The web app is being served from the main domain, while the backend lambdas are on the usual lambda weird UUID url. The lambdas are returning the proper headers, as you can see in the screenshot: access-control-allow-origin is set to the domain the web-app is being served from and access-control-allow-credentials is true. The screenshot is from the app without the withCredentials option activated, so it is being triggered from the web-app 100% sure.
Everything is being served over https with a valid certificate (I want to test this also on localhost, but that is a different story)

This is the error I'm getting on the console. One weird thing is that it claims that Access-Control-Allow-Credentials is set to '', which is not true

Access to XMLHttpRequest at 'https://p3doiszvgg.execute-api.eu-central-1.amazonaws.com/dev/sessions'
from origin 'https://pento.danielo.es' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Is there anything missing?

EDIT:

This are the headers that I'm sending. The problem with this headers is that they are obtained without the withCredentials flag, because if I add such flag the only headers I can see are the provisional headers.

:authority: p3doiszvgg.execute-api.eu-central-1.amazonaws.com
:method: POST
:path: /dev/sessions
:scheme: https
accept: application/json, text/plain, */*
accept-encoding: gzip, deflate, br
accept-language: en-GB,en;q=0.9,es-ES;q=0.8,es;q=0.7,en-US;q=0.6
authorization: Bearer the.bearer.token
cache-control: no-cache
content-length: 58
content-type: application/json;charset=UTF-8
origin: https://pento.danielo.es
pragma: no-cache
referer: https://pento.danielo.es/
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36

Here is a provisional headers screenshot:

The cookie sent by the server looks something like this:

 Set-Cookie: refresh_token=uuid-string-with-letters-numbers; HttpOnly; Secure;

Body:
Finally I found the problem and a temporary solution (I'm not very happy with it).
The problem was not my lambda response, that was correct and including the required headers, the problem was with the preflight request. Your browser will send a preflight request almost for every CORS request you made, and, while that request was being successful it was missing some headers. This can be very confusing because the request that it is failing is your actual request (that is what the browser flags as failed) but the problem is on the preflight response.

To be fair, the error on the console was already pointing this out:

Response to preflight request doesn't pass access control check

But it is abit buried, easy to miss and the documentation about it is sparse.

The way I fixed it is by adding some extra props to the CORS definition of my serverless template:

  authEcho:
    handler: src/users/me.handler
    events:
      - http:
          path: me
          method: get
          cors:
            origin: https://frontend.domain.es
            allowCredentials: true # <-- this is the key part

It is not clear on the serverless documentation, but those will be merged with the final response, so you don't need to specify everything or all the headers. The only thing I don't like is that I have to hardcode the origin, while on the actual labmda responses I can calculate it dynamically.


问:
Advantage of Upper Bound over Subtyping in Scala
I know this question has been asked before here. But the answers there do not satisfy my doubt.

I was told that they prevent mix-up of class types, the code below shows that they're not mixed up at all.

So, it shouldn't matter right?

Classes:

```<code>package Practice

abstract class Animal {
  def name: String
}

abstract class Pet extends Animal {}

class Cat extends Pet {
  override def name: String = "Cat"
}

class Dog extends Pet {
  override def name: String = "Dog"
}
</code>```

Here is the real confusion:

```<code>//Class with Upper Bound
class PetContainer[P <: Pet](p: P) {
  def pet: P = p
}

//Class with Subtyping(Or Upcasting, I think they're the same)
class SimplePetContainer(p: Pet){
  def pet: Pet = p
}
</code>```

Driver Code:

```<code>val CatContainer: PetContainer[Cat] = new PetContainer[Cat](new Cat)
val DogContainer: SimplePetContainer = new SimplePetContainer(new Dog
println(CatContainer.pet.getClass)
println(DogContainer.pet.getClass)
</code>```

Output:

```<code>class Practice.Cat
class Practice.Dog
//Practice was the package
</code>```

Like I mentioned before, the classes are preserved.

So my question is, What advantage does Upper Bound have on Subtyping?

答:
With your CatContainer, you know that CatContainer.pet is a Cat at compile-time. Meaning that the compiler also knows that. So you can say

```<code> CatContainer.pet.meow()
</code>```

For the SimplePetContainer you do not have static type information about the pet inside anymore.

Like I mentioned before, the classes are preserved.

At runtime, the pet of course still knows its type (well, almost, it knows its class, which in your case would have been enough, any extra type information such as the generic types of that class has been erased).
But the variable DogContainer.pet lacks information about what sort of Pet it contains.

I was told that they prevent mix-up of class types

The compiler won't stop you from writing

```<code>val DogContainer = new SimplePetContainer(new Cat())
</code>```

but it will reject this

```<code>val DogContainer = new PetContainer[Dog](new Cat())
</code>```

Body:
I know this question has been asked before here. But the answers there do not satisfy my doubt.

I was told that they prevent mix-up of class types, the code below shows that they're not mixed up at all.

So, it shouldn't matter right?

Classes:

package Practice

abstract class Animal {
  def name: String
}

abstract class Pet extends Animal {}

class Cat extends Pet {
  override def name: String = "Cat"
}

class Dog extends Pet {
  override def name: String = "Dog"
}

Here is the real confusion:

//Class with Upper Bound
class PetContainer[P <: Pet](p: P) {
  def pet: P = p
}

//Class with Subtyping(Or Upcasting, I think they're the same)
class SimplePetContainer(p: Pet){
  def pet: Pet = p
}

Driver Code:

val CatContainer: PetContainer[Cat] = new PetContainer[Cat](new Cat)
val DogContainer: SimplePetContainer = new SimplePetContainer(new Dog
println(CatContainer.pet.getClass)
println(DogContainer.pet.getClass)

Output:

class Practice.Cat
class Practice.Dog
//Practice was the package

Like I mentioned before, the classes are preserved.

So my question is, What advantage does Upper Bound have on Subtyping?

Body:
With your CatContainer, you know that CatContainer.pet is a Cat at compile-time. Meaning that the compiler also knows that. So you can say

 CatContainer.pet.meow()

For the SimplePetContainer you do not have static type information about the pet inside anymore.

Like I mentioned before, the classes are preserved.

At runtime, the pet of course still knows its type (well, almost, it knows its class, which in your case would have been enough, any extra type information such as the generic types of that class has been erased).
But the variable DogContainer.pet lacks information about what sort of Pet it contains.

I was told that they prevent mix-up of class types

The compiler won't stop you from writing

val DogContainer = new SimplePetContainer(new Cat())

but it will reject this

val DogContainer = new PetContainer[Dog](new Cat())


问:
Removing key/value pairs in list of dictionary having None Values
inputs : [{'test1': 'test', 'test2': None}]

Exected output : [{'test1': 'test'}]

答:
Here's a way to process the inputs that results in your expected output. It eliminates key: value pairs from dictionaries where the value is None then eliminates totally empty dictionaries from the list.

```<code>data = [{'test1': 'test', 'test2': None}]

output = [entry for entry in [{key: value for key, value in dictionary.items() if value != None} for dictionary in data] if len(entry)>0]
print(output)
</code>```

EDIT: As per Itamar's comment below, you might want to maintain the original length of the list, for example in the case where you wanted to compare output from a consistent number of functions. Just eliminate the outermost digest:

```<code>data = [{'test1': 'test', 'test2': None}]

output = [{key: value for key, value in dictionary.items() if value != None} for dictionary in data]
print(output)
</code>```

Body:
Here's a way to process the inputs that results in your expected output. It eliminates key: value pairs from dictionaries where the value is None then eliminates totally empty dictionaries from the list.

data = [{'test1': 'test', 'test2': None}]

output = [entry for entry in [{key: value for key, value in dictionary.items() if value != None} for dictionary in data] if len(entry)>0]
print(output)

EDIT: As per Itamar's comment below, you might want to maintain the original length of the list, for example in the case where you wanted to compare output from a consistent number of functions. Just eliminate the outermost digest:

data = [{'test1': 'test', 'test2': None}]

output = [{key: value for key, value in dictionary.items() if value != None} for dictionary in data]
print(output)


问:
mat-form-field' is not a known element in angular
i am using input from angular material but i get this error
    **ERROR in src/app/modules/posts/posts.component.html:2:5 - error NG8001: 'mat-form-field' is not a known element:
    1. If 'mat-form-field' is an Angular component, then verify that it is part of this module.
    2. If 'mat-form-field' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

this is my html code

```<code><form class="example-form">
    <mat-form-field class="example-full-width">
     Favorite food
      <input matInput >
    </mat-form-field>

  </form>
</code>```

this is my app module

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { DefaultModule } from './layouts/default/default.module';
import { MatTableModule } from '@angular/material/table';
import { HttpClientModule } from '@angular/common/http';
import {UserInfoService} from './services/user-info.service'
import {MatCardModule} from '@angular/material/card';
import {MatDialogModule} from '@angular/material/dialog';
import { PostsComponent } from './modules/posts/posts.component';
import {  MatFormFieldModule} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';

@NgModule({
  declarations: [
    AppComponent,

  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    DefaultModule,
    MatTableModule,
    HttpClientModule,
    MatCardModule,
    MatDialogModule,
    MatFormFieldModule,
    MatInputModule
  ],
  exports: [

    MatFormFieldModule,
    MatInputModule,

  ],
  providers: [UserInfoService],
  bootstrap: [AppComponent],
  entryComponents:[PostsComponent]
})
export class AppModule { }
</code>```

i can not find the right solution for this can you help me?

答: Add FormsModule, ReactiveFormsModule, to imports section. Remove both exports elements.

Body:
i am using input from angular material but i get this error
    **ERROR in src/app/modules/posts/posts.component.html:2:5 - error NG8001: 'mat-form-field' is not a known element:
    1. If 'mat-form-field' is an Angular component, then verify that it is part of this module.
    2. If 'mat-form-field' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

this is my html code

<form class="example-form">
    <mat-form-field class="example-full-width">
     Favorite food
      <input matInput >
    </mat-form-field>

  </form>

this is my app module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { DefaultModule } from './layouts/default/default.module';
import { MatTableModule } from '@angular/material/table';
import { HttpClientModule } from '@angular/common/http';
import {UserInfoService} from './services/user-info.service'
import {MatCardModule} from '@angular/material/card';
import {MatDialogModule} from '@angular/material/dialog';
import { PostsComponent } from './modules/posts/posts.component';
import {  MatFormFieldModule} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';

@NgModule({
  declarations: [
    AppComponent,

  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    DefaultModule,
    MatTableModule,
    HttpClientModule,
    MatCardModule,
    MatDialogModule,
    MatFormFieldModule,
    MatInputModule
  ],
  exports: [

    MatFormFieldModule,
    MatInputModule,

  ],
  providers: [UserInfoService],
  bootstrap: [AppComponent],
  entryComponents:[PostsComponent]
})
export class AppModule { }

i can not find the right solution for this can you help me?


问:
Flutter "argument type not assignable" Error with two identical types
Flutter shows me this error, but the two types are identical.

[CartItem it's just a simple model; there was a conflict since another widget had the same name but I resolved it using "as" in the import statement]

The argument type List<CartItems> (where CartItem is defined in /Users/marco/Documenti Locali/shop_app/lib/providers/cart.dart)' can't be assigned to the parameter type  List<CartItems> (where CartItem is defined in /Users/marco/Documenti Locali/shop_app/lib/providers/cart.dart)'.dartargument_type_not_assignable

list.dart(56, 16): List is defined in /Users/marco/flutter/bin/cache/pkg/sky_engine/lib/core/list.dart

cart.dart(3, 7): CartItem is defined in /Users/marco/Documenti Locali/shop_app/lib/providers/cart.dart

list.dart(56, 16): List is defined in /Users/marco/flutter/bin/cache/pkg/sky_engine/lib/core/list.dart

cart.dart(3, 7): CartItem is defined in /Users/marco/Documenti Locali/shop_app/lib/providers/cart.dart

Peek Problem (⌥F8)
No quick fixes available

答: It was a double slash in the import statement that generated this strange error.


答:
The complexity will be O(N).

Adding an item to an HashSet is O(1) and it won't compare strings char by char, which is probably how you would get O(MxN).

Yes, creating the HashSet passing the list in the constructor will have the same complexity.
Actually you can check HashSet implementation code and it does exactly the same thing you did, except for a more optimised object creation based on your list size.


问:
Why is there a performance difference between the following two methods?
After I submitted my solution to the Maximum Subarray problem on leetcode, it said my runtime was 1ms (beating ~66% submissions), then I made a couple of changes and resubmitted. This time, the runtime was 0ms (beating ~100%). I do not quite understand what contributed to the reduction in time. Here the are two versions.

Original:

```<code>public int maxSubArray(int[] nums) {
        if (nums == null) return 0;
        if (nums.length == 1) return nums[0];

        int current_max = nums[0];
        int cur = 1;
        int max = current_max;

        while (cur < nums.length) {
            current_max = Math.max(nums[cur] + current_max, nums[cur]);
            if (current_max > max) {
                max = current_max;
            }
            cur++;
        }
        return max;
    }
</code>```

Updated:

```<code>public int maxSubArray(int[] nums) {
        if (nums == null) return 0;
        int l = nums.length;
        if (l == 1) return nums[0];

        int current_max = nums[0];
        int max = current_max;

        for (int i = 1; i < l; i++) {
            current_max = Math.max(nums[i] + current_max, nums[i]);
            if (current_max > max) {
                max = current_max;
            }
        }

        return max;
    }
</code>```

The only two changes I did, were

Changing the while loop to a for loop - Apparently there is no difference ref

Store the length in a separate variable - Since Array does not compute the length and array.length is only fetching from an internal variable, I do not see any difference here either.

[EDIT]

I agree. leetcode's performance is not 100% accurate.
Funny thing, I submitted my updated code again the other day, and suddenly now it's 0ms.

答:
First. Every time you run the same code, time consumption is not completely equals

Second. LeetCode just give you an approximate consumption, MAYBE < 1ms will return 0ms

If you want more accurate time to consider test it with jmh

https://openjdk.java.net/projects/code-tools/jmh/

https://hg.openjdk.java.net/code-tools/jmh/file/tip/jmh-samples/src/main/java/org/openjdk/jmh/samples/

Hope this may help

update

if you want compare difference between the two method just put them in one class and

```<code>javac filename.java
</code>```

then

```<code>javap -c classname
</code>```

you will get bytecode of these two methods, these byte codes are what real executed in jvm

reference :

https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-6.html#jvms-6.5.invokespecial]

Body:
After I submitted my solution to the Maximum Subarray problem on leetcode, it said my runtime was 1ms (beating ~66% submissions), then I made a couple of changes and resubmitted. This time, the runtime was 0ms (beating ~100%). I do not quite understand what contributed to the reduction in time. Here the are two versions.

Original:

public int maxSubArray(int[] nums) {
        if (nums == null) return 0;
        if (nums.length == 1) return nums[0];

        int current_max = nums[0];
        int cur = 1;
        int max = current_max;

        while (cur < nums.length) {
            current_max = Math.max(nums[cur] + current_max, nums[cur]);
            if (current_max > max) {
                max = current_max;
            }
            cur++;
        }
        return max;
    }

Updated:

public int maxSubArray(int[] nums) {
        if (nums == null) return 0;
        int l = nums.length;
        if (l == 1) return nums[0];

        int current_max = nums[0];
        int max = current_max;

        for (int i = 1; i < l; i++) {
            current_max = Math.max(nums[i] + current_max, nums[i]);
            if (current_max > max) {
                max = current_max;
            }
        }

        return max;
    }

The only two changes I did, were

Changing the while loop to a for loop - Apparently there is no difference ref

Store the length in a separate variable - Since Array does not compute the length and array.length is only fetching from an internal variable, I do not see any difference here either.

[EDIT]

I agree. leetcode's performance is not 100% accurate.
Funny thing, I submitted my updated code again the other day, and suddenly now it's 0ms.

Body:
First. Every time you run the same code, time consumption is not completely equals

Second. LeetCode just give you an approximate consumption, MAYBE < 1ms will return 0ms

If you want more accurate time to consider test it with jmh

https://openjdk.java.net/projects/code-tools/jmh/

https://hg.openjdk.java.net/code-tools/jmh/file/tip/jmh-samples/src/main/java/org/openjdk/jmh/samples/

Hope this may help

update

if you want compare difference between the two method just put them in one class and

javac filename.java

then

javap -c classname

you will get bytecode of these two methods, these byte codes are what real executed in jvm

reference :

https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-6.html#jvms-6.5.invokespecial]


问:
Use a string to specify filepath in C++ (store files in a folder)
I am generating hundreds of output files and would like to store them in a folder called OUT in the working directory rather than the working directory itself. Each file is name according to the current iteration. (out1.txt, out2.txt...etc). I have been looking at the documentation for quite a while and trying different things but not having success.  Here is the code. (it is within a loop where k is the iteration number.

```<code>char outname[50];
char filepath[30];
char iter_str[10];
sprintf(iter_str,"%d",k)
strcpy(outname,"out");
strcat(outname,iter_str);
strcat(outname,".txt");
strcpy(filepath,"..\\OUT\\");
strcat(filepath,outname);
file = fopen(filepath,"w");
</code>```

Instead of going into the "OUT" folder, it goes into the working directory and names it like this:

```<code>..\OUT\out1.txt
..\OUT\out2.txt
..\OUT\out3.txt
etc
</code>```

Any suggestions would be much appreciated!

I have now realized that on unix I should have "/" instead of "\". I have done this and have gotten a seg fault. Also a seg fault when using "//".

答:
I think you can use std::stringstream instead of strcpy() and sprintf();</p>

```<code>std::stringstream l_strStream{};
#if defined(_WIN32)
    l_strStream << outName << "\\" << iter_str << ".txt";//for filename with path
#elif defined(__linux__)
    l_strStream << outName << "/" << iter_str << ".txt";//for filename with path
#endif // try this , no need to use other libs
</code>```

Body:
I am generating hundreds of output files and would like to store them in a folder called OUT in the working directory rather than the working directory itself. Each file is name according to the current iteration. (out1.txt, out2.txt...etc). I have been looking at the documentation for quite a while and trying different things but not having success.  Here is the code. (it is within a loop where k is the iteration number.

char outname[50];
char filepath[30];
char iter_str[10];
sprintf(iter_str,"%d",k)
strcpy(outname,"out");
strcat(outname,iter_str);
strcat(outname,".txt");
strcpy(filepath,"..\\OUT\\");
strcat(filepath,outname);
file = fopen(filepath,"w");

Instead of going into the "OUT" folder, it goes into the working directory and names it like this:

..\OUT\out1.txt
..\OUT\out2.txt
..\OUT\out3.txt
etc

Any suggestions would be much appreciated!

I have now realized that on unix I should have "/" instead of "\". I have done this and have gotten a seg fault. Also a seg fault when using "//".

Body:
I think you can use std::stringstream instead of strcpy() and sprintf();

std::stringstream l_strStream{};
#if defined(_WIN32)
    l_strStream << outName << "\\" << iter_str << ".txt";//for filename with path
#elif defined(__linux__)
    l_strStream << outName << "/" << iter_str << ".txt";//for filename with path
#endif // try this , no need to use other libs


问:
Check if two conditions are both true, only one is true or none is true in Python
I have two conditions C1 and C2. I want my program to perform something different in case that C1 and C2 are true, C1 is true but not C2, C2 is true but not C1, neither C1 nor C2 is true.

Now I have this code:

```<code>if C1 and C2:
    ...
elif C1:
    ...
elif C2:
    ...
else:
    ...
</code>```

Is there a more efficient way to code this in Python?

答:
Just slightly.

```<code>if C1:
    if C2:
        # both true
    else:
        # only C1 true
elif C2:
    # only C2 true
else:
    # both false
</code>```

This way, both C1 and C2 are checked exactly once each. The question is, are you more interested in efficiency or readability.

Body:
I have two conditions C1 and C2. I want my program to perform something different in case that C1 and C2 are true, C1 is true but not C2, C2 is true but not C1, neither C1 nor C2 is true.

Now I have this code:

if C1 and C2:
    ...
elif C1:
    ...
elif C2:
    ...
else:
    ...

Is there a more efficient way to code this in Python?

Body:
Just slightly.

if C1:
    if C2:
        # both true
    else:
        # only C1 true
elif C2:
    # only C2 true
else:
    # both false

This way, both C1 and C2 are checked exactly once each. The question is, are you more interested in efficiency or readability.


问:
How to set match password in react Js
I need some help how could I match the password in react js. I used ant design the first password is working but for conform password I put statement its not working how could I do it </p>

```<code>handlePasswordChange = event => {
  this.setState({
    password: event.target.value,
  });
};
handleConfirmPassword = event => {
  if (event.handleConfirmPassword !== event.handlePasswordChange) {
    message.error('error');
  }
};
</code>```

<p>these are fun and below is the ant design </p>

```<code><FormItem {...styles.formItemLayout} label="Password">
  {getFieldDecorator('Password', {
    rules: [{ required: true, message: 'Password is Required!' }],
  })(
    <Input
      onChange={this.handlePasswordChange}
      name="password"
      type="password"
      value={password}
      style={styles.margin}
    />,
  )}
</FormItem>
<FormItem {...styles.formItemLayout} label="Confirm Password">
  {getFieldDecorator('Confirm Password', {
    rules: [{ required: true, message: 'Confirm your Password!' }],
  })(
    <Input
      name="password"
      type="password"
      style={styles.margin}
      onChange={this.handleConfirmPassword}
    />,
  )}
</FormItem>
</code>```

答:
```<code>import { useForm } from 'react-hook-form'

const { register, errors, handleSubmit, formState } = useForm({
    mode: "onChange"
  })

  const [newpassword, setNewPassword] = useState('')

  const [confirmpassword, setConfirmPassword] = useState('')

  const  { touched  } = formState;

  const onVerifyNewPassword = () => {

    if(touched.newpassword === true && touched.confirmpassword === true){
      if(newpassword !== confirmpassword){
        console.log('The passwords dont match')
        return
      }else{
        console.log('Ok.')
      }
   }
  }

              <form onSubmit={handleSubmit(onSubmit)}>
                <div className="input-group">
                  <label htmlFor="new">New Password</label>
                </div>
                <input type="newpassword"
                  ref={register({ required: true })}

                  name="newpassword"
                  onChange={(e) => setNewPassword(e.target.value)}
                  onBlur={onVerifyNewPassword}
                />
                <label htmlFor="new">Confirm Password</label>
                <input type="confirmpassword"
                  ref={register({ required: true })}
                  name="confirmpassword"
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  onBlur={onVerifyNewPassword}

               />
                {/* ```{JSON.stringify(formState, null, 2)}``` */}

                <button><span>Change</span></button>
</code>```

Title: How to set match password in react Js

Body:
I need some help how could I match the password in react js. I used ant design the first password is working but for conform password I put statement its not working how could I do it

handlePasswordChange = event => {
  this.setState({
    password: event.target.value,
  });
};
handleConfirmPassword = event => {
  if (event.handleConfirmPassword !== event.handlePasswordChange) {
    message.error('error');
  }
};

these are fun and below is the ant design

<FormItem {...styles.formItemLayout} label="Password">
  {getFieldDecorator('Password', {
    rules: [{ required: true, message: 'Password is Required!' }],
  })(
    <Input
      onChange={this.handlePasswordChange}
      name="password"
      type="password"
      value={password}
      style={styles.margin}
    />,
  )}
</FormItem>
<FormItem {...styles.formItemLayout} label="Confirm Password">
  {getFieldDecorator('Confirm Password', {
    rules: [{ required: true, message: 'Confirm your Password!' }],
  })(
    <Input
      name="password"
      type="password"
      style={styles.margin}
      onChange={this.handleConfirmPassword}
    />,
  )}
</FormItem>

Body:
import { useForm } from 'react-hook-form'

const { register, errors, handleSubmit, formState } = useForm({
    mode: "onChange"
  })

  const [newpassword, setNewPassword] = useState('')

  const [confirmpassword, setConfirmPassword] = useState('')

  const  { touched  } = formState;

  const onVerifyNewPassword = () => {

    if(touched.newpassword === true && touched.confirmpassword === true){
      if(newpassword !== confirmpassword){
        console.log('The passwords dont match')
        return
      }else{
        console.log('Ok.')
      }
   }
  }

              <form onSubmit={handleSubmit(onSubmit)}>
                <div className="input-group">
                  <label htmlFor="new">New Password</label>
                </div>
                <input type="newpassword"
                  ref={register({ required: true })}

                  name="newpassword"
                  onChange={(e) => setNewPassword(e.target.value)}
                  onBlur={onVerifyNewPassword}
                />
                <label htmlFor="new">Confirm Password</label>
                <input type="confirmpassword"
                  ref={register({ required: true })}
                  name="confirmpassword"
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  onBlur={onVerifyNewPassword}

               />
                {/* <pre>{JSON.stringify(formState, null, 2)}</pre> */}

                <button><span>Change</span></button>


问:
why I got memory still reachable when it's not reachable
this is the struct of list:

```<code>struct link {
    char name[20];
    list* next;
};
</code>```

this is the function that valgrind say that the memory is still reachable.

```<code>list* make_new_link(char* name) {
    list* new_link = (list*)malloc(sizeof(list));
    new_link->name = name;
    new_link->next = NULL;

    return new_link;

}
</code>```

at the end of the code I freed the list like so:
NOTE: list* lst is the pointer of the list

```<code>void free_list(list* lst) {
    list* temp = NULL;

    while(lst->next != NULL) {
        temp = lst;
        lst = lst->next;
        free(temp);
    }
}
</code>```

so why I still get an memory problem?

答:
You never clean up the first element because of while(lst->next != NULL). Fix it like this:

```<code>void free_list(list* lst) {
    list* temp = NULL;

    while(lst != NULL) {
        temp = lst;
        lst = lst->next;
        free(temp);
    }
}
</code>```

Body:
this is the struct of list:

struct link {
    char name[20];
    list* next;
};

this is the function that valgrind say that the memory is still reachable.

list* make_new_link(char* name) {
    list* new_link = (list*)malloc(sizeof(list));
    new_link->name = name;
    new_link->next = NULL;

    return new_link;

}

at the end of the code I freed the list like so:
NOTE: list* lst is the pointer of the list

void free_list(list* lst) {
    list* temp = NULL;

    while(lst->next != NULL) {
        temp = lst;
        lst = lst->next;
        free(temp);
    }
}

so why I still get an memory problem?

Body:
You never clean up the first element because of while(lst->next != NULL). Fix it like this:

void free_list(list* lst) {
    list* temp = NULL;

    while(lst != NULL) {
        temp = lst;
        lst = lst->next;
        free(temp);
    }
}


问:
Server Side Event - PHP echo after Event not wanted
In my project I try to send a PHP Script message to the client, this also works perfectly:

JS

```<code>    //EVENTLISTENER - MESSAGES
let event_messages = new EventSource('overlays/artikel_einstellen/php/artikel_einstellen.php');
event_messages.addEventListener("messages", function(message) {
    $("#modal_message").append(message.data);
    if (message.data == ''){event_messages.close();}
    console.log(message.data);
}, false);
</code>```

PHP (data: is written with a div - by display: none)
Think thats an uggly way to do that.

```<code> echo "<div class='notvisible'>\n\n"; `<-- div container to display:none echos from PHP`
    echo "event: messages\n";
    echo "data: - Daten Komplimentierung abgeschlossen ✔<br/>" . "\n\n";
    echo "event: progress_bar\n";
    echo "data: 20" . "\n\n";
    echo "</div>\n\n";
    echo str_pad('', 60 * 1024);
    flush();sleep (1);
</code>```

image

As u can see,
But after end of PHP Script, the echo's fires again (what its normal doing)
Is there a way to prevent this?

best regards

答:
Was my fault,

was a Fetch response

```<code>//FETCH
const MyForm = document.getElementById('form_artikel_einstellen');
const formData = new FormData(MyForm);

fetch('overlays/artikel_einstellen/funktion/comp_doctrine_tmp_insert.php',{

    method: 'post',
    body: formData,

}).then(function(response){
    return response.text();

    //return response.json();
}).then(function (text){

    $(".modal_small div.modal-close").show();
    //**$(".modal_small div.modal div.modal_content").append(text);** //<<--
    return console.log(text);

}).catch(function(error){
    console.error(error);
})
</code>```

Body:
In my project I try to send a PHP Script message to the client, this also works perfectly:

JS

    //EVENTLISTENER - MESSAGES
let event_messages = new EventSource('overlays/artikel_einstellen/php/artikel_einstellen.php');
event_messages.addEventListener("messages", function(message) {
    $("#modal_message").append(message.data);
    if (message.data == ''){event_messages.close();}
    console.log(message.data);
}, false);

PHP (data: is written with a div - by display: none)
Think thats an uggly way to do that.

 echo "
\n\n"; `<-- div container to display:none echos from PHP`
    echo "event: messages\n";
    echo "data: - Daten Komplimentierung abgeschlossen ✔
" . "\n\n";
    echo "event: progress_bar\n";
    echo "data: 20" . "\n\n";
    echo "
\n\n";
    echo str_pad('', 60 * 1024);
    flush();sleep (1);

image

As u can see,
But after end of PHP Script, the echo's fires again (what its normal doing)
Is there a way to prevent this?

best regards

Body:
Was my fault,

was a Fetch response

//FETCH
const MyForm = document.getElementById('form_artikel_einstellen');
const formData = new FormData(MyForm);

fetch('overlays/artikel_einstellen/funktion/comp_doctrine_tmp_insert.php',{

    method: 'post',
    body: formData,

}).then(function(response){
    return response.text();

    //return response.json();
}).then(function (text){

    $(".modal_small div.modal-close").show();
    //**$(".modal_small div.modal div.modal_content").append(text);** //<<--
    return console.log(text);

}).catch(function(error){
    console.error(error);
})