问:
How can I use nginx for load balancer -simple node.js with docker compose?
I am googling and trying to use nginx for simple node.js application with docker compose. But when I look at localhost:8081 My request returned me as 502 bad gate way. How can I handle this error?

My file structure below:

Load-Balancer:

DockerFile:

```<code>FROM nginx:stable-alpine
LABEL xxx yyyyyy
COPY nginx.conf /etc/nginx/nginx.conf

EXPOSE 8081
CMD ["nginx", "-g", "daemon off;"]
</code>```

nginx.conf:

```<code>events { worker_connections 1024; }

http {

upstream localhost {
server backend1:3001;
server backend2:3001;
server backend3:3001;
}

server {
listen 8081;
server_name localhost;

location / {
   proxy_pass http://localhost;
   proxy_set_header X-Real-IP $remote_addr;
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_set_header X-Forwarded-Proto $scheme;
   proxy_set_header Host $http_host;
   proxy_set_header X-NginX-Proxy true;
}
 }
 }
</code>```

docker-compose.yml

version: '3.2'
services:
  backend1:
      build: ./backend
      tty: true
      volumes:
        - './backend'

  backend2:
      build: ./backend
      tty: true
      volumes:
        - './backend'

  backend3:
      build: ./backend
      tty: true
      volumes:
        - './backend'

  loadbalancer:
      build: ./load-balancer
      tty: true
      links:
          - backend1
          - backend2
          - backend3
      ports:
          - '8081:8081'

volumes:
  backend:

```

My repository: https://github.com/yusufkaratoprak/nginx_docker_loadbalancer

答:
There is no command set for the backend container images to run.

The official nodejs  images run node by default, which will start the cli when a tty exists. I assuming the tty was enabled in the compose definition to keep the containers from crashing.

A simple Dockerfile for an app would look like:

```<code>FROM node:boron
WORKDIR /app
COPY src/. /app/
RUN npm install
EXPOSE 3001
CMD [ "node", "/app/index.js" ]
</code>```

A tty shouldn't be needed for most daemons, remove the tty settings from the docker-compose.yml. The links are also redundant in version 2+ compose files.

```<code>version: '3.2'
services:
  backend1:
      build: ./backend
      volumes:
        - './backend'

  backend2:
      build: ./backend
      volumes:
        - './backend'

  backend3:
      build: ./backend
      volumes:
        - './backend'

  loadbalancer:
      build: ./load-balancer
      ports:
          - '8081:8081'

volumes:
  backend:
</code>```

Body:
I am googling and trying to use nginx for simple node.js application with docker compose. But when I look at localhost:8081 My request returned me as 502 bad gate way. How can I handle this error?

My file structure below:

Load-Balancer:

DockerFile:

FROM nginx:stable-alpine
LABEL xxx yyyyyy
COPY nginx.conf /etc/nginx/nginx.conf

EXPOSE 8081
CMD ["nginx", "-g", "daemon off;"]

nginx.conf:

events { worker_connections 1024; }

http {

upstream localhost {
server backend1:3001;
server backend2:3001;
server backend3:3001;
}

server {
listen 8081;
server_name localhost;

location / {
   proxy_pass http://localhost;
   proxy_set_header X-Real-IP $remote_addr;
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_set_header X-Forwarded-Proto $scheme;
   proxy_set_header Host $http_host;
   proxy_set_header X-NginX-Proxy true;
}
 }
 }

docker-compose.yml

version: '3.2'
services:
  backend1:
      build: ./backend
      tty: true
      volumes:
        - './backend'

  backend2:
      build: ./backend
      tty: true
      volumes:
        - './backend'

  backend3:
      build: ./backend
      tty: true
      volumes:
        - './backend'

  loadbalancer:
      build: ./load-balancer
      tty: true
      links:
          - backend1
          - backend2
          - backend3
      ports:
          - '8081:8081'

volumes:
  backend:

My repository: https://github.com/yusufkaratoprak/nginx_docker_loadbalancer

Body:
There is no command set for the backend container images to run.

The official nodejs  images run node by default, which will start the cli when a tty exists. I assuming the tty was enabled in the compose definition to keep the containers from crashing.

A simple Dockerfile for an app would look like:

FROM node:boron
WORKDIR /app
COPY src/. /app/
RUN npm install
EXPOSE 3001
CMD [ "node", "/app/index.js" ]

A tty shouldn't be needed for most daemons, remove the tty settings from the docker-compose.yml. The links are also redundant in version 2+ compose files.

version: '3.2'
services:
  backend1:
      build: ./backend
      volumes:
        - './backend'

  backend2:
      build: ./backend
      volumes:
        - './backend'

  backend3:
      build: ./backend
      volumes:
        - './backend'

  loadbalancer:
      build: ./load-balancer
      ports:
          - '8081:8081'

volumes:
  backend:


来源: stackexchange

问:
setText function does not change the TextView
the app runs the way I want I can see that in the Logcat
but the text view is not changing and keeps the default value
i also tried to change button enable status programmatically but stayed in the same , nothing get changed !!

I tried in the setText method both
String.valueof(int)
and
Integer.toString(int)

java

```<code> @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         play =(Button) findViewById(R.id.button4);
         Pause =(Button) findViewById(R.id.button5);
        hourstext =(TextView) findViewById(R.id.textView1);
        mintext =(TextView) findViewById(R.id.textView2);
        sectext =(TextView) findViewById(R.id.textView3);

    }

    void playb(View v)  {

        while (!ispause) {
            sec = 0 ;
            while (sec < 60) {
                SystemClock.sleep(1000);
                sec++;
               sectext.setText(Integer.toString(sec));
                Log.d("this", "sec value=" + sec);
            }
            sec = 0;
            min++;
            Log.d("this","min value ="+min);

           mintext.setText(String.valueOf(min));

        }

    }
</code>```

XML

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="114dp"
        android:layout_height="94dp"
        android:layout_marginTop="159dp"
        android:layout_marginEnd="16dp"
        android:layout_x="274dp"
        android:layout_y="120dp"
        android:gravity="center|center_horizontal"
        android:text="00"
        android:textSize="40sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/pauseButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="72dp"
        android:layout_marginTop="116dp"
        android:layout_marginEnd="93dp"
        android:layout_x="217dp"
        android:layout_y="296dp"
        android:enabled="false"
        android:onClick="playb"
        android:text="Pause"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/playbutton"
        app:layout_constraintTop_toBottomOf="@+id/textView3" />

    <Button
        android:id="@+id/playbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="70dp"
        android:layout_marginTop="116dp"
        android:layout_x="63dp"
        android:layout_y="293dp"
        android:onClick="playb"
        android:text="playb"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="120dp"
        android:layout_height="97dp"
        android:layout_marginTop="156dp"
        android:layout_marginEnd="17dp"
        android:layout_x="139dp"
        android:layout_y="117dp"
        android:gravity="center|center_horizontal"
        android:text="00"
        android:textSize="40sp"
        app:layout_constraintEnd_toStartOf="@+id/textView3"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="103dp"
        android:layout_height="94dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="159dp"
        android:layout_x="11dp"
        android:layout_y="117dp"
        android:gravity="center_horizontal|center_vertical"
        android:text="00"
        android:textSize="40sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
</code>```

i get no error message ! the app keeps working but no updated textView

i've included my XML Code

答:
Before trying to fix this problem, let first understand why it happens

CAUSE

When you call View.setText(), Android doesn't actually set the text immediately. It pushes all of these set-text works to a queue on main thread to do LATER whenever it has free time.

Let's try to run this block, you will notice that until this while loop finish, View.setText() will not be done.

```<code>void playb(View v) {
    min = 0
    while (min < 1000000) {
        min++
        Log.d("this", "min value =$min")

        mintext.setText(String.valueOf(min))
    }
}
</code>```

So in your situtation, actually the TextView will still be set, but you will not see the change until the while loop finishes.

SOLUTION

You should move this while loop to another thread, you can simply use an AsyncTask or a HandlerThread for that

Ex. Use a HandlerThread:

```<code>void playb() {

    // Start a new background thread
    HandlerThread thread = new HandlerThread("");
    thread.start();

    // Obtain the handler of new background thread
    Handler handler = new Handler(thread.getLooper());

    // Obtain the handler of main thread (UI Thread)
    final Handler mainHandler = new Handler(this.getMainLooper());

    // Create a runnable and send it to background thread to execute
    handler.post(new Runnable() {

        public final void run() {

            // Do the job
            int min = 0;
            while(true) {
                int sec = 0;
                while(sec < 60) {
                    SystemClock.sleep(1000L);
                    sec ++;
                    final int currentSec = sec;

                    // Send the update-text job to main thread to execute
                    mainHandler.post(new Runnable() {
                        public final void run() {
                            secText.setText(currentSec);
                        }
                    });
                }
                sec = 0;
                min++;
                final int currentMin = min;

                // Send the update-text job to main thread to execute
                mainHandler.post(new Runnable() {
                    public final void run() {
                        minText.setText(currentMin);
                    }
                });
            }
        }
    });
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
the app runs the way I want I can see that in the Logcat
but the text view is not changing and keeps the default value
i also tried to change button enable status programmatically but stayed in the same , nothing get changed !!

I tried in the setText method both
String.valueof(int)
and
Integer.toString(int)

java

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         play =(Button) findViewById(R.id.button4);
         Pause =(Button) findViewById(R.id.button5);
        hourstext =(TextView) findViewById(R.id.textView1);
        mintext =(TextView) findViewById(R.id.textView2);
        sectext =(TextView) findViewById(R.id.textView3);

    }

    void playb(View v)  {

        while (!ispause) {
            sec = 0 ;
            while (sec < 60) {
                SystemClock.sleep(1000);
                sec++;
               sectext.setText(Integer.toString(sec));
                Log.d("this", "sec value=" + sec);
            }
            sec = 0;
            min++;
            Log.d("this","min value ="+min);

           mintext.setText(String.valueOf(min));

        }

    }

XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="114dp"
        android:layout_height="94dp"
        android:layout_marginTop="159dp"
        android:layout_marginEnd="16dp"
        android:layout_x="274dp"
        android:layout_y="120dp"
        android:gravity="center|center_horizontal"
        android:text="00"
        android:textSize="40sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/pauseButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="72dp"
        android:layout_marginTop="116dp"
        android:layout_marginEnd="93dp"
        android:layout_x="217dp"
        android:layout_y="296dp"
        android:enabled="false"
        android:onClick="playb"
        android:text="Pause"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/playbutton"
        app:layout_constraintTop_toBottomOf="@+id/textView3" />

    <Button
        android:id="@+id/playbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="70dp"
        android:layout_marginTop="116dp"
        android:layout_x="63dp"
        android:layout_y="293dp"
        android:onClick="playb"
        android:text="playb"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="120dp"
        android:layout_height="97dp"
        android:layout_marginTop="156dp"
        android:layout_marginEnd="17dp"
        android:layout_x="139dp"
        android:layout_y="117dp"
        android:gravity="center|center_horizontal"
        android:text="00"
        android:textSize="40sp"
        app:layout_constraintEnd_toStartOf="@+id/textView3"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="103dp"
        android:layout_height="94dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="159dp"
        android:layout_x="11dp"
        android:layout_y="117dp"
        android:gravity="center_horizontal|center_vertical"
        android:text="00"
        android:textSize="40sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

i get no error message ! the app keeps working but no updated textView

i've included my XML Code

Body:
Before trying to fix this problem, let first understand why it happens

CAUSE

When you call View.setText(), Android doesn't actually set the text immediately. It pushes all of these set-text works to a queue on main thread to do LATER whenever it has free time.

Let's try to run this block, you will notice that until this while loop finish, View.setText() will not be done.

void playb(View v) {
    min = 0
    while (min < 1000000) {
        min++
        Log.d("this", "min value =$min")

        mintext.setText(String.valueOf(min))
    }
}

So in your situtation, actually the TextView will still be set, but you will not see the change until the while loop finishes.

SOLUTION

You should move this while loop to another thread, you can simply use an AsyncTask or a HandlerThread for that

Ex. Use a HandlerThread:

void playb() {

    // Start a new background thread
    HandlerThread thread = new HandlerThread("");
    thread.start();

    // Obtain the handler of new background thread
    Handler handler = new Handler(thread.getLooper());

    // Obtain the handler of main thread (UI Thread)
    final Handler mainHandler = new Handler(this.getMainLooper());

    // Create a runnable and send it to background thread to execute
    handler.post(new Runnable() {

        public final void run() {

            // Do the job
            int min = 0;
            while(true) {
                int sec = 0;
                while(sec < 60) {
                    SystemClock.sleep(1000L);
                    sec ++;
                    final int currentSec = sec;

                    // Send the update-text job to main thread to execute
                    mainHandler.post(new Runnable() {
                        public final void run() {
                            secText.setText(currentSec);
                        }
                    });
                }
                sec = 0;
                min++;
                final int currentMin = min;

                // Send the update-text job to main thread to execute
                mainHandler.post(new Runnable() {
                    public final void run() {
                        minText.setText(currentMin);
                    }
                });
            }
        }
    });
}


问:
How can I use same mouse events in another form / user control?
Im creating winforms c# application with multiple user controls. It's flat application without any borders, so the only way to move windows is by using mouse control events. I used this part of code in my main window, but I cant apply it in any other user controls. I don't want to copy & paste for all user controls, so is there any way to use it?

This code works in my main form, but when i create user control i dont have access to those and i cant wire them up to objects.

```<code>    private bool mouseDown;
    private Point lastLocation;

    private void _MouseDown(object sender, MouseEventArgs e)
    {
        mouseDown = true;
        lastLocation = e.Location;
    }

    private void _MouseMove(object sender, MouseEventArgs e)
    {
        if (mouseDown)
        {
            this.Location = new Point((this.Location.X - lastLocation.X) + e.X, (this.Location.Y - lastLocation.Y) + e.Y);
            this.Update();
        }
    }
    private void _MouseUp(object sender, MouseEventArgs e)
    {
        mouseDown = false;
    }
</code>```

Can I make event handler / delegate to solve it?

答:
Could you explain little more how to cast sender parameter to a
  control?

Sure:

```<code>private void _MouseMove(object sender, MouseEventArgs e)
{
    Control source = (Control)sender; // cast "sender" to a control
    if (mouseDown)
    {
        source.Location = new Point((source.Location.X - lastLocation.X) + e.X, (source.Location.Y - lastLocation.Y) + e.Y);
    }
}
</code>```

Now whatever control is the "source" of the event will be acted upon (instead of always being the form with "this").

Body:
Im creating winforms c# application with multiple user controls. It's flat application without any borders, so the only way to move windows is by using mouse control events. I used this part of code in my main window, but I cant apply it in any other user controls. I don't want to copy & paste for all user controls, so is there any way to use it?

This code works in my main form, but when i create user control i dont have access to those and i cant wire them up to objects.

    private bool mouseDown;
    private Point lastLocation;

    private void _MouseDown(object sender, MouseEventArgs e)
    {
        mouseDown = true;
        lastLocation = e.Location;
    }

    private void _MouseMove(object sender, MouseEventArgs e)
    {
        if (mouseDown)
        {
            this.Location = new Point((this.Location.X - lastLocation.X) + e.X, (this.Location.Y - lastLocation.Y) + e.Y);
            this.Update();
        }
    }
    private void _MouseUp(object sender, MouseEventArgs e)
    {
        mouseDown = false;
    }

Can I make event handler / delegate to solve it?

Body:
Could you explain little more how to cast sender parameter to a
  control?

Sure:

private void _MouseMove(object sender, MouseEventArgs e)
{
    Control source = (Control)sender; // cast "sender" to a control
    if (mouseDown)
    {
        source.Location = new Point((source.Location.X - lastLocation.X) + e.X, (source.Location.Y - lastLocation.Y) + e.Y);
    }
}

Now whatever control is the "source" of the event will be acted upon (instead of always being the form with "this").


问:
Dialogflow context lifespan expires before 20 mins
According to the Dialogflow documentation by default, output contexts expire after either five requests or 20 mins after its corresponding intent is matched.

But when I'm trying this out (2nd request and the lifespan of the particular context was 5) I observed that this is less than 20 mins. When I tried after 11 mins it is already expired. I'm using an Enterprise Bot of V2.

I'm experiencing 10 mins context expiration time. What is the actual expiration time of a context?

答: According to this blog post from DialogFlow, apparently the contexts are only supposed to last 10 minutes.</p>


问:
How to make a player only be able to jump a certain height in Java?
So, for a school project, I've been trying to get a jumping mechanism down. However, the problem I've been having is that the player is able to just float around, rather than having to fall down after reaching a certain jump height.

I have tried many things, including the normal idea of when the up key is pressed, setting jumping equal to true, and then in the actionPerformed method, setting the yVelocity to -4. But, when the jump key is clicked, I record the yPosition at the time, and when the current yPosition is less than the original position - 50, I set the yVelocity equal to 0, and the fallVelocity to 1.

This is the code in my actionPerformed method:

```<code>if (jumping) {
            if (yPos <= homeY - 50) {
                yVel = 0;
                fallVel = 1;
                falling = true;
                jumping = false;
                System.out.println("bye");
            }   else {
                yVel = -JUMP_SPEED;
            }
        }
        yPos += yVel + fallVel;
</code>```

'''

This is the code in the keyPressed method:

```<code>if (!jumping && !falling) {
            jumping = true;
            homeY = yPos;
            count = 0;
        }
</code>```

So, I expect the result to be a player that goes up 50 pixels, and then starts falling down. But in the program, the player just sort of keeps on floating, as long as the up key is pressed.

答:
Jumping does not really work properly as an up/down switch imo. The best approach is to use gravity (which is very easy to add).

To add gravity just modify the player velocity each tick. This should be run on a fixed time update loop to make consistent gravity at different frame rates:

```<code>// Play with this number for rate of gravity
player.ySpeed -= 4.9; // Gravity = 9.8m/s^2
</code>```

Then for your jumping just add to the player ySpeed. This will create a natural parabolic jump.

```<code>if (jumpWasPressed) {
    player.ySpeed += 50; // play with this number for jump height
}
</code>```

This approach does assume you have a hotbox for your "ground" object to stop the player from falling through the ground

Body:
So, for a school project, I've been trying to get a jumping mechanism down. However, the problem I've been having is that the player is able to just float around, rather than having to fall down after reaching a certain jump height.

I have tried many things, including the normal idea of when the up key is pressed, setting jumping equal to true, and then in the actionPerformed method, setting the yVelocity to -4. But, when the jump key is clicked, I record the yPosition at the time, and when the current yPosition is less than the original position - 50, I set the yVelocity equal to 0, and the fallVelocity to 1.

This is the code in my actionPerformed method:

if (jumping) {
            if (yPos <= homeY - 50) {
                yVel = 0;
                fallVel = 1;
                falling = true;
                jumping = false;
                System.out.println("bye");
            }   else {
                yVel = -JUMP_SPEED;
            }
        }
        yPos += yVel + fallVel;

'''

This is the code in the keyPressed method:

if (!jumping && !falling) {
            jumping = true;
            homeY = yPos;
            count = 0;
        }

So, I expect the result to be a player that goes up 50 pixels, and then starts falling down. But in the program, the player just sort of keeps on floating, as long as the up key is pressed.

Body:
Jumping does not really work properly as an up/down switch imo. The best approach is to use gravity (which is very easy to add).

To add gravity just modify the player velocity each tick. This should be run on a fixed time update loop to make consistent gravity at different frame rates:

// Play with this number for rate of gravity
player.ySpeed -= 4.9; // Gravity = 9.8m/s^2

Then for your jumping just add to the player ySpeed. This will create a natural parabolic jump.

if (jumpWasPressed) {
    player.ySpeed += 50; // play with this number for jump height
}

This approach does assume you have a hotbox for your "ground" object to stop the player from falling through the ground


问:
How to get key from object in map function?
How to get the key from object in

```<code>{this.state.data.map((object, index) => (
      <div>object.key</div>

    ))}
</code>```

For example if this.state.data was

```<code> [{mykey1:23},{mykey2:24},{mykey3:34}]
</code>```

I would want it to return

```<code> <div>mykey1</div>
 <div>mykey2</div>
 <div>mykey3</div>
</code>```

答:
You are not interpolating the value you want to render to start with. You would have to put values that you want to be evaluated within curly brackets for them to be rendered from your states/props.
Though I'm assuming your example was typed in haste and that is not the reason why this is not working for you.
To get keys defined in an object you would have to use Object.keys() which returns an array of strings with all the keys. Then you could loop over the resulting array and render them within your JSX view.

Here's a working fiddle for your reference:
https://jsfiddle.net/2q19rpaz/

```<code>let data = [{mykey1:23},{mykey2:24},{mykey3:34, mykey4:34}];
return data.map((object, index) => {
    return Object.keys(object).map((key, index) => {
        return (<div>{key}</div>);
    })
})
</code>```

Body:
How to get the key from object in

{this.state.data.map((object, index) => (

object.key

    ))}

For example if this.state.data was

 [{mykey1:23},{mykey2:24},{mykey3:34}]

I would want it to return

mykey1

mykey2

mykey3

Body:
You are not interpolating the value you want to render to start with. You would have to put values that you want to be evaluated within curly brackets for them to be rendered from your states/props.
Though I'm assuming your example was typed in haste and that is not the reason why this is not working for you.
To get keys defined in an object you would have to use Object.keys() which returns an array of strings with all the keys. Then you could loop over the resulting array and render them within your JSX view.

Here's a working fiddle for your reference:
https://jsfiddle.net/2q19rpaz/

let data = [{mykey1:23},{mykey2:24},{mykey3:34, mykey4:34}];
return data.map((object, index) => {
    return Object.keys(object).map((key, index) => {
        return (<div>{key}</div>);
    })
})


问:
Amazon rds Aurora clone/restore point in time API
When I try to use clone/restore point in time from amazon console. It clones cluster as well as all the instances which belongs to that. But  when I consume the same functionality using amazon API, it clones only cluster alone.

Is there any other API to clone cluster alone with their instances, security/parameter group and other settings?

答:
Console adds a convenience layer where in it internally makes multiple API calls to make the experience better. Restoring from a snapshot or from point in time is done in 2 steps:

RestoreDBClusterFromSnapshot or RestoreDBClusterToPointInTime API - To create a new cluster, backed by a new distributed aurora volume. No DB instances are added when then API is issued.

CreateDBInstance API - To add instances to the cluster.

So in short, if you want to do it via CLI, you need to issue both these API calls. The same is true while creating a cluster with instances as well. Console would create a cluster and add instances in the same UX workflow, but behind the scenes, it is actually issuing a CreateDBCluster API followed by one or more CreateDBInstance API call(s).

Hope this helps.


问:
Matplotlib: How to make scatter plot of arbitrary pyplot figures
This is a question linked to this well received one. In that question I see an answers on how to plot images (or different images) at different coordinates like a scatter plot.

Using TextArea I can put little strings instead of images at different coordinates.

How about if I want to put a mini version of a plot/image generated by matplotlib itself? Suppose I want instead of using an image.jpg I want to use the result of plt.stem(arr) as the image in the scatter plots.

How can I do this? How about a miniature version of the output of plt.plot(x, y)?

I tried modifying the function given in the linked question to be like:

```<code>def stem_scatter(x, y, arr, ax=None):

    from matplotlib.offsetbox import AnnotationBbox, DrawingArea

    if ax is None:
        ax = plt.gca()
    im = DrawingArea(0.1, 0.1)
    im.add_artist(plt.stem(arr))
    x, y = np.atleast_1d(x, y)
    artists = []
    for x0, y0 in zip(x, y):
        ab = AnnotationBbox(im, (x0, y0), xycoords='data', frameon=False)
        artists.append(ax.add_artist(ab))
    ax.update_datalim(np.column_stack([x, y]))
    ax.autoscale()
    return artists
</code>```

But that gives an error:
AttributeError: 'StemContainer' object has no attribute 'is_transform_set'

EDIT: From the linked question:

```<code>"…. but the second has a large advantage. The annotation box approach will allow the image to stay at a constant size as you zoom in."
</code>```

this would be a desirable feature in an accepted answer because on zooming in one would like to see the relative positions of the scatter points. If the scatter plotted image did not maintain a fixed size (relative to the screen as opposed to current axis limits), then zooming in would be of little help.

答: You could try something like: https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.inset_axes.html</p>

Body:
This is a question linked to this well received one. In that question I see an answers on how to plot images (or different images) at different coordinates like a scatter plot.

Using TextArea I can put little strings instead of images at different coordinates.

How about if I want to put a mini version of a plot/image generated by matplotlib itself? Suppose I want instead of using an image.jpg I want to use the result of plt.stem(arr) as the image in the scatter plots.

How can I do this? How about a miniature version of the output of plt.plot(x, y)?

I tried modifying the function given in the linked question to be like:

def stem_scatter(x, y, arr, ax=None):

    from matplotlib.offsetbox import AnnotationBbox, DrawingArea

    if ax is None:
        ax = plt.gca()
    im = DrawingArea(0.1, 0.1)
    im.add_artist(plt.stem(arr))
    x, y = np.atleast_1d(x, y)
    artists = []
    for x0, y0 in zip(x, y):
        ab = AnnotationBbox(im, (x0, y0), xycoords='data', frameon=False)
        artists.append(ax.add_artist(ab))
    ax.update_datalim(np.column_stack([x, y]))
    ax.autoscale()
    return artists

But that gives an error:
AttributeError: 'StemContainer' object has no attribute 'is_transform_set'

EDIT: From the linked question:

"…. but the second has a large advantage. The annotation box approach will allow the image to stay at a constant size as you zoom in."

this would be a desirable feature in an accepted answer because on zooming in one would like to see the relative positions of the scatter points. If the scatter plotted image did not maintain a fixed size (relative to the screen as opposed to current axis limits), then zooming in would be of little help.


问:
Is it safe to make ApplicationDbContext public? ASP.Net core
Actually you can't directly make ApplicationDbContext public, but you can make some tricks like here https://codedocu.com/Net-Framework/ASP_dot_Net-Core/Data-Model/Asp_dot_Net-Core_colon_-How-to-get-the-ApplicationDbContext-in-an-Asp_dot_Net-Core-MVC-application?2221

So the question is, is that safe to make ApplicationDbContext context public, do you get any vulnerabilities by this way?

答:
Access Modifier are mostly used for the developer to prevent breaking internal workings.   You may make a variable private,  this shouldn't be consider a vulnerability

There may be a few case where an access modifier may cause a vulnerability, such as exposing a method on a controller in MVC(which will open that method up to the world).

But for the most part access modifiers are used by someone who already has access to your code

If someone has access to the inner workings of dlls, they can use reflection to change whatever values they would like.


问:
How to create Full-text search index in MySQL AWS Aurora DB InnoDB engine
While trying to add full-text index on the table I am getting below error.

Error Code: 1214. The used table type doesn't support FULLTEXT indexes

And while trying to create a table with MyTSAM engine I am getting below warning message.

0 row(s) affected, 1 warning(s): 1266 Using storage engine InnoDB for
  table

答: I don't think Aurora supports full text indexing natively. You may want to enable binlogs and stream that out to an elastic search cluster that you manage on your own. As for the second error, Aurora supports only the InnoDB storage engine. Other engine types are not supported. </p>


问:
Stack trace after catching exception
I would like too see the stacktrace after the exception is thrown of course using debugger. Normally, when the exception is never caught, the debugger stops the program after receiving SIGABRT and I can see the whole stack trace and recognize the reason for the exception.

However how to diagnose the cause of the exception after catching it?

```<code>#include <iostream>
#include <stdexcept>

void foo() {
    throw std::runtime_error("An error message");
}

int main() {
    try {
        foo();
    } catch (const std::exception &e) {
        std::cerr << e.what(); // add breakpoint here
    }
    return 0;
}
</code>```

Adding a breakpoint in the catch section naturally stops the program after catching exception however the stack trace doesn't contain foo() call therefore the cause of the exception cannot be diagnosed.

Please note that the example is really minimal and simple. With complex and nested calls the information that exception occurred somewhere in the try section is virtually useless. And I cannot simply avoid catching exception because if I don't catch it then it is caught by the framework I'm using and the stacktrace is lost.

答:
If you are working with your own exceptions, then my libexcept library may be useful to you. This library offers a few class. The base class is capable of collecting a stack trace at the time it gets instantiated. 99% of the time, this gives you all the information you need to debug the issue. When you just know where the exception occurred, but not how it was called, it can be much more difficult to kow how to fix the problem. (Yeah! Because the same function may be called in 20 different ways so just knowing exactly which exception occurred is often not enough.)

In a project where you throw exceptions only when something really bad happens, this can even be kept in your release version. Then you can log the stack traces in your client's logs and make it hundred of times easier to debug remote/end client crashes.

I have a binary (pre-compiled version) for Ubuntu 16.04 on Launchpad (install the PPA in your apt lists and then install libexcept_1.0.5.0~xenial_amd64.deb or whatever version is current.)

To use, derive from one of the two classes offered:

```<code>class my_exception : public libexcept::logic_exception_t
{
   ...
};
</code>```

And in your catch() you can print the stack trace using the get_stack_trace() to get a vector of strings. In our case, we actually send that to our logs.

```<code>try
{
    ...
    throw my_exception("what happened?!");
    ...
}
catch(my_exception const & e)
{
    stack_trace_t const & stack(e.get_stack_trace());
    for(auto s : stack)
    {
        SNAP_LOG_ERROR(*s);
    }
}
</code>```

Obviously, you probably will want to have a function if you are to log the stack trace in many places.

For exceptions that you do not generate, though, you just can't really do much. However, you can re-throw with your own exception if you want to write a wrapper so as to at least narrow the location where the exceptions are coming from.

Say you are using a 3rd party library and expect library to throw once in a while...

```<code>try
{
    library::func();   // may throw
}
catch(library::exception const & e)
{
    throw my_exception(e.what());   // converted exception
}
</code>```

Now you at least have a stack trace from this low level catch.

Title: Stack trace after catching exception

Body:
I would like too see the stacktrace after the exception is thrown of course using debugger. Normally, when the exception is never caught, the debugger stops the program after receiving SIGABRT and I can see the whole stack trace and recognize the reason for the exception.

However how to diagnose the cause of the exception after catching it?

#include <iostream>
#include <stdexcept>

void foo() {
    throw std::runtime_error("An error message");
}

int main() {
    try {
        foo();
    } catch (const std::exception &e) {
        std::cerr << e.what(); // add breakpoint here
    }
    return 0;
}

Adding a breakpoint in the catch section naturally stops the program after catching exception however the stack trace doesn't contain foo() call therefore the cause of the exception cannot be diagnosed.

Please note that the example is really minimal and simple. With complex and nested calls the information that exception occurred somewhere in the try section is virtually useless. And I cannot simply avoid catching exception because if I don't catch it then it is caught by the framework I'm using and the stacktrace is lost.

Body:
If you are working with your own exceptions, then my libexcept library may be useful to you. This library offers a few class. The base class is capable of collecting a stack trace at the time it gets instantiated. 99% of the time, this gives you all the information you need to debug the issue. When you just know where the exception occurred, but not how it was called, it can be much more difficult to kow how to fix the problem. (Yeah! Because the same function may be called in 20 different ways so just knowing exactly which exception occurred is often not enough.)

In a project where you throw exceptions only when something really bad happens, this can even be kept in your release version. Then you can log the stack traces in your client's logs and make it hundred of times easier to debug remote/end client crashes.

I have a binary (pre-compiled version) for Ubuntu 16.04 on Launchpad (install the PPA in your apt lists and then install libexcept_1.0.5.0~xenial_amd64.deb or whatever version is current.)

To use, derive from one of the two classes offered:

class my_exception : public libexcept::logic_exception_t
{
   ...
};

And in your catch() you can print the stack trace using the get_stack_trace() to get a vector of strings. In our case, we actually send that to our logs.

try
{
    ...
    throw my_exception("what happened?!");
    ...
}
catch(my_exception const & e)
{
    stack_trace_t const & stack(e.get_stack_trace());
    for(auto s : stack)
    {
        SNAP_LOG_ERROR(*s);
    }
}

Obviously, you probably will want to have a function if you are to log the stack trace in many places.

For exceptions that you do not generate, though, you just can't really do much. However, you can re-throw with your own exception if you want to write a wrapper so as to at least narrow the location where the exceptions are coming from.

Say you are using a 3rd party library and expect library to throw once in a while...

try
{
    library::func();   // may throw
}
catch(library::exception const & e)
{
    throw my_exception(e.what());   // converted exception
}

Now you at least have a stack trace from this low level catch.


问:
How to average the values of different files and save them in a new file
I have about 140 files with data which I would like to process with a script.

The files have two types of names:

sys-time-4-16-80-15-1-1.txt

known-ratio-4-16-80-15-1-1.txt

where the two last numbers vary. The penultimate number takes 1, 50, 100, 150,...,300, and the last number ranges from 1,2,3,4,5...,10. A sample of these files are in this link.

I would like to write a new file with 3 columns as follows:

A 1st column with the penultimate number of the file, i.e., 1,25,50...
A 2nd column with the mean value of the second column in each sys-time-.. file.
A 3rd column with the mean value of the second column in each known-ratio-.. file.

The result might have a row for each pair of averaged 2nd columns of sys and known files:

```<code>1    mean-sys-1 mean-know-1
1    mean-sys-2 mean-know-2
.
.
1    mean-sys-10 mean-know-10
50   mean-sys-1  mean-know-1
50   mean-sys-2  mean-know-2
.
.
50   mean-sys-10 mean-know-10
100  mean-sys-1  mean-know-1
100  mean-sys-2  mean-know-2
.
.
100  mean-sys-10 mean-know-10
....
....
300  mean-sys-10 mean-know-10
</code>```

where each row corresponds with the sys and known files with the same two last numbers.
Besides, I would like to copy in the first column the penultimate number of the files.

I know how to compute the mean value of the second column of a file with awk:

```<code>awk '{ sum += $2; n++ } END { if (n > 0) print sum / n; }' sys-time-4-16-80-15-1-5.txt
</code>```

but I do not know how to iterate on all the files and build a result file with the three columns as above.

答:
Here's a shell script that uses GNU datamash to compute the averages (Though you can easily swap out to awk if desired; I prefer datamash for calculating stats):

```<code>#!/bin/sh

nums=$(mktemp)
sysmeans=$(mktemp)
knownmeans=$(mktemp)

for systime in sys-time-*.txt
do
    knownratio=$(echo -n "$systime" | sed -e 's/sys-time/known-ratio/')
    echo "$systime" | sed -E 's/.*-([0-9]+)-[0-9]+\.txt/\1/' >> "$nums"
    datamash -W mean 2 < "$systime" >> "$sysmeans"
    datamash -W mean 2 < "$knownratio" >> "$knownmeans"
done

paste "$nums" "$sysmeans" "$knownmeans"
rm -f "$nums" "$sysmeans" "$knownmeans"
</code>```

It creates three temporary files, one per column, and after populating them with the data from each pair of files, one pair per line of each, uses paste to combine them all and print the result to standard output.

Body:
I have about 140 files with data which I would like to process with a script.

The files have two types of names:

sys-time-4-16-80-15-1-1.txt

known-ratio-4-16-80-15-1-1.txt

where the two last numbers vary. The penultimate number takes 1, 50, 100, 150,...,300, and the last number ranges from 1,2,3,4,5...,10. A sample of these files are in this link.

I would like to write a new file with 3 columns as follows:

A 1st column with the penultimate number of the file, i.e., 1,25,50...
A 2nd column with the mean value of the second column in each sys-time-.. file.
A 3rd column with the mean value of the second column in each known-ratio-.. file.

The result might have a row for each pair of averaged 2nd columns of sys and known files:

1    mean-sys-1 mean-know-1
1    mean-sys-2 mean-know-2
.
.
1    mean-sys-10 mean-know-10
50   mean-sys-1  mean-know-1
50   mean-sys-2  mean-know-2
.
.
50   mean-sys-10 mean-know-10
100  mean-sys-1  mean-know-1
100  mean-sys-2  mean-know-2
.
.
100  mean-sys-10 mean-know-10
....
....
300  mean-sys-10 mean-know-10

where each row corresponds with the sys and known files with the same two last numbers.
Besides, I would like to copy in the first column the penultimate number of the files.

I know how to compute the mean value of the second column of a file with awk:

awk '{ sum += $2; n++ } END { if (n > 0) print sum / n; }' sys-time-4-16-80-15-1-5.txt

but I do not know how to iterate on all the files and build a result file with the three columns as above.

Body:
Here's a shell script that uses GNU datamash to compute the averages (Though you can easily swap out to awk if desired; I prefer datamash for calculating stats):

#!/bin/sh

nums=$(mktemp)
sysmeans=$(mktemp)
knownmeans=$(mktemp)

for systime in sys-time-*.txt
do
    knownratio=$(echo -n "$systime" | sed -e 's/sys-time/known-ratio/')
    echo "$systime" | sed -E 's/.*-([0-9]+)-[0-9]+\.txt/\1/' >> "$nums"
    datamash -W mean 2 < "$systime" >> "$sysmeans"
    datamash -W mean 2 < "$knownratio" >> "$knownmeans"
done

paste "$nums" "$sysmeans" "$knownmeans"
rm -f "$nums" "$sysmeans" "$knownmeans"

It creates three temporary files, one per column, and after populating them with the data from each pair of files, one pair per line of each, uses paste to combine them all and print the result to standard output.


问:
How to convert a string to a date in sybase
I need to specify a date value in a sybase where clause. For example:</p>

```<code>select *
from data
where dateVal < [THE DATE]
</code>```

答:
Use the convert function, for example:

```<code>select * from data
where dateVal < convert(datetime, '01/01/2008', 103)
</code>```

Where the convert style (103) determines the date format to use.

OwnerDisplayName: cmsherratt

ContentLicense: CC BY-SA 2.5

Body:
I need to specify a date value in a sybase where clause. For example:

select *
from data
where dateVal < [THE DATE]

Body:
Use the convert function, for example:

select * from data
where dateVal < convert(datetime, '01/01/2008', 103)

Where the convert style (103) determines the date format to use.


问:
script to map network drive
I want to be able to connect to a (wifi) network hard drive from my laptop, but only occasionally. If I use the "Map a network drive" command in WinXP explorer, I have to put in the drive's IP address and name, then the router name and its password. Too much to remember!

I'm looking for a way of scripting this activity (in any language), something like:

```<code>map Z: \\10.0.1.1\DRIVENAME "ROUTERNAME\PW"
</code>```

I don't particularly care what language the script is written in. BTW, I'm aware of the DOS 'subst' command, but I don't think I can use that in this case because of the password protection.

答: Why not map the network drive but deselect "Reconnect at logon"?  The drive will only connect when you try to access it.  Note that some applications will fail if they point to it, but if you're accessing files directly through Windows Explorer this works great.</p>

OwnerDisplayName: Don

Title: script to map network drive

Body:
I want to be able to connect to a (wifi) network hard drive from my laptop, but only occasionally. If I use the "Map a network drive" command in WinXP explorer, I have to put in the drive's IP address and name, then the router name and its password. Too much to remember!

I'm looking for a way of scripting this activity (in any language), something like:

map Z: \\10.0.1.1\DRIVENAME "ROUTERNAME\PW"

I don't particularly care what language the script is written in. BTW, I'm aware of the DOS 'subst' command, but I don't think I can use that in this case because of the password protection.

LastEditorDisplayName: Rich B

OwnerDisplayName: C. Ross


答: The binary representation of a number doesn't include leading zeros.  Just as str(1) and str(11) are different lengths because they don't pad with leading zeros to a fixed length.

Title: Hash algorithm(sha-512) doesn't return fixed length of bits

Body:
I am wondering why sha-512 or sha-256 function will return not fixed length bits in hashlib library, Python3.6.x

Firstly, I changed string like 'aaa' or 'mov' with hashlib.sha512 function.

then made return object hexdecimal, then changed hex value into binary.

it happens 2~3 in 100000times.

can anyone explain this?

i1 = h.sha512(b'mov')
num= int(i1.hexdigest(),16)
>>>11775820457324453297447618001055999940741095690927818803951219801773598183145805229667200223221871868971369247216868356532234761527576077269523848115505381

binary = bin(num)
>>>'0b1110000011010111000000101110101100011111100100001000101010011111011000010001101101101100010000110000111101010000001011000010011101110110010110111111011000100011011101000001111001111001111000001101101011100111010110001010110101111011001010100001001111010111000111110110110011110001110010111100110100001111011111000101101110001101001011001001111101111110010011010011111110101011010100101101111011001000011001100000000110101110110110001111110101011101001000011111111101110011001000111110000101111111110010001110010101'

len(binary[2:])   # to remove prefix
>>> 514


问:
Getting communication Link failure while connecting to Aurora-Mysql after cluster failover
My java application is working fine and inserting data into Aurora-Mysql before failover after failover it gives error "Communication link failure".Ours is 2 node cluster of Aurora-Mysql.

Below is the error:
ould not open Hibernate Session for transaction; nested exception is org.hibernate.TransactionException: JDBC begin transaction failed:

```<code>    at org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:542)

    at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)

    at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:430)

    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)

    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)

    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)

    at com.sun.proxy.$Proxy104.save(Unknown Source)

    at com.wu.oneplatform.controller.OrderControllerImpl.saveOrderDetail(OrderControllerImpl.java:81)

    at sun.reflect.GeneratedMethodAccessor107.invoke(Unknown Source)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

    at java.lang.reflect.Method.invoke(Method.java:498)

    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)

    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)

    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)

    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)

    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)

    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)

    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)

    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)

    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)

    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)

    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)

    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)

    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)

    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)

    at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55)

    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)

    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:105)

    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)

    at com.wu.oneplatform.utils.tracing.JaegerFilter.doFilter(JaegerFilter.java:21)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)

    at com.wu.oneplatform.utils.logging.LoggerFilter.doFilter(LoggerFilter.java:30)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)

    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)

    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)

    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:89)

    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)

    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)

    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)

    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)

    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)

    at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:106)

    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)

    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)

    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)

    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)

    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)

    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)

    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)

    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)

    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)

    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)

    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)

    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)

    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)

    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)

    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)

    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)

    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)

    at java.lang.Thread.run(Thread.java:745)
</code>```

Caused by: org.hibernate.TransactionException: JDBC begin transaction failed:

```<code>    at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.begin(AbstractLogicalConnectionImplementor.java:72)

    at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.begin(LogicalConnectionManagedImpl.java:238)

    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.begin(JdbcResourceLocalTransactionCoordinatorImpl.java:214)

    at org.hibernate.engine.transaction.internal.TransactionImpl.begin(TransactionImpl.java:52)

    at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1512)

    at org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:500)

    ... 80 common frames omitted
</code>```

Caused by: java.sql.SQLNonTransientConnectionException: No operations allowed after connection closed.

```<code>    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:110)

    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)

    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)

    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)

    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73)

    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:73)

    at com.mysql.cj.jdbc.ConnectionImpl.setAutoCommit(ConnectionImpl.java:2074)

    at sun.reflect.GeneratedMethodAccessor109.invoke(Unknown Source)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

    at java.lang.reflect.Method.invoke(Method.java:498)

    at org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:126)

    at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108)

    at org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:81)

    at com.sun.proxy.$Proxy87.setAutoCommit(Unknown Source)

    at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.begin(AbstractLogicalConnectionImplementor.java:67)

    ... 85 common frames omitted
</code>```

Caused by: com.mysql.cj.exceptions.ConnectionIsClosedException: No operations allowed after connection closed.

```<code>    at sun.reflect.GeneratedConstructorAccessor121.newInstance(Unknown Source)

    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)

    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)

    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)

    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105)

    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151)

    at com.mysql.cj.NativeSession.checkClosed(NativeSession.java:1259)

    at com.mysql.cj.jdbc.ConnectionImpl.checkClosed(ConnectionImpl.java:575)

    at com.mysql.cj.jdbc.ConnectionImpl.setAutoCommit(ConnectionImpl.java:2024)

    ... 93 common frames omitted
</code>```

Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure

The last packet successfully received from the server was 86 milliseconds ago.  The last packet sent successfully to the server was 86 milliseconds ago.

```<code>    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)

    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)

    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)

    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)

    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105)

    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151)

    at com.mysql.cj.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:167)

    at com.mysql.cj.protocol.a.NativeProtocol.readMessage(NativeProtocol.java:555)

    at com.mysql.cj.protocol.a.NativeProtocol.checkErrorMessage(NativeProtocol.java:725)

    at com.mysql.cj.protocol.a.NativeProtocol.sendCommand(NativeProtocol.java:664)

    at com.mysql.cj.protocol.a.NativeProtocol.sendQueryPacket(NativeProtocol.java:979)

    at com.mysql.cj.protocol.a.NativeProtocol.sendQueryString(NativeProtocol.java:914)

    at com.mysql.cj.NativeSession.execSQL(NativeSession.java:1150)

    at com.mysql.cj.jdbc.ConnectionImpl.commit(ConnectionImpl.java:801)

    at sun.reflect.GeneratedMethodAccessor115.invoke(Unknown Source)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

    at java.lang.reflect.Method.invoke(Method.java:498)

    at org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:126)

    at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108)

    at org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:81)

    at com.sun.proxy.$Proxy87.commit(Unknown Source)

    at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.commit(AbstractLogicalConnectionImplementor.java:80)

    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:232)

    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:65)

    at org.springframework.orm.hibernate5.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:582)

    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761)

    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730)

    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:487)

    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:291)

    ... 77 common frames omitted
</code>```

Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.

```<code>    at com.mysql.cj.protocol.FullReadInputStream.readFully(FullReadInputStream.java:67)

    at com.mysql.cj.protocol.a.SimplePacketReader.readHeader(SimplePacketReader.java:63)

    at com.mysql.cj.protocol.a.SimplePacketReader.readHeader(SimplePacketReader.java:45)

    at com.mysql.cj.protocol.a.TimeTrackingPacketReader.readHeader(TimeTrackingPacketReader.java:52)

    at com.mysql.cj.protocol.a.TimeTrackingPacketReader.readHeader(TimeTrackingPacketReader.java:41)

    at com.mysql.cj.protocol.a.MultiPacketReader.readHeader(MultiPacketReader.java:54)

    at com.mysql.cj.protocol.a.MultiPacketReader.readHeader(MultiPacketReader.java:44)

    at com.mysql.cj.protocol.a.NativeProtocol.readMessage(NativeProtocol.java:549)
</code>```

.
Any suggestion

答:
Not sure if I understand your issue fully, but it looks like your app was running fine, and then when the cluster had a failover, your app stopped working with a bunch of errors. </p>

<p>The stack traces that you have shared indicate that the app has detected connection closure, but is continuing to use the stale connections to open new transactions. Do you have logic to gracefully re-open connections if they end up getting closed? That is a common paradigm when interacting with databases that work with persisted connections. </p>

Body:
My java application is working fine and inserting data into Aurora-Mysql before failover after failover it gives error "Communication link failure".Ours is 2 node cluster of Aurora-Mysql.

Below is the error:
ould not open Hibernate Session for transaction; nested exception is org.hibernate.TransactionException: JDBC begin transaction failed:

    at org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:542)

    at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)

    at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:430)

    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)

    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)

    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)

    at com.sun.proxy.$Proxy104.save(Unknown Source)

    at com.wu.oneplatform.controller.OrderControllerImpl.saveOrderDetail(OrderControllerImpl.java:81)

    at sun.reflect.GeneratedMethodAccessor107.invoke(Unknown Source)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

    at java.lang.reflect.Method.invoke(Method.java:498)

    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)

    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)

    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)

    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)

    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)

    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)

    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)

    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)

    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)

    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)

    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)

    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)

    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)

    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)

    at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55)

    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)

    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:105)

    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)

    at com.wu.oneplatform.utils.tracing.JaegerFilter.doFilter(JaegerFilter.java:21)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)

    at com.wu.oneplatform.utils.logging.LoggerFilter.doFilter(LoggerFilter.java:30)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)

    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)

    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)

    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:89)

    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)

    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)

    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)

    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)

    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)

    at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:106)

    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)

    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)

    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)

    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)

    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)

    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)

    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)

    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)

    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)

    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)

    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)

    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)

    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)

    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)

    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)

    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)

    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)

    at java.lang.Thread.run(Thread.java:745)

Caused by: org.hibernate.TransactionException: JDBC begin transaction failed:

    at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.begin(AbstractLogicalConnectionImplementor.java:72)

    at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.begin(LogicalConnectionManagedImpl.java:238)

    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.begin(JdbcResourceLocalTransactionCoordinatorImpl.java:214)

    at org.hibernate.engine.transaction.internal.TransactionImpl.begin(TransactionImpl.java:52)

    at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1512)

    at org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:500)

    ... 80 common frames omitted

Caused by: java.sql.SQLNonTransientConnectionException: No operations allowed after connection closed.

    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:110)

    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)

    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)

    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)

    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73)

    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:73)

    at com.mysql.cj.jdbc.ConnectionImpl.setAutoCommit(ConnectionImpl.java:2074)

    at sun.reflect.GeneratedMethodAccessor109.invoke(Unknown Source)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

    at java.lang.reflect.Method.invoke(Method.java:498)

    at org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:126)

    at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108)

    at org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:81)

    at com.sun.proxy.$Proxy87.setAutoCommit(Unknown Source)

    at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.begin(AbstractLogicalConnectionImplementor.java:67)

    ... 85 common frames omitted

Caused by: com.mysql.cj.exceptions.ConnectionIsClosedException: No operations allowed after connection closed.

    at sun.reflect.GeneratedConstructorAccessor121.newInstance(Unknown Source)

    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)

    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)

    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)

    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105)

    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151)

    at com.mysql.cj.NativeSession.checkClosed(NativeSession.java:1259)

    at com.mysql.cj.jdbc.ConnectionImpl.checkClosed(ConnectionImpl.java:575)

    at com.mysql.cj.jdbc.ConnectionImpl.setAutoCommit(ConnectionImpl.java:2024)

    ... 93 common frames omitted

Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure

The last packet successfully received from the server was 86 milliseconds ago.  The last packet sent successfully to the server was 86 milliseconds ago.

    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)

    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)

    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)

    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)

    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105)

    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151)

    at com.mysql.cj.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:167)

    at com.mysql.cj.protocol.a.NativeProtocol.readMessage(NativeProtocol.java:555)

    at com.mysql.cj.protocol.a.NativeProtocol.checkErrorMessage(NativeProtocol.java:725)

    at com.mysql.cj.protocol.a.NativeProtocol.sendCommand(NativeProtocol.java:664)

    at com.mysql.cj.protocol.a.NativeProtocol.sendQueryPacket(NativeProtocol.java:979)

    at com.mysql.cj.protocol.a.NativeProtocol.sendQueryString(NativeProtocol.java:914)

    at com.mysql.cj.NativeSession.execSQL(NativeSession.java:1150)

    at com.mysql.cj.jdbc.ConnectionImpl.commit(ConnectionImpl.java:801)

    at sun.reflect.GeneratedMethodAccessor115.invoke(Unknown Source)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

    at java.lang.reflect.Method.invoke(Method.java:498)

    at org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:126)

    at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108)

    at org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:81)

    at com.sun.proxy.$Proxy87.commit(Unknown Source)

    at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.commit(AbstractLogicalConnectionImplementor.java:80)

    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:232)

    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:65)

    at org.springframework.orm.hibernate5.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:582)

    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761)

    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730)

    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:487)

    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:291)

    ... 77 common frames omitted

Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.

    at com.mysql.cj.protocol.FullReadInputStream.readFully(FullReadInputStream.java:67)

    at com.mysql.cj.protocol.a.SimplePacketReader.readHeader(SimplePacketReader.java:63)

    at com.mysql.cj.protocol.a.SimplePacketReader.readHeader(SimplePacketReader.java:45)

    at com.mysql.cj.protocol.a.TimeTrackingPacketReader.readHeader(TimeTrackingPacketReader.java:52)

    at com.mysql.cj.protocol.a.TimeTrackingPacketReader.readHeader(TimeTrackingPacketReader.java:41)

    at com.mysql.cj.protocol.a.MultiPacketReader.readHeader(MultiPacketReader.java:54)

    at com.mysql.cj.protocol.a.MultiPacketReader.readHeader(MultiPacketReader.java:44)

    at com.mysql.cj.protocol.a.NativeProtocol.readMessage(NativeProtocol.java:549)

.
Any suggestion

Body:
Not sure if I understand your issue fully, but it looks like your app was running fine, and then when the cluster had a failover, your app stopped working with a bunch of errors.

The stack traces that you have shared indicate that the app has detected connection closure, but is continuing to use the stale connections to open new transactions. Do you have logic to gracefully re-open connections if they end up getting closed? That is a common paradigm when interacting with databases that work with persisted connections.


问:
Updating colors of plot_model when I have only a single line?
I want to change the color of the plot outputted by plot_model. I have no trouble with these when I create multiple lines by including multiple variables in terms = c(..., ...), but I can't get the color to be anything other than black when I do the following code:

```<code>df_test <- data.frame('subj' = c('Joe', 'Joe', 'Moe', 'Moe'), 'A' = c(1, 0, 1, 0), 'B' = c(3, 2, 1, 4))

m = glmer(A ~ B + (B | subj), data=df_test, family='binomial')

print(plot_model(m, type='pred', colors = 'blue'))
</code>```

Output: https://imgur.com/a/pApsmH4

What am I missing here?

Thanks for the help

答:
To perform this action, I modified the structure for data.frame and I used ggplot2.

```<code>library(lme4)
library(ggplot2)
library(scales)
library(sjPlot)
df_test <- data.frame('subj' = c('Joe', 'Joe', 'Moe', 'Moe'), 'A' = c(1, 0, 1, 0), 'B' = c(3, 2, 1, 4))

m <- lme4::glmer(A ~ B + (B | subj), data=df_test, family='binomial')

p <- sjPlot::plot_model(m, type='pred', colors = 'blue')

df <- as.data.frame(p$B$data)
df
ggplot2::ggplot(df, aes(x = x)) +
  geom_ribbon(aes(ymin = conf.low, ymax = conf.high), fill = "grey70") +
  geom_line(aes(y = predicted), col = "blue") +
  scale_y_continuous(labels = scales::percent,
                     limits = c(0, 1))
</code>```

```<code>ggplot2::ggplot(df, aes(x = x)) +
  geom_ribbon(aes(ymin = conf.low, ymax = conf.high),
              fill = "deepskyblue", alpha = 0.25) +
  geom_line(aes(y = predicted), col = "darkred") +
  scale_y_continuous(labels = scales::percent,
                     limits = c(0, 1))
</code>```

Body:
I want to change the color of the plot outputted by plot_model. I have no trouble with these when I create multiple lines by including multiple variables in terms = c(..., ...), but I can't get the color to be anything other than black when I do the following code:

df_test <- data.frame('subj' = c('Joe', 'Joe', 'Moe', 'Moe'), 'A' = c(1, 0, 1, 0), 'B' = c(3, 2, 1, 4))

m = glmer(A ~ B + (B | subj), data=df_test, family='binomial')

print(plot_model(m, type='pred', colors = 'blue'))

Output: https://imgur.com/a/pApsmH4

What am I missing here?

Thanks for the help

Body:
To perform this action, I modified the structure for data.frame and I used ggplot2.

library(lme4)
library(ggplot2)
library(scales)
library(sjPlot)
df_test <- data.frame('subj' = c('Joe', 'Joe', 'Moe', 'Moe'), 'A' = c(1, 0, 1, 0), 'B' = c(3, 2, 1, 4))

m <- lme4::glmer(A ~ B + (B | subj), data=df_test, family='binomial')

p <- sjPlot::plot_model(m, type='pred', colors = 'blue')

df <- as.data.frame(p$B$data)
df
ggplot2::ggplot(df, aes(x = x)) +
  geom_ribbon(aes(ymin = conf.low, ymax = conf.high), fill = "grey70") +
  geom_line(aes(y = predicted), col = "blue") +
  scale_y_continuous(labels = scales::percent,
                     limits = c(0, 1))

ggplot2::ggplot(df, aes(x = x)) +
  geom_ribbon(aes(ymin = conf.low, ymax = conf.high),
              fill = "deepskyblue", alpha = 0.25) +
  geom_line(aes(y = predicted), col = "darkred") +
  scale_y_continuous(labels = scales::percent,
                     limits = c(0, 1))


问:
Is there an R function for subtracting values in a variable by group based on specified conditions?
I have a df that takes this general form:

ID    votes
1      65
1      85
2      100
2      20
2      95
3      50
3      60
```

<p>I want to create a new df that takes the two highest values in votes for each ID and shows their difference. The new df should look like this:</p>

<pre class="lang-r prettyprint-override"><code>ID    margin
1      20
2      5
3      10
</code>```

Is there a way to use dplyr for this?

答:
An option would be to be arrange by 'ID', 'votes' (either in descending or ascending), grouped by 'ID' and get the diff of the first two 'votes'

```<code>library(dplyr)
df1 %>%
    arrange(ID, desc(votes)) %>%
    group_by(ID) %>%
    summarise(margin = abs(diff(votes[1:2])))
# A tibble: 3 x 2
#     ID margin
#  <int>  <int>
#1     1     20
#2     2      5
#3     3     10
</code>```

Or another option is

```<code>df1 %>%
  group_by(ID) %>%
  summarise(margin = max(votes) - max(votes[-which.max(votes)]))
</code>```

Or with slice and diff

```<code>df1 %>%
   group_by(ID) %>%
   slice(row_number(votes)[1:2]) %>%
   summarise(margin = diff(votes))
</code>```

data

```<code>df1 <- structure(list(ID = c(1L, 1L, 2L, 2L, 2L, 3L, 3L), votes = c(65L,
85L, 100L, 20L, 95L, 50L, 60L)), class = "data.frame", row.names = c(NA,
-7L))
</code>```

Body:
I have a df that takes this general form:

ID    votes
1      65
1      85
2      100
2      20
2      95
3      50
3      60

I want to create a new df that takes the two highest values in votes for each ID and shows their difference. The new df should look like this:

ID    margin
1      20
2      5
3      10

Is there a way to use dplyr for this?

Body:
An option would be to be arrange by 'ID', 'votes' (either in descending or ascending), grouped by 'ID' and get the diff of the first two 'votes'

library(dplyr)
df1 %>%
    arrange(ID, desc(votes)) %>%
    group_by(ID) %>%
    summarise(margin = abs(diff(votes[1:2])))
# A tibble: 3 x 2
#     ID margin
#  <int>  <int>
#1     1     20
#2     2      5
#3     3     10

Or another option is

df1 %>%
  group_by(ID) %>%
  summarise(margin = max(votes) - max(votes[-which.max(votes)]))

Or with slice and diff

df1 %>%
   group_by(ID) %>%
   slice(row_number(votes)[1:2]) %>%
   summarise(margin = diff(votes))

data

df1 <- structure(list(ID = c(1L, 1L, 2L, 2L, 2L, 3L, 3L), votes = c(65L,
85L, 100L, 20L, 95L, 50L, 60L)), class = "data.frame", row.names = c(NA,
-7L))


问:
Subnet not appearing when creating AuroraDB
I've created a VPC.  By default the VPC created one public and one private subnet.  I've created an additional private subnet in a different availability zone.

I then (in the ElasticCache console) created a new subnet group that contains these two private subnets from the VPC.  This subnet group is also associated, of course, with the VPC.

Then, on creating an Aurora RDS within this VPC, it asks for a subnet group.  There's one there, a 'default' group, but my new subnet group doesn't appear.

How do I create a subnet group that is acceptable when creating a database?

答:
ElasticCache and RDS are different types of product groups. Their SubnetGroups are different entities and they don't over lap with each other. You would need to create subnet groups in RDS to use it with RDS engines (database engines). They are not tied to any db engine, so you can re-use them within RDS. </p>

<p>One additional thing to note is that some other Database productions like Amazon Neptune and Amazon DocDB are able to access your RDS subnet groups as well. Just an FYI. </p>

Body:
ElasticCache and RDS are different types of product groups. Their SubnetGroups are different entities and they don't over lap with each other. You would need to create subnet groups in RDS to use it with RDS engines (database engines). They are not tied to any db engine, so you can re-use them within RDS.

One additional thing to note is that some other Database productions like Amazon Neptune and Amazon DocDB are able to access your RDS subnet groups as well. Just an FYI.


Title: How to decode encoded text from a web page

Body:
I have an API page of my school site and I want to parse the data from it but the page looks like this and I don't know how to decode this text using python.
(The encoded letters are cyryllic)

The data from the page(it looks like this even in the browser):

\u0421\u0434\u0430\u0442\u044c \u043f\u043e\u0441\u043b\u0435 \u043a\u0430\u043d\u0438\u043a\u0443\u043b, 15 \u0430\u043f\u0440\u0435\u043b\u044f.
\r\n\u0423\u0431\u0435\u0434\u0438\u0442\u0435\u043b\u044c\u043d\u0430\u044f \u043f\u0440\u043e\u0441\u044c\u0431\u0430 \u043e\u0444\u043e\u0440\u043c\u043b\u044f\u0442\u044c \u0440\u0435\u0448\u0435\u043d\u0438\u0435 "\u043a\u0430\u043a \u043f\u043e\u043b\u043e\u0436\u0435\u043d\u043e" \u0432 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u0438 \u0441 \u0442\u0435\u043c "\u043a\u0430\u043a \u0443\u0447\u0438\u043b\u0438", \u0430 \u043d\u0435 \u0442\u0430\u043a, \u0431\u0443\u0434\u0442\u043e \u0431\u044b \u0432\u044b \u0435\u0433\u043e \u043d\u0430 \u043a\u043e\u043b\u0435\u043d\u043a\u0435 \u0437\u0430 5 \u043c\u0438\u043d\u0443\u0442 \u043f\u0435\u0440\u0435\u0434 \u0441\u0434\u0430\u0447\u0435\u0439 \u0434\u0435\u043b\u0430\u043b\u0438. \u041f\u0438\u0441\u0430\u0442\u044c \u0440\u0430\u0437\u0431\u043e\u0440\u0447\u0438\u0432\u043e \u0438 \u0430\u043a\u043a\u0443\u0440\u0430\u0442\u043d\u043e.

The data that I want to get:

Сдать после каникул, 15 апреля.
\r\nУбедительная просьба оформлять решение "как положено" в соответствии с тем "как учили", а не так, будто бы вы его на коленке за 5 минут перед сдачей делали. Писать разборчиво и аккуратно.

Body:
Prepared by @APIuz team

#For python3

import json
import io
text = '\u0421\u0434\u0430\u0442\u044c \u043f\u043e\u0441\u043b\u0435 \u043a\u0430\u043d\u0438\u043a\u0443\u043b, 15 \u0430\u043f\u0440\u0435\u043b\u044f.&nbsp;<br />\r\n\u0423\u0431\u0435\u0434\u0438\u0442\u0435\u043b\u044c\u043d\u0430\u044f \u043f\u0440\u043e\u0441\u044c\u0431\u0430 \u043e\u0444\u043e\u0440\u043c\u043b\u044f\u0442\u044c \u0440\u0435\u0448\u0435\u043d\u0438\u0435 &quot;\u043a\u0430\u043a \u043f\u043e\u043b\u043e\u0436\u0435\u043d\u043e&quot; \u0432 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u0438 \u0441 \u0442\u0435\u043c &quot;\u043a\u0430\u043a \u0443\u0447\u0438\u043b\u0438&quot;, \u0430 \u043d\u0435 \u0442\u0430\u043a, \u0431\u0443\u0434\u0442\u043e \u0431\u044b \u0432\u044b \u0435\u0433\u043e \u043d\u0430 \u043a\u043e\u043b\u0435\u043d\u043a\u0435 \u0437\u0430 5 \u043c\u0438\u043d\u0443\u0442 \u043f\u0435\u0440\u0435\u0434 \u0441\u0434\u0430\u0447\u0435\u0439 \u0434\u0435\u043b\u0430\u043b\u0438. \u041f\u0438\u0441\u0430\u0442\u044c \u0440\u0430\u0437\u0431\u043e\u0440\u0447\u0438\u0432\u043e \u0438 \u0430\u043a\u043a\u0443\u0440\u0430\u0442\u043d\u043e.'

io.open("APIuz.txt", "w", encoding="utf-8").write(json.dumps(text, ensure_ascii=False))
print(open("APIuz.txt", "r").read())

#For python2

print(repr(u'\u0421\u0434\u0430\u0442\u044c \u043f\u043e\u0441\u043b\u0435 \u043a\u0430\u043d\u0438\u043a\u0443\u043b, 15 \u0430\u043f\u0440\u0435\u043b\u044f.&nbsp;<br />\r\n\u0423\u0431\u0435\u0434\u0438\u0442\u0435\u043b\u044c\u043d\u0430\u044f \u043f\u0440\u043e\u0441\u044c\u0431\u0430 \u043e\u0444\u043e\u0440\u043c\u043b\u044f\u0442\u044c \u0440\u0435\u0448\u0435\u043d\u0438\u0435 &quot;\u043a\u0430\u043a \u043f\u043e\u043b\u043e\u0436\u0435\u043d\u043e&quot; \u0432 \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u0438 \u0441 \u0442\u0435\u043c &quot;\u043a\u0430\u043a \u0443\u0447\u0438\u043b\u0438&quot;, \u0430 \u043d\u0435 \u0442\u0430\u043a, \u0431\u0443\u0434\u0442\u043e \u0431\u044b \u0432\u044b \u0435\u0433\u043e \u043d\u0430 \u043a\u043e\u043b\u0435\u043d\u043a\u0435 \u0437\u0430 5 \u043c\u0438\u043d\u0443\u0442 \u043f\u0435\u0440\u0435\u0434 \u0441\u0434\u0430\u0447\u0435\u0439 \u0434\u0435\u043b\u0430\u043b\u0438. \u041f\u0438\u0441\u0430\u0442\u044c \u0440\u0430\u0437\u0431\u043e\u0440\u0447\u0438\u0432\u043e \u0438 \u0430\u043a\u043a\u0443\u0440\u0430\u0442\u043d\u043e.').decode('unicode-escape'))

#The code is just what you think

#>>> u'Сдать после каникул, 15 апреля.&nbsp;<br /> Убедительная просьба оформлять решение &quot;как положено&quot; в соответствии с тем &quot;как учили&quot;, а не так, будто бы вы его на коленке за 5 минутперед сдачей делали. Писать разборчиво и аккуратно.'


问:
Finding ordered array in an ordered array
```<code>c = [-1, 0, 1, 2, 3, 4]
d = [-1,0,2,3,4,5,6]
a = [-1, 1, 6, 8, 9, 12]
main = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
</code>```

desired output:

```<code>fc = [-1,0,1,2,3],[0,1,2,3,4]
fd = [2,3,4,5,6]
fa = []
</code>```

I want to find how many times the ordered set is in the larger set given an interval. In my case, I choose 5 since this is for my poker game. Set's won't work since they need to be in order so I don't know what to use.

In my program, I tried using for loops but I'm not getting it.

```<code>ns = len(c)-5
nt = range(0,ns)
if ns >= 0:
    for n in nt:
        templist = c[n:n+5]
</code>```

I just need a function to compare both lists.

答:
Here is a function that I made that might help you. You can pass your list as an argument and it will compare the lists. </p>

```<code>main_set = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
c = [-1, 0, 1, 2, 3, 4]

def compare(cmp_array):
  new_arrays = []
  temp = []
  for pos, i in enumerate(cmp_array):
        for i2 in range(pos, pos+5):
              temp.append(cmp_array[i2])
        new_arrays.append(temp)
        temp = []
        if pos >= len(cmp_array)-5:
              break
  return_arrays = []
  for array in new_arrays:
        for pos, i in enumerate(main_set):
              match = True
              if i == array[0]:
                    for pos2 in range(pos, pos+5):
                          if array[pos2-pos] != main_set[pos2]:
                                match = False
                                break
                    if match:
                          return_arrays.append(array)
  return return_arrays

fc = compare(c)

print(fc)
</code>```

Body:
c = [-1, 0, 1, 2, 3, 4]
d = [-1,0,2,3,4,5,6]
a = [-1, 1, 6, 8, 9, 12]
main = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

desired output:

fc = [-1,0,1,2,3],[0,1,2,3,4]
fd = [2,3,4,5,6]
fa = []

I want to find how many times the ordered set is in the larger set given an interval. In my case, I choose 5 since this is for my poker game. Set's won't work since they need to be in order so I don't know what to use.

In my program, I tried using for loops but I'm not getting it.

ns = len(c)-5
nt = range(0,ns)
if ns >= 0:
    for n in nt:
        templist = c[n:n+5]

I just need a function to compare both lists.

Body:
Here is a function that I made that might help you. You can pass your list as an argument and it will compare the lists.

main_set = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
c = [-1, 0, 1, 2, 3, 4]

def compare(cmp_array):
  new_arrays = []
  temp = []
  for pos, i in enumerate(cmp_array):
        for i2 in range(pos, pos+5):
              temp.append(cmp_array[i2])
        new_arrays.append(temp)
        temp = []
        if pos >= len(cmp_array)-5:
              break
  return_arrays = []
  for array in new_arrays:
        for pos, i in enumerate(main_set):
              match = True
              if i == array[0]:
                    for pos2 in range(pos, pos+5):
                          if array[pos2-pos] != main_set[pos2]:
                                match = False
                                break
                    if match:
                          return_arrays.append(array)
  return return_arrays

fc = compare(c)

print(fc)