问:
Right way to update state with react socket hooks
I am a beginner to react and I feel this question has been asked several times in the past but I can't see to understand what I am missing to get this working.

I am writing a simple browser based game. I am using socket-io to connect to the server and I am using a custom hook for obtaining state sent by the server

```<code>  export const useSocketState = (serverUrl: string) => {
    const [isConnected, setConnected] = useState(false)
    const [socketId, setSocketId] = useState('')
    const [gameState, setGameState] = useState(DEFAULT_INITIAL_STATE)
    useEffect(() => {
      const client = socket.connect(serverUrl)
      client.on("connect", () => {
        console.log("connected with id " + client.id)
        setConnected(true)
        setSocketId(client.id)
      });
      client.on("disconnect", () => {
        setConnected(false)
      });
      client.on("gameStateUpdate", (data: ClientGameState) => {
        console.dir("Recieved new state from server" + data);
        console.dir("GameState is " + gameState);
        setGameState(prevState => {
          const newState = data
          console.log(" new state is " + newState)
          return newState
        })
      });
    }, gameState);

    return {gameState, isConnected, socketId}
  }
</code>```

I am using this hook in a component where I am referrring to the gameState returned by this hook.

I am expecting that when server sends a new state my gameState is actually set with a new state. I do see the log statement where a newState is printed when the server returns a new state but I am not seeing it being reflected in the component I am using.

```<code>Game component

  import React from "react";
  import {useSocketState} from "./useSocket";
  import {ClientGameState} from "../game/GameState";

  export function GameComponent(props: any) {
  const {gameState, isConnected, socketId} = useSocketState("http://127.0.0.1:8080");

    if (gameState.state === 'created') {
      return (

        <div>
          <p> Game id for this game: {props.location.state.gameId} and playerId:  {props.location.state.playerId} </p>
          <p>{JSON.stringify(gameState)}</p>
        </div>

      );
    } else {
      return (
        <div>
          <p> Game state is not created </p>
        </div>
      )
    }
  }
</code>```

答:
How about just passing the data that is returned from the socket to your setGameState hook. </p>

```<code>client.on("gameStateUpdate", (data: ClientGameState) => {
    setGameState(data);
  });
</code>```

Body:
I am a beginner to react and I feel this question has been asked several times in the past but I can't see to understand what I am missing to get this working.

I am writing a simple browser based game. I am using socket-io to connect to the server and I am using a custom hook for obtaining state sent by the server

  export const useSocketState = (serverUrl: string) => {
    const [isConnected, setConnected] = useState(false)
    const [socketId, setSocketId] = useState('')
    const [gameState, setGameState] = useState(DEFAULT_INITIAL_STATE)
    useEffect(() => {
      const client = socket.connect(serverUrl)
      client.on("connect", () => {
        console.log("connected with id " + client.id)
        setConnected(true)
        setSocketId(client.id)
      });
      client.on("disconnect", () => {
        setConnected(false)
      });
      client.on("gameStateUpdate", (data: ClientGameState) => {
        console.dir("Recieved new state from server" + data);
        console.dir("GameState is " + gameState);
        setGameState(prevState => {
          const newState = data
          console.log(" new state is " + newState)
          return newState
        })
      });
    }, gameState);

    return {gameState, isConnected, socketId}
  }

I am using this hook in a component where I am referrring to the gameState returned by this hook.

I am expecting that when server sends a new state my gameState is actually set with a new state. I do see the log statement where a newState is printed when the server returns a new state but I am not seeing it being reflected in the component I am using.

Game component

  import React from "react";
  import {useSocketState} from "./useSocket";
  import {ClientGameState} from "../game/GameState";

  export function GameComponent(props: any) {
  const {gameState, isConnected, socketId} = useSocketState("http://127.0.0.1:8080");

    if (gameState.state === 'created') {
      return (

 Game id for this game: {props.location.state.gameId} and playerId:  {props.location.state.playerId}

{JSON.stringify(gameState)}

      );
    } else {
      return (

 Game state is not created

      )
    }
  }

Body:
How about just passing the data that is returned from the socket to your setGameState hook.

client.on("gameStateUpdate", (data: ClientGameState) => {
    setGameState(data);
  });


来源: stackexchange

问:
How to search in multiple columns using the like operator in slick?
I want to get all users from the database that have the word foo either in their username or in their email address. How is this written in Slick 3.x?

```<code>select * from users where username like '%foo%' or email like '%foo%';
</code>```

答:
If you have defined a user table, then using the tablequery object of user, you can do it by doing the following:

```<code>// select * from users where username like '%foo%' or email like '%foo%';
users.filter(e => e.username like '%foo%' || e.email like '%foo%').result
</code>```

And if you run the above DBIOAction, then you will get the expected result.

http://scala-slick.org/doc/3.3.1/queries.html#sorting-and-filtering

ContentLicense: CC BY-SA 4.0

Body:
I want to get all users from the database that have the word foo either in their username or in their email address. How is this written in Slick 3.x?

select * from users where username like '%foo%' or email like '%foo%';

Body:
If you have defined a user table, then using the tablequery object of user, you can do it by doing the following:

// select * from users where username like '%foo%' or email like '%foo%';
users.filter(e => e.username like '%foo%' || e.email like '%foo%').result

And if you run the above DBIOAction, then you will get the expected result.

http://scala-slick.org/doc/3.3.1/queries.html#sorting-and-filtering


问:
http post sends wrong data
i have create a simple input form/fields with tkinter
what i wanted was to send the entered information to a webserver
this is the code :

```<code>import tkinter as tk
from tkinter import *
import requests
API_ENDPOINT = "http://123.123.123.12"

def send_req():
    r = requests.post(url = API_ENDPOINT, data = data)
    # extracting response text
    pastebin_url = r.text
    print("The pastebin URL is:%s"%pastebin_url)

    e1.delete(0, tk.END)
    e2.delete(0, tk.END)
    e3.delete(0, tk.END)
    e4.delete(0, tk.END)
master = tk.Tk()
tk.Label(master, text="first name").grid(row=0)
tk.Label(master, text="last name").grid(row=1)
tk.Label(master, text="Add").grid(row=2)
tk.Label(master, text="Phone").grid(row=3)

e1 = tk.Entry(master)
e2 = tk.Entry(master)
e3 = tk.Entry(master)
e4 = tk.Entry(master)

e1.insert(10, "")
e2.insert(10, "")
e3.insert(10, "")
e4.insert(10, "")

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)
e4.grid(row=3, column=1)
data = {'key1': e1,
                'key2':e2,
                'key3':e3,
                'key4':e4}

tk.Button(master, text='send',command=send_req).grid(row=4,column=1, sticky=tk.W, pady=5,)

master.mainloop()

tk.mainloop()
</code>```

and no matter what i enter into the fields at the client end, i always get this at server side instead of the fields data:

答:
Clearly there is issue with the code.
First, you should pass data as argument to send_req

Second, you are assigning key1 to e1 which is a tkinter Entry object not a text.

I believe you want to send text from Text field.
So you need to do this:

```<code>data = {'key1': e1.get(),
                'key2':e2.get(),
                'key3':e3.get(),
                'key4':e4.get()}
</code>```

Hope this helps.

Title: http post sends wrong data

Body:
i have create a simple input form/fields with tkinter
what i wanted was to send the entered information to a webserver
this is the code :

import tkinter as tk
from tkinter import *
import requests
API_ENDPOINT = "http://123.123.123.12"

def send_req():
    r = requests.post(url = API_ENDPOINT, data = data)
    # extracting response text
    pastebin_url = r.text
    print("The pastebin URL is:%s"%pastebin_url)

    e1.delete(0, tk.END)
    e2.delete(0, tk.END)
    e3.delete(0, tk.END)
    e4.delete(0, tk.END)
master = tk.Tk()
tk.Label(master, text="first name").grid(row=0)
tk.Label(master, text="last name").grid(row=1)
tk.Label(master, text="Add").grid(row=2)
tk.Label(master, text="Phone").grid(row=3)

e1 = tk.Entry(master)
e2 = tk.Entry(master)
e3 = tk.Entry(master)
e4 = tk.Entry(master)

e1.insert(10, "")
e2.insert(10, "")
e3.insert(10, "")
e4.insert(10, "")

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)
e4.grid(row=3, column=1)
data = {'key1': e1,
                'key2':e2,
                'key3':e3,
                'key4':e4}

tk.Button(master, text='send',command=send_req).grid(row=4,column=1, sticky=tk.W, pady=5,)

master.mainloop()

tk.mainloop()

and no matter what i enter into the fields at the client end, i always get this at server side instead of the fields data:

Body:
Clearly there is issue with the code.
First, you should pass data as argument to send_req

Second, you are assigning key1 to e1 which is a tkinter Entry object not a text.

I believe you want to send text from Text field.
So you need to do this:

data = {'key1': e1.get(),
                'key2':e2.get(),
                'key3':e3.get(),
                'key4':e4.get()}

Hope this helps.


问:
Need a delay to wait for GPS
Using the iPhone and objective C, is there a way to stall or perform a timing loop to allow for the GPS to catch up and return a valid set of coordinates?

Currently, the application runs too quickly and the GPS cannot supply the coordinates fast enough...

答: Since you said you're on iPhone, you're using CLLocationManager. Just set a delegate on the manager and wait for the locationManager:didUpdateToLocation:fromLocation: message to know when the GPS data is ready.

ContentLicense: CC BY-SA 3.0

Title: Need a delay to wait for GPS


问:
multiline grok pattern matched to multiple single lines inside kibana
I am trying to setup the sebp/elk docker container to run the ELK stack on my machine.
Goal is to use ELK to log/parse/search through log files like access/error logs for apache as well as logging php error logs that occur during php execution (which are multiline errors with stack traces).

An example of a php error log file I try to parse is:

```<code>[03-Jun-2020 00:39:11 Europe/Berlin] PHP Stack trace:
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   1. {main}() /var/www/myserver.domain/html/index.php:0
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   2. require() /var/www/myserver.domain/html/index.php:17
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   3. require_once() /var/www/myserver.domain/html/wp-blog-header.php:16
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   4. include() /var/www/myserver.domain/html/wp-includes/template-loader.php:27
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   5. the_content() /var/www/myserver.domain/html/wp-content/themes/summer_freedom/index.php:20
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   6. apply_filters() /var/www/myserver.domain/html/wp-includes/post-template.php:79
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   7. call_user_func_array:{/var/www/myserver.domain/html/wp-includes/plugin.php:163}() /var/www/myserver.domain/html/wp-includes/plugin.php:163
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   8. searchnggallerytags() /var/www/myserver.domain/html/wp-includes/plugin.php:163
</code>```

I use filebeat to send the log from my local machine to my logstash container with the following filebeat.yml config:

```<code>  logstash:
    enabled: true
    hosts:
      - localhost:5044
    ssl:
      certificate_authorities:
        - /etc/filebeat/logstash-beats.crt
    timeout: 15

filebeat:
  prospectors:

    -
      paths:
        - /var/log/php/php_errors.log
      document_type: php-errors
</code>```

the logstash configuration that I came up with for inside the elk container so far is the following:

```<code>input {
    stdin {
        codec => multiline {
            pattern => "^\[%{MONTHDAY}-%{MONTH}-%{YEAR} %{TIME} (?<tzname>[a-zA-Z]+/[a-zA-Z]+)\]"
            negate => true
            what => "previous"
            auto_flush_interval => 10
        }
        type => "php-errors"
    }
}

filter {
  if [type] == "php-errors" {
    grok {
        match => { "message" => "(?m)\[(?<logtime>%{MONTHDAY}-%{MONTH}-%{YEAR} %{TIME} (?<tzname>[a-zA-Z]+/[a-zA-Z]+))\] ?%{GREEDYDATA:message}" }
        overwrite => [ "message" ]
    }

    date {
        match => [ "logtime", "dd-MMM-yyyy HH:mm:ss" ]
        remove_field => [ "logtime" ]
    }
  }
}

output {
    stdout {
        codec => rubydebug
    }
}
</code>```

In the beginning I was not sure if the pattern would really match, so I used the grok debugger inside kibana to double check it would be correct and really match against the input in the log file.

When using this configuration inside logstash in the sebp/elk container, I can see entries in kibana, so the general transfer via filebeat works and logstash is able to match the data as well.
Unfortunately I get a message inside kibana for every line in the php errors log file, although I would like to have all the lines that belong to each other are concatenated and stored as one event inside elk.

As far as I understood the grok patterns here, logstash should use the same timestamp in every line and match multiline to write all the lines in one message instead of creating several events.

So the question is, if I just use the configuration wrong, or if there is anything missing so i will get only 1 event instead of multiple ones.

Update:
as requested by @leandrojmp, i updated the logstash configuration as suggested but still got the following output for every line out of the php-error.log from logstash on stdout when running on cli:

```<code>{
          "host" => {
        "name" => "myserver.domain"
    },
      "@version" => "1",
    "@timestamp" => 2020-06-03T21:54:53.886Z,
       "message" => "[03-Jun-2020 23:54:49 Europe/Berlin] PHP   1. {main}() /var/www/myserver.domain/html/index.php:0",
          "beat" => {
         "version" => "6.4.3",
        "hostname" => "myserver.domain",
            "name" => "myserver.domain"
    },
          "tags" => [
        [0] "beats_input_codec_plain_applied"
    ],
        "offset" => 15896045,
        "source" => "/var/log/php/php_errors.log"
}
</code>```

so it looks like the multiline matching is not working inside logstash for me.

update 2:
after some more research i found out that it is not recommended to match multiline content inside logstash, since it might end up mixing different logs into one message if you send multiple logs from different machines to one logstash instance.
The suggested way to go is use filebeat.yml to merge multiline messages before sending them to logstash.

答:
Your multiline pattern is not right, it makes every line that does not match it to be considered part of a multiline event (the negate option) and included in the previous event (the what option), but in your example every line starts with the same pattern, so you will never have a multiline event.

Your pattern needs to match something that is unique to the start of your multiline event, in your case it could be the "PHP Stack trace" string

Changing your multiline pattern to this one:

```<code>codec => multiline {
    pattern => "PHP Stack trace"
    negate => true
    what => "previous"
}
</code>```

This would give you the following result:

```<code>{
      "@version" => "1",
          "tags" => [
        [0] "multiline"
    ],
    "@timestamp" => 2020-06-02T22:39:11.000Z,
        "tzname" => "Europe/Berlin",
          "type" => "php-errors",
       "message" => "PHP Stack trace:\n[03-Jun-2020 00:39:11 Europe/Berlin] PHP   1. {main}() /var/www/myserver.domain/html/index.php:0\n[03-Jun-2020 00:39:11 Europe/Berlin] PHP   2. require() /var/www/myserver.domain/html/index.php:17\n[03-Jun-2020 00:39:11 Europe/Berlin] PHP   3. require_once() /var/www/myserver.domain/html/wp-blog-header.php:16\n[03-Jun-2020 00:39:11 Europe/Berlin] PHP   4. include() /var/www/myserver.domain/html/wp-includes/template-loader.php:27\n[03-Jun-2020 00:39:11 Europe/Berlin] PHP   5. the_content() /var/www/myserver.domain/html/wp-content/themes/summer_freedom/index.php:20\n[03-Jun-2020 00:39:11 Europe/Berlin] PHP   6. apply_filters() /var/www/myserver.domain/html/wp-includes/post-template.php:79\n[03-Jun-2020 00:39:11 Europe/Berlin] PHP   7. call_user_func_array:{/var/www/myserver.domain/html/wp-includes/plugin.php:163}() /var/www/myserver.domain/html/wp-includes/plugin.php:163\n[03-Jun-2020 00:39:11 Europe/Berlin] PHP   8. searchnggallerytags() /var/www/myserver.domain/html/wp-includes/plugin.php:163",
          "host" => "logstash"
}
</code>```

See that now all your lines are in the same event and in kibana you will have something like this in the message field:

```<code>PHP Stack trace:
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   1. {main}() /var/www/myserver.domain/html/index.php:0\n[03-Jun-2020 00:39:11 Europe/Berlin] PHP   2. require() /var/www/myserver.domain/html/index.php:17
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   3. require_once() /var/www/myserver.domain/html/wp-blog-header.php:16
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   4. include() /var/www/myserver.domain/html/wp-includes/template-loader.php:27
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   5. the_content() /var/www/myserver.domain/html/wp-content/themes/summer_freedom/index.php:20
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   6. apply_filters() /var/www/myserver.domain/html/wp-includes/post-template.php:79
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   7. call_user_func_array:{/var/www/myserver.domain/html/wp-includes/plugin.php:163}() /var/www/myserver.domain/html/wp-includes/plugin.php:163
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   8. searchnggallerytags() /var/www/myserver.domain/html/wp-includes/plugin.php:163
</code>```

Also, you need to fix your date filter, your timestamp has timezone information, you need to add it to the pattern.

The correct one would be:

```<code>date {
    match => [ "logtime", "dd-MMM-yyyy HH:mm:ss ZZZ" ]
    remove_field => [ "logtime" ]
}
</code>```

Body:
I am trying to setup the sebp/elk docker container to run the ELK stack on my machine.
Goal is to use ELK to log/parse/search through log files like access/error logs for apache as well as logging php error logs that occur during php execution (which are multiline errors with stack traces).

An example of a php error log file I try to parse is:

[03-Jun-2020 00:39:11 Europe/Berlin] PHP Stack trace:
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   1. {main}() /var/www/myserver.domain/html/index.php:0
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   2. require() /var/www/myserver.domain/html/index.php:17
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   3. require_once() /var/www/myserver.domain/html/wp-blog-header.php:16
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   4. include() /var/www/myserver.domain/html/wp-includes/template-loader.php:27
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   5. the_content() /var/www/myserver.domain/html/wp-content/themes/summer_freedom/index.php:20
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   6. apply_filters() /var/www/myserver.domain/html/wp-includes/post-template.php:79
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   7. call_user_func_array:{/var/www/myserver.domain/html/wp-includes/plugin.php:163}() /var/www/myserver.domain/html/wp-includes/plugin.php:163
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   8. searchnggallerytags() /var/www/myserver.domain/html/wp-includes/plugin.php:163

I use filebeat to send the log from my local machine to my logstash container with the following filebeat.yml config:

  logstash:
    enabled: true
    hosts:
      - localhost:5044
    ssl:
      certificate_authorities:
        - /etc/filebeat/logstash-beats.crt
    timeout: 15

filebeat:
  prospectors:

    -
      paths:
        - /var/log/php/php_errors.log
      document_type: php-errors

the logstash configuration that I came up with for inside the elk container so far is the following:

input {
    stdin {
        codec => multiline {
            pattern => "^\[%{MONTHDAY}-%{MONTH}-%{YEAR} %{TIME} (?<tzname>[a-zA-Z]+/[a-zA-Z]+)\]"
            negate => true
            what => "previous"
            auto_flush_interval => 10
        }
        type => "php-errors"
    }
}

filter {
  if [type] == "php-errors" {
    grok {
        match => { "message" => "(?m)\[(?<logtime>%{MONTHDAY}-%{MONTH}-%{YEAR} %{TIME} (?<tzname>[a-zA-Z]+/[a-zA-Z]+))\] ?%{GREEDYDATA:message}" }
        overwrite => [ "message" ]
    }

    date {
        match => [ "logtime", "dd-MMM-yyyy HH:mm:ss" ]
        remove_field => [ "logtime" ]
    }
  }
}

output {
    stdout {
        codec => rubydebug
    }
}

In the beginning I was not sure if the pattern would really match, so I used the grok debugger inside kibana to double check it would be correct and really match against the input in the log file.

When using this configuration inside logstash in the sebp/elk container, I can see entries in kibana, so the general transfer via filebeat works and logstash is able to match the data as well.
Unfortunately I get a message inside kibana for every line in the php errors log file, although I would like to have all the lines that belong to each other are concatenated and stored as one event inside elk.

As far as I understood the grok patterns here, logstash should use the same timestamp in every line and match multiline to write all the lines in one message instead of creating several events.

So the question is, if I just use the configuration wrong, or if there is anything missing so i will get only 1 event instead of multiple ones.

Update:
as requested by @leandrojmp, i updated the logstash configuration as suggested but still got the following output for every line out of the php-error.log from logstash on stdout when running on cli:

{
          "host" => {
        "name" => "myserver.domain"
    },
      "@version" => "1",
    "@timestamp" => 2020-06-03T21:54:53.886Z,
       "message" => "[03-Jun-2020 23:54:49 Europe/Berlin] PHP   1. {main}() /var/www/myserver.domain/html/index.php:0",
          "beat" => {
         "version" => "6.4.3",
        "hostname" => "myserver.domain",
            "name" => "myserver.domain"
    },
          "tags" => [
        [0] "beats_input_codec_plain_applied"
    ],
        "offset" => 15896045,
        "source" => "/var/log/php/php_errors.log"
}

so it looks like the multiline matching is not working inside logstash for me.

update 2:
after some more research i found out that it is not recommended to match multiline content inside logstash, since it might end up mixing different logs into one message if you send multiple logs from different machines to one logstash instance.
The suggested way to go is use filebeat.yml to merge multiline messages before sending them to logstash.

Body:
Your multiline pattern is not right, it makes every line that does not match it to be considered part of a multiline event (the negate option) and included in the previous event (the what option), but in your example every line starts with the same pattern, so you will never have a multiline event.

Your pattern needs to match something that is unique to the start of your multiline event, in your case it could be the "PHP Stack trace" string

Changing your multiline pattern to this one:

codec => multiline {
    pattern => "PHP Stack trace"
    negate => true
    what => "previous"
}

This would give you the following result:

{
      "@version" => "1",
          "tags" => [
        [0] "multiline"
    ],
    "@timestamp" => 2020-06-02T22:39:11.000Z,
        "tzname" => "Europe/Berlin",
          "type" => "php-errors",
       "message" => "PHP Stack trace:\n[03-Jun-2020 00:39:11 Europe/Berlin] PHP   1. {main}() /var/www/myserver.domain/html/index.php:0\n[03-Jun-2020 00:39:11 Europe/Berlin] PHP   2. require() /var/www/myserver.domain/html/index.php:17\n[03-Jun-2020 00:39:11 Europe/Berlin] PHP   3. require_once() /var/www/myserver.domain/html/wp-blog-header.php:16\n[03-Jun-2020 00:39:11 Europe/Berlin] PHP   4. include() /var/www/myserver.domain/html/wp-includes/template-loader.php:27\n[03-Jun-2020 00:39:11 Europe/Berlin] PHP   5. the_content() /var/www/myserver.domain/html/wp-content/themes/summer_freedom/index.php:20\n[03-Jun-2020 00:39:11 Europe/Berlin] PHP   6. apply_filters() /var/www/myserver.domain/html/wp-includes/post-template.php:79\n[03-Jun-2020 00:39:11 Europe/Berlin] PHP   7. call_user_func_array:{/var/www/myserver.domain/html/wp-includes/plugin.php:163}() /var/www/myserver.domain/html/wp-includes/plugin.php:163\n[03-Jun-2020 00:39:11 Europe/Berlin] PHP   8. searchnggallerytags() /var/www/myserver.domain/html/wp-includes/plugin.php:163",
          "host" => "logstash"
}

See that now all your lines are in the same event and in kibana you will have something like this in the message field:

PHP Stack trace:
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   1. {main}() /var/www/myserver.domain/html/index.php:0\n[03-Jun-2020 00:39:11 Europe/Berlin] PHP   2. require() /var/www/myserver.domain/html/index.php:17
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   3. require_once() /var/www/myserver.domain/html/wp-blog-header.php:16
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   4. include() /var/www/myserver.domain/html/wp-includes/template-loader.php:27
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   5. the_content() /var/www/myserver.domain/html/wp-content/themes/summer_freedom/index.php:20
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   6. apply_filters() /var/www/myserver.domain/html/wp-includes/post-template.php:79
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   7. call_user_func_array:{/var/www/myserver.domain/html/wp-includes/plugin.php:163}() /var/www/myserver.domain/html/wp-includes/plugin.php:163
[03-Jun-2020 00:39:11 Europe/Berlin] PHP   8. searchnggallerytags() /var/www/myserver.domain/html/wp-includes/plugin.php:163

Also, you need to fix your date filter, your timestamp has timezone information, you need to add it to the pattern.

The correct one would be:

date {
    match => [ "logtime", "dd-MMM-yyyy HH:mm:ss ZZZ" ]
    remove_field => [ "logtime" ]
}


问:
Join Tables and Select as List of KeyValuePairs
with one having a reference to the other in a one-to-many relationship

Here's a simplified version of the two tables (don't know how to format the tables to look pretty sorry...):

Table A:
Id

Table B: TableAId(FK), Key, Value

When I retrieve the values using a LINQ join I need the values in the referenced table transformed into a list of keyvaluepairs.
So the example answer I'm looking for is:

```<code>{
   Id : 1,
   Data:
   [
      {
         key : key1,
         value : valu1
      },
      {
         key : key2,
         value : value2
      }
   ]
}
</code>```

Here's what my current LINQ looks like...

```<code>from a in _context.A
  join b in _context.B
  on a.Id equals b.AId
select new {
  Id = a.Id,
  Data = new List<KeyValuePair<string, string>()
          .Select(b => new KeyValuePair<string, string>(b.Key, b.Value))
          .ToList()
}
</code>```

Hope my question/example makes sense but please let me know if there's any clarification required!

UPDATE: Per the comment I tried changing the LINQ to:

```<code>from a in _context.A
select new {
   Id = a.Id,
   Data = (from b in _context.B
          where b.AId = a.Id
          select new{
             b.Key,
             b.Value
          }).AsEnumerable()
          .Select(b => new KeyValuePair<string, string>(b.Key, b.Value))
          .ToList()
}
</code>```

But it popped a exception

答:
Your are lacked of grouping data after joining 2 tables.

```<code>from grp in (from a in listA
            join b in listB
            on a.Id equals b.TableAId
            select new { a.Id, b.Key, b.Value })
group grp by grp.Id into i
select new
{
    Id = i,
    Data = (from x in i select new KeyValuePair<string, string>(x.Key, x.Value)).ToList()
};
</code>```

Linq Lambda version

```<code>listA.Join(listB,
           a => a.Id,
           b => b.TableAId,
           (objectA, objectB) => new { objectA.Id, objectB.Key, objectB.Value })
     .GroupBy(x => x.Id)
     .Select(group => new {
                Id = group.Key, //it's group by key (your Id, not your Key)
                Data = group.Select(x => new KeyValuePair<string, string>(x.Key, x.Value)).ToList()
            });
</code>```

Body:
with one having a reference to the other in a one-to-many relationship

Here's a simplified version of the two tables (don't know how to format the tables to look pretty sorry...):

Table A:
Id

Table B: TableAId(FK), Key, Value

When I retrieve the values using a LINQ join I need the values in the referenced table transformed into a list of keyvaluepairs.
So the example answer I'm looking for is:

{
   Id : 1,
   Data:
   [
      {
         key : key1,
         value : valu1
      },
      {
         key : key2,
         value : value2
      }
   ]
}

Here's what my current LINQ looks like...

from a in _context.A
  join b in _context.B
  on a.Id equals b.AId
select new {
  Id = a.Id,
  Data = new List<KeyValuePair<string, string>()
          .Select(b => new KeyValuePair<string, string>(b.Key, b.Value))
          .ToList()
}

Hope my question/example makes sense but please let me know if there's any clarification required!

UPDATE: Per the comment I tried changing the LINQ to:

from a in _context.A
select new {
   Id = a.Id,
   Data = (from b in _context.B
          where b.AId = a.Id
          select new{
             b.Key,
             b.Value
          }).AsEnumerable()
          .Select(b => new KeyValuePair<string, string>(b.Key, b.Value))
          .ToList()
}

But it popped a exception

Body:
Your are lacked of grouping data after joining 2 tables.

from grp in (from a in listA
            join b in listB
            on a.Id equals b.TableAId
            select new { a.Id, b.Key, b.Value })
group grp by grp.Id into i
select new
{
    Id = i,
    Data = (from x in i select new KeyValuePair<string, string>(x.Key, x.Value)).ToList()
};

Linq Lambda version

listA.Join(listB,
           a => a.Id,
           b => b.TableAId,
           (objectA, objectB) => new { objectA.Id, objectB.Key, objectB.Value })
     .GroupBy(x => x.Id)
     .Select(group => new {
                Id = group.Key, //it's group by key (your Id, not your Key)
                Data = group.Select(x => new KeyValuePair<string, string>(x.Key, x.Value)).ToList()
            });


问:
Changing data table td value in php
I am populating data table dynamically. In here I am assigning values to td, in IF clause based on the serial number. I want to change the assigned value of specific td in else part. here is my code.

```<code>@foreach($tasks as $task)
        if($ser_no != $task->serial_number){
          $officer_name="";
          $ser_no =$task->serial_number;
          $officer_name =$officer_name.",". $task->name;
        ?>

   <tr style=" border-left:1px solid; border-right:1px solid; border-top:1px solid; ">
    <td style=" border-left:1px solid; border-right:1px solid; border-top:1px solid; " id="{{$task->task_user_id}}_officer">{{$officer_name}}</td>

     <?php
    }else{
      $officer_name =$officer_name.",". $task->name;
    }

                 ?>
    </tr>
 @endforeach
</code>```

I want to change the assigned td value in else part

答:
The easiest way would be to place your else clause before the TDs are printed.

```<code>@foreach($tasks as $task)
        if($ser_no != $task->serial_number){
          $officer_name="";
          $ser_no =$task->serial_number;
          $officer_name =$officer_name.",". $task->name;
    }else{
      $officer_name =$officer_name.",". $task->name;
    }
  ?>

   <tr style=" border-left:1px solid; border-right:1px solid; border-top:1px solid; ">
    <td style=" border-left:1px solid; border-right:1px solid; border-top:1px solid; " id="{{$task->task_user_id}}_officer">{{$officer_name}}</td>

    </tr>
 @endforeach
</code>```

Once the markup is sent to the client it cannot be changed.

Title: Changing data table td value in php

Body:
I am populating data table dynamically. In here I am assigning values to td, in IF clause based on the serial number. I want to change the assigned value of specific td in else part. here is my code.

@foreach($tasks as $task)
        if($ser_no != $task->serial_number){
          $officer_name="";
          $ser_no =$task->serial_number;
          $officer_name =$officer_name.",". $task->name;
        ?>

    task_user_id}}_officer">{{$officer_name}}

     <?php
    }else{
      $officer_name =$officer_name.",". $task->name;
    }

                 ?>

 @endforeach

I want to change the assigned td value in else part

Body:
The easiest way would be to place your else clause before the TDs are printed.

@foreach($tasks as $task)
        if($ser_no != $task->serial_number){
          $officer_name="";
          $ser_no =$task->serial_number;
          $officer_name =$officer_name.",". $task->name;
    }else{
      $officer_name =$officer_name.",". $task->name;
    }
  ?>

   <tr style=" border-left:1px solid; border-right:1px solid; border-top:1px solid; ">
    <td style=" border-left:1px solid; border-right:1px solid; border-top:1px solid; " id="{{$task->task_user_id}}_officer">{{$officer_name}}</td>

    </tr>
 @endforeach

Once the markup is sent to the client it cannot be changed.


问:
Simulate text writing using Cocos2d on iOS
I am looking for suggestions on how to simulate the writing of dynamic text using Cocos2d on iOS.

The effect should look as though the text is being written by an actual pen in real time.

My main concern is the best way to convert the text into a path that I can move the pen along.

I really don't want to create my own paths manually. It would be great if I could somehow generate a path from a Cocos2d sprite.

答:
The last time I had to do that. I resigned myself to create a video with After Effect... (here is a good tuto to do that)

Play it with MPMoviePlayerController and replace the view at the end of the video by your sprite.

The bad thing about this methods is you can't do that on iOS earlier than 3.2 (MPMoviePlayerController can only be in fullscreen mode)

 I don't think it's the answer you are looking for but I've spent some time before did that

Anyway, good luck


问:
create a variable from multiple variables in R
I have a data set looks like, dat. I want to create one new variable (newVar) with values 1 through 4 using the Q1 through Q6 in R. Can anyone help how to do this, please?

```<code>newVar of 1: If any variable in Q1 through Q6 = "A"
newVar of 2: **If none of variables in Q1 through Q6 = "A", and** If any variable in Q59_1 through Q6= "B"
newVar of 3: **If none of variables in Q1 through Q6 = "A" or "B", and** If any variable in Q1 through Q6= "C"
newVar of 4: If none of variables in Q1 through Q6 = "A" or "B" or "C" , and**strong text** If any variable in Q1 through Q6= "D"

dat = data.frame(Q1 = c("A","D","B","A","D","C","B"),
                 Q2 = c("C","A","B","A","C","C","B"),
                 Q3 = c("B","D","D","A","B","C","A"),
                 Q4 = c("A","C","A","D","B","D","B"),
                 Q5 = c("C","D","D","A","A","C","B"),
                 Q6 = c("D","B","A","A","C","C","A"),
                 Q7 = c("5","1","2","2","4","0","3"),
                 Q8 = c("T","U","O","O","Z","W","Y"),
                 Q9 = c("X","T","V","P","I","U","Y"))
</code>```

Additional comment: I actually need all the conditions especially the bold parts (If none of variables in ...) such as
    NewVar 2: If none of variables in Q1 through Q6 = "A", and If any variable in Q59_1 through Q6= "B"
       3: If none of variables in Q1 through Q6 = "A" or "B", and If any variable in Q1 through Q6= "C"
       4: If none of variables in Q1 through Q6 = "A" or "B" or "C" , and If any variable in Q1 through Q6= "D"

答:
In base R, you can use apply row-wise on selected columns and assign value to newVar checking conditions one by one.

```<code>cols <- paste0('Q', 1:6)

dat$newVar <- apply(dat[cols], 1, function(x) {
    if(any(x == 'A')) 1
    else if(any(x == 'B')) 2
    else if(any(x == 'C')) 3
    else if(any(x == 'D')) 4
    else NA
})

dat
#  Q1 Q2 Q3 Q4 Q5 Q6 Q7 Q8 Q9 newVar
#1  A  C  B  A  C  D  5  T  X      1
#2  D  A  D  C  D  B  1  U  T      1
#3  B  B  D  A  D  A  2  O  V      1
#4  A  A  A  D  A  A  2  O  P      1
#5  D  C  B  B  A  C  4  Z  I      1
#6  C  C  C  D  C  C  0  W  U      3
#7  B  B  A  B  B  A  3  Y  Y      1
</code>```

Body:
I have a data set looks like, dat. I want to create one new variable (newVar) with values 1 through 4 using the Q1 through Q6 in R. Can anyone help how to do this, please?

newVar of 1: If any variable in Q1 through Q6 = "A"
newVar of 2: **If none of variables in Q1 through Q6 = "A", and** If any variable in Q59_1 through Q6= "B"
newVar of 3: **If none of variables in Q1 through Q6 = "A" or "B", and** If any variable in Q1 through Q6= "C"
newVar of 4: If none of variables in Q1 through Q6 = "A" or "B" or "C" , and**strong text** If any variable in Q1 through Q6= "D"

dat = data.frame(Q1 = c("A","D","B","A","D","C","B"),
                 Q2 = c("C","A","B","A","C","C","B"),
                 Q3 = c("B","D","D","A","B","C","A"),
                 Q4 = c("A","C","A","D","B","D","B"),
                 Q5 = c("C","D","D","A","A","C","B"),
                 Q6 = c("D","B","A","A","C","C","A"),
                 Q7 = c("5","1","2","2","4","0","3"),
                 Q8 = c("T","U","O","O","Z","W","Y"),
                 Q9 = c("X","T","V","P","I","U","Y"))

Additional comment: I actually need all the conditions especially the bold parts (If none of variables in ...) such as
    NewVar 2: If none of variables in Q1 through Q6 = "A", and If any variable in Q59_1 through Q6= "B"
       3: If none of variables in Q1 through Q6 = "A" or "B", and If any variable in Q1 through Q6= "C"
       4: If none of variables in Q1 through Q6 = "A" or "B" or "C" , and If any variable in Q1 through Q6= "D"

Body:
In base R, you can use apply row-wise on selected columns and assign value to newVar checking conditions one by one.

cols <- paste0('Q', 1:6)

dat$newVar <- apply(dat[cols], 1, function(x) {
    if(any(x == 'A')) 1
    else if(any(x == 'B')) 2
    else if(any(x == 'C')) 3
    else if(any(x == 'D')) 4
    else NA
})

dat
#  Q1 Q2 Q3 Q4 Q5 Q6 Q7 Q8 Q9 newVar
#1  A  C  B  A  C  D  5  T  X      1
#2  D  A  D  C  D  B  1  U  T      1
#3  B  B  D  A  D  A  2  O  V      1
#4  A  A  A  D  A  A  2  O  P      1
#5  D  C  B  B  A  C  4  Z  I      1
#6  C  C  C  D  C  C  0  W  U      3
#7  B  B  A  B  B  A  3  Y  Y      1


问:
Client Authentication Tomcat - trustAnchors parameter must be non-empty
I know this question appears no stackoverflow a lot, and the exception is to do with a missing truststore - but here is my issue:

Using Apache Tomcat v7.0.56 as server on Windows with Java 8.0.71

modified tomcat/conf/server.xml to include SSL Connector with truststoreType="PKCS12", truststoreFile="conf/regtomcat.truststore" truststorePass="password"

I launch tomcat and I know it is reading this truststore file correctly as I originally did not have the file in pkcs12 format and tomcat reported an error on startup.  I also have tried breaking the file location just to see tomcat startup fail as it can not find the file.  So tomcat launches okay - it is reading the truststore which must mean it exists and can be read.

I load a p12 file into my browser certificate, and go to my application URL.  I then get the tomcat error:

```<code>handling exception: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException:
the trustAnchors parameter must be non-empty
</code>```

Given that my trustore exists, and contains my certificate - what could the problem be?

I generated all certificates and truststores using keytool.  The truststore was created using the command

```<code>keytool -importcert -alias regClient -storetype PKCS12 -keystore regtomcat.truststore -file regClient.cer
</code>```

答: Faced same issue. My keystore only had private key pair of the website. Imported the public certificates from the key pair all the way down to the root and it worked.</p>

Body:
I know this question appears no stackoverflow a lot, and the exception is to do with a missing truststore - but here is my issue:

Using Apache Tomcat v7.0.56 as server on Windows with Java 8.0.71

modified tomcat/conf/server.xml to include SSL Connector with truststoreType="PKCS12", truststoreFile="conf/regtomcat.truststore" truststorePass="password"

I launch tomcat and I know it is reading this truststore file correctly as I originally did not have the file in pkcs12 format and tomcat reported an error on startup.  I also have tried breaking the file location just to see tomcat startup fail as it can not find the file.  So tomcat launches okay - it is reading the truststore which must mean it exists and can be read.

I load a p12 file into my browser certificate, and go to my application URL.  I then get the tomcat error:

handling exception: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException:
the trustAnchors parameter must be non-empty

Given that my trustore exists, and contains my certificate - what could the problem be?

I generated all certificates and truststores using keytool.  The truststore was created using the command

keytool -importcert -alias regClient -storetype PKCS12 -keystore regtomcat.truststore -file regClient.cer


问:
Double Dispatch in C++
I have the need for the following type of dispatch function.  In my application, what I really have is a pointer to a state base class (foo) as well as a pointer to a measurement base class (bar).  Based on what derived instance is passed to the dispatch2 function, I need to produce an estimated measurement given the state.  For instance, the derived state class can be position and the derived measurement class can be ToF (time of flight).  The handler would then take the state information from f (e.g. emitter location) as well as the collector information from b (e.g. sensor positions), and calculate the expect ToF given those.  This is then returned and can be compared against the actual measurement value (b).

```<code>string dispatch2(foo* f, bar* b) {
  if      ( dynamic_cast<Foo>(f) )  return foo1(f,b);
  else if ( dynamic_cast<FOo>(f) )  return foo2(f,b);
  else if ( dynamic_cast<FOO>(f) )  return foo3(f,b);
  throw std::runtime_error("dispatch for f not defined");
}

string foo1(foo* f, bar* b) {
  if      ( dynamic_cast<Bar>(b) )  return foo1bar1handler(f,b);
  else if ( dynamic_cast<BAR>(b) )  return foo1bar2handler(f,b);
  throw std::runtime_error("foo1: dispatch for b not defined");
}

string foo2(foo* f, bar* b) {
  if      ( dynamic_cast<Bar>(b) )  return foo2bar1handler(f,b);
  else if ( dynamic_cast<BAR>(b) )  return foo2bar2handler(f,b);
  throw std::runtime_error("foo2: dispatch for b not defined");
}

string foo3(foo* f, bar* b) {
  if      ( dynamic_cast<Bar>(b) )  return foo3bar1handler(f,b);
  else if ( dynamic_cast<BAR>(b) )  return foo3bar2handler(f,b);
  throw std::runtime_error("foo3: dispatch for b not defined");
}

string foo1bar1handler(foo* f, bar* b) {return "FooBar";}
string foo2bar2handler(foo* f, bar* b) {return "FooBAR";}
string foo3bar1handler(foo* f, bar* b) {return "FOoBar";}
string foo2bar2handler(foo* f, bar* b) {return "FOoBAR";}
string foo2bar1handler(foo* f, bar* b) {return "FOOBar";}
string foo2bar2handler(foo* f, bar* b) {return "FOOBAR";}
</code>```

Obviously, there is no way to get around the need for defining the end methods for each combination I'd like to explicitly handle.  But, I'm looking for alternative ways to implement this.  Ideally, some pattern that would allow users to register each handler explicitly, and any combination that isn't handled could throw a runtime exception.  Any suggestions would be appreciated.  Thanks

答:
One way (certainly not the only way) is to call a virtual function on foo, passing it bar.  Each derived type of foo implements this dispatch function the same way, which will pass itself to a virtual handler function in bar.
When you need to add more, you extend the interfaces to accept the new type(s).  All the foo functions have the same implementation but they differ such that "this" is correctly the dynamic type of the object.

Also, Andrei Alexandrescu had a nice investigation into this with design alternatives in his (now not-so-modern) book Modern C++ Design, which still covers the idea but is written for c++98, but definitely still worth reading (though many things it says can't be done are now part of C++, partly due to that book.)

See it live: https://godbolt.org/z/oRyVJx

This example has 3 Foo classes, and 2 Bar classes.

```<code>#include <iostream>

class BarBase;

class FooBase {
public:
    virtual ~FooBase() = default;
    virtual void dispatch(BarBase*) = 0;
};

class Foo1;
class Foo2;
class Foo3;

class BarBase {
public:
    virtual ~BarBase() = default;
    virtual void accept(Foo1*) = 0;
    virtual void accept(Foo2*) = 0;
    virtual void accept(Foo3*) = 0;
};

class Bar1 : public BarBase {
public:
    void accept(Foo1*) override;
    void accept(Foo2*) override;
    void accept(Foo3*) override;
};

class Bar2 : public BarBase {
public:
    void accept(Foo1*) override;
    void accept(Foo2*) override;
    void accept(Foo3*) override;
};

class Foo1 : public FooBase {
public:
    void dispatch(BarBase* bar) override { bar->accept(this); }
};

class Foo2 : public FooBase {
public:
    void dispatch(BarBase* bar) override { bar->accept(this); }
};

class Foo3 : public FooBase {
public:
    void dispatch(BarBase* bar) override { bar->accept(this); }
};

void Bar1::accept(Foo1 * f) { std::cout << "Bar1 accepting Foo1\n"; }
void Bar1::accept(Foo2 * f) { std::cout << "Bar1 accepting Foo2\n"; }
void Bar1::accept(Foo3 * f) { std::cout << "Bar1 accepting Foo3\n"; }
void Bar2::accept(Foo1 * f) { std::cout << "Bar2 accepting Foo1\n"; }
void Bar2::accept(Foo2 * f) { std::cout << "Bar2 accepting Foo2\n"; }
void Bar2::accept(Foo3 * f) { std::cout << "Bar2 accepting Foo3\n"; }

//
// Doesn't know which types of foo and bar it has, but it doesn't matter...
//
void call(FooBase& foo, BarBase& bar) {
    foo.dispatch(&bar);
}

int main() {
    Foo1 f1;
    Foo2 f2;
    Foo3 f3;
    Bar1 b1;
    Bar2 b2;

    call(f1, b1);
    call(f2, b1);
    call(f3, b1);
    call(f1, b2);
    call(f2, b2);
    call(f3, b2);
}
</code>```

output:

```<code>Bar1 accepting Foo1
Bar1 accepting Foo2
Bar1 accepting Foo3
Bar2 accepting Foo1
Bar2 accepting Foo2
Bar2 accepting Foo3
</code>```

Title: Double Dispatch in C++

Body:
I have the need for the following type of dispatch function.  In my application, what I really have is a pointer to a state base class (foo) as well as a pointer to a measurement base class (bar).  Based on what derived instance is passed to the dispatch2 function, I need to produce an estimated measurement given the state.  For instance, the derived state class can be position and the derived measurement class can be ToF (time of flight).  The handler would then take the state information from f (e.g. emitter location) as well as the collector information from b (e.g. sensor positions), and calculate the expect ToF given those.  This is then returned and can be compared against the actual measurement value (b).

string dispatch2(foo* f, bar* b) {
  if      ( dynamic_cast<Foo>(f) )  return foo1(f,b);
  else if ( dynamic_cast<FOo>(f) )  return foo2(f,b);
  else if ( dynamic_cast<FOO>(f) )  return foo3(f,b);
  throw std::runtime_error("dispatch for f not defined");
}

string foo1(foo* f, bar* b) {
  if      ( dynamic_cast<Bar>(b) )  return foo1bar1handler(f,b);
  else if ( dynamic_cast<BAR>(b) )  return foo1bar2handler(f,b);
  throw std::runtime_error("foo1: dispatch for b not defined");
}

string foo2(foo* f, bar* b) {
  if      ( dynamic_cast<Bar>(b) )  return foo2bar1handler(f,b);
  else if ( dynamic_cast<BAR>(b) )  return foo2bar2handler(f,b);
  throw std::runtime_error("foo2: dispatch for b not defined");
}

string foo3(foo* f, bar* b) {
  if      ( dynamic_cast<Bar>(b) )  return foo3bar1handler(f,b);
  else if ( dynamic_cast<BAR>(b) )  return foo3bar2handler(f,b);
  throw std::runtime_error("foo3: dispatch for b not defined");
}

string foo1bar1handler(foo* f, bar* b) {return "FooBar";}
string foo2bar2handler(foo* f, bar* b) {return "FooBAR";}
string foo3bar1handler(foo* f, bar* b) {return "FOoBar";}
string foo2bar2handler(foo* f, bar* b) {return "FOoBAR";}
string foo2bar1handler(foo* f, bar* b) {return "FOOBar";}
string foo2bar2handler(foo* f, bar* b) {return "FOOBAR";}

Obviously, there is no way to get around the need for defining the end methods for each combination I'd like to explicitly handle.  But, I'm looking for alternative ways to implement this.  Ideally, some pattern that would allow users to register each handler explicitly, and any combination that isn't handled could throw a runtime exception.  Any suggestions would be appreciated.  Thanks

Body:
One way (certainly not the only way) is to call a virtual function on foo, passing it bar.  Each derived type of foo implements this dispatch function the same way, which will pass itself to a virtual handler function in bar.
When you need to add more, you extend the interfaces to accept the new type(s).  All the foo functions have the same implementation but they differ such that "this" is correctly the dynamic type of the object.

Also, Andrei Alexandrescu had a nice investigation into this with design alternatives in his (now not-so-modern) book Modern C++ Design, which still covers the idea but is written for c++98, but definitely still worth reading (though many things it says can't be done are now part of C++, partly due to that book.)

See it live: https://godbolt.org/z/oRyVJx

This example has 3 Foo classes, and 2 Bar classes.

#include <iostream>

class BarBase;

class FooBase {
public:
    virtual ~FooBase() = default;
    virtual void dispatch(BarBase*) = 0;
};

class Foo1;
class Foo2;
class Foo3;

class BarBase {
public:
    virtual ~BarBase() = default;
    virtual void accept(Foo1*) = 0;
    virtual void accept(Foo2*) = 0;
    virtual void accept(Foo3*) = 0;
};

class Bar1 : public BarBase {
public:
    void accept(Foo1*) override;
    void accept(Foo2*) override;
    void accept(Foo3*) override;
};

class Bar2 : public BarBase {
public:
    void accept(Foo1*) override;
    void accept(Foo2*) override;
    void accept(Foo3*) override;
};

class Foo1 : public FooBase {
public:
    void dispatch(BarBase* bar) override { bar->accept(this); }
};

class Foo2 : public FooBase {
public:
    void dispatch(BarBase* bar) override { bar->accept(this); }
};

class Foo3 : public FooBase {
public:
    void dispatch(BarBase* bar) override { bar->accept(this); }
};

void Bar1::accept(Foo1 * f) { std::cout << "Bar1 accepting Foo1\n"; }
void Bar1::accept(Foo2 * f) { std::cout << "Bar1 accepting Foo2\n"; }
void Bar1::accept(Foo3 * f) { std::cout << "Bar1 accepting Foo3\n"; }
void Bar2::accept(Foo1 * f) { std::cout << "Bar2 accepting Foo1\n"; }
void Bar2::accept(Foo2 * f) { std::cout << "Bar2 accepting Foo2\n"; }
void Bar2::accept(Foo3 * f) { std::cout << "Bar2 accepting Foo3\n"; }

//
// Doesn't know which types of foo and bar it has, but it doesn't matter...
//
void call(FooBase& foo, BarBase& bar) {
    foo.dispatch(&bar);
}

int main() {
    Foo1 f1;
    Foo2 f2;
    Foo3 f3;
    Bar1 b1;
    Bar2 b2;

    call(f1, b1);
    call(f2, b1);
    call(f3, b1);
    call(f1, b2);
    call(f2, b2);
    call(f3, b2);
}

output:

Bar1 accepting Foo1
Bar1 accepting Foo2
Bar1 accepting Foo3
Bar2 accepting Foo1
Bar2 accepting Foo2
Bar2 accepting Foo3


问:
Fetch Order details between two dates in Mongodb from PHP
First of all I can find some questions asked related to this topic. But I could not able get through. This is more of a solution asked for my code.

I am sending two dates from Ajax with Javascript date.

```<code>var sd = new Date("2016-10-15T00:00:00.000Z");
var ed = new Date("2016-10-17T00:00:00.000Z");
$.ajax({
          type: "GET",
          url: "dashboard/load_revenue_chart",
          data: {type:"revenue",period:"no of days",start_date: sd.getTime(),end_date: ed.getTime()},
          dataType: 'json',
          success: function(data){
            line_chart(data);
        }
    });
</code>```

Controller:

```<code>if (isset($_GET['period'])) {

        $collection = $this->selectCollection(); // public function for setting the collection.
        $start = $_GET['start_date'];
        $end = $_GET['end_date'];
        print_r($_GET['start_date']); // Outputs : 1476489600000
        print_r($_GET['end_date']); // Outputs : 1476662400000

        $result = $collection->find(array("OrderedOn" => array('$gt' => $start, '$lt' => $end)));
        print_r($result);
}
</code>```

Output:

MongoCursor Object
  (
  )

Have tried with ISOString also. Not able to get the output. But when i try the same with Mongo Shell, I am able to get the result.

I dont know what i am missing. It will be a great help if you explain me how to get the result with PHP.

Thanks in advance.

答:
When you save date in mongo DB database using php using gine mongo function.
new \MongoDB\BSON\UTCDateTime() then date format will be save on DB like this:

updateTime :  ISODate("2020-06-02T07:09:57.099+0000")

When you want fetch all records between two dates. Example like current date and 60 day.

Back date using php then ex like this:

```<code>$milliseconds = round(microtime(true) * 1000);

$dt1 = date("Y-m-d", strtotime("-60 day"));
$dt2 = date("Y-m-d", strtotime("-1 day"));

$where = [ "updateTime" => array('$gte' => new MongoDB\BSON\UTCDateTime(strtotime("$dt1")* 1000), '$lte' => new MongoDB\BSON\UTCDateTime(strtotime("$dt2")* 1000))];

$fetchAllUser = new MongoDB\Driver\Query($where);
$fetchAllUser =  $connection->executeQuery($db.".collname", $fetchAllUser);
</code>```

Body:
First of all I can find some questions asked related to this topic. But I could not able get through. This is more of a solution asked for my code.

I am sending two dates from Ajax with Javascript date.

var sd = new Date("2016-10-15T00:00:00.000Z");
var ed = new Date("2016-10-17T00:00:00.000Z");
$.ajax({
          type: "GET",
          url: "dashboard/load_revenue_chart",
          data: {type:"revenue",period:"no of days",start_date: sd.getTime(),end_date: ed.getTime()},
          dataType: 'json',
          success: function(data){
            line_chart(data);
        }
    });

Controller:

if (isset($_GET['period'])) {

        $collection = $this->selectCollection(); // public function for setting the collection.
        $start = $_GET['start_date'];
        $end = $_GET['end_date'];
        print_r($_GET['start_date']); // Outputs : 1476489600000
        print_r($_GET['end_date']); // Outputs : 1476662400000

        $result = $collection->find(array("OrderedOn" => array('$gt' => $start, '$lt' => $end)));
        print_r($result);
}

Output:

MongoCursor Object
  (
  )

Have tried with ISOString also. Not able to get the output. But when i try the same with Mongo Shell, I am able to get the result.

I dont know what i am missing. It will be a great help if you explain me how to get the result with PHP.

Thanks in advance.

Body:
When you save date in mongo DB database using php using gine mongo function.
new \MongoDB\BSON\UTCDateTime() then date format will be save on DB like this:

updateTime :  ISODate("2020-06-02T07:09:57.099+0000")

When you want fetch all records between two dates. Example like current date and 60 day.

Back date using php then ex like this:

$milliseconds = round(microtime(true) * 1000);

$dt1 = date("Y-m-d", strtotime("-60 day"));
$dt2 = date("Y-m-d", strtotime("-1 day"));

$where = [ "updateTime" => array('$gte' => new MongoDB\BSON\UTCDateTime(strtotime("$dt1")* 1000), '$lte' => new MongoDB\BSON\UTCDateTime(strtotime("$dt2")* 1000))];

$fetchAllUser = new MongoDB\Driver\Query($where);
$fetchAllUser =  $connection->executeQuery($db.".collname", $fetchAllUser);


问:
How do you disable viewport zooming on Mobile Safari?
I've tried all three of these to no avail:

```<code><meta name=”viewport” content=”width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;” />

<meta name=”viewport” content=”width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=false;” />

<meta name=”viewport” content=”width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;” />
</code>```

each are different values I found recommended by google searching or SO searching, but none of the 'user-scalable=X' values seem to be working

I also tried comma delimiting the values instead of semicolon, no luck. Then I tried ONLY having the user-scalable value present, still no luck.

UPDATE

Got this from Apple's site and it works:

```<code><meta name="viewport" content="width=device-width, user-scalable=no" />
</code>```

it turns out that the problem was the non-standard quotes because I had copied the meta tag from a website that was using them, whoops

答:
Using the CSS touch-action property is the most elegant solution. Tested on iOS 13.5 and iOS 14.

To disable pinch zoom gestures and and double-tap to zoom:

body {
  touch-action: pan-x pan-y;
}
```
<p>If your app also has no need for <strong>panning</strong>, i.e. scrolling, use this:</p>
<pre class="lang-css prettyprint-override"><code>body {
  touch-action: none;
}
</code>```

Body:
I've tried all three of these to no avail:

<meta name=”viewport” content=”width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;” />

<meta name=”viewport” content=”width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=false;” />

<meta name=”viewport” content=”width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;” />

each are different values I found recommended by google searching or SO searching, but none of the 'user-scalable=X' values seem to be working

I also tried comma delimiting the values instead of semicolon, no luck. Then I tried ONLY having the user-scalable value present, still no luck.

UPDATE

Got this from Apple's site and it works:

<meta name="viewport" content="width=device-width, user-scalable=no" />

it turns out that the problem was the non-standard quotes because I had copied the meta tag from a website that was using them, whoops

Body:
Using the CSS touch-action property is the most elegant solution. Tested on iOS 13.5 and iOS 14.

To disable pinch zoom gestures and and double-tap to zoom:

body {
  touch-action: pan-x pan-y;
}

If your app also has no need for panning, i.e. scrolling, use this:

body {
  touch-action: none;
}


问:
How to handle social login? - example flow
I have more conteptual question, how exactly should I handle social login in my project.
The use case is that I would like to allow user to login with Facebook, and keep on my backend information about this user (email, firstname, lastname)

I have some proposal Flow, but I'm not sure if it's a proper approach.

Let's say that I have application architecture as above. Now I would like to explain step-by-step full success flow.

Client (Vue application) make a call to AuthProvider (Facebook)

AuthProvider returns access_token

Client after reciving access_token make a call to backend endpoint like /fb_profile with access_token and userID (?)

Backend make a call to AuthProvider to check if given by client access_token is valid or not.

AuthProvider returns information about user. Backend after getting information about user, save it to database and generate new JWT token

Backend returns generated token to user

Now my question is - Is this good approach? Or should i handle it in other way? Like keep more logic to backend part? Instead of make a call to Facebook from Client, maybe should I make a call to backend, and backend make a call to Facebook?

答:
You seem to be on right track. There could me many ways to do the same thing, here is the way which is working for me using vue/laravel/passport/socialite/github.

Trigger redirect in controller from frontend,

Provider(here github app) is triggered in browser with its url using client id/app name saved in back end config/env. Fill out your login details

It will redirect as created in provider and configured in backend-> show it on frontend, in my case its

http://localhost:8080/authorize/github/callback

From frontend now trigger callback in controller, it will check if user details already exist and will insert if its first time user as per logic. Then it will send back access_token to frontend which can be used in frontend for all the operations

DB


问:
az keyvault certificate import fails with 'NoneType' object has no attribute 'get_notBefore'
Trying to import a certificate converted from jks format to pfx, but I get the following error:

```<code>az keyvault certificate import --name truststore-pfx --vault-name mykeyvault --file truststore.pfx --password *******
'NoneType' object has no attribute 'get_notBefore'
</code>```

Both keytool -list and openssl pkcs12 -info correctly shows the cert.

Importing fails also via the portal. Any idea how to get it imported?

答:
Looking at the error, it looks like it has no notBefore field, which is a critical requirement. Take a look at the cert; if you're on Windows use certutil:

certutil -dump

or, on Linux/Mac, you can use OpenSSL:

openssl x509 -inform der -in  -noout -text

And double-check there is a NotBefore field.

If you're not 100% sure, go ahead and dump the output here and I can take a look!

Body:
Trying to import a certificate converted from jks format to pfx, but I get the following error:

az keyvault certificate import --name truststore-pfx --vault-name mykeyvault --file truststore.pfx --password *******
'NoneType' object has no attribute 'get_notBefore'

Both keytool -list and openssl pkcs12 -info correctly shows the cert.

Importing fails also via the portal. Any idea how to get it imported?


问:
isEnabled property not working as expected in Appium
Can someone explain to me in layman terms how command isEnabled() works in Appium
Scenario: There are 3 checkboxes on a specific mobile page.
-   Checkbox 1, Checkbox2 & Checkbox3
“Checbox3” is disabled by default and only enables when we select “Checkbox2”

TC is to verify if “Checkbox3” is disabled by default and print the following output
“Checkbox3 is currently Disabled”

Once the “Checkbox3” is enabled we need to print the following output
“Checkbox3 is currently Enabled”

I am executing this as a TestNG and am using the following line of code

```<code>boolean FirstValue = XMLPage.ListofCheckboxes.get(2).isEnabled();
System.out.println(FirstValue);
if(FirstValue=false)
{
    System.out.println("Checkbox3 is currently Disabled");
}
else
{
    System.out.println("Checkbox3 is currently Enabled");
}
Thread.sleep(4000);
XMLPage.ListofCheckboxes.get(1).click();
boolean SecondValue = XMLPage.ListofCheckboxes.get(2).isEnabled();
System.out.println(SecondValue);
if(SecondValue=true)
{
    System.out.println("Checkbox3 is currently Enabled");
}
else
{
    System.out.println("Checkbox3 is currently Disabled");
}
</code>```

Expected Output :

false

"Checkbox3 is currently Disabled"

true

"Checkbox3 is currently Enabled"

Actual Output:

false

"Checkbox3 is currently Enabled"

true

"Checkbox3 is currently Enabled"

The first time it encounters the if statement shouldn’t it print the output as "Checkbox3 is currently Disabled" I am not sure why it prints the output mentioned under ‘else’{i.e.:- "Checkbox3 is currently Enabled"}.
As displayed in the output the value returned by command  “boolean FirstValue = XMLPage.ListofCheckboxes.get(2).isEnabled();” is false and hence the code should print the output mentioned under ‘if’ and not ‘else’.

答:
The if statement you are using in your code is wrong.

if statement in your code

```<code>if(FirstValue=false){
....
}
</code>```

this is an assignment operation since you use a single = symbol. What it will do is, it will assign FirstValue equal to false, then since the value inside the if block now is false, it is going to the else block. This is a valid operation so it will compile fine. But the if statement should be a comparison step like below using == symbol,

if statement should be a comparison step,

```<code>if(FirstValue==false){
....
}
</code>```

This is the reason for your wrong output.

Body:
Can someone explain to me in layman terms how command isEnabled() works in Appium
Scenario: There are 3 checkboxes on a specific mobile page.
-   Checkbox 1, Checkbox2 & Checkbox3
“Checbox3” is disabled by default and only enables when we select “Checkbox2”

TC is to verify if “Checkbox3” is disabled by default and print the following output
“Checkbox3 is currently Disabled”

Once the “Checkbox3” is enabled we need to print the following output
“Checkbox3 is currently Enabled”

I am executing this as a TestNG and am using the following line of code

boolean FirstValue = XMLPage.ListofCheckboxes.get(2).isEnabled();
System.out.println(FirstValue);
if(FirstValue=false)
{
    System.out.println("Checkbox3 is currently Disabled");
}
else
{
    System.out.println("Checkbox3 is currently Enabled");
}
Thread.sleep(4000);
XMLPage.ListofCheckboxes.get(1).click();
boolean SecondValue = XMLPage.ListofCheckboxes.get(2).isEnabled();
System.out.println(SecondValue);
if(SecondValue=true)
{
    System.out.println("Checkbox3 is currently Enabled");
}
else
{
    System.out.println("Checkbox3 is currently Disabled");
}

Expected Output :

false

"Checkbox3 is currently Disabled"

true

"Checkbox3 is currently Enabled"

Actual Output:

false

"Checkbox3 is currently Enabled"

true

"Checkbox3 is currently Enabled"

The first time it encounters the if statement shouldn’t it print the output as "Checkbox3 is currently Disabled" I am not sure why it prints the output mentioned under ‘else’{i.e.:- "Checkbox3 is currently Enabled"}.
As displayed in the output the value returned by command  “boolean FirstValue = XMLPage.ListofCheckboxes.get(2).isEnabled();” is false and hence the code should print the output mentioned under ‘if’ and not ‘else’.

Body:
The if statement you are using in your code is wrong.

if statement in your code

if(FirstValue=false){
....
}

this is an assignment operation since you use a single = symbol. What it will do is, it will assign FirstValue equal to false, then since the value inside the if block now is false, it is going to the else block. This is a valid operation so it will compile fine. But the if statement should be a comparison step like below using == symbol,

if statement should be a comparison step,

if(FirstValue==false){
....
}

This is the reason for your wrong output.


问:
How does sorted work with both positive and negative values?
Ex:

dictionary = {"sand": 1, "coal": -2, "apples": -1, "corn": 5}

I want to arrange it in ascending order with the lowest value first "coal: -2"

answer = [coal, apples, sand, corn]

But when I tried to sort the dictionary using sorted function below:

print(sorted(dictionary, key=lambda x: x[1]))

I got this:

['sand', 'coal', 'corn', 'apples']

how does the sorted function work for both + and - values?

答:
What's wrong

sorted(dictionary, key=lambda x: x[1])
```
<p>Above statement not comparing with value but comparing with sencond char in key</p>
<h1>Solution</h1>
<pre class="lang-py prettyprint-override"><code>sorted(dictionary, key=lambda x: dictionary[x])
</code>```

Body:
What's wrong

sorted(dictionary, key=lambda x: x[1])

Above statement not comparing with value but comparing with sencond char in key

Solution

sorted(dictionary, key=lambda x: dictionary[x])


问:
complex<> using list initializer vs constructor?
I'm reading Stroustrup C++ 4th Ed. Page 162 Types and Declarations.  Specifically, where the following is allowed to construct a complex<> object.

The book comments that case A is "use constructor".  Is case A really a list initializer and the constructor method of initialization is performed in B or C?

```<code>#include <iostream>
#include <complex>
using namespace std;

int main(int argc, char *argv[])
{
    complex<double> z = { 0, 3.14 }; // A
    complex<double> h(0, 3.14); // B
    complex<double> i{0, 3.14}; // C

    return 0;
}
</code>```

答:
complex<double> z = { 0, 3.14 }; // A performs copy-list-initliazation (since C++11).

complex<double> h(0, 3.14); // B performs direct initliazation.

complex<double> i{0, 3.14}; // C performs direct-list-initliazation (since C++11).

The effects are all the same for this case; objects are initialized by the constructor complex::complex(double, double).

Body:
I'm reading Stroustrup C++ 4th Ed. Page 162 Types and Declarations.  Specifically, where the following is allowed to construct a complex<> object.

The book comments that case A is "use constructor".  Is case A really a list initializer and the constructor method of initialization is performed in B or C?

#include <iostream>
#include <complex>
using namespace std;

int main(int argc, char *argv[])
{
    complex<double> z = { 0, 3.14 }; // A
    complex<double> h(0, 3.14); // B
    complex<double> i{0, 3.14}; // C

    return 0;
}


问:
Starting python if function with an empty value possibility
Automated stock bot in development here.

I'm trying to start an "if" function when an empty list value is returned as the argument, and end the script if a text (string?) value is returned. The reason for this is because I don't want to execute the if function if I currently have a trade open, only when I have no trades open. As far as I know the only modules from my broker's API(Oanda) useful to execute this task is one that outputs [] when I don't have a trade open. This was retrieved from the following list {'positions': [], 'lastTransactionID': '4765'} Part of me thinks what I'm trying to do is impossible, based on the research I've done, but I'm hoping someone has an idea. I put double asterisks around the important part of the script.

```<code>    from flask import Flask, request, abort
    import oandapyV20
    import oandapyV20.endpoints.positions as positions
    from exampleauth import exampleAuth

    # Create Flask object called app.
    app = Flask(__name__)

    # Create root to easily let us know its on/working.
    @app.route('/')
    def root():
        return 'online'

    @app.route('/webhook', methods=['POST'])
    def webhook():
        if request.method == 'POST':
            accountID, access_token = exampleAuth()
            api = oandapyV20.API(access_token=access_token)
            client=oandapyV20.API(access_token)
            r=positions.OpenPositions(accountID)
            x=client.request(r)
            **if x['positions']=='[]': #if empty execute if function, if not return 'okay'
            data = parse_webhook(request.get_data(as_text=True))
            sell=data['side']
            if data['side']=='sellEURAUD':
                exec(open("marketTPSLEURAUDv2sell.py").read())
            elif data['side']=='buyEURAUD':
                exec(open("marketTPSLEURAUDv2buy.py").read())
        else:
            return 'okay'**

    if __name__ == '__main__':
        app.run()
</code>```

答:
Just remove the qutos from empty list.
Should be like this-</p>

```<code>if x['positions']==[]:
</code>```

Body:
Automated stock bot in development here.

I'm trying to start an "if" function when an empty list value is returned as the argument, and end the script if a text (string?) value is returned. The reason for this is because I don't want to execute the if function if I currently have a trade open, only when I have no trades open. As far as I know the only modules from my broker's API(Oanda) useful to execute this task is one that outputs [] when I don't have a trade open. This was retrieved from the following list {'positions': [], 'lastTransactionID': '4765'} Part of me thinks what I'm trying to do is impossible, based on the research I've done, but I'm hoping someone has an idea. I put double asterisks around the important part of the script.

    from flask import Flask, request, abort
    import oandapyV20
    import oandapyV20.endpoints.positions as positions
    from exampleauth import exampleAuth

    # Create Flask object called app.
    app = Flask(__name__)

    # Create root to easily let us know its on/working.
    @app.route('/')
    def root():
        return 'online'

    @app.route('/webhook', methods=['POST'])
    def webhook():
        if request.method == 'POST':
            accountID, access_token = exampleAuth()
            api = oandapyV20.API(access_token=access_token)
            client=oandapyV20.API(access_token)
            r=positions.OpenPositions(accountID)
            x=client.request(r)
            **if x['positions']=='[]': #if empty execute if function, if not return 'okay'
            data = parse_webhook(request.get_data(as_text=True))
            sell=data['side']
            if data['side']=='sellEURAUD':
                exec(open("marketTPSLEURAUDv2sell.py").read())
            elif data['side']=='buyEURAUD':
                exec(open("marketTPSLEURAUDv2buy.py").read())
        else:
            return 'okay'**

    if __name__ == '__main__':
        app.run()

Body:
Just remove the qutos from empty list.
Should be like this-

if x['positions']==[]:


问:
Intentionally Recreating a Multithreading SQL Error
So I have a batch processor which is multithreaded that takes some values and inserts them into an Oracle DB. I'm receiving reports that this processor is logging Unique Constraint errors.

This is the query that the processor is using to insert:

```<code>INSERT INTO TABLE_T

(VALUE_A_PK, VALUE_B_PK, VALUE_C, VALUE_D, VALUE_E, VALUE_F, VALUE_G, VALUE_H, VALUE_I, VALUE_J)

      SELECT ?,?,?,?,?,?,?,?,?,? FROM DUAL

               WHERE NOT EXISTS

                        (SELECT 1 FROM TABLE_T WHERE

                         VALUE_A_PK= ? AND VALUE_B_PK = ?);
</code>```

I know of ways to fix this, but first I need to recreate the error to prove that I've actually fixed it.
Despite feeding multiple duplicate records to the processor, I cannot manually get the error to resurface.

It seems almost certain to me that this is a multithreading issue where multiple threads are attempting to insert a new record at the same time.

Is there a reliable way to force more than one thread to execute at exactly the same time? If I could do that, then it seems like I should be able to get the error pop back up.

答:
There's no way to fire two statements in two sessions at the exact same time. Tools like DBMS_SCHEDULER could perhaps reliably start two processes within a second, but to imitate primary key errors for one-row inserts you'll need a much higher precision.

It might be easier to run the statement in two separate sessions in a loop, and just wait until one of them fails. I've done this several times before to reproduce intermittent problems.

Run this pseudo-code in two or more sessions and wait for an error:

```<code>begin
    for i in 1 .. 1000000 loop
        INSERT INTO TABLE_T ...
    end loop;
end;
/
</code>```

Body:
So I have a batch processor which is multithreaded that takes some values and inserts them into an Oracle DB. I'm receiving reports that this processor is logging Unique Constraint errors.

This is the query that the processor is using to insert:

INSERT INTO TABLE_T

(VALUE_A_PK, VALUE_B_PK, VALUE_C, VALUE_D, VALUE_E, VALUE_F, VALUE_G, VALUE_H, VALUE_I, VALUE_J)

      SELECT ?,?,?,?,?,?,?,?,?,? FROM DUAL

               WHERE NOT EXISTS

                        (SELECT 1 FROM TABLE_T WHERE

                         VALUE_A_PK= ? AND VALUE_B_PK = ?);

I know of ways to fix this, but first I need to recreate the error to prove that I've actually fixed it.
Despite feeding multiple duplicate records to the processor, I cannot manually get the error to resurface.

It seems almost certain to me that this is a multithreading issue where multiple threads are attempting to insert a new record at the same time.

Is there a reliable way to force more than one thread to execute at exactly the same time? If I could do that, then it seems like I should be able to get the error pop back up.

Body:
There's no way to fire two statements in two sessions at the exact same time. Tools like DBMS_SCHEDULER could perhaps reliably start two processes within a second, but to imitate primary key errors for one-row inserts you'll need a much higher precision.

It might be easier to run the statement in two separate sessions in a loop, and just wait until one of them fails. I've done this several times before to reproduce intermittent problems.

Run this pseudo-code in two or more sessions and wait for an error:

begin
    for i in 1 .. 1000000 loop
        INSERT INTO TABLE_T ...
    end loop;
end;
/


问:
Array.map( ) only works on First Array but not on the Second. Can someone please explain why it doesn't work and provide proper solution
I have two arrays, each array gets mapped over and if the array doesn't match with "apiSuggestion" the element gets black background-color with red text.
This works:

```<code>let sentenceOne = ["somthing", "life", "nothing"];
let sentenceTwo = ["nummber", "seven", everythng"];

let apiSuggestion = ["something", "life", "nothing", "number", "seven", "everything"];

let matchMakerOne = sentenceOne.map(function(word,index){
   if( word !== apiSuggestion[index]){
        return `
               <span style="background-color:black; color:red">
                     ${word}
               </span>
       } else {
               return word
              }
          })
document.getElementById("sentenceOne").innerHTML = machMakerOne.join(' ')
//in the HTML i see "somthing" highlighted in black background-color with red text, as it doesnt match to api suggesstion
</code>```

This doesn't work even though its the same logic, where am I making a mistake?

```<code>let matchMakerTwo = sentenceTwo.map(function(word,index){
   if( word !== apiSuggestion[index]){
        return `
               <span style="background-color:black; color:red">
                     ${word}
               </span>
       } else {
               return word
              }
          })
document.getElementById("sentenceTwo").innerHTML = machMakerTwo.join(' ')
// "nummber", "seven", everythng" all get black background and red text
// nummber and everythng should get black background and red text
</code>```

I tried to "concat" sentenceOne and sentenceTwo, it only catches the spelling mistakes from first array but not the second. How can I highlight the spelling mistakes in both these arrays and render it in the HTML? Any help is appreciated. Thank you in advance.
i created JSFiddle

答:
@Thakur is correct - in both cases, you're only checking the first three elements of the apiSuggestion array.

Replace

```<code>if (word !== apiSuggestion[index]) {...}
</code>```

with

```<code>if (apiSuggestion.indexOf(word) === -1) {...}
</code>```

Array.indexOf(arg) returns -1 if arg is NOT an element of the target array.

Reference: MDN: Array.prototype.indexOf()

Body:
I have two arrays, each array gets mapped over and if the array doesn't match with "apiSuggestion" the element gets black background-color with red text.
This works:

let sentenceOne = ["somthing", "life", "nothing"];
let sentenceTwo = ["nummber", "seven", everythng"];

let apiSuggestion = ["something", "life", "nothing", "number", "seven", "everything"];

let matchMakerOne = sentenceOne.map(function(word,index){
   if( word !== apiSuggestion[index]){
        return `

                     ${word}

       } else {
               return word
              }
          })
document.getElementById("sentenceOne").innerHTML = machMakerOne.join(' ')
//in the HTML i see "somthing" highlighted in black background-color with red text, as it doesnt match to api suggesstion

This doesn't work even though its the same logic, where am I making a mistake?

let matchMakerTwo = sentenceTwo.map(function(word,index){
   if( word !== apiSuggestion[index]){
        return `

                     ${word}

       } else {
               return word
              }
          })
document.getElementById("sentenceTwo").innerHTML = machMakerTwo.join(' ')
// "nummber", "seven", everythng" all get black background and red text
// nummber and everythng should get black background and red text

I tried to "concat" sentenceOne and sentenceTwo, it only catches the spelling mistakes from first array but not the second. How can I highlight the spelling mistakes in both these arrays and render it in the HTML? Any help is appreciated. Thank you in advance.
i created JSFiddle

Body:
@Thakur is correct - in both cases, you're only checking the first three elements of the apiSuggestion array.

Replace

if (word !== apiSuggestion[index]) {...}

with

if (apiSuggestion.indexOf(word) === -1) {...}

Array.indexOf(arg) returns -1 if arg is NOT an element of the target array.

Reference: MDN: Array.prototype.indexOf()


问:
How do I recursively rename folders with Powershell?
Recursive renaming files using PS is trivial (variation on example from Mike Ormond's blog):

```<code>dir *_t*.gif -recurse
    | foreach { move-item -literal $_ $_.Name.Replace("_thumb[1]", "")}
</code>```

I'm trying to recursively rename a folder structure.

The use case is I'd like to be able to rename a whole VS.NET Solution (e.g. from Foo.Bar to Bar.Foo). To do this there are several steps:

Rename folders (e.g. \Foo.Bar\Foo.Bar.Model => \Bar.Foo\Bar.Foo.Model)

Rename files (e.g. Foo.Bar.Model.csproj => Bar.Foo.Model.csproj)

Find and Replace within files to correct for namespace changes (e.g. 'namespace Foo.Bar' => 'namespace Bar.Foo')

I'm currently working the first step in this process.

I found this posting, which talks about the challenges, and claims a solution but doesn't talk about what that solution is.

I keep running into the recursion wall. If I let PS deal with the recursion using a flag, the parent folder gets renamed before the children, and the script throws an error. If I try to implement the recursion myself, my head get's all achy and things go horribly wrong - for the life of me I cannot get things to start their renames at the tail of the recursion tree.

答:
How about this - do a recursive list of the full names, sort it in descending order by the length of the full name,  and then run that back through your rename routine.  </p>

<p>e.g. </p>

```<code>gci <directory> -recurse |
 foreach {$_.fullname} |
  sort -length -desc
</code>```

Body:
Recursive renaming files using PS is trivial (variation on example from Mike Ormond's blog):

dir *_t*.gif -recurse
    | foreach { move-item -literal $_ $_.Name.Replace("_thumb[1]", "")}

I'm trying to recursively rename a folder structure.

The use case is I'd like to be able to rename a whole VS.NET Solution (e.g. from Foo.Bar to Bar.Foo). To do this there are several steps:

Rename folders (e.g. \Foo.Bar\Foo.Bar.Model => \Bar.Foo\Bar.Foo.Model)

Rename files (e.g. Foo.Bar.Model.csproj => Bar.Foo.Model.csproj)

Find and Replace within files to correct for namespace changes (e.g. 'namespace Foo.Bar' => 'namespace Bar.Foo')

I'm currently working the first step in this process.

I found this posting, which talks about the challenges, and claims a solution but doesn't talk about what that solution is.

I keep running into the recursion wall. If I let PS deal with the recursion using a flag, the parent folder gets renamed before the children, and the script throws an error. If I try to implement the recursion myself, my head get's all achy and things go horribly wrong - for the life of me I cannot get things to start their renames at the tail of the recursion tree.

Body:
How about this - do a recursive list of the full names, sort it in descending order by the length of the full name,  and then run that back through your rename routine.

e.g.

gci <directory> -recurse |
 foreach {$_.fullname} |
  sort -length -desc


问:
Debezium MongoDB source JSON sink to Cassandra (LENSES.IO)
I need to sink a JSON object from MongoDB to a column in Cassandra. I'm using ExtractNewDocumentState, AvroConverter. But it seems I'm wrong. And AvroConverter used in source or sink? If I used it in the source then I used it in the sink too?

```<code>{
"name": "mongodb_source_connector",
"config": {
    "connector.class": "io.debezium.connector.mongodb.MongoDbConnector",
    "tasks.max": "1",
    "mongodb.hosts": "rs0/mongo:27017",
    "mongodb.name": "dbserver1",
    "mongodb.user": "scorpion",
    "mongodb.password": "123123123",
    "database.whitelist": "ladiform",
    "database.history.kafka.bootstrap.servers": "kafka_3:9093",
    "transforms": "route,unwrap",
    "transforms.route.type": "org.apache.kafka.connect.transforms.RegexRouter",
    "transforms.route.regex": "([^.]+)\\.([^.]+)\\.([^.]+)",
    "transforms.route.replacement": "$3",
    "transforms.unwrap.type": "io.debezium.connector.mongodb.transforms.ExtractNewDocumentState",
    "transforms.unwrap.drop.tombstones": "false",
    "transforms.unwrap.delete.handling.mode": "drop",
    "transforms.unwrap.operation.header": "true",
    "key.converter": "io.confluent.connect.avro.AvroConverter",
    "value.converter": "io.confluent.connect.avro.AvroConverter",
    "key.converter.schema.registry.url": "http://schema-registry:8081",
    "value.converter.schema.registry.url": "http://schema-registry:8081"
}
</code>```

}

```<code>{
"name": "cassandra_sink_connector",
"config": {
    "connector.class": "com.datamountaineer.streamreactor.connect.cassandra.sink.CassandraSinkConnector",
    "tasks.max": "1",
    "topics": "test34",
    "connect.cassandra.port": "9042",
    "connect.cassandra.key.space": "test",
    "connect.cassandra.contact.points": "cassandra",
    "connect.cassandra.username": "cassandra",
    "connect.cassandra.password": "123123123",
    "connect.cassandra.kcql": "INSERT INTO test33 SELECT id, data FROM test34"
}
</code>```

答: the converters must be the same on both source and sink side as serialization is done in the source side and deserialization on the sink side.</p>

Body:
I need to sink a JSON object from MongoDB to a column in Cassandra. I'm using ExtractNewDocumentState, AvroConverter. But it seems I'm wrong. And AvroConverter used in source or sink? If I used it in the source then I used it in the sink too?

{
"name": "mongodb_source_connector",
"config": {
    "connector.class": "io.debezium.connector.mongodb.MongoDbConnector",
    "tasks.max": "1",
    "mongodb.hosts": "rs0/mongo:27017",
    "mongodb.name": "dbserver1",
    "mongodb.user": "scorpion",
    "mongodb.password": "123123123",
    "database.whitelist": "ladiform",
    "database.history.kafka.bootstrap.servers": "kafka_3:9093",
    "transforms": "route,unwrap",
    "transforms.route.type": "org.apache.kafka.connect.transforms.RegexRouter",
    "transforms.route.regex": "([^.]+)\\.([^.]+)\\.([^.]+)",
    "transforms.route.replacement": "$3",
    "transforms.unwrap.type": "io.debezium.connector.mongodb.transforms.ExtractNewDocumentState",
    "transforms.unwrap.drop.tombstones": "false",
    "transforms.unwrap.delete.handling.mode": "drop",
    "transforms.unwrap.operation.header": "true",
    "key.converter": "io.confluent.connect.avro.AvroConverter",
    "value.converter": "io.confluent.connect.avro.AvroConverter",
    "key.converter.schema.registry.url": "http://schema-registry:8081",
    "value.converter.schema.registry.url": "http://schema-registry:8081"
}

}

{
"name": "cassandra_sink_connector",
"config": {
    "connector.class": "com.datamountaineer.streamreactor.connect.cassandra.sink.CassandraSinkConnector",
    "tasks.max": "1",
    "topics": "test34",
    "connect.cassandra.port": "9042",
    "connect.cassandra.key.space": "test",
    "connect.cassandra.contact.points": "cassandra",
    "connect.cassandra.username": "cassandra",
    "connect.cassandra.password": "123123123",
    "connect.cassandra.kcql": "INSERT INTO test33 SELECT id, data FROM test34"
}


问:
Adding a Dash in the editText automatically in Android
Have a look at my codes:

```<code>txt_HomeNo.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            boolean flag = true;
            String eachBlock[] = txt_HomeNo.getText().toString().split("-");
            for (int i = 0; i < eachBlock.length; i++) {
                if (eachBlock[i].length() > 3) {
                    flag = false;
                }
            }

            if (flag) {

                txt_HomeNo.setOnKeyListener(new OnKeyListener() {

                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {

                        if (keyCode == KeyEvent.KEYCODE_DEL)
                            keyDel = 1;
                        return false;
                    }
                });

                if (keyDel == 0) {

                    if (((txt_HomeNo.getText().length() + 1) % 4) == 0) {

                        if (txt_HomeNo.getText().toString().split("-").length <= 3) {
                            txt_HomeNo.setText(txt_HomeNo.getText() + "-");
                            txt_HomeNo.setSelection(txt_HomeNo.getText().length());
                        }
                    }
                    a = txt_HomeNo.getText().toString();
                } else {
                    a = txt_HomeNo.getText().toString();
                    keyDel = 0;
                }

            } else {
                txt_HomeNo.setText(a);
            }

        }
</code>```

The maximum length of the phone number is only 7. And when I already inputted 3 digits, it appends dash (that's what I'd like to happen) but my problem here is that the next 3 digits also appends dash (Like this: 511-871-)... My question is how can I do the codings with the next 4 digit number with having a dash on it. Please help me with this. thanks!

答:
Improvement on @techroid's answer: (kotlin version)

This will fix on the issue if the character are alphabet, start is always 0 but count and after are correct, while if the character is number, start is correct while the count is always 1, and the after is always 0.

To test the bug:

setDashMasking(yourInput, intArrayOf(3))

type: asd (this will append dash on after the d, so it will become asd-)

Then try deleting it, it cannot be deleted, unless you input 123, then @techroid's answer will not work.

Below code will be the fix for this issue.

```<code>    private fun setDashMasking(input: AppCompatEditText, dashIndexes: IntArray) {
        input.addTextChangedListener(object : TextWatcher {

            private var isFormatting = false
            private var deletingHyphen = false
            private var hyphenStart = 0
            private var deletingBackward = false

            override fun afterTextChanged(editable: Editable) {
                if (isFormatting) return

                isFormatting = true

                // If deleting hyphen, also delete character before or after it
                if (deletingHyphen && hyphenStart > 0) {
                    if (deletingBackward) {
                        if (hyphenStart - 1 < editable.length) {
                            editable.delete(hyphenStart - 1, hyphenStart)
                        }
                    } else if (hyphenStart < editable.length) {
                        editable.delete(hyphenStart, hyphenStart + 1)
                    }
                }

                if (!deletingHyphen &&
                    dashIndexes.contains(editable.toString().length)
                ) {
                    editable.append('-')
                }

                isFormatting = false
            }

            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
                if (isFormatting) return

                // Make sure user is deleting one char, without a selection
                val selStart = Selection.getSelectionStart(s)
                val selEnd = Selection.getSelectionEnd(s)

                if (s.length > 1 // Can delete another character
                    && count - after == 1 // deleting only 1 character
                    && s[selStart - 1] == '-' // a hyphen
                    && selStart == selEnd
                ) { // no selection
                    deletingHyphen = true
                    hyphenStart = selStart - 1
                    // Check if the user is deleting forward or backward
                    deletingBackward = selStart == (selStart - 1) + 1
                } else {
                    deletingHyphen = false
                }
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                listener?.onChanged(s.toString())
            }
        })
    }
</code>```

Body:
Have a look at my codes:

txt_HomeNo.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            boolean flag = true;
            String eachBlock[] = txt_HomeNo.getText().toString().split("-");
            for (int i = 0; i < eachBlock.length; i++) {
                if (eachBlock[i].length() > 3) {
                    flag = false;
                }
            }

            if (flag) {

                txt_HomeNo.setOnKeyListener(new OnKeyListener() {

                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {

                        if (keyCode == KeyEvent.KEYCODE_DEL)
                            keyDel = 1;
                        return false;
                    }
                });

                if (keyDel == 0) {

                    if (((txt_HomeNo.getText().length() + 1) % 4) == 0) {

                        if (txt_HomeNo.getText().toString().split("-").length <= 3) {
                            txt_HomeNo.setText(txt_HomeNo.getText() + "-");
                            txt_HomeNo.setSelection(txt_HomeNo.getText().length());
                        }
                    }
                    a = txt_HomeNo.getText().toString();
                } else {
                    a = txt_HomeNo.getText().toString();
                    keyDel = 0;
                }

            } else {
                txt_HomeNo.setText(a);
            }

        }

The maximum length of the phone number is only 7. And when I already inputted 3 digits, it appends dash (that's what I'd like to happen) but my problem here is that the next 3 digits also appends dash (Like this: 511-871-)... My question is how can I do the codings with the next 4 digit number with having a dash on it. Please help me with this. thanks!

Body:
Improvement on @techroid's answer: (kotlin version)

This will fix on the issue if the character are alphabet, start is always 0 but count and after are correct, while if the character is number, start is correct while the count is always 1, and the after is always 0.

To test the bug:

setDashMasking(yourInput, intArrayOf(3))

type: asd (this will append dash on after the d, so it will become asd-)

Then try deleting it, it cannot be deleted, unless you input 123, then @techroid's answer will not work.

Below code will be the fix for this issue.

    private fun setDashMasking(input: AppCompatEditText, dashIndexes: IntArray) {
        input.addTextChangedListener(object : TextWatcher {

            private var isFormatting = false
            private var deletingHyphen = false
            private var hyphenStart = 0
            private var deletingBackward = false

            override fun afterTextChanged(editable: Editable) {
                if (isFormatting) return

                isFormatting = true

                // If deleting hyphen, also delete character before or after it
                if (deletingHyphen && hyphenStart > 0) {
                    if (deletingBackward) {
                        if (hyphenStart - 1 < editable.length) {
                            editable.delete(hyphenStart - 1, hyphenStart)
                        }
                    } else if (hyphenStart < editable.length) {
                        editable.delete(hyphenStart, hyphenStart + 1)
                    }
                }

                if (!deletingHyphen &&
                    dashIndexes.contains(editable.toString().length)
                ) {
                    editable.append('-')
                }

                isFormatting = false
            }

            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
                if (isFormatting) return

                // Make sure user is deleting one char, without a selection
                val selStart = Selection.getSelectionStart(s)
                val selEnd = Selection.getSelectionEnd(s)

                if (s.length > 1 // Can delete another character
                    && count - after == 1 // deleting only 1 character
                    && s[selStart - 1] == '-' // a hyphen
                    && selStart == selEnd
                ) { // no selection
                    deletingHyphen = true
                    hyphenStart = selStart - 1
                    // Check if the user is deleting forward or backward
                    deletingBackward = selStart == (selStart - 1) + 1
                } else {
                    deletingHyphen = false
                }
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                listener?.onChanged(s.toString())
            }
        })
    }