问:
Java multi-client chat server private message options
I am new at stackoverflow and I am sorry if this kind of a question is asked before but did a quick search and I could not find any title like mine. I am working on a multi-client chat application on Java. I was following the tutorials and I can send messages that every user in the application can see. But I wonder how to create and send a private message to a spesific user into the chat.

import java.io.*;
import java.net.*;
import java.util.HashSet;
import java.util.Set;

public class ChatServer {
    private int port;

    private Set<String> userNames = new HashSet<>();
    private Set<UserThread> userThreads = new HashSet<>();

    public ChatServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) {
        new ChatServer(9999).execute();
    }

    private void execute() {
        try {
            ServerSocket serverSocket = new ServerSocket(9999);
            System.out.println("Server is running");
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("New user connected");
                UserThread newUser = new UserThread(socket, this);
                userThreads.add(newUser);
                newUser.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void addUserName(String s) {
        this.userNames.add(s);
    }

    public void broadcast(String serverMessage, UserThread excludeUser) {
        for (UserThread aUser : userThreads) {
            if (aUser != excludeUser)
                aUser.sendMessage(serverMessage);
        }
    }
}
```

<p>The code above is my server code.</p>

<pre class="lang-java prettyprint-override"><code>public void run() {
    Console console = System.console();
    String userName = console.readLine("Enter your username : ");
    writer.println(userName);
    String text;
    do {
        text = console.readLine("[" + userName + "]: ");
        if (text.startsWith("[")) {
            isTargeted = true;
            this.aimUserName = text.substring(text.indexOf("[") + 1, text.indexOf("]"));
            //System.out.println("Private Message to: " + aimUserName);
        } else {
            isTargeted = false;
        }
        writer.println(text);
    } while (!text.equals("bye"));

    try {
        socket.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
</code>```

and this code above is a part of my write thread class. As you can see, if a message starts with '[name]' part, the "name" means the user that we want to send a private message. By doing this, I can get the name of the user that I want to send a private message but I could not figure out how to broadcast this message just to that spesific user. I believe I need to configure my broadcast function in ChatServer class but I don't really know how to do. What steps should I follow?

--Edit--

I've been working on my question and I did some additions to solve my problem. First of all, I think I should share everything I have to you. I shared my ChatServer class previously. Other classes I have are:

```<code>import java.io.IOException;
import java.net.Socket;

public class ChatClient {

    public static void main(String[] args) {
        new ChatClient().execute();
    }

    private void execute() {
        try {
            Socket socket = new Socket("localhost", 3);
            System.out.println("Connected to chat server");
            new ReadThread(socket, this).start();
            new WriteThread(socket, this).start();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

</code>```

```<code>import java.net.*;
import java.io.*;

public class ReadThread extends Thread{
    private BufferedReader reader;
    private Socket socket;
    private ChatClient client;
    public ReadThread(Socket socket, ChatClient client) {
        this.socket = socket;
        this.client = client;

        InputStream input;
        try {
            input = this.socket.getInputStream();
            this.reader = new BufferedReader(new InputStreamReader(input));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void run() {
        while(true) {
            try {
                String response = this.reader.readLine();
                System.out.println("\n" + response);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                break;
            }
        }
    }
}

</code>```

```<code>import java.net.Socket;
import java.io.*;
public class UserThread extends Thread {

    private Socket socket;
    private ChatServer server;
    PrintWriter writer = null;
    public String userName;
    public UserThread(Socket socket, ChatServer chatServer) {
        this.socket = socket;
        this.server = chatServer;
    }

    public void run() {
        try {
            InputStream input = socket.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            OutputStream output = socket.getOutputStream();
            writer = new PrintWriter(output,true);

            String userName = reader.readLine();
            this.userName = userName;
            server.addUserName(userName);
            String serverMessage = "New user connected: " + userName;
            server.broadcast(serverMessage,this);

            String clientMessage;
            do {
                clientMessage = reader.readLine();
                serverMessage = "[" + userName + "] : " + clientMessage;
                server.broadcast(serverMessage, this);

            }while(!clientMessage.equals("bye"));

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void sendMessage(String serverMessage) {
        writer.println(serverMessage);
    }

}

</code>```

```<code>import java.net.*;
import java.io.*;
public class WriteThread extends Thread {
    private Socket socket;
    private ChatClient client;
    private PrintWriter writer;
    public WriteThread(Socket socket, ChatClient client) {
        this.socket = socket;
        this.client = client;
        OutputStream output;
        try {
            output = socket.getOutputStream();
            this.writer = new PrintWriter(output, true);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void run() {
        Console console = System.console();
        String userName = console.readLine("Enter your username : ");
        writer.println(userName);
        String text;
        do {
            text = console.readLine("[" + userName + "]: ");
            if(text.startsWith("[")){
                String aimUserName = text.substring(text.indexOf("[")+1,text.indexOf("]"));
                System.out.println("Private Message to: " + aimUserName);}
            writer.println(text);
        }while(!text.equals("bye"));

        /*do {
            text = console.readLine("[" + userName + "]: ");
            writer.println(text);
        }while(!text.equals("bye"));*/

        try {
            socket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

</code>```

These codes work properly and I can multi-chat very clean. But while working on private chat stuff, I added to the ChatServer the line of:

```<code>public void privatebr(String serverMessage, String targetUserName){
        for(UserThread aUser: userThreads){
            if(aUser.userName == targetUserName)
                aUser.sendMessage(serverMessage);
        }
</code>```

to the UserThread, I edited the part as:

```<code>String clientMessage;
            do {
                clientMessage = reader.readLine();
                serverMessage = "[" + userName + "] : " + clientMessage;
                if(clientMessage.startsWith("[")){
                    String targetUserName = clientMessage.substring(clientMessage.indexOf("[")+1,clientMessage.indexOf("]"));
                    serverMessage = "[" + userName + "] : " + clientMessage;
                    server.privatebr(serverMessage, targetUserName);
                }else{

                    server.broadcast(serverMessage, this);
                }

            }while(!clientMessage.equals("bye"));
</code>```

But when I did all these edits, the normal multi-chat progress became broken where is my fault? Why everything has broken?

答:
Good question! To answer the question you asked is that you should maintain a Map of Users to their Socket connections, so that way with DMs you can just select the user(s) that you want to message. You will also need a messaging protocol for that (see below)

...But I have to tell you that using Sockets and SocketServer classes in today's day and age is like re-inventing the wheel. The place to start in doing a chat server is using the web sockets protocol. Even under this, you will probably want to define a message protocol (like I did - I created a messaging protocol using JSON and message types, where the string message in the websocket event onMessage first gets parsed into an object)

There are implementations for supporting WS on all platforms: java, .net, python, php etc. This should be your starting point.

--- Update ---

I understand where you are coming from. To help you along in understanding Sockets / ServerSockets, here are a couple of pointers & resources

DatagramSockets (aka UDP): This is a different transmission protocol than the regular TCP, used by Shockwave and then Flash, and is the fundamental reason that Flash is problematic. I strongly recommend against this

Data & Object Input/OutputStreams: "Data" streams are Java only (can't connect to technologgy built on other platforms). Object streams are similar, except you are transporting actual whole objects through the stream (also Java only) No one* (almost no one) uses these anymore.

SocketException: Using java.net.[Server]Socket(s), you are likely to encounter this exception. It happens when you are waiting for more data (through a read / readLine call) on a socket, and the socket closes. It took me a long time to figure this out, but THIS EXCEPTION IS YOUR FRIEND! You get it when the connection has closed (either on the client or server side). It allows the thread that was waiting on the socket to wake up, and allows you to do whatever clean-up you need to do. SocketException is a subclass of IOException, so you may not even realize what this is. But now at least I have warned you

Streams vs. Writers and Readers: Writers and Readers are for interpreting raw bytes as Java characters and Strings. This is necessary, as there are multiple text formats (i.e. ascii, windows-xx, utf-8, utf-16). Readers and Writers help you read and write text in different text formats (and also interpreting Images from image formats).

Buffered Writers and Streams: These are for INEFFICIENT reading and writing. For writing, this means enabling you to write part of a message and not send it until you are ready. For reading, this means reading streams line by line for example rather than reading everything at one go.

TUS: tjacobs/io - https://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/io/ this is an old collection of Java libraries I put on SourceForge years ago, but a lot of the classes here pertain to dealing with Sockets. In particular, see SocketServerEx, DataFetcher, Main/App, Timeout, and maybe IOUtils. And of everything, really look at DataFetcher which is a lightweight threadableframework for Callback I/O listening.

Good luck and have fun!

Body:
I am new at stackoverflow and I am sorry if this kind of a question is asked before but did a quick search and I could not find any title like mine. I am working on a multi-client chat application on Java. I was following the tutorials and I can send messages that every user in the application can see. But I wonder how to create and send a private message to a spesific user into the chat.

import java.io.*;
import java.net.*;
import java.util.HashSet;
import java.util.Set;

public class ChatServer {
    private int port;

    private Set<String> userNames = new HashSet<>();
    private Set<UserThread> userThreads = new HashSet<>();

    public ChatServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) {
        new ChatServer(9999).execute();
    }

    private void execute() {
        try {
            ServerSocket serverSocket = new ServerSocket(9999);
            System.out.println("Server is running");
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("New user connected");
                UserThread newUser = new UserThread(socket, this);
                userThreads.add(newUser);
                newUser.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void addUserName(String s) {
        this.userNames.add(s);
    }

    public void broadcast(String serverMessage, UserThread excludeUser) {
        for (UserThread aUser : userThreads) {
            if (aUser != excludeUser)
                aUser.sendMessage(serverMessage);
        }
    }
}

The code above is my server code.

public void run() {
    Console console = System.console();
    String userName = console.readLine("Enter your username : ");
    writer.println(userName);
    String text;
    do {
        text = console.readLine("[" + userName + "]: ");
        if (text.startsWith("[")) {
            isTargeted = true;
            this.aimUserName = text.substring(text.indexOf("[") + 1, text.indexOf("]"));
            //System.out.println("Private Message to: " + aimUserName);
        } else {
            isTargeted = false;
        }
        writer.println(text);
    } while (!text.equals("bye"));

    try {
        socket.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

and this code above is a part of my write thread class. As you can see, if a message starts with '[name]' part, the "name" means the user that we want to send a private message. By doing this, I can get the name of the user that I want to send a private message but I could not figure out how to broadcast this message just to that spesific user. I believe I need to configure my broadcast function in ChatServer class but I don't really know how to do. What steps should I follow?

--Edit--

I've been working on my question and I did some additions to solve my problem. First of all, I think I should share everything I have to you. I shared my ChatServer class previously. Other classes I have are:

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

public class ChatClient {

    public static void main(String[] args) {
        new ChatClient().execute();
    }

    private void execute() {
        try {
            Socket socket = new Socket("localhost", 3);
            System.out.println("Connected to chat server");
            new ReadThread(socket, this).start();
            new WriteThread(socket, this).start();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

import java.net.*;
import java.io.*;

public class ReadThread extends Thread{
    private BufferedReader reader;
    private Socket socket;
    private ChatClient client;
    public ReadThread(Socket socket, ChatClient client) {
        this.socket = socket;
        this.client = client;

        InputStream input;
        try {
            input = this.socket.getInputStream();
            this.reader = new BufferedReader(new InputStreamReader(input));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void run() {
        while(true) {
            try {
                String response = this.reader.readLine();
                System.out.println("\n" + response);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                break;
            }
        }
    }
}

import java.net.Socket;
import java.io.*;
public class UserThread extends Thread {

    private Socket socket;
    private ChatServer server;
    PrintWriter writer = null;
    public String userName;
    public UserThread(Socket socket, ChatServer chatServer) {
        this.socket = socket;
        this.server = chatServer;
    }

    public void run() {
        try {
            InputStream input = socket.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            OutputStream output = socket.getOutputStream();
            writer = new PrintWriter(output,true);

            String userName = reader.readLine();
            this.userName = userName;
            server.addUserName(userName);
            String serverMessage = "New user connected: " + userName;
            server.broadcast(serverMessage,this);

            String clientMessage;
            do {
                clientMessage = reader.readLine();
                serverMessage = "[" + userName + "] : " + clientMessage;
                server.broadcast(serverMessage, this);

            }while(!clientMessage.equals("bye"));

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void sendMessage(String serverMessage) {
        writer.println(serverMessage);
    }

}

import java.net.*;
import java.io.*;
public class WriteThread extends Thread {
    private Socket socket;
    private ChatClient client;
    private PrintWriter writer;
    public WriteThread(Socket socket, ChatClient client) {
        this.socket = socket;
        this.client = client;
        OutputStream output;
        try {
            output = socket.getOutputStream();
            this.writer = new PrintWriter(output, true);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void run() {
        Console console = System.console();
        String userName = console.readLine("Enter your username : ");
        writer.println(userName);
        String text;
        do {
            text = console.readLine("[" + userName + "]: ");
            if(text.startsWith("[")){
                String aimUserName = text.substring(text.indexOf("[")+1,text.indexOf("]"));
                System.out.println("Private Message to: " + aimUserName);}
            writer.println(text);
        }while(!text.equals("bye"));

        /*do {
            text = console.readLine("[" + userName + "]: ");
            writer.println(text);
        }while(!text.equals("bye"));*/

        try {
            socket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

These codes work properly and I can multi-chat very clean. But while working on private chat stuff, I added to the ChatServer the line of:

public void privatebr(String serverMessage, String targetUserName){
        for(UserThread aUser: userThreads){
            if(aUser.userName == targetUserName)
                aUser.sendMessage(serverMessage);
        }

to the UserThread, I edited the part as:

String clientMessage;
            do {
                clientMessage = reader.readLine();
                serverMessage = "[" + userName + "] : " + clientMessage;
                if(clientMessage.startsWith("[")){
                    String targetUserName = clientMessage.substring(clientMessage.indexOf("[")+1,clientMessage.indexOf("]"));
                    serverMessage = "[" + userName + "] : " + clientMessage;
                    server.privatebr(serverMessage, targetUserName);
                }else{

                    server.broadcast(serverMessage, this);
                }

            }while(!clientMessage.equals("bye"));

But when I did all these edits, the normal multi-chat progress became broken where is my fault? Why everything has broken?


来源: stackexchange

问:
BigQuery - Delete rows from Partitioned Table
I have a Day-Partitioned Table on BigQuery. When I try to delete some rows from the table using a query like:

```<code>DELETE FROM `MY_DATASET.partitioned_table` WHERE id = 2374180
</code>```

I get the following error:

Error: DML statements are not yet supported over partitioned tables.

A quick Google search leads me to: https://cloud.google.com/bigquery/docs/loading-data-sql-dml where it also says: "DML statements that modify partitioned tables are not yet supported."

So for now, is there a workaround that we can use in deleting rows from a partitioned table?

答:
Looks like as of my writing, this is no longer a BigQuery limitation!

In standard SQL, a statement like the above, over a partitioned table, will succeed, assuming rows being deleted weren't recently (within last 30 minutes) inserted via a streaming insert.

Current docs on DML: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-manipulation-language

Example Query that worked for me in the BQ UI:

```<code>DELETE
FROM dataset_name.partitioned_table_on_timestamp_column
WHERE
timestamp >= '2020-02-01' AND timestamp < '2020-06-01'
</code>```

After the hamsters are done spinning, we get the BQ response:

```<code>This statement removed 101 rows from partitioned_table_on_timestamp_column
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a Day-Partitioned Table on BigQuery. When I try to delete some rows from the table using a query like:

DELETE FROM `MY_DATASET.partitioned_table` WHERE id = 2374180

I get the following error:

Error: DML statements are not yet supported over partitioned tables.

A quick Google search leads me to: https://cloud.google.com/bigquery/docs/loading-data-sql-dml where it also says: "DML statements that modify partitioned tables are not yet supported."

So for now, is there a workaround that we can use in deleting rows from a partitioned table?

Body:
Looks like as of my writing, this is no longer a BigQuery limitation!

In standard SQL, a statement like the above, over a partitioned table, will succeed, assuming rows being deleted weren't recently (within last 30 minutes) inserted via a streaming insert.

Current docs on DML: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-manipulation-language

Example Query that worked for me in the BQ UI:

DELETE
FROM dataset_name.partitioned_table_on_timestamp_column
WHERE
timestamp >= '2020-02-01' AND timestamp < '2020-06-01'

After the hamsters are done spinning, we get the BQ response:

This statement removed 101 rows from partitioned_table_on_timestamp_column

ContentLicense: CC BY-SA 4.0


问:
Sending a message from a node to its neighbour
I am trying to create a grid network and send messages.
My Node is as follows:

```<code>simple Node
{
    parameters:
        @display("i=misc/node");
        gates:
        inout up;
        inout left;
        inout down;
        inout right;
}
</code>```

And i am sending a msg as follows:

```<code>if(this->gate("right$o")->isConnected())
        {
            send(msg,"right$o",k);
        }
</code>```

It doesn't give any build errors but gives an error in simulation. What am i doing wrong? The error is as below:

```<code>send()/sendDelayed(): Scalar gate 'right$o' referenced with index -- in module (Node) GridNetwork.sensor[0] (id=2), at t=0s, event #1
</code>```

答:
Your example Node has a inout right gate, which is a scalar inout gate rather than a vector. This means that there's only one, and it has two gates: right$i and right$o, as you're trying to use in your example.

You must thus replace inout right with inout right[], as well as create connections from it to another gate. See the OMNeT++ documentation on gates.

Body:
I am trying to create a grid network and send messages.
My Node is as follows:

simple Node
{
    parameters:
        @display("i=misc/node");
        gates:
        inout up;
        inout left;
        inout down;
        inout right;
}

And i am sending a msg as follows:

if(this->gate("right$o")->isConnected())
        {
            send(msg,"right$o",k);
        }

It doesn't give any build errors but gives an error in simulation. What am i doing wrong? The error is as below:

send()/sendDelayed(): Scalar gate 'right$o' referenced with index -- in module (Node) GridNetwork.sensor[0] (id=2), at t=0s, event #1


问:
SMTP Error: Could not connect to SMTP host
I have this code, and all works well in my local server. The email is sent without any problem.

But now I pass the content to webserver, and I get this error...

```<code>SMTP Error: Could not connect to SMTP host.
</code>```

SSL is enable in the server..correct? so, what is the problem?

```<code>            $mail = new PHPMailer();
            $mail->IsSMTP();
            $mail->SMTPAuth   = true;                  // enable SMTP authentication
            $mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
            $mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
            $mail->Port       = 465;                   // set the SMTP port
            $mail->Username   = "dnteiro"; // GMAIL username
            $mail->Password   = "xxx";      // GMAIL password
</code>```

答:
It sounds like your web host is blocking outbound connections to smtp.gmail.com:465.  Suggestions:

Verify:  If you have shell/terminal access to your web hosting server, try a telnet test to verify that they are in fact blocking this.  Run telnet smtp.gmail.com 465

Contact:  Call or email your hosting provider and find out what SMTP server they provide for outbound relay.  Make sure they know you want to use your @gmail.com address as the From/Reply-to address.

Update code:  Once your host provides you with a different mail server, update your code and try again.

If your web host doesn't allow outbound relay from its servers at all, then  you need to look at switching hosts, if this is a requirement for your application.

Body:
I have this code, and all works well in my local server. The email is sent without any problem.

But now I pass the content to webserver, and I get this error...

SMTP Error: Could not connect to SMTP host.

SSL is enable in the server..correct? so, what is the problem?

            $mail = new PHPMailer();
            $mail->IsSMTP();
            $mail->SMTPAuth   = true;                  // enable SMTP authentication
            $mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
            $mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
            $mail->Port       = 465;                   // set the SMTP port
            $mail->Username   = "dnteiro"; // GMAIL username
            $mail->Password   = "xxx";      // GMAIL password


问:
How do I keep a user logged into a firebase app after refresh?
I have an application built in firebase and angular, and am wanting to be able to keep users logged in after refreshing the page. Right now I have a login screen with two basic input fields which bind to a controller

```<code>    this.email = "";
    this.pass = "";
    this.emessage = "";

    this.loginUser = function() {
        ref.authWithPassword({
            email: this.email,
            password: this.pass
        }, function(error, authData) {
            if (error) {
                console.log("Login Failed!", error);
                this.emessage = error.message;
                $scope.$apply();
            } else {
                dataStorage.uid = authData.uid;
                $location.path('/projects');
                $scope.$apply();
            }
        }.bind(this));
    }
</code>```

This is all fine and dandy and it works, but when the user refreshes the page they are logged back out. Is there some way to, when the controller loads, see if the user is already logged in and auto-redirect? Thanks!

答:
For any ReactJS users, here's a simple Hook that I have created based on the answers provided in this thread which redirects the user to login route if the current user is not loggedIn.

```<code>import { useEffect } from 'react';
import * as firebase from 'firebase';
import { useHistory } from 'react-router-dom';

export default function useProtectedRoute() {
  const history = useHistory();

  useEffect(() => {
    firebase.auth().onAuthStateChanged(function(user) {
      if (!user) {
        console.error(
          'Access to protected route denied, redirecting to login...'
        );
        history.push('/auth/login');
      }
    });
  }, [history]);
}
</code>```

You just need to import this hook and run inside any component that you don't want to render unless the user is logged in.

Example:

```<code>import React from 'react';
import useProtectedRoute from 'hooks/useProtectedRoute';

export default function UserDetailsComponent() {
  useProtectedRoute();
  return <div>This is only visible when user is logged in</div>;
}
</code>```

Body:
I have an application built in firebase and angular, and am wanting to be able to keep users logged in after refreshing the page. Right now I have a login screen with two basic input fields which bind to a controller

    this.email = "";
    this.pass = "";
    this.emessage = "";

    this.loginUser = function() {
        ref.authWithPassword({
            email: this.email,
            password: this.pass
        }, function(error, authData) {
            if (error) {
                console.log("Login Failed!", error);
                this.emessage = error.message;
                $scope.$apply();
            } else {
                dataStorage.uid = authData.uid;
                $location.path('/projects');
                $scope.$apply();
            }
        }.bind(this));
    }

This is all fine and dandy and it works, but when the user refreshes the page they are logged back out. Is there some way to, when the controller loads, see if the user is already logged in and auto-redirect? Thanks!

Body:
For any ReactJS users, here's a simple Hook that I have created based on the answers provided in this thread which redirects the user to login route if the current user is not loggedIn.

import { useEffect } from 'react';
import * as firebase from 'firebase';
import { useHistory } from 'react-router-dom';

export default function useProtectedRoute() {
  const history = useHistory();

  useEffect(() => {
    firebase.auth().onAuthStateChanged(function(user) {
      if (!user) {
        console.error(
          'Access to protected route denied, redirecting to login...'
        );
        history.push('/auth/login');
      }
    });
  }, [history]);
}

You just need to import this hook and run inside any component that you don't want to render unless the user is logged in.

Example:

import React from 'react';
import useProtectedRoute from 'hooks/useProtectedRoute';

export default function UserDetailsComponent() {
  useProtectedRoute();
  return <div>This is only visible when user is logged in</div>;
}


问:
How to return HTML file as Symfony response
I'm new to Symfony and am trying to understand that controller response function. I just want to return a simple HTML file home.html, that at the moment just has a Hello World line in it.

How do I return the file as a response? As it stands with the code below it's just returning the string 'home.html'.

Many thanks.

```<code><?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class MainController
{
    /**
     * @Route("/")
     */
    public function homepage()
    {
        return new Response('home.html');
    }
}
</code>```

答:
Because you need to extend your controller with AbstractController and use the render method to generate the view from html.</p>

```<code>class MainController extends AbstractController
{
    /**
     * @Route("/")
     */
    public function homepage()
    {
        return $this->render('home.html');
    }
}
</code>```

Body:
I'm new to Symfony and am trying to understand that controller response function. I just want to return a simple HTML file home.html, that at the moment just has a Hello World line in it.

How do I return the file as a response? As it stands with the code below it's just returning the string 'home.html'.

Many thanks.

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class MainController
{
    /**
     * @Route("/")
     */
    public function homepage()
    {
        return new Response('home.html');
    }
}

Body:
Because you need to extend your controller with AbstractController and use the render method to generate the view from html.

class MainController extends AbstractController
{
    /**
     * @Route("/")
     */
    public function homepage()
    {
        return $this->render('home.html');
    }
}


问:
People Picker from Microsoft graph API toolkit is not working
I am using msal authentication same as this example microsoft-authentication-library-for-js on login page. Once you are logged in I am redirecting to page where I have People picker component. That component code is something like down below. My front end client is React. I am using NPM package "@microsoft/mgt": "^1.3.0-preview.2" for people picker and "msal": "^1.3.0" for logging in user

```<code>import React, { useState, useRef } from 'react';

import '@microsoft/mgt';

const PeoplePicker = props => {

      // reference to access mgt-people-picker on DOM
      const peoplePicker = useRef();

      return (
         <div>
            <mgt-msal-provider client-id={process.env.REACT_APP_DEV_AZURE_APP_CLIENT_ID} />
            <mgt-people-picker ref={peoplePicker} />
         </div>
      )

}
</code>```

As I start typing People Picker is not getting any list of people from our organization AD. I checked Network tab in console, there is no network calls made as you type in this input. It's not throwing error so I assume Provider is working but it could be issue of having session or token attached to people picker though I am not completely sure How would I do that.

I browsed microsoft docs, github issues etc. but it didn't help either

答:
Similar to the answer here: https://stackoverflow.com/a/62024758/13040450

Due to how react handles custom elements, they must be referenced differently. Alternatively you can use our wrapper here:

https://github.com/nmetulev/mgt-react

which will allow you to reference the component in the following way:

```<code>import { PeoplePicker } from 'mgt-react';
<PeoplePicker ></PeoplePicker >
</code>```

quick note: The names of the React components are in PascalCase and do not include the Mgt prefix

Another note: mgt-react is in preview and hasn't been fully tested or documented.Check it out and keep an eye out for V1 in the future: https://github.com/nmetulev/mgt-react

Body:
I am using msal authentication same as this example microsoft-authentication-library-for-js on login page. Once you are logged in I am redirecting to page where I have People picker component. That component code is something like down below. My front end client is React. I am using NPM package "@microsoft/mgt": "^1.3.0-preview.2" for people picker and "msal": "^1.3.0" for logging in user

import React, { useState, useRef } from 'react';

import '@microsoft/mgt';

const PeoplePicker = props => {

      // reference to access mgt-people-picker on DOM
      const peoplePicker = useRef();

      return (

            <mgt-msal-provider client-id={process.env.REACT_APP_DEV_AZURE_APP_CLIENT_ID} />
            <mgt-people-picker ref={peoplePicker} />

      )

}

As I start typing People Picker is not getting any list of people from our organization AD. I checked Network tab in console, there is no network calls made as you type in this input. It's not throwing error so I assume Provider is working but it could be issue of having session or token attached to people picker though I am not completely sure How would I do that.

I browsed microsoft docs, github issues etc. but it didn't help either

Body:
Similar to the answer here: https://stackoverflow.com/a/62024758/13040450

Due to how react handles custom elements, they must be referenced differently. Alternatively you can use our wrapper here:

https://github.com/nmetulev/mgt-react

which will allow you to reference the component in the following way:

import { PeoplePicker } from 'mgt-react';
<PeoplePicker ></PeoplePicker >

quick note: The names of the React components are in PascalCase and do not include the Mgt prefix

Another note: mgt-react is in preview and hasn't been fully tested or documented.Check it out and keep an eye out for V1 in the future: https://github.com/nmetulev/mgt-react


问:
How can I show only one item from current position to horizontal RecyclerView?
I have horizontal RecyclerView which has GridView. When I scroll RecyclerView, 2 elements appear at the same time. I just want to show the item at the current position.

Activity:

```<code>recyclerView = findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
recyclerView.setHasFixedSize(false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(new MyRecyclerViewAdapter(this, getTotalCount()));
</code>```

My adapter:

```<code>public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.MyViewHolder> {

    private int count;
    private Context context;

    public MyRecyclerViewAdapter(Context context, int count) {
        this.context = context;
        this.count = count;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new MyViewHolder(ViewUtil.inflate(LayoutInflater.from(context), parent, R.layout.my_recyclerView));
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        MyGridViewAdapter myGridViewAdapter = new MyGridViewAdapter(position);
        holder.gridView.setAdapter(myGridViewAdapter);
    }

    @Override
    public int getItemCount() {
        return count;
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {

        private GridView gridView;

        MyViewHolder(View itemView) {
            super(itemView);
            gridView = itemView.findViewById(R.id.grid);
        }
    }
</code>```

答:
1-Always use "wrap_content" for the height of the row otherwise in "match_parent" it will occupy the whole screen for a single row.

2-You can also take the height in dp.

Body:
I have horizontal RecyclerView which has GridView. When I scroll RecyclerView, 2 elements appear at the same time. I just want to show the item at the current position.

Activity:

recyclerView = findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
recyclerView.setHasFixedSize(false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(new MyRecyclerViewAdapter(this, getTotalCount()));

My adapter:

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.MyViewHolder> {

    private int count;
    private Context context;

    public MyRecyclerViewAdapter(Context context, int count) {
        this.context = context;
        this.count = count;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new MyViewHolder(ViewUtil.inflate(LayoutInflater.from(context), parent, R.layout.my_recyclerView));
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        MyGridViewAdapter myGridViewAdapter = new MyGridViewAdapter(position);
        holder.gridView.setAdapter(myGridViewAdapter);
    }

    @Override
    public int getItemCount() {
        return count;
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {

        private GridView gridView;

        MyViewHolder(View itemView) {
            super(itemView);
            gridView = itemView.findViewById(R.id.grid);
        }
    }


问:
Finding the websphere version in java application
Its very common question to find the java version installed on the websphere, but how do we find the websphere version itself from an java application? My java application exists on the same server, please help.

I am aware of solution to add the version as the enviroment variable and reading it an app. But I am looking for a solution where in we don't have to add anything to WAS.

答: Use the Server MBean to programatically access product version information within your deployed application. The serverVersion attribute will provide the information you need and then some.  Within a scripting environment you have a couple options involving wsadmin objects: Use the AdminTask object to access the serverVersion attribute of the server MBean; or, use the AdminControl.getNodeBaseProductVersion command. Finally, from the command line use the  versionInfo command. -Regards.


问:
How to update a mysql database via SMS text messaging
I want to add an additional functionality to a CMS I am making that will allow users to add content to a site via text message. The user should be able to add text by send the message to a number which when received will update the database accordingly. </p>

答:
You have some options - but a SMS gateway is the ideal solution.

Alternatively,

What you will do outside of a number - is to email from the phone. Using PHP - you can interpret the email to look for a keyword in the body or subject line and run a script accordingly.

All SMS capable phones can SEND email from text messages. Instead of entering number - you enter an email address.

It is a very lo-fi version of the implementation - but this method worked perfectly for me and for those not interested in investing in an SMS gateway.


问:
Os.system and mysql restore not working in python unittest
I am doing a unit test for a program that saves entries in a database "mydatabase". Therefore, I need to restore the db once I test each function so that the other tests are not compromised. I tried to use os.system() to write a mysql command to restore. Below is the relevant part of the program:

```<code>class testSql(unittest.TestCase):

    def setUp(self,
        dbName = "mydatabase",
        existingUser = "John",
        nonExistingUser = "thisnamedoesnotexist",
    ):
        os.system('mysql -u root -ppassword mydatabase < "mypath/schema.sql"')
        self.dbName = dbName
        self.existingUser = existingUser
        self.nonExistingUser = nonExistingUser

    def test_signUp(self):
        self.assertFalse(sql.userExists(self.nonExistingUser))
        sql.signUp(self.nonExistingUser,"password")
        self.assertTrue(sql.userExists(self.nonExistingUser))
</code>```

When I run the program, however, instead of showing the result of the test, I only see the result from the mysql command, and the terminal freezes, so I can't enter anything and am forced to close it: Result from terminal

What I tried: making a function with the os.system and calling it; importing a file with that function; using the exec() function to execute a file with the statement; importing the file to execute the statement.

Apparently, os.system("mysql -u root -ppassword") works just fine, but not the restore and dump commands. Does anyone know how to fix this or another way I can accomplish my goal?

答:
Ok, I found out that the problem was that when the user already existed, I did not commit the database, which resulted in the connection not closing, and when I tried to create another one (i.e. used the mysql command), the latter waited forever for the first to end.

To prevent this: either commit or close a connection to the database, or close the cursor before creating another connection to the database (or use the same cursor to restore).

Body:
I am doing a unit test for a program that saves entries in a database "mydatabase". Therefore, I need to restore the db once I test each function so that the other tests are not compromised. I tried to use os.system() to write a mysql command to restore. Below is the relevant part of the program:

class testSql(unittest.TestCase):

    def setUp(self,
        dbName = "mydatabase",
        existingUser = "John",
        nonExistingUser = "thisnamedoesnotexist",
    ):
        os.system('mysql -u root -ppassword mydatabase < "mypath/schema.sql"')
        self.dbName = dbName
        self.existingUser = existingUser
        self.nonExistingUser = nonExistingUser

    def test_signUp(self):
        self.assertFalse(sql.userExists(self.nonExistingUser))
        sql.signUp(self.nonExistingUser,"password")
        self.assertTrue(sql.userExists(self.nonExistingUser))

When I run the program, however, instead of showing the result of the test, I only see the result from the mysql command, and the terminal freezes, so I can't enter anything and am forced to close it: Result from terminal

What I tried: making a function with the os.system and calling it; importing a file with that function; using the exec() function to execute a file with the statement; importing the file to execute the statement.

Apparently, os.system("mysql -u root -ppassword") works just fine, but not the restore and dump commands. Does anyone know how to fix this or another way I can accomplish my goal?


问:
Why does pandas value_counts() show a count of zero for some values?
I have a dataframe where one column is a categorical variable with the following labels: ['Short', 'Medium', 'Long', 'Very Long', 'Extremely Long'].  I am trying to create a new dataframe that drops all the rows that are Extremely Long.

I have tried doing this in the following ways:

```<code>df2 = df.query('ride_type != "Extremely Long"')
df2 = df[df['ride_type'] != 'Extremely Long']
</code>```

However, when I run .value_counts() I get the following:

```<code>df2.ride_type.value_counts()
>>> Short             130474
Long              129701
Medium            129607
Very Long         110988
Extremely Long         0
Name: ride_type, dtype: int64
</code>```

In other words, Extremely Long is still there, so I can't plot charts with just the four categories I want.

答:
You could drop rows like this:</p>

```<code>df = df.drop(df.index[df['A'] == 'cat'])
print(df['A'].value_counts())

dog       2
rabbit    2
Name: A, dtype: int64
</code>```

Body:
I have a dataframe where one column is a categorical variable with the following labels: ['Short', 'Medium', 'Long', 'Very Long', 'Extremely Long'].  I am trying to create a new dataframe that drops all the rows that are Extremely Long.

I have tried doing this in the following ways:

df2 = df.query('ride_type != "Extremely Long"')
df2 = df[df['ride_type'] != 'Extremely Long']

However, when I run .value_counts() I get the following:

df2.ride_type.value_counts()
>>> Short             130474
Long              129701
Medium            129607
Very Long         110988
Extremely Long         0
Name: ride_type, dtype: int64

In other words, Extremely Long is still there, so I can't plot charts with just the four categories I want.

Body:
You could drop rows like this:

df = df.drop(df.index[df['A'] == 'cat'])
print(df['A'].value_counts())

dog       2
rabbit    2
Name: A, dtype: int64


问:
How do I check/change the text in a React button?
I have a react button and I want to change the text depending on what text is already displayed. How can I do this using a conditional statement?

I have the following code setup:

```<code>buttonClicked() {

}

create() {
  return (
    <button>X</button>
  );
}
</code>```

Sorry if this is really simple, I searched for it and couldn't find anything, and I am very new to React.

答:
You can check the button text using JS QuerySelector.

buttonClicked() {
  const btn = document.querySelector("#myButton"); // get button elm by id
  const text = btn.textContent || btn.innerText; // get button text (the prop is browser-dependant)

  // change button text based on condition
  if (text === 'X') btn.innerHTML = 'button has X value';
  else btn.innerHTML = 'button has another value';
}

create() {
  return (
    <button id="myButton">X</button>
  );
}
```

Body:
I have a react button and I want to change the text depending on what text is already displayed. How can I do this using a conditional statement?

I have the following code setup:

buttonClicked() {

}

create() {
  return (
    <button>X</button>
  );
}

Sorry if this is really simple, I searched for it and couldn't find anything, and I am very new to React.


问:
Accessing Nuxt plugin function in vuex getter
I am getting started with nuxtjs and vuex. I just encountered an issue accessing a combined injected plugin function from a getter. E.g.:

nuxt.config.js

```<code>...
plugins: [
  '~/plugins/myplugin.js'
  ],
...
</code>```

~/plugins/myplugin.js

```<code>function doSomething(string) {
        console.log("done something: " + string)
    }

export default ({ app }, inject) => {
    inject('doSomething', (string) => doSomething(string))
  }
</code>```

~/store/index.js

```<code>export const actions = {
    someAction({commit}) {
        this.$doSomething("Called from Action") // works
    }
}

export const getters = {
    someGetter: state => {
        this.$doSomething("Called from Getter") // throws error
    }
}
</code>```

The code works for the action someAction but the call in getter someGetter will result in a error suggesting this is undefined.

The nuxt documentation only shows examples for accessing injected plugin functions from mutations and actions but does not explicitly mention that getters can not access plugin functions. Is this even possible in nuxt or is there a good reason not to call a plugin method in a getter? Any help appreciated.

答:
I faced the same issue and I was able to get around it by doing

```<code>export const getters = {
  someGetter: state => {
    $nuxt.$doSomething("Called from Getter") // Grab $nuxt from the global scope
  }
}
</code>```

Not sure if this works in SSR mode however

Body:
I am getting started with nuxtjs and vuex. I just encountered an issue accessing a combined injected plugin function from a getter. E.g.:

nuxt.config.js

...
plugins: [
  '~/plugins/myplugin.js'
  ],
...

~/plugins/myplugin.js

function doSomething(string) {
        console.log("done something: " + string)
    }

export default ({ app }, inject) => {
    inject('doSomething', (string) => doSomething(string))
  }

~/store/index.js

export const actions = {
    someAction({commit}) {
        this.$doSomething("Called from Action") // works
    }
}

export const getters = {
    someGetter: state => {
        this.$doSomething("Called from Getter") // throws error
    }
}

The code works for the action someAction but the call in getter someGetter will result in a error suggesting this is undefined.

The nuxt documentation only shows examples for accessing injected plugin functions from mutations and actions but does not explicitly mention that getters can not access plugin functions. Is this even possible in nuxt or is there a good reason not to call a plugin method in a getter? Any help appreciated.

Body:
I faced the same issue and I was able to get around it by doing

export const getters = {
  someGetter: state => {
    $nuxt.$doSomething("Called from Getter") // Grab $nuxt from the global scope
  }
}

Not sure if this works in SSR mode however


答:
What you are asking is to break the first normal form and this is bad practice.

The solution is to have a one to many relation in the table so eloquent can query the result and create the object with the relations you want.
Adapt your situation to this solution here

```<code>$item->qty_by_warehouses;
</code>```

if you cannot modify the table then

you must get all the items id,
Loop each one and create an "each_id" object and add to a Result list.

query each id to get warehouse_id and qty and add them to a list
add this list to each_id object.

This will get you the same result as if you have had the eloquent with the one to many relation.

Title: How to select statement for showing data

Body:
i have table in mysql like this

-----------------------------
|id|warehouse_id|item_id|qty|
---|------------|-------|---|
|1 | 1          | 1     |10 |
|2 | 1          | 2     |23 |
|3 | 2          | 1     |45 |
|4 | 2          | 2     |66 |
|5 | 1          | 3     |44 |

How using select statement to show table what i want like this

------------------------------------------
|id|item_id|qty warehouse 1|qty warehouse 2
---|-------|---------------|-------------
|1 | 1     | 10            |45         |
|2 | 2     | 23            |66         |
|3 | 3     | 44            |0          |

i was trying using eloquent laravel like this

ItemStockModel::get()

thank you

Body:
What you are asking is to break the first normal form and this is bad practice.

The solution is to have a one to many relation in the table so eloquent can query the result and create the object with the relations you want.
Adapt your situation to this solution here

$item->qty_by_warehouses;

if you cannot modify the table then

you must get all the items id,
Loop each one and create an "each_id" object and add to a Result list.

query each id to get warehouse_id and qty and add them to a list
add this list to each_id object.

This will get you the same result as if you have had the eloquent with the one to many relation.


问:
How to remove _id from collection in mongodb using mongoose
Tried to remove _id from collection but not working. I do not know how to resolve this issue. Need help anyone.

model.js:

```<code>const schemmaodel = new mongoose.Schema({
  "name": { type: string}
}, { _id: false, versionKey: false });
</code>```

data.controller.js:

```<code>var newModel = require(path.resolve('./models/model.js'))(collectionName);
newModel.create({}, function(err, doc) {
});
</code>```

答:
_id is like a primary key for the collection. If _id is not specified in the Schema then Mongoose will by default _id of type ObjectId.

As per the mongoose documentation you can disable _id on subdocuments only. So in your case, schemmaodel is considered as parent schema and since you have set { _id: false } option on parent schema while saving  it will throw an error related to missing _id

Body:
Tried to remove _id from collection but not working. I do not know how to resolve this issue. Need help anyone.

model.js:

const schemmaodel = new mongoose.Schema({
  "name": { type: string}
}, { _id: false, versionKey: false });

data.controller.js:

var newModel = require(path.resolve('./models/model.js'))(collectionName);
newModel.create({}, function(err, doc) {
});


问:
Simulated IoT with MQTT
so I am having some issues with the publishing / subscribing part of my code. Completely new, so forgive the ignorance. :)
I am using Mosquitto.

THIS PART SIMPLY GENERATES SOME RANDOM TEMPERATURES:

```<code>from random import random
class TemperatureSensor:
    sensor_type='temperature'
    units='celcius'
    instance_id='SN123'

def __init__(self, average_temperature, temperature_variation, min_temperature, max_temperature):
    self.average_temperature=average_temperature
    self.temperature_variation=temperature_variation
    self.min_temperature=min_temperature
    self.max_temperature=max_temperature
    self.value=0.0

def sense(self):
    self.value= self.simple_random()
    return self.value

def simple_random(self):
    value = self.min_temperature + (random() * (self.max_temperature - self.min_temperature))
    return value

ts = TemperatureSensor(20,20, 16, 35)
</code>```

THIS IS THE PUBLISHER:

```<code>    import paho.mqtt.client as mqtt
import datetime
from datetime import datetime
from Script1 import TemperatureSensor
import json

class Simulator:
    def __init__(self, interval):
        self.interval = interval

    def start(self):
        ts= TemperatureSensor(20,10,16,35)

        mqtt_publisher = mqtt.Client('Temperature publisher')
        mqtt_publisher.connect('127.0.0.1',1883,60)
        mqtt_publisher.loop_start()

        while True:
          dt = datetime.now().strftime("%d-%m-%YT%H:%M:%S")
          message = {
             "type-id": "de.uni-stuttgart.iaas.sc." + ts.sensor_type,
             "instance-id": ts.instance_id,
             "timestamp": dt,
             "value":{
             ts.units: ts.sense()
             }

          }

          jmsg = json.dumps(message, indent=4)
          mqtt_publisher.publish('TopicID', ts.sensor_type + '/' + ts.instance_id, jmsg, 2)

          print(ts.sensor_type , ts.sense())
          time.sleep(self.interval)

s = Simulator(5)
s.start()
</code>```

FINALLY, HERE IS THE SUBSCRIBER:

```<code>import paho.mqtt.client as mqtt
import json

def on_message(client, userdata, message):
    print('Message topic{}'.format(message.topic))
    print('Message payload:')
    print(json.message.payload.decode())

mqtt_subscriber = mqtt.Client('Temperature subscriber')
mqtt_subscriber.on_message = on_message
mqtt_subscriber.connect('127.0.0.1',1883,60)
mqtt_subscriber.subscribe('TopicID', qos=2)

mqtt_subscriber.loop_forever()
</code>```

When runnning the publisher, I get an error as follows:

```<code>Traceback (most recent call last):
  File "Script2.py", line 40, in <module>
    s.start()
  File "Script2.py", line 33, in start
    mqtt_publisher.publish('TopicID', ts.sensor_type + '/' + ts.instance_id, 2, jmsg)
  File "/Library/Python/2.7/site-packages/paho_mqtt-1.5.0.dev0-py2.7.egg/paho/mqtt/client.py", line 1300, in publish
    message.dup, message.info, message.properties)
  File "/Library/Python/2.7/site-packages/paho_mqtt-1.5.0.dev0-py2.7.egg/paho/mqtt/client.py", line 2523, in _send_publish
    command = PUBLISH | ((dup & 0x1) << 3) | (qos << 1) | retain
TypeError: unsupported operand type(s) for |: 'int' and 'str'
</code>```

答:
From the Paho Python docs:

publish()

publish(topic, payload=None, qos=0, retain=False)

You appear to be passing an extra argument to the publish function.

You have the following:

A string that should be the topic "TopicID"

Another string that looks like to topic, but will actually be interpreted as the payload

A JSON string that is I expect you want to be the payload.

A QOS value

Since your subscribing code is only subscribing to the topic "TopicID" I suggest you remove the second string so it matches the doc.

```<code>mqtt_publisher.publish('TopicID', jmsg, 2)
</code>```

Title: Simulated IoT with MQTT

Body:
so I am having some issues with the publishing / subscribing part of my code. Completely new, so forgive the ignorance. :)
I am using Mosquitto.

THIS PART SIMPLY GENERATES SOME RANDOM TEMPERATURES:

from random import random
class TemperatureSensor:
    sensor_type='temperature'
    units='celcius'
    instance_id='SN123'

def __init__(self, average_temperature, temperature_variation, min_temperature, max_temperature):
    self.average_temperature=average_temperature
    self.temperature_variation=temperature_variation
    self.min_temperature=min_temperature
    self.max_temperature=max_temperature
    self.value=0.0

def sense(self):
    self.value= self.simple_random()
    return self.value

def simple_random(self):
    value = self.min_temperature + (random() * (self.max_temperature - self.min_temperature))
    return value

ts = TemperatureSensor(20,20, 16, 35)

THIS IS THE PUBLISHER:

    import paho.mqtt.client as mqtt
import datetime
from datetime import datetime
from Script1 import TemperatureSensor
import json

class Simulator:
    def __init__(self, interval):
        self.interval = interval

    def start(self):
        ts= TemperatureSensor(20,10,16,35)

        mqtt_publisher = mqtt.Client('Temperature publisher')
        mqtt_publisher.connect('127.0.0.1',1883,60)
        mqtt_publisher.loop_start()

        while True:
          dt = datetime.now().strftime("%d-%m-%YT%H:%M:%S")
          message = {
             "type-id": "de.uni-stuttgart.iaas.sc." + ts.sensor_type,
             "instance-id": ts.instance_id,
             "timestamp": dt,
             "value":{
             ts.units: ts.sense()
             }

          }

          jmsg = json.dumps(message, indent=4)
          mqtt_publisher.publish('TopicID', ts.sensor_type + '/' + ts.instance_id, jmsg, 2)

          print(ts.sensor_type , ts.sense())
          time.sleep(self.interval)

s = Simulator(5)
s.start()

FINALLY, HERE IS THE SUBSCRIBER:

import paho.mqtt.client as mqtt
import json

def on_message(client, userdata, message):
    print('Message topic{}'.format(message.topic))
    print('Message payload:')
    print(json.message.payload.decode())

mqtt_subscriber = mqtt.Client('Temperature subscriber')
mqtt_subscriber.on_message = on_message
mqtt_subscriber.connect('127.0.0.1',1883,60)
mqtt_subscriber.subscribe('TopicID', qos=2)

mqtt_subscriber.loop_forever()

When runnning the publisher, I get an error as follows:

Traceback (most recent call last):
  File "Script2.py", line 40, in <module>
    s.start()
  File "Script2.py", line 33, in start
    mqtt_publisher.publish('TopicID', ts.sensor_type + '/' + ts.instance_id, 2, jmsg)
  File "/Library/Python/2.7/site-packages/paho_mqtt-1.5.0.dev0-py2.7.egg/paho/mqtt/client.py", line 1300, in publish
    message.dup, message.info, message.properties)
  File "/Library/Python/2.7/site-packages/paho_mqtt-1.5.0.dev0-py2.7.egg/paho/mqtt/client.py", line 2523, in _send_publish
    command = PUBLISH | ((dup & 0x1) << 3) | (qos << 1) | retain
TypeError: unsupported operand type(s) for |: 'int' and 'str'

Body:
From the Paho Python docs:

publish()

publish(topic, payload=None, qos=0, retain=False)

You appear to be passing an extra argument to the publish function.

You have the following:

A string that should be the topic "TopicID"

Another string that looks like to topic, but will actually be interpreted as the payload

A JSON string that is I expect you want to be the payload.

A QOS value

Since your subscribing code is only subscribing to the topic "TopicID" I suggest you remove the second string so it matches the doc.

mqtt_publisher.publish('TopicID', jmsg, 2)


问:
File is always empty after submiting FileField
I have a form where I need to gather some text data and a file.After submiting, the textFields are fine, but the FileField seems to be empty.

The validator FileRequired claims that the field is empty, and if I remove it it is indeed NoneType.

Form Class:

from wtforms import Form, StringField,validators,SubmitField,DateField
from wtforms.fields.html5 import DateField
from flask_wtf.file import FileField, FileRequired,FileAllowed
from flask_wtf import FlaskForm
from flask import flash
import baseDatos

class  AnadirForm(FlaskForm):
    id=StringField('id')
    nombre=StringField('nombre',[validators.InputRequired()])
    volumen=StringField('volumen',[validators.InputRequired()])
    fecha= DateField('fecha',[validators.InputRequired()])
    file = FileField('Introduce Gcode',validators=[FileRequired()])
    submit = SubmitField('Post')
```

<p>Rendering Class:</p>

<pre class="lang-py prettyprint-override"><code>@app.route("/",methods=['GET', 'POST'])
def main():
    primeraForm=AnadirForm(request.form)

    if(primeraForm.validate_on_submit()):
        print(primeraForm.file.data)
</code>```

HTML:

<form method="POST" action="/" enctype="multipart/form-data">
            <fieldset class="form-group">

                {{form.hidden_tag()}}
                {{form.id(class="form-control",placeholder="Id")}}

                {{form.hidden_tag()}}
                {{form.nombre(class="form-control",placeholder="Nombre")}}

                {{form.hidden_tag()}}
                {{form.volumen(class="form-control",placeholder="Volumen")}}

                {{form.hidden_tag()}}
                {{form.fecha(class="form-control",placeholder="Fecha")}}

                {{form.hidden_tag()}}
                {{form.file(placeholder="File")}}

            </fieldset>

            {{ form.submit(class="btn btn-primary") }}

        </form>

```

I cannot manage to access the file data(which I will have to store later, but after I manage to get the file)

答:
I had the same problem. What worked for me was replacing FileField() with MultipleFileField() and then adjusting the data processing, as you get a list of files and not just a file.

I have no idea, where this error came from and it seems totally strange to me, as FileField worked for me in another case, although there was no real difference.

Body:
I have a form where I need to gather some text data and a file.After submiting, the textFields are fine, but the FileField seems to be empty.

The validator FileRequired claims that the field is empty, and if I remove it it is indeed NoneType.

Form Class:

from wtforms import Form, StringField,validators,SubmitField,DateField
from wtforms.fields.html5 import DateField
from flask_wtf.file import FileField, FileRequired,FileAllowed
from flask_wtf import FlaskForm
from flask import flash
import baseDatos

class  AnadirForm(FlaskForm):
    id=StringField('id')
    nombre=StringField('nombre',[validators.InputRequired()])
    volumen=StringField('volumen',[validators.InputRequired()])
    fecha= DateField('fecha',[validators.InputRequired()])
    file = FileField('Introduce Gcode',validators=[FileRequired()])
    submit = SubmitField('Post')

Rendering Class:

@app.route("/",methods=['GET', 'POST'])
def main():
    primeraForm=AnadirForm(request.form)

    if(primeraForm.validate_on_submit()):
        print(primeraForm.file.data)

HTML:

<form method="POST" action="/" enctype="multipart/form-data">
            <fieldset class="form-group">

                {{form.hidden_tag()}}
                {{form.id(class="form-control",placeholder="Id")}}

                {{form.hidden_tag()}}
                {{form.nombre(class="form-control",placeholder="Nombre")}}

                {{form.hidden_tag()}}
                {{form.volumen(class="form-control",placeholder="Volumen")}}

                {{form.hidden_tag()}}
                {{form.fecha(class="form-control",placeholder="Fecha")}}

                {{form.hidden_tag()}}
                {{form.file(placeholder="File")}}

            </fieldset>

            {{ form.submit(class="btn btn-primary") }}

        </form>

I cannot manage to access the file data(which I will have to store later, but after I manage to get the file)


问:
Markdown file path complete in VSCode
Is there any path-autocompletion extension for Markdown in VSCode?

I tried Path Intellisense but this seems to be effective only when using (double) quotation.

I want to use autocompletion when insert images stored in local directory, e.g.:

```<code>![](./img/local-img-file.png)
</code>```

答:
Yes, you can make that happen by using this extension on VS Code.

Relative Path extension

Juste type ctrl (or cmd on mac) + shift + H and type your file name.

Title: Markdown file path complete in VSCode

Body:
Is there any path-autocompletion extension for Markdown in VSCode?

I tried Path Intellisense but this seems to be effective only when using (double) quotation.

I want to use autocompletion when insert images stored in local directory, e.g.:

![](./img/local-img-file.png)


问:
API call in NextJS getStaticProps causes error 500
An API call made in getStaticProps seems to cause an error 500.

Here's my component's code:

import React from "react";
import API from "services/api";

const ArtistListPage = (props) => {
    return (
        <>
            {props.artists.map((artist) => (

{artist.first_name}

            ))}
        </>
    );
};

export async function getStaticProps() {
    // Get external data from the file system, API, DB, etc.
    const res = await API.get("/get_artists");
    const artists = await res.data.json();
    return {
        props: { artists },
    };
}

export default ArtistListPage;
```

I'd like to mention that the same API call in a useEffect works, as well as passing in a hard coded object to props in getStaticProps. Only the API call inside the getStaticProps seems  to cause an issue.

Does anyone know where the error could come from and how to solve it?

答:
getStaticProps is executed at a build time and you can't call your own API because Next.js server is not running.

You can execute DB queries or read from file system inside getStaticProps directly, without making an API call.

Body:
An API call made in getStaticProps seems to cause an error 500.

Here's my component's code:

import React from "react";
import API from "services/api";

const ArtistListPage = (props) => {
    return (
        <>
            {props.artists.map((artist) => (

{artist.first_name}

            ))}
        </>
    );
};

export async function getStaticProps() {
    // Get external data from the file system, API, DB, etc.
    const res = await API.get("/get_artists");
    const artists = await res.data.json();
    return {
        props: { artists },
    };
}

export default ArtistListPage;

I'd like to mention that the same API call in a useEffect works, as well as passing in a hard coded object to props in getStaticProps. Only the API call inside the getStaticProps seems  to cause an issue.

Does anyone know where the error could come from and how to solve it?


问:
Python realtime camera(video) image process
When realtime camera detects some text, it would be processed through function(img_process in my code)

but it takes so long time(long lag), camera seems to be stopped.

I'd like to make camera pretend working continuously (keep taking and showing image)

code is as below

```<code>from PIL import Image     #pip install pillow
from pytesseract import * #pip install pytesseract
import pytesseract
import configparser
import os
import cv2
import numpy as np
import pandas as pd
from imutils.video import VideoStream
from imutils.video import FPS
import argparse
import imutils
import time
from concurrent.futures import ThreadPoolExecutor

config = configparser.ConfigParser()
config.read(os.path.dirname(os.path.realpath(__file__)) + os.sep + 'envs' + os.sep + 'property.ini')

if __name__ == "__main__":
data = pd.read_csv('./test6.txt', sep='\t', engine='python')

print("Part N/O Scan...")

vs = VideoStream(src=1).start()
time.sleep(2.0)
fps = FPS().start()

while True:

    frame = vs.read()
    frame = imutils.resize(frame, width=500)

    (h, w) = frame.shape[:2]
    blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)),
        0.007843, (300, 300), 127.5)

    #problem(delay) happen in this line
    img_process(frame)

    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1) & 0xFF

    if key == ord("q"):
        break

    fps.update()

fps.stop()
print("[INFO] elapsed time: {:.2f}".format(fps.elapsed()))
print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))

cv2.destroyAllWindows()
vs.stop()
</code>```

答:
In that case, what I usually do is skip a few frames from the input. Add something like this in the while loop

```<code>while True:
    for i in range(5): # you can adjust this number
        frame = vs.read()
    frame = imutils.resize(frame, width=500)
</code>```

This works pretty well if you want the video output in realtime.

Body:
When realtime camera detects some text, it would be processed through function(img_process in my code)

but it takes so long time(long lag), camera seems to be stopped.

I'd like to make camera pretend working continuously (keep taking and showing image)

code is as below

from PIL import Image     #pip install pillow
from pytesseract import * #pip install pytesseract
import pytesseract
import configparser
import os
import cv2
import numpy as np
import pandas as pd
from imutils.video import VideoStream
from imutils.video import FPS
import argparse
import imutils
import time
from concurrent.futures import ThreadPoolExecutor

config = configparser.ConfigParser()
config.read(os.path.dirname(os.path.realpath(__file__)) + os.sep + 'envs' + os.sep + 'property.ini')

if __name__ == "__main__":
data = pd.read_csv('./test6.txt', sep='\t', engine='python')

print("Part N/O Scan...")

vs = VideoStream(src=1).start()
time.sleep(2.0)
fps = FPS().start()

while True:

    frame = vs.read()
    frame = imutils.resize(frame, width=500)

    (h, w) = frame.shape[:2]
    blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)),
        0.007843, (300, 300), 127.5)

    #problem(delay) happen in this line
    img_process(frame)

    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1) & 0xFF

    if key == ord("q"):
        break

    fps.update()

fps.stop()
print("[INFO] elapsed time: {:.2f}".format(fps.elapsed()))
print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))

cv2.destroyAllWindows()
vs.stop()

Body:
In that case, what I usually do is skip a few frames from the input. Add something like this in the while loop

while True:
    for i in range(5): # you can adjust this number
        frame = vs.read()
    frame = imutils.resize(frame, width=500)

This works pretty well if you want the video output in realtime.


问:
generating and mapping two sets of numbers
I have 2 numbers 25798709 and 25716544 representing the minimum and maximum values of some consecutive numbers with each number differing from the preceeding number by one eg. 25798709,25798710, 25798711................25716544  I want a python code that will convert these figures to 1,2,3,4,5,.............. and map the 1,2,3,4,5 to the original figures in two columns:
Like: </p>

```<code>  1     25798709
  2     25798710
  3     25798711
</code>```

答:
```<code># make it work in both Python 2 and 3
from __future__ import print_function
try: xrange
except NameError: xrange= range

def my_enumerate(num1, num2):
    start= min(num1, num2)
    end= max(num1, num2) + 1
    for data in enumerate(xrange(start, end), 1):
        print("%d\t%d" % data)
</code>```

Body:
I have 2 numbers 25798709 and 25716544 representing the minimum and maximum values of some consecutive numbers with each number differing from the preceeding number by one eg. 25798709,25798710, 25798711................25716544  I want a python code that will convert these figures to 1,2,3,4,5,.............. and map the 1,2,3,4,5 to the original figures in two columns:
Like:

  1     25798709
  2     25798710
  3     25798711


答:
useState in react and then a switch for the current value</p>

```<code>export default function App() {
  const [buttonText, setButtonText] = useState("My Button");

  handleClick = () => {
    switch (buttonText) {
      case "My Button":
        setButtonText("My Button 1");
        break;
      case "My Button 1":
        setButtonText("My Button 2");
        break;
      case "My Button 2":
        setButtonText("Whoops");
        break;
      default:
        setButtonText("My Button");
        break;
    }
  };
  return (
    <div className="App">
      <button onClick={() => handleClick()}>{buttonText}</button>
    </div>
  );
}
</code>```

Title: How do I check/change the text in a React button?

Body:
useState in react and then a switch for the current value

export default function App() {
  const [buttonText, setButtonText] = useState("My Button");

  handleClick = () => {
    switch (buttonText) {
      case "My Button":
        setButtonText("My Button 1");
        break;
      case "My Button 1":
        setButtonText("My Button 2");
        break;
      case "My Button 2":
        setButtonText("Whoops");
        break;
      default:
        setButtonText("My Button");
        break;
    }
  };
  return (
    <div className="App">
      <button onClick={() => handleClick()}>{buttonText}</button>
    </div>
  );
}


问:
flutter program work okay on chrome, but cannot work correctly on web server
I'm pretty new to flutter, and wrote the following flutter program to get the client IP address and location. I'm calling "http://ip-api.com/json" for IP address and location information. The program works okay by using device "chrome" and "web server", I can print client's location on the page.

.
When I deployed to github webpage or firebase hosting , and the program  shows "loading circle" for ever. It seems that the program cannot get the ip address after it was deployed to the github web server (or other web server).

I found the program throw "XMLHTTPRequest Error" once i deployed it to Github html page or firebase hosting.  It works fine on the local web server or chrome.  any suggestion on that?  Thanks a lot.

```<code>import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class IP_info{
  final String IP;
  final String city;
  final String ZIP;
  final String st_code;
  final String state_name;
  final String country_code;
  final String country_name;

  IP_info({this.IP, this.city, this.st_code,this.ZIP,
     this.state_name,this.country_code,this.country_name});

  factory IP_info.fromJson(Map<String, dynamic> json){
    return IP_info(
      IP:json['query'],
      ZIP:json['zip'],
      city:json['city'],
      country_code:json['countryCode'],
      st_code:json['region'],
      country_name:json['country_name'],
      state_name:json['regionName'],
    );
  }

}
void main() {
  runApp(MaterialApp(
      title: 'Covid 19 cases near you',
      home: MyApp()
  ),
  );
}

class MyApp extends StatefulWidget{
  @override
  State<StatefulWidget> createState()  => MyAppState();
}

class MyAppState extends State<MyApp> {

  bool _isLoading = false;
  IP_info ip_info;

  @override
  void initState() {
     _isLoading=true;
    _getPublicIP();
  }

_getPublicIP() async {
    try {

      const url = 'http://ip-api.com/json';

      final response = await http.get(url);
      if (response.statusCode == 200) {
        ip_info = IP_info.fromJson(json.decode(response.body));
        print(ip_info.toString());

        setState(() {
          _isLoading = false;
        });
        }
      else {
        // The request failed with a non-200 code
        print(response.statusCode);
        print(response.body);
      }

    } catch (e) {
      print(e);
    }
  }

 @override
  Widget build(BuildContext context) {
    return  Scaffold(
        appBar: AppBar(title: Text('Testing IP address'),    ),
        body: Container(
          padding: const EdgeInsets.all(8.0),
          decoration: BoxDecoration(
            color: Colors.white,
          ),
          child: _isLoading? Center(
              child: Column(children: [
                CircularProgressIndicator(),
                SizedBox(height: 10,),
                Text("Loading your location infomation ...", style: TextStyle(color: Colors.blueAccent),),
              ]
              )
          )
              : new Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.center ,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget> [
              Text('You are in ${ip_info.city} ${ip_info.state_name} ',
                style: TextStyle(
                  fontWeight: FontWeight.bold,),
              ),

            ],
          ),
        )
    );
  }
</code>```

答:
This is probably because of the service worker file generated only for the release build. The { credentials: 'include' } part of service work file breaks all requests without Access-Control-Allow-Origin or with that of value * which is all public APIs.

There is an issue on that, and it is said to be fixed in master which has not been released yet. So some workarounds you can do currently is to remove the credentials part manually after every build or to unregister the service worker.

Here's how you can remove that part if you still want to use service worker. There should be a flutter_service_worker.js file inside the build/web folder. You will find that credentials part as the second argument of the fetch function. You can remove that argument. But the bad thing about this is you have to remove that part manually every time after building, which is not programmatic or effective.

The best way for this problem is to completely unregister the service worker. You can do that by, removing this script part from the web/index.html file.

```

Body:
I'm pretty new to flutter, and wrote the following flutter program to get the client IP address and location. I'm calling "http://ip-api.com/json" for IP address and location information. The program works okay by using device "chrome" and "web server", I can print client's location on the page.

.
When I deployed to github webpage or firebase hosting , and the program  shows "loading circle" for ever. It seems that the program cannot get the ip address after it was deployed to the github web server (or other web server).

I found the program throw "XMLHTTPRequest Error" once i deployed it to Github html page or firebase hosting.  It works fine on the local web server or chrome.  any suggestion on that?  Thanks a lot.

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class IP_info{
  final String IP;
  final String city;
  final String ZIP;
  final String st_code;
  final String state_name;
  final String country_code;
  final String country_name;

  IP_info({this.IP, this.city, this.st_code,this.ZIP,
     this.state_name,this.country_code,this.country_name});

  factory IP_info.fromJson(Map<String, dynamic> json){
    return IP_info(
      IP:json['query'],
      ZIP:json['zip'],
      city:json['city'],
      country_code:json['countryCode'],
      st_code:json['region'],
      country_name:json['country_name'],
      state_name:json['regionName'],
    );
  }

}
void main() {
  runApp(MaterialApp(
      title: 'Covid 19 cases near you',
      home: MyApp()
  ),
  );
}

class MyApp extends StatefulWidget{
  @override
  State<StatefulWidget> createState()  => MyAppState();
}

class MyAppState extends State<MyApp> {

  bool _isLoading = false;
  IP_info ip_info;

  @override
  void initState() {
     _isLoading=true;
    _getPublicIP();
  }

_getPublicIP() async {
    try {

      const url = 'http://ip-api.com/json';

      final response = await http.get(url);
      if (response.statusCode == 200) {
        ip_info = IP_info.fromJson(json.decode(response.body));
        print(ip_info.toString());

        setState(() {
          _isLoading = false;
        });
        }
      else {
        // The request failed with a non-200 code
        print(response.statusCode);
        print(response.body);
      }

    } catch (e) {
      print(e);
    }
  }

 @override
  Widget build(BuildContext context) {
    return  Scaffold(
        appBar: AppBar(title: Text('Testing IP address'),    ),
        body: Container(
          padding: const EdgeInsets.all(8.0),
          decoration: BoxDecoration(
            color: Colors.white,
          ),
          child: _isLoading? Center(
              child: Column(children: [
                CircularProgressIndicator(),
                SizedBox(height: 10,),
                Text("Loading your location infomation ...", style: TextStyle(color: Colors.blueAccent),),
              ]
              )
          )
              : new Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.center ,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget> [
              Text('You are in ${ip_info.city} ${ip_info.state_name} ',
                style: TextStyle(
                  fontWeight: FontWeight.bold,),
              ),

            ],
          ),
        )
    );
  }

Body:
This is probably because of the service worker file generated only for the release build. The { credentials: 'include' } part of service work file breaks all requests without Access-Control-Allow-Origin or with that of value * which is all public APIs.

There is an issue on that, and it is said to be fixed in master which has not been released yet. So some workarounds you can do currently is to remove the credentials part manually after every build or to unregister the service worker.

Here's how you can remove that part if you still want to use service worker. There should be a flutter_service_worker.js file inside the build/web folder. You will find that credentials part as the second argument of the fetch function. You can remove that argument. But the bad thing about this is you have to remove that part manually every time after building, which is not programmatic or effective.

The best way for this problem is to completely unregister the service worker. You can do that by, removing this script part from the web/index.html file.

<script>
      if ("serviceWorker" in navigator) {
        window.addEventListener("load", function() {
          navigator.serviceWorker.register("/flutter_service_worker.js");
        });
      }
</script>