问:
Make the value from option select auto-entered to the textarea
Is there any way that the value from select option to be auto-inserted into a textarea? (in php)

Option Select:

```<code><select id="Branch">
  <option value="MCG">MCG</option>
  <option value="KB">KB</option>
  <option value="KT">KT</option>
</select>
</code>```

TextArea

```<code><input name="street" type=text value=>
</code>```

Sorry in advance if I didn't ask the question correctly

答:
It is not possible using PHP at a time on change select but,
You can select option to be auto-inserted into a textarea using javascript like blow example

function updateTextareaValue(selectVal){
      document.getElementById("street").value = selectVal;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
    <body>
        <select id="Branch" onchange="updateTextareaValue(this.value);">
            <option value="MCG">MCG</option>
            <option value="KB">KB</option>
            <option value="KT">KT</option>
            <option value="XX">XX</option>
            <option value="YY">YY</option>
        </select>
        <textarea id="street"></textarea>
    </body>
</html></code>```

Body:
Is there any way that the value from select option to be auto-inserted into a textarea? (in php)

Option Select:

<select id="Branch">
  <option value="MCG">MCG</option>
  <option value="KB">KB</option>
  <option value="KT">KT</option>
</select>

TextArea

<input name="street" type=text value=>

Sorry in advance if I didn't ask the question correctly

Body:
It is not possible using PHP at a time on change select but,
You can select option to be auto-inserted into a textarea using javascript like blow example

function updateTextareaValue(selectVal){
      document.getElementById("street").value = selectVal;
}

<html>
    <body>
        <select id="Branch" onchange="updateTextareaValue(this.value);">
            <option value="MCG">MCG</option>
            <option value="KB">KB</option>
            <option value="KT">KT</option>
            <option value="XX">XX</option>
            <option value="YY">YY</option>
        </select>
        <textarea id="street"></textarea>
    </body>
</html>


来源: stackexchange

问:
How to implement internal member of public interface in external project
In c# version 8 (or higher) we're able to create internal member in interfaces. For example, I have project A that have interface IRunnable with internal void:

```<code>public interface IRunnable
{
    internal void DoSomeInternalStuff();
}
</code>```

Now, I have Student class in project A that implements IRunnable:

```<code>public class Student : IRunnable
{
    void IRunnable.DoSomeInternalStuff()
    {
        //Do stuff
    }
}
</code>```

Everything is working. But now, I created project B and created class Teacher. Now I want to implement IRunnable:

```<code>public class Teacher : IRunnable
{
    void IRunnable.DoSomeInternalStuff()
    {
        //Do stuff
    }
}
</code>```

The compiler is giving me an error:

IRunnable.DoSomeInternalStuff()' is inaccessible due to its protection

How to deal with this? How can I implement that interface on project B?

答:
Unfortunately, that breaks the use of internal. As per the definition, internal restricts the use of the method to the files or assemblies it is within. This is why it won't work for you in this situation.

Edit:
The question was closed as a duplicate, and the answer linked will show you how to expand the applicability of internal to other assemblies. As per Alexei's suggestion, I'll include the appropriate information here.

In Project A, you can include the InternalsVisibleTo([Name]) attribute on your assembly to enable visibility to a different assembly. For example:

```<code>[assembly: InternalsVisibleTo("ProjectB")]
namespace TestApp1
{
</code>```

This will enable ProjectB to access the method marked as internal on the IRunnable.DoSomeInternalStuff() interface, as it has been expressly allowed.

ContentLicense: CC BY-SA 4.0

Body:
In c# version 8 (or higher) we're able to create internal member in interfaces. For example, I have project A that have interface IRunnable with internal void:

public interface IRunnable
{
    internal void DoSomeInternalStuff();
}

Now, I have Student class in project A that implements IRunnable:

public class Student : IRunnable
{
    void IRunnable.DoSomeInternalStuff()
    {
        //Do stuff
    }
}

Everything is working. But now, I created project B and created class Teacher. Now I want to implement IRunnable:

public class Teacher : IRunnable
{
    void IRunnable.DoSomeInternalStuff()
    {
        //Do stuff
    }
}

The compiler is giving me an error:

IRunnable.DoSomeInternalStuff()' is inaccessible due to its protection

How to deal with this? How can I implement that interface on project B?

Body:
Unfortunately, that breaks the use of internal. As per the definition, internal restricts the use of the method to the files or assemblies it is within. This is why it won't work for you in this situation.

Edit:
The question was closed as a duplicate, and the answer linked will show you how to expand the applicability of internal to other assemblies. As per Alexei's suggestion, I'll include the appropriate information here.

In Project A, you can include the InternalsVisibleTo([Name]) attribute on your assembly to enable visibility to a different assembly. For example:

[assembly: InternalsVisibleTo("ProjectB")]
namespace TestApp1
{

This will enable ProjectB to access the method marked as internal on the IRunnable.DoSomeInternalStuff() interface, as it has been expressly allowed.


问:
How do I convert docker-compose configuration to dockerfile
I am a bit confused I was trying to convert dockercompose of elastic kibana to dockerfile. But networking part and connectivity part is bit confusing for me. Can anyone help me with conversion and a bit of explanation.

Thanks a lot!

```<code>version: "3.0"

services:
  elasticsearch:
    container_name: es-container
    image: docker.elastic.co/elasticsearch/elasticsearch:6.5.4
    environment:
      - xpack.security.enabled=true
      - "discovery.type=single-node"
    networks:
      - es-net
    ports:
      - 9200:9200
  kibana:
    container_name: kb-container
    image: docker.elastic.co/kibana/kibana:6.5.4
    environment:
      - ELASTICSEARCH_HOSTS=http://es-container:9200
    networks:
      - es-net
    depends_on:
      - elasticsearch
    ports:
      - 5601:5601

networks:
  es-net:
    driver: bridge
</code>```

答:
Docker Compose and Dockerfiles are completely different things. The Dockerfile is a configuration file used to create Docker images.  The docker-compose.yml file is a configuration file used by Docker Compose to launch Docker containers using Docker images.

To launch the above containers without using Docker Compose you could run:

```<code> docker network create es-net
 docker run -d -e xpack.security.enabled=true -e "discovery.type=single-node" -p 9200:9200 --network es-net --name es-container docker.elastic.co/elasticsearch/elasticsearch:6.5.4
 docker run -d -e ELASTICSEARCH_HOSTS=http://es-container:9200 -p 5601:5601 --network es-net --name kb-container docker.elastic.co/kibana/kibana:6.5.4
</code>```

Alternatively, you could run the containers on the hosts network stack (rather than the es-net nework). Kibana would then be able to talk to ElasticSearch on localhost:

```<code> docker run -d -e xpack.security.enabled=true -e "discovery.type=single-node" --network host --name es-container docker.elastic.co/elasticsearch/elasticsearch:6.5.4
 docker run -d -e ELASTICSEARCH_HOSTS=http://localhost:9200 --network host --name kb-container docker.elastic.co/kibana/kibana:6.5.4
</code>```

(I haven't actually run these so the commands might need some tweaking).

Body:
I am a bit confused I was trying to convert dockercompose of elastic kibana to dockerfile. But networking part and connectivity part is bit confusing for me. Can anyone help me with conversion and a bit of explanation.

Thanks a lot!

version: "3.0"

services:
  elasticsearch:
    container_name: es-container
    image: docker.elastic.co/elasticsearch/elasticsearch:6.5.4
    environment:
      - xpack.security.enabled=true
      - "discovery.type=single-node"
    networks:
      - es-net
    ports:
      - 9200:9200
  kibana:
    container_name: kb-container
    image: docker.elastic.co/kibana/kibana:6.5.4
    environment:
      - ELASTICSEARCH_HOSTS=http://es-container:9200
    networks:
      - es-net
    depends_on:
      - elasticsearch
    ports:
      - 5601:5601

networks:
  es-net:
    driver: bridge

Body:
Docker Compose and Dockerfiles are completely different things. The Dockerfile is a configuration file used to create Docker images.  The docker-compose.yml file is a configuration file used by Docker Compose to launch Docker containers using Docker images.

To launch the above containers without using Docker Compose you could run:

 docker network create es-net
 docker run -d -e xpack.security.enabled=true -e "discovery.type=single-node" -p 9200:9200 --network es-net --name es-container docker.elastic.co/elasticsearch/elasticsearch:6.5.4
 docker run -d -e ELASTICSEARCH_HOSTS=http://es-container:9200 -p 5601:5601 --network es-net --name kb-container docker.elastic.co/kibana/kibana:6.5.4

Alternatively, you could run the containers on the hosts network stack (rather than the es-net nework). Kibana would then be able to talk to ElasticSearch on localhost:

 docker run -d -e xpack.security.enabled=true -e "discovery.type=single-node" --network host --name es-container docker.elastic.co/elasticsearch/elasticsearch:6.5.4
 docker run -d -e ELASTICSEARCH_HOSTS=http://localhost:9200 --network host --name kb-container docker.elastic.co/kibana/kibana:6.5.4

(I haven't actually run these so the commands might need some tweaking).


问:
How to update a single column in a Pandas df with data from a second Pandas df using pd.merge function
Please see my code below.  I was stuck on this problem for a while and so thought I would share the solution I found in case it helps someone else.

The problem (now solved; see solution below) is as follows:

I have a "master" df, called df_master, that holds a large amount of information.

The data in column 'c' of df_master contains pricing data that must sometimes be updated with data found in column 'c' of a second, smaller df.  I call this smaller df 'df_updates'.

df_updates contains pricing updates for only a small portion of the rows in df_master, meaning that only a few updates to column 'c' of df_master need to be made.

The column names in df_updates are identical to the column names in df_master.

I wish to update the pricing data in col 'c' of df_master with the information in col 'c' of df_updates.

The solution I found is in the answer below.  Hopefully this helps someone facing this same problem.

答:
It is unclear from your question how you find the rows that needs to be updated, but if df_master and df_updates matches on the index, it is as simple as using .loc and an assignment:

# Build the datasets with dummy data
df_master = pd.DataFrame({'c': range(20)})
# Prices are changed for every other row from row 1 up to (but not including) row 15
df_updates = df_master[1:15:2] * 20
```
<pre class="lang-py prettyprint-override"><code># update values that matches on the index of df_updates

df_master.loc[df_updates.index, 'c'] = df_updates['c']
</code>```
```<code>    c
0   0
1   20
2   2
3   60
4   4
5   100
6   6
7   140
8   8
9   180
10  10
11  220
12  12
13  260
14  14
15  15
16  16
17  17
18  18
19  19
</code>```

Body:
It is unclear from your question how you find the rows that needs to be updated, but if df_master and df_updates matches on the index, it is as simple as using .loc and an assignment:

# Build the datasets with dummy data
df_master = pd.DataFrame({'c': range(20)})
# Prices are changed for every other row from row 1 up to (but not including) row 15
df_updates = df_master[1:15:2] * 20

# update values that matches on the index of df_updates

df_master.loc[df_updates.index, 'c'] = df_updates['c']

    c
0   0
1   20
2   2
3   60
4   4
5   100
6   6
7   140
8   8
9   180
10  10
11  220
12  12
13  260
14  14
15  15
16  16
17  17
18  18
19  19


问:
yq - Find and replace map value by map key
I have a yml file called output.yml which contains a K8s Service, Deployment and Ingress resources like so (lots of fields omitted for brevity):

```<code>apiVersion: v1
kind: Service
metadata:
  labels:
    app.kubernetes.io/name: app-name
    app.kubernetes.io/instance: instance-name
spec:
  selector:
    app.kubernetes.io/name: app-name
    app.kubernetes.io/instance: instance-name
---
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app.kubernetes.io/name: app-name
    app.kubernetes.io/instance: instance-name
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: app-name
      app.kubernetes.io/instance: instance-name
  template:
    metadata:
      labels:
        app.kubernetes.io/name: app-name
        app.kubernetes.io/instance: instance-name
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  labels:
    app.kubernetes.io/name: app-name
    app.kubernetes.io/instance: instance-name
</code>```

What I would like to do is, for all occurrences of where the key = app.kubernetes.io/instance, replace all values of instance-name with a different value say app-instance-name2. I have tried several things like using the select and has operators like so: yq eval '(.. | select(has("app.kubernetes.io/instance"))' but it returns all map keys instead of just the one I want to update and then I'm not really sure where to go from there.

At the moment, I am just updating each individual value like so:

```<code>yq e '.metadata.labels["app.kubernetes.io/instance"] = strenv(INSTANCE_NAME)' -i output.yml
yq e 'select(.kind == "Service").spec.selector["app.kubernetes.io/instance"] = strenv(INSTANCE_NAME)' -i output.yml
yq e 'select(.kind == "Deployment").spec.selector.matchLabels["app.kubernetes.io/instance"] = strenv(INSTANCE_NAME)' -i output.yml
yq e 'select(.kind == "Deployment").spec.template.metadata.labels["app.kubernetes.io/instance"] = strenv(INSTANCE_NAME)' -i output.yml
</code>```

which works but is pretty verbose so I'd like if there was a succinct single line option?

I am using yq version 4.17.2 from https://mikefarah.gitbook.io/yq

Any advice is much appreciated

答:
It can be accomplished by doing a recursive decent to identify keys matching your string and update their value part using |=

yq e '(..|select(has("app.kubernetes.io/instance")).["app.kubernetes.io/instance"]) |= "app-instance-name2"' output.yml
```

Starting v4.18.1, the eval flag is the default action, so the e flag can be avoided

Body:
I have a yml file called output.yml which contains a K8s Service, Deployment and Ingress resources like so (lots of fields omitted for brevity):

apiVersion: v1
kind: Service
metadata:
  labels:
    app.kubernetes.io/name: app-name
    app.kubernetes.io/instance: instance-name
spec:
  selector:
    app.kubernetes.io/name: app-name
    app.kubernetes.io/instance: instance-name
---
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app.kubernetes.io/name: app-name
    app.kubernetes.io/instance: instance-name
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: app-name
      app.kubernetes.io/instance: instance-name
  template:
    metadata:
      labels:
        app.kubernetes.io/name: app-name
        app.kubernetes.io/instance: instance-name
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  labels:
    app.kubernetes.io/name: app-name
    app.kubernetes.io/instance: instance-name

What I would like to do is, for all occurrences of where the key = app.kubernetes.io/instance, replace all values of instance-name with a different value say app-instance-name2. I have tried several things like using the select and has operators like so: yq eval '(.. | select(has("app.kubernetes.io/instance"))' but it returns all map keys instead of just the one I want to update and then I'm not really sure where to go from there.

At the moment, I am just updating each individual value like so:

yq e '.metadata.labels["app.kubernetes.io/instance"] = strenv(INSTANCE_NAME)' -i output.yml
yq e 'select(.kind == "Service").spec.selector["app.kubernetes.io/instance"] = strenv(INSTANCE_NAME)' -i output.yml
yq e 'select(.kind == "Deployment").spec.selector.matchLabels["app.kubernetes.io/instance"] = strenv(INSTANCE_NAME)' -i output.yml
yq e 'select(.kind == "Deployment").spec.template.metadata.labels["app.kubernetes.io/instance"] = strenv(INSTANCE_NAME)' -i output.yml

which works but is pretty verbose so I'd like if there was a succinct single line option?

I am using yq version 4.17.2 from https://mikefarah.gitbook.io/yq

Any advice is much appreciated

Body:
It can be accomplished by doing a recursive decent to identify keys matching your string and update their value part using |=

yq e '(..|select(has("app.kubernetes.io/instance")).["app.kubernetes.io/instance"]) |= "app-instance-name2"' output.yml

Starting v4.18.1, the eval flag is the default action, so the e flag can be avoided


问:
Error starting Guile with `readline` support
I'm trying to configure Guile to use readline.

Here's my ~/.guile:

(use-modules (ice-9 readline))
```
<p>(there was more, this one line is sufficient to have this failure)</p>
<p>Here's a log of my interaction:</p>
<pre class="lang-lisp prettyprint-override"><code>agam@ssdnodes-61de65ea00d0b:~$ guile
guile: warning: failed to install locale
Backtrace:
In ice-9/boot-9.scm:
  1752:10 12 (with-exception-handler _ _ #:unwind? _ # _)
In unknown file:
          11 (apply-smob/0 #<thunk 7fb7984660c0>)
In ice-9/boot-9.scm:
    724:2 10 (call-with-prompt ("prompt") #<procedure 7fb796fc2e80 ?> ?)
In ice-9/eval.scm:
    619:8  9 (_ #(#(#<directory (guile-user) 7fb79846cc80>)))
In unknown file:
           8 (primitive-load "/home/agam/.guile")
In ice-9/eval.scm:
   721:20  7 (primitive-eval (use-modules (ice-9 readline)))
In ice-9/psyntax.scm:
  1230:36  6 (expand-top-sequence ((use-modules (ice-9 readline))) _ ?)
  1222:19  5 (parse _ (("placeholder" placeholder)) ((top) #(# # ?)) ?)
   259:10  4 (parse _ (("placeholder" placeholder)) (()) _ c&e (eval) ?)
In ice-9/boot-9.scm:
  3927:20  3 (process-use-modules _)
   222:17  2 (map1 (((ice-9 readline))))
  3928:31  1 (_ ((ice-9 readline)))
   3329:6  0 (resolve-interface (ice-9 readline) #:select _ #:hide _ ?)

ice-9/boot-9.scm:3329:6: In procedure resolve-interface:
no code for module (ice-9 readline)
</code>```

If it helps, I'm doing this within Guile installed via guix install guile. I have installed glibc-locales, and GUIX_LOCPATH is set to "$HOME/.guix-profile/lib/locale"

答:
Turns out the locale ... warning was a red herring, I was missing the readline package.

I needed to

guix install guile-readline, followed by

. "$GUIX_PROFILE/etc/profile"

After that, guile starts up fine.

Body:
I'm trying to configure Guile to use readline.

Here's my ~/.guile:

(use-modules (ice-9 readline))

(there was more, this one line is sufficient to have this failure)

Here's a log of my interaction:

agam@ssdnodes-61de65ea00d0b:~$ guile
guile: warning: failed to install locale
Backtrace:
In ice-9/boot-9.scm:
  1752:10 12 (with-exception-handler _ _ #:unwind? _ # _)
In unknown file:
          11 (apply-smob/0 #<thunk 7fb7984660c0>)
In ice-9/boot-9.scm:
    724:2 10 (call-with-prompt ("prompt") #<procedure 7fb796fc2e80 ?> ?)
In ice-9/eval.scm:
    619:8  9 (_ #(#(#<directory (guile-user) 7fb79846cc80>)))
In unknown file:
           8 (primitive-load "/home/agam/.guile")
In ice-9/eval.scm:
   721:20  7 (primitive-eval (use-modules (ice-9 readline)))
In ice-9/psyntax.scm:
  1230:36  6 (expand-top-sequence ((use-modules (ice-9 readline))) _ ?)
  1222:19  5 (parse _ (("placeholder" placeholder)) ((top) #(# # ?)) ?)
   259:10  4 (parse _ (("placeholder" placeholder)) (()) _ c&e (eval) ?)
In ice-9/boot-9.scm:
  3927:20  3 (process-use-modules _)
   222:17  2 (map1 (((ice-9 readline))))
  3928:31  1 (_ ((ice-9 readline)))
   3329:6  0 (resolve-interface (ice-9 readline) #:select _ #:hide _ ?)

ice-9/boot-9.scm:3329:6: In procedure resolve-interface:
no code for module (ice-9 readline)

If it helps, I'm doing this within Guile installed via guix install guile. I have installed glibc-locales, and GUIX_LOCPATH is set to "$HOME/.guix-profile/lib/locale"


问:
How to read a file into a dataframe where the values are grouped in parentheses?
I need to import a text file that is formatted as such

```<code>(201803, 95), (201708, 61)
(202002, 88), (201501, 88)
(202004, 76), (201602, 35)
(201012, 113), (201012, 115)
(201009, 114), (201708, 114)
(201603, 31), (201206, 78)
</code>```

And turn it into a dataframe with this format where the first column is a date and the second column is an integer for temperature.

```<code>Year Temp
201803 95
201708 61
202002 88
201501 88
202004 76
201602 35
201012 113
201012 115
201009 114
201708 114
201603 31
201206 78
</code>```

I tried to import it using pandas.read_csv but I get a dataframe with 4 columns and 2 rows of data in a row.

```<code>           0      1         2      3
0    (201803    95)   (201708    61)
1    (202002    88)   (201501    88
</code>```

答: Pandas imports exactly how it sees. To group things how you want in your case, you'll need to wrap the columns in the same set of quotes or simply restructure the CSV to be linearly stacked as you want for the output.</p>

Body:
I need to import a text file that is formatted as such

(201803, 95), (201708, 61)
(202002, 88), (201501, 88)
(202004, 76), (201602, 35)
(201012, 113), (201012, 115)
(201009, 114), (201708, 114)
(201603, 31), (201206, 78)

And turn it into a dataframe with this format where the first column is a date and the second column is an integer for temperature.

Year Temp
201803 95
201708 61
202002 88
201501 88
202004 76
201602 35
201012 113
201012 115
201009 114
201708 114
201603 31
201206 78

I tried to import it using pandas.read_csv but I get a dataframe with 4 columns and 2 rows of data in a row.

           0      1         2      3
0    (201803    95)   (201708    61)
1    (202002    88)   (201501    88


问:
Can't input negative integer into SQLite table
I'm trying to put a negative integer into my sqlite database but it's not being inserted for some reason.

I get the error:

TypeError: can't multiply sequence by non-int of type 'float'

And when I checked with printing the value, I find that it's empty.

This is the command I use to insert to the table:

db.execute(
    "INSERT INTO history (id,date,symbol,shares,price) VALUES (?,?,?,?,?)",
    session["user_id"],
    time,
    request.form.get("symbol").upper(),
    request.form.get("shares") * -1,
    price,
)
```
<p><code>request.form.get("shares")</code> is a number input from a HTML form.</p>
<p>And I use this to make the table:</p>
<pre class="lang-py prettyprint-override"><code>db.execute(
    "CREATE TABLE history (id int, date varchar(255), symbol varchar(9), shares int, price int)"
)
</code>```

I've tried surrounding request.form.get("shares") with an int() but it didn't work.

Positive integers work fine.

答:
The reason is exactly what the error is saying. The returned data from the request form is returning a non digit type. Any input is returned as a string and then needs to be redefined. If you try doing

print(type(request.form.get("shares")
```

You can see the type of the result and work from there. What @Jack Deeth said in his answer will work. You can also always do the math before insert and declare as an int beforehand.

Body:
I'm trying to put a negative integer into my sqlite database but it's not being inserted for some reason.

I get the error:

TypeError: can't multiply sequence by non-int of type 'float'

And when I checked with printing the value, I find that it's empty.

This is the command I use to insert to the table:

db.execute(
    "INSERT INTO history (id,date,symbol,shares,price) VALUES (?,?,?,?,?)",
    session["user_id"],
    time,
    request.form.get("symbol").upper(),
    request.form.get("shares") * -1,
    price,
)

request.form.get("shares") is a number input from a HTML form.

And I use this to make the table:

db.execute(
    "CREATE TABLE history (id int, date varchar(255), symbol varchar(9), shares int, price int)"
)

I've tried surrounding request.form.get("shares") with an int() but it didn't work.

Positive integers work fine.

Body:
The reason is exactly what the error is saying. The returned data from the request form is returning a non digit type. Any input is returned as a string and then needs to be redefined. If you try doing

print(type(request.form.get("shares")

You can see the type of the result and work from there. What @Jack Deeth said in his answer will work. You can also always do the math before insert and declare as an int beforehand.


问:
Run on server option not appearing in Eclipse
I'm learning SpringMVC framework and checked out a copy of their code:
https://src.springframework.org/svn/spring-samples/mvc-basic/trunk/
I can do maven build, install and everything. But on Eclipse, run on server option never appeared. I have tomcat server up and running, also got plugin for eclipse. Why run on server option is missing? This is a Ubuntu machine.
When I tried the exact same thing on my Windows machine, everything was fine. It has the same version of eclipse and all sorts of plugins installed as the Ubuntu machine. I was able to launch it from Eclipse "run on server" option there.

Can someone help me to figure out why? Thanks.

答:
Perhaps you lost some configuration, check jar dependencies in properties -> Deployment Assembly. If you miss something, try to add dependencies again.

in my case, fixing this, Run on Server appear again.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
REST API not recognizing events (AWS)
I have an API that is connected to a lambda function that has queryStringParameters. On the function end I have

```<code>VARIABLE = event['queryStringParameters']['variable']
</code>```

When I deploy my API and try to use it "api_url"?variable=something,

I get {"message": "Internal server error"}.

In Cloudwatch I get:

```<code>[ERROR] KeyError: 'queryStringParameters'

Traceback (most recent call last):

File "/var/task/index.py", line 217, in handler

VARIABLE = event['queryStringParameters']['variable']
</code>```

To help troubleshoot I print the event. In Cloudwatch it does, and it appears as "{}", so pretty much as empty.

When I test the function in the console I use the event:

```<code>{ "queryStringParameters": {"variable": "T"}}
</code>```

and the function works just fine.

I've made APIs that are connected to lambda functions before almost identical to this and have had no problem. I'm stumped. Any advice is appreciated.

答:
Based on this AWS guide, you can access the query string parameters using get methods of the event object.

query_string = event.get('queryStringParameters')

if query_string is not None:
  name = query_string.get('variable')

```
<p>In your lambda's case, its quite strange that no <code>queryStringParameters</code> key could be found on the event object. It would be interesting to see if there's an actual parameter sent to the REST API or if the positioning of parameters in the handler's parameters are correct and that the parameter is provided on all requests.</p>
<pre class="lang-py prettyprint-override"><code>
def event_handler(event, context): # Make sure event goes first
  query_string = event.get('queryStringParameters')

  if query_string is None:
   // Return 400 / 422 here to indicate a bad request
</code>```

Title: REST API not recognizing events (AWS)

Body:
I have an API that is connected to a lambda function that has queryStringParameters. On the function end I have

VARIABLE = event['queryStringParameters']['variable']

When I deploy my API and try to use it "api_url"?variable=something,

I get {"message": "Internal server error"}.

In Cloudwatch I get:

[ERROR] KeyError: 'queryStringParameters'

Traceback (most recent call last):

File "/var/task/index.py", line 217, in handler

VARIABLE = event['queryStringParameters']['variable']

To help troubleshoot I print the event. In Cloudwatch it does, and it appears as "{}", so pretty much as empty.

When I test the function in the console I use the event:

{ "queryStringParameters": {"variable": "T"}}

and the function works just fine.

I've made APIs that are connected to lambda functions before almost identical to this and have had no problem. I'm stumped. Any advice is appreciated.

Body:
Based on this AWS guide, you can access the query string parameters using get methods of the event object.

query_string = event.get('queryStringParameters')

if query_string is not None:
  name = query_string.get('variable')

In your lambda's case, its quite strange that no queryStringParameters key could be found on the event object. It would be interesting to see if there's an actual parameter sent to the REST API or if the positioning of parameters in the handler's parameters are correct and that the parameter is provided on all requests.

def event_handler(event, context): # Make sure event goes first
  query_string = event.get('queryStringParameters')

  if query_string is None:
   // Return 400 / 422 here to indicate a bad request


问:
After onBlur the input is not accessible
I am using onBlur to change the state of the error, to validate the value in the input component. But as the user click away from the input, it takes a few seconds until he can click back the input to change the value.

Can anyone know why this happens?
Another question,how can I change the type of the event returned from onBlur so not to be 'any'?

Form.tsx

```<code>  const [errorFlag, setErrorFlag] = useState(false);
  const [plz, setPLZ] = useState<string | undefined>(undefined);

  const onBlur = (e:any) => {
    setErrorFlag(e.target.checkValidity());
    };
      return (<Fragment>
          ...
          <Input
            onChange={setPLZ}
            name="PLZ"
            pattern="^[0-9]{5}$"
            errorMessage="* Invalid Postal Code"
            error={plz === ''}
            required={true}
            onBlur={onBlur}
            style={{ flexGrow: 0, width: '100px', marginRight: '20px' }}
          />
        </Fragment>)
</code>```

FormInput.tsx

```<code>export interface InputProps {
  ...
  onChange?: (value: string) => void;
  onBlur?:(event: React.ChangeEvent<HTMLInputElement>) => void;
}

export class Input extends React.Component<InputProps, {
  value: string;
}> {

  constructor(props: InputProps) {
    super(props);
    this.state = { value: '' };
  }

  private onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    this.setState({ value: event.target.value });
    this.props.onChange?.(event.target.value);

  }
  private onBlur = (event: React.ChangeEvent<HTMLInputElement>) => {
    this.props.onBlur?.(event);
 }

  render() {

    return (
      <div key="form-name" className="formrow" style={{...this.props.style}}>
        <input
          ...
          onChange={this.onChange}
          onBlur={this.onBlur}
          />
        <span id="formInput-errorspan" className="errorSpan">{this.props.errorMessage}</span>
      </div>
    );
  }
}

</code>```

答:
I have not an idea for your first question, but you can use

```<code><React.FocusEventHandler<HTMLInputElement | HTMLTextAreaElement> | undefined>
</code>```

as type for your onBlur Event

Body:
I am using onBlur to change the state of the error, to validate the value in the input component. But as the user click away from the input, it takes a few seconds until he can click back the input to change the value.

Can anyone know why this happens?
Another question,how can I change the type of the event returned from onBlur so not to be 'any'?

Form.tsx

  const [errorFlag, setErrorFlag] = useState(false);
  const [plz, setPLZ] = useState<string | undefined>(undefined);

  const onBlur = (e:any) => {
    setErrorFlag(e.target.checkValidity());
    };
      return (<Fragment>
          ...
          <Input
            onChange={setPLZ}
            name="PLZ"
            pattern="^[0-9]{5}$"
            errorMessage="* Invalid Postal Code"
            error={plz === ''}
            required={true}
            onBlur={onBlur}
            style={{ flexGrow: 0, width: '100px', marginRight: '20px' }}
          />
        </Fragment>)

FormInput.tsx

export interface InputProps {
  ...
  onChange?: (value: string) => void;
  onBlur?:(event: React.ChangeEvent<HTMLInputElement>) => void;
}

export class Input extends React.Component<InputProps, {
  value: string;
}> {

  constructor(props: InputProps) {
    super(props);
    this.state = { value: '' };
  }

  private onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    this.setState({ value: event.target.value });
    this.props.onChange?.(event.target.value);

  }
  private onBlur = (event: React.ChangeEvent<HTMLInputElement>) => {
    this.props.onBlur?.(event);
 }

  render() {

    return (

        <input
          ...
          onChange={this.onChange}
          onBlur={this.onBlur}
          />
        {this.props.errorMessage}

    );
  }
}

Body:
I have not an idea for your first question, but you can use

<React.FocusEventHandler<HTMLInputElement | HTMLTextAreaElement> | undefined>

as type for your onBlur Event


问:
closing opening container on click
Container is initially hidden.

Container opens when clicked on ".myclass".

Container should stay open until clicked on anything! outside of ".container".

Container should also close, when clicked on ".myclass"

Elements inside of "div class='myclass'" do not fully overlap parent divs, so user can click on parent div or any inside elements (depending on click location).

problems here: ".container" closes immediately once it opens.

Code below.

```<code><div class="myclass">
<div>
    <div>
        <div>
        </div>
    </div>
    <div>
    </div>
</div>
</div>
<div class="container"></div>

<script>
//click to open
$(".myclass").click(function(){

        var target = $('.container');
        if( target.is(':hidden') ) {
            $(".container").slideDown("fast");
        } else {
            $(".container").slideUp("fast");
        }
    });

//click outside to close
$(document.body).click(function(event){
        var outside_area = $(event.target);

        if (!outside_area.is(".myclass") && !outside_area.is(".container") ){
            $(".container").slideUp("fast");
        }
    });
</code>```

答:
```<code>$(".myclass").click(function(){

    var target = $('.container');
    if( target.is(':hidden') ) {
        $(".container").slideDown("fast");
    } else {
        $(".container").slideUp("fast");
    }
});

$(document.body).click(function(){
   $(".container").slideUp("fast");
});
$(".container, .myclass").click(function(event){
     event.stopPropagation();
});
</code>```

Title: closing opening container on click


问:
SQLAlchemy: session.begin_nested() with session.commit()
I am using Flask-SQLAlchemy, with autocommit set to False and autoflush set to True. It's connecting to a mysql database.

I have 3 methods like this:

```<code>def insert_something():
   insert_statement = <something>
   db.session.execute(insert_statement);
   db.session.commit()

def delete_something():
   delete_statement = <something>
   db.session.execute(delete_statement);
   db.session.commit()

def delete_something_else():
   delete_statement = <something>
   db.session.execute(delete_statement);
   db.session.commit()
</code>```

Sometimes I want to run these methods individually; no problems there — but sometimes I want to run them together in a nested transaction. I want insert_something to run first, and delete_something to run afterwards, and delete_something_else to run last. If any of those methods fail then I want everything to be rolled back.

I've tried the following:

```<code>db.session.begin_nested()
insert_something()
delete_something()
delete_something_else()
db.session.commit()
</code>```

This doesn't work, though, because insert_something exits the nested transaction (and releases the savepoint). Then, when delete_something runs db.session.commit() it actually commits the deletion to the database because it is in the outermost transaction.
That final db.session.commit() in the code block above doesn't do anything..everything is already committed by that point.

Maybe I can do something like this, but it's ugly as hell:

```<code>db.session.begin_nested()
db.session.begin_nested()
db.session.begin_nested()
db.session.begin_nested()
insert_something()
delete_something()
delete_something_else()
db.session.commit()
</code>```

There's gotta be a better way to do it without touching the three methods..

Edit:
Now I'm doing it like this:

```<code>with db.session.begin_nested():
    insert_something()
with db.session.begin_nested():
    delete_something()
with db.session.begin_nested():
    delete_something_else()

db.session.commit()
</code>```

Which is better, but still not great.

I'd love to be able to do something like this:

```<code>with db.session.begin_nested() as nested:
    insert_something()
    delete_something()
    delete_something_else()
    nested.commit() #  though I feel like you shouldn't need this in a with block
</code>```

答:
The docs discuss avoiding this pattern in arbitrary-transaction-nesting-as-an-antipattern and session-faq-whentocreate.

But there is an example in the docs that is similar to this but it is for testing.

https://docs.sqlalchemy.org/en/14/orm/session_transaction.html?highlight=after_transaction_end#joining-a-session-into-an-external-transaction-such-as-for-test-suites

Regardless, here is a gross transaction manager based on the example that "seems" to work but don't do this.  I think there are a lot of gotchas in here.

import contextlib

from sqlalchemy import (
    create_engine,
    Integer,
    String,
)
from sqlalchemy.schema import (
    Column,
    MetaData,
)
from sqlalchemy.orm import declarative_base, Session
from sqlalchemy import event
from sqlalchemy.sql import delete, select

db_uri = 'postgresql+psycopg2://username:password@/database'

engine = create_engine(db_uri, echo=True)

metadata = MetaData()

Base = declarative_base(metadata=metadata)

class Device(Base):
    __tablename__ = "devices"
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(50))

def get_devices(session):
    return [d.name for (d,) in session.execute(select(Device)).all()]

def create_device(session, name):
    session.add(Device(name=name))
    session.commit()

def delete_device(session, name):
    session.execute(delete(Device).filter(Device.name == name))
    session.commit()

def almost_create_device(session, name):
    session.add(Device(name=name))
    session.flush()
    session.rollback()

@contextlib.contextmanager
def force_nested_transaction_forever(session, commit_on_complete=True):
    """
    Keep re-entering a nested transaction everytime a transaction ends.
    """
    d = {
        'nested': session.begin_nested()
    }
    @event.listens_for(session, "after_transaction_end")
    def end_savepoint(session, transaction):
        # Start another nested trans if the prior one is no longer active.
        if not d['nested'].is_active:
            d['nested'] = session.begin_nested()

    try:
        yield
    finally:
        # Stop trapping us in perpetual nested transactions.
        # Is this the right place for this ?
        event.remove(session, "after_transaction_end", end_savepoint)

    # This seems like it would be error prone.
    if commit_on_complete and d['nested'].is_active:
        d.pop('nested').commit()

if __name__ == '__main__':

    metadata.create_all(engine)

    with Session(engine) as session:
        with session.begin():
            # THIS IS NOT RECOMMENDED
            with force_nested_transaction_forever(session):
                create_device(session, "0")
                create_device(session, "a")
                delete_device(session, "a")
                almost_create_device(session, "a")
                create_device(session, "b")
            assert len(get_devices(session)) == 2
        assert len(get_devices(session)) == 2

```

Body:
I am using Flask-SQLAlchemy, with autocommit set to False and autoflush set to True. It's connecting to a mysql database.

I have 3 methods like this:

def insert_something():
   insert_statement = <something>
   db.session.execute(insert_statement);
   db.session.commit()

def delete_something():
   delete_statement = <something>
   db.session.execute(delete_statement);
   db.session.commit()

def delete_something_else():
   delete_statement = <something>
   db.session.execute(delete_statement);
   db.session.commit()

Sometimes I want to run these methods individually; no problems there — but sometimes I want to run them together in a nested transaction. I want insert_something to run first, and delete_something to run afterwards, and delete_something_else to run last. If any of those methods fail then I want everything to be rolled back.

I've tried the following:

db.session.begin_nested()
insert_something()
delete_something()
delete_something_else()
db.session.commit()

This doesn't work, though, because insert_something exits the nested transaction (and releases the savepoint). Then, when delete_something runs db.session.commit() it actually commits the deletion to the database because it is in the outermost transaction.
That final db.session.commit() in the code block above doesn't do anything..everything is already committed by that point.

Maybe I can do something like this, but it's ugly as hell:

db.session.begin_nested()
db.session.begin_nested()
db.session.begin_nested()
db.session.begin_nested()
insert_something()
delete_something()
delete_something_else()
db.session.commit()

There's gotta be a better way to do it without touching the three methods..

Edit:
Now I'm doing it like this:

with db.session.begin_nested():
    insert_something()
with db.session.begin_nested():
    delete_something()
with db.session.begin_nested():
    delete_something_else()

db.session.commit()

Which is better, but still not great.

I'd love to be able to do something like this:

with db.session.begin_nested() as nested:
    insert_something()
    delete_something()
    delete_something_else()
    nested.commit() #  though I feel like you shouldn't need this in a with block


问:
'PopularProductController' doesn't conform to the bound 'GetxController' of the type parameter 'T'

ist code is there . some one help me for this issu . i can't solve this issu .this type of problem i face first time so i can't solve it .please someone help me

```<code>  Widget build(BuildContext context) {
    print("current height is " + MediaQuery.of(context).size.height.toString());
    print("current width is " + MediaQuery.of(context).size.width.toString());
    return Column(
      children: [
        //slider section
        GetBuilder<PopularProductController>(builder:(popularproducts){
          return Container(
            // color: Colors.blue,
            height: Dimentions.pageView,
            child: PageView.builder(
              controller: pageController,
              itemCount: 5,
              itemBuilder: (context, position) {
                return _buildPageItem(position);
              },
            ),
          );
</code>```

second code is controller section code  . some one help me for this issu . i can't solve this issu .this type of problem i face first time so i can't solve it .please someone help me.

```<code>import 'package:fooddeliver/data/repository/popular_product_repo.dart';
import 'package:fooddeliver/modals/products_modal.dart';
import 'package:get/get.dart';

class PopularProductController extends GetxService {
  final PopularProductRepo popularProductRepo;
  PopularProductController({required this.popularProductRepo});
  List<dynamic> _popularProductList = [];
  List<dynamic> get popularProductList => _popularProductList;
  Future<void> getPopularProductList() async {
    Response response = await popularProductRepo.getPopularProductlist();
    if (response.statusCode == 200) {
      _popularProductList = [];
      print('product list');

      _popularProductList.addAll(Product.fromJson(response.body).products);
      print(_popularProductList);
    }
  }
}
</code>```

答:
You should extends from GetxController in the controller.

So just change GetxService to GetxController in the controller.

Please check below sample :

class PopularProductController extends GetxController {
  final PopularProductRepo popularProductRepo;
  PopularProductController({required this.popularProductRepo});
  List<dynamic> _popularProductList = [];
  List<dynamic> get popularProductList => _popularProductList;
  Future<void> getPopularProductList() async {
    Response response = await popularProductRepo.getPopularProductlist();
    if (response.statusCode == 200) {
      _popularProductList = [];
      print('product list');

      _popularProductList.addAll(Product.fromJson(response.body).products);
      print(_popularProductList);
    }
  }
}
```

Body:
ist code is there . some one help me for this issu . i can't solve this issu .this type of problem i face first time so i can't solve it .please someone help me

  Widget build(BuildContext context) {
    print("current height is " + MediaQuery.of(context).size.height.toString());
    print("current width is " + MediaQuery.of(context).size.width.toString());
    return Column(
      children: [
        //slider section
        GetBuilder<PopularProductController>(builder:(popularproducts){
          return Container(
            // color: Colors.blue,
            height: Dimentions.pageView,
            child: PageView.builder(
              controller: pageController,
              itemCount: 5,
              itemBuilder: (context, position) {
                return _buildPageItem(position);
              },
            ),
          );

second code is controller section code  . some one help me for this issu . i can't solve this issu .this type of problem i face first time so i can't solve it .please someone help me.

import 'package:fooddeliver/data/repository/popular_product_repo.dart';
import 'package:fooddeliver/modals/products_modal.dart';
import 'package:get/get.dart';

class PopularProductController extends GetxService {
  final PopularProductRepo popularProductRepo;
  PopularProductController({required this.popularProductRepo});
  List<dynamic> _popularProductList = [];
  List<dynamic> get popularProductList => _popularProductList;
  Future<void> getPopularProductList() async {
    Response response = await popularProductRepo.getPopularProductlist();
    if (response.statusCode == 200) {
      _popularProductList = [];
      print('product list');

      _popularProductList.addAll(Product.fromJson(response.body).products);
      print(_popularProductList);
    }
  }
}


问:
Dockerfile not reading build arg or secret from file/stdin but works when hardcoded
I have the following dockerfile:

```<code>FROM node:14-alpine
RUN mkdir /app && chown -R node:node /app
WORKDIR /app
USER node
RUN --mount=type=secret,id=ghtoken echo "//npm.pkg.github.com/:_authToken=$(cat /run/secrets/ghtoken)" > ~/.npmrc
COPY package.json yarn.lock .npmrc ./
RUN yarn install
RUN yarn install --only=dev
COPY --chown=node:node . .
CMD ["yarn", "start"]
</code>```

This is a nextjs application and it has a private node module as a dependency which is hosted on GitHub NPM Registry. GitHub requires a personal access token for installing private node modules. So I cannot hardcode the token in the ~/.npmrc file. I have two options: a) Pass the token via build arg 2) Use docker secrets. Unfortunately neither of these works for me. In line 5 of the Dockerfile, you can see that I am expecting a secret called ghtoken which I am loading from a file called secret.txt when running the build command:

DOCKER_BUILDKIT=1 docker build . --secret id=ghtoken,src=secret.txt -t dashboard:latest --no-cache
```
<p>This doesn't work. I get 401 unauthorized from GitHub's end. For some reason, the Dockerfile acts as if I didn't pass any secret at all.</p>
<p>If I change line 5 from this:</p>
```RUN --mount=type=secret,id=ghtoken echo "//npm.pkg.github.com/:_authToken=$(cat /run/secrets/ghtoken)" > ~/.npmrc
```
<p>...to this:</p>
```RUN echo "//npm.pkg.github.com/:_authToken=<Real-Token-Here>" > ~/.npmrc
```
<p>...then it works.</p>
<p>Similarly, if I go for the build arg approach, with a slight modification to my Dockerfile:</p>
```ARG GHTOKEN
FROM node:14-alpine
RUN mkdir /app && chown -R node:node /app
WORKDIR /app
USER node
RUN echo "//npm.pkg.github.com/:_authToken=$GHTOKEN" > ~/.npmrc
COPY package.json yarn.lock .npmrc ./
RUN yarn install
RUN yarn install --only=dev
COPY --chown=node:node . .
CMD ["yarn", "start"]
```
<p>...and pass the GHTOKEN as the build arg:</p>
```docker build --build-arg GHTOKEN=<Real-Token-Here> . -t dashboard:latest --no-cache
```
<p>...then I get 401 Unauthorized again. If I change line 6 from this:</p>
```RUN echo "//npm.pkg.github.com/:_authToken=$GHTOKEN" > ~/.npmrc
```
<p>...to this:</p>
```RUN echo "//npm.pkg.github.com/:_authToken=<Real-Token-Here>" > ~/.npmrc
```
<p>I don't get errors. Apparently, my Dockerfile cannot read from the build arg or secret. How can I fix this?</p>
<p><strong>UPDATE:</strong>
The ARG approach was not working because I was using the ARG statement before the FROM statement. If I update the first two lines to look like this:</p>
```FROM node:14-alpine
ARG GHTOKEN
```

...then the token is properly retrieved. But I'm still in the dark why the docker secret approach wouldn't work. Besides, this arg passing approach is insecure.

答:
will advise you not to use build arguments for passing secrets:

Warning: It is not recommended to use build-time variables for passing secrets like github keys, user credentials etc. Build-time variable values are visible to any user of the image with the docker history command.

maybe you just need to take a different approach, such as:

create .npmrc file dynamically outside of your container

spin-up a vanilla node container and mount .npmrc and node_modules directory or a volume

run npm within the container

at this stage, you have the node_modules directory/volume ready and you can mount\copy it to your application container\image.

or... (you should do it wisely, do the file won't be stored in a layered cache)

create .npmrc file dynamically outside of your container

copy .npmrc into your application container

run npm

delete the .npmrc file from the container

Body:
I have the following dockerfile:

FROM node:14-alpine
RUN mkdir /app && chown -R node:node /app
WORKDIR /app
USER node
RUN --mount=type=secret,id=ghtoken echo "//npm.pkg.github.com/:_authToken=$(cat /run/secrets/ghtoken)" > ~/.npmrc
COPY package.json yarn.lock .npmrc ./
RUN yarn install
RUN yarn install --only=dev
COPY --chown=node:node . .
CMD ["yarn", "start"]

This is a nextjs application and it has a private node module as a dependency which is hosted on GitHub NPM Registry. GitHub requires a personal access token for installing private node modules. So I cannot hardcode the token in the ~/.npmrc file. I have two options: a) Pass the token via build arg 2) Use docker secrets. Unfortunately neither of these works for me. In line 5 of the Dockerfile, you can see that I am expecting a secret called ghtoken which I am loading from a file called secret.txt when running the build command:

DOCKER_BUILDKIT=1 docker build . --secret id=ghtoken,src=secret.txt -t dashboard:latest --no-cache

This doesn't work. I get 401 unauthorized from GitHub's end. For some reason, the Dockerfile acts as if I didn't pass any secret at all.

If I change line 5 from this:

RUN --mount=type=secret,id=ghtoken echo "//npm.pkg.github.com/:_authToken=$(cat /run/secrets/ghtoken)" > ~/.npmrc

...to this:

RUN echo "//npm.pkg.github.com/:_authToken=<Real-Token-Here>" > ~/.npmrc

...then it works.

Similarly, if I go for the build arg approach, with a slight modification to my Dockerfile:

ARG GHTOKEN
FROM node:14-alpine
RUN mkdir /app && chown -R node:node /app
WORKDIR /app
USER node
RUN echo "//npm.pkg.github.com/:_authToken=$GHTOKEN" > ~/.npmrc
COPY package.json yarn.lock .npmrc ./
RUN yarn install
RUN yarn install --only=dev
COPY --chown=node:node . .
CMD ["yarn", "start"]

...and pass the GHTOKEN as the build arg:

docker build --build-arg GHTOKEN=<Real-Token-Here> . -t dashboard:latest --no-cache

...then I get 401 Unauthorized again. If I change line 6 from this:

RUN echo "//npm.pkg.github.com/:_authToken=$GHTOKEN" > ~/.npmrc

...to this:

RUN echo "//npm.pkg.github.com/:_authToken=<Real-Token-Here>" > ~/.npmrc

I don't get errors. Apparently, my Dockerfile cannot read from the build arg or secret. How can I fix this?

UPDATE:
The ARG approach was not working because I was using the ARG statement before the FROM statement. If I update the first two lines to look like this:

FROM node:14-alpine
ARG GHTOKEN

...then the token is properly retrieved. But I'm still in the dark why the docker secret approach wouldn't work. Besides, this arg passing approach is insecure.


问:
How to add background color for all the text come inside curly brackets in reactjs
I am using sunEditor-react to get HTML files into a text editor. I got the HTML value and displayed inside the editor successfully.

The purpose of this to edit the HTML file in the frontend.
But when I am getting the HTML template, there are some places I need to highlight and show.

I need to highlight the text inside curly brackets {}.
Can any explain me how can I do this using CSS or a function to highlight the values inside {}.

This is my current class.

```<code>import { useState } from 'react';
import SunEditor from 'suneditor-react';

import { useLocale } from 'hooks/useLocale/useLocale';
import { Button, Heading, Loader, Typography } from 'ui/atoms';

import 'suneditor/dist/css/suneditor.min.css';

import { useStyles } from './Edit.styles';
import { EditProps } from './Edit.types';
import { EditWarning } from './editWarning/EditWarning';

export const EMAIL_EDIT_WARNING_COOKIE_KEY = 'emailEditWarning';

export const Edit = ({ title, defaultTemplate }: EditProps) => {
 const classes = useStyles();
 const { formatMessage } = useLocale();
 const [htmlData, setHtmlData] = useState(defaultTemplate?.html);

 if (!defaultTemplate) {
   return <Loader className={classes.loader} />;
 }

 function reset() {
   setHtmlData(defaultTemplate?.html);
 }

 return (
   <>
     <div className={classes.button}>
       <Button type="button" onClick={reset}>
         {formatMessage({ id: 'event.emails.edit.reset' })}
       </Button>
     </div>

     <div className={classes.container}>
       <Heading variant="h4" bold className={classes.title}>
         {formatMessage({ id: 'event.emails.edit.title' })}
       </Heading>
       <Typography variant="h5" className={classes.subtitle}>
         {title}
       </Typography>

       <EditWarning name={EMAIL_EDIT_WARNING_COOKIE_KEY}>
         <div>{formatMessage({ id: 'event.emails.edit.warning_message' })}</div>
         <div>{formatMessage({ id: 'event.emails.edit.warning_note' })}</div>
       </EditWarning>
     </div>
     <SunEditor
       width="100%"
       height="100%"
       autoFocus={true}
       setContents={htmlData}

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

I need to add css to  to highlight all the values inside curly brackets {}.

This is the current UI.

Here I need to highlight {{FULL_NAME}} and {{{event_name}}}.
How can I do this using CSS or any function in react?

Can any one please give a solution for this? I am trying this more than a week to get a solution?

答:
I know that with regular React, adding an Inline style like this  style={{ color: "blue" }} to any tag would do the trick. (Note the double brackets are necessary for JSX.)

But I'm not all that familiar with sunEditor. If it lets you use a custom CSS stylesheet, you could try adding an id or className and changing color with !important to try and override the Atom ui framework your using.

Body:
I am using sunEditor-react to get HTML files into a text editor. I got the HTML value and displayed inside the editor successfully.

The purpose of this to edit the HTML file in the frontend.
But when I am getting the HTML template, there are some places I need to highlight and show.

I need to highlight the text inside curly brackets {}.
Can any explain me how can I do this using CSS or a function to highlight the values inside {}.

This is my current class.

import { useState } from 'react';
import SunEditor from 'suneditor-react';

import { useLocale } from 'hooks/useLocale/useLocale';
import { Button, Heading, Loader, Typography } from 'ui/atoms';

import 'suneditor/dist/css/suneditor.min.css';

import { useStyles } from './Edit.styles';
import { EditProps } from './Edit.types';
import { EditWarning } from './editWarning/EditWarning';

export const EMAIL_EDIT_WARNING_COOKIE_KEY = 'emailEditWarning';

export const Edit = ({ title, defaultTemplate }: EditProps) => {
 const classes = useStyles();
 const { formatMessage } = useLocale();
 const [htmlData, setHtmlData] = useState(defaultTemplate?.html);

 if (!defaultTemplate) {
   return <Loader className={classes.loader} />;
 }

 function reset() {
   setHtmlData(defaultTemplate?.html);
 }

 return (
   <>

       <Button type="button" onClick={reset}>
         {formatMessage({ id: 'event.emails.edit.reset' })}
       </Button>

       <Heading variant="h4" bold className={classes.title}>
         {formatMessage({ id: 'event.emails.edit.title' })}
       </Heading>
       <Typography variant="h5" className={classes.subtitle}>
         {title}
       </Typography>

       <EditWarning name={EMAIL_EDIT_WARNING_COOKIE_KEY}>

{formatMessage({ id: 'event.emails.edit.warning_message' })}

{formatMessage({ id: 'event.emails.edit.warning_note' })}

       </EditWarning>

     <SunEditor
       width="100%"
       height="100%"
       autoFocus={true}
       setContents={htmlData}

     />
   </>
 ); };

I need to add css to  to highlight all the values inside curly brackets {}.

This is the current UI.

Here I need to highlight {{FULL_NAME}} and {{{event_name}}}.
How can I do this using CSS or any function in react?

Can any one please give a solution for this? I am trying this more than a week to get a solution?


问:
Exclude Qt and Boost includes from CMake dependencies
Does someone know a way how to exclude all Qt and Boost dependencies from a CMake project?</p>

答: I use command include_regular_expression("^([^b]|b[^o]|bo[^o]|boo[^s]|boos[^t]|boost[^/]).*$") to skip all includes starting with "boost/" (if somebody knows a simpler regex - please add a comment). Certainly, it may be extended to Qt headers.


问:
How to find min/max aggregations with diffrerent filters in MongoDB?
Considering collection clothing of documents with this strucure

```<code>{
  "brand": <string>,
  "color": <string>,
  "size": <number>
}
</code>```

In a single aggregation grouing by brand I would like to find two values:

min size for all documents in a group where color="blue"

max size for all documents in a group where color="red"

In SQL it would be something like this:

```<code>SELECT MIN(CASE color WHEN "blue" THEN size ELSE NULL END),
       MAX(CASE color WHEN "red" THEN size ELSE NULL END),
       brand
  FROM clothing
 GROUP BY brand
</code>```

How to express this in MongoDB query?

答:
$group - Group by brand and $push size into red or blue array by $cond.

$project - Decorate output document with $min (blue) and $max (red).

```<code>db.collection.aggregate([
  {
    "$group": {
      "_id": "$brand",
      "red": {
        $push: {
          $cond: [
            {
              $eq: [
                "$color",
                "red"
              ]
            },
            "$$ROOT.size",
            "$$REMOVE"
          ]
        }
      },
      "blue": {
        $push: {
          $cond: [
            {
              $eq: [
                "$color",
                "blue"
              ]
            },
            "$$ROOT.size",
            "$$REMOVE"
          ]
        }
      }
    }
  },
  {
    $project: {
      brand: "$brand",
      min: {
        $min: "$blue"
      },
      max: {
        $max: "$red"
      }
    }
  }
])
</code>```

Sample Mongo Playground

Body:
Considering collection clothing of documents with this strucure

{
  "brand": <string>,
  "color": <string>,
  "size": <number>
}

In a single aggregation grouing by brand I would like to find two values:

min size for all documents in a group where color="blue"

max size for all documents in a group where color="red"

In SQL it would be something like this:

SELECT MIN(CASE color WHEN "blue" THEN size ELSE NULL END),
       MAX(CASE color WHEN "red" THEN size ELSE NULL END),
       brand
  FROM clothing
 GROUP BY brand

How to express this in MongoDB query?

Body:
$group - Group by brand and $push size into red or blue array by $cond.

$project - Decorate output document with $min (blue) and $max (red).

db.collection.aggregate([
  {
    "$group": {
      "_id": "$brand",
      "red": {
        $push: {
          $cond: [
            {
              $eq: [
                "$color",
                "red"
              ]
            },
            "$$ROOT.size",
            "$$REMOVE"
          ]
        }
      },
      "blue": {
        $push: {
          $cond: [
            {
              $eq: [
                "$color",
                "blue"
              ]
            },
            "$$ROOT.size",
            "$$REMOVE"
          ]
        }
      }
    }
  },
  {
    $project: {
      brand: "$brand",
      min: {
        $min: "$blue"
      },
      max: {
        $max: "$red"
      }
    }
  }
])

Sample Mongo Playground


问:
HackerRank Staircase Python
I am trying to solve a problem in HackerRank and I am having an issue with my submission. My code works in PyCharm but HackerRank is not accepting my submission.

Here is the problem I am trying to solve: https://www.hackerrank.com/challenges/staircase

Here is my code:

```<code>def staircase(num_stairs):
    n = num_stairs - 1
    for stairs in range(num_stairs):
        print ' ' * n, '#' * stairs
        n -= 1
    print '#' * num_stairs
staircase(12)
</code>```

Any ideas why HackerRank is not accpeting my answer?

答:
You can just change the sep argument of print from ' ' to '', and your answer will be correct

```<code>def staircase(n):
    for i in range(1, n+1):
        print(' ' * (n-i), '#' * (i), sep='')
</code>```

The answer you submitted is not accepted because the default print settings adds an empty space in front of the printouts, and one of the question requirements is for there to have no spaces in the output.

The default sep in print is a space character i.e. ' '.

Title: HackerRank Staircase Python

Body:
I am trying to solve a problem in HackerRank and I am having an issue with my submission. My code works in PyCharm but HackerRank is not accepting my submission.

Here is the problem I am trying to solve: https://www.hackerrank.com/challenges/staircase

Here is my code:

def staircase(num_stairs):
    n = num_stairs - 1
    for stairs in range(num_stairs):
        print ' ' * n, '#' * stairs
        n -= 1
    print '#' * num_stairs
staircase(12)

Any ideas why HackerRank is not accpeting my answer?

Body:
You can just change the sep argument of print from ' ' to '', and your answer will be correct

def staircase(n):
    for i in range(1, n+1):
        print(' ' * (n-i), '#' * (i), sep='')

The answer you submitted is not accepted because the default print settings adds an empty space in front of the printouts, and one of the question requirements is for there to have no spaces in the output.

The default sep in print is a space character i.e. ' '.


问:
VS Code Ctrl+C has a wrong behaviour
In Visual Studio Code, when i try to use Ctrl+C to copy something, it changes the insert mode instead. There is a blue bar at the bottom of the screen, with all the informations about the file (python interpreter, number of line and column of the cursor, ...) and -INSERT- . When I press Ctrl+C, the -INSERT- switches to -NORMAL- and I can't copy what I highlighted.

答: I too had this issue. Resolved was by disabling the VIM extension or you can uninstall it too.

Title: VS Code Ctrl+C has a wrong behaviour


问:
Getting error : Caused by: java.net.SocketTimeoutException: Accept timed out
I am getting error while running pyspark in Jupyter Notebook using python 3.7 using this below code.

```<code>from pyspark import SparkContext
from pyspark.sql.session import SparkSession
from pyspark.sql import SQLContext
import pyspark as ps

conf = ps.SparkConf().setMaster("yarn-client").setAppName("sparK-mer")
conf.set("spark.executor.heartbeatInterval","3600s")
sc = SparkContext('local')
sqlContext = SQLContext(sc)
from pyspark.mllib.linalg import Vector, Vectors
from nltk.stem.wordnet import WordNetLemmatizer
from pyspark.ml.feature import RegexTokenizer, StopWordsRemover, Word2Vec
</code>```

I am reading the csv file based on the following code:

```<code>datanew = sqlContext.read.format("csv") \
   .options(header='true', inferschema='true') \
   .load("C://Users//mypath//data.csv")

parts = datanew.rdd.map(lambda l: l.split(","))
datapysp = parts.map(lambda p: Row(uiid=p[0],title=(p[3].strip()),text=(p[4].strip())))
schemaString = "uiid title text"
fields = [StructField(field_name, StringType(), True) for  field_name in schemaString.split()]
schema = StructType(fields)
sqlContext.createDataFrame(datapysp, schema).show()
</code>```

This is the error message, and I am receiving and there are columns mentioned UIID, Title and text.

```<code>Py4JJavaError: An error occurred while calling o74.showString.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 2.0 failed 1 times, most recent failure: Lost task 0.0 in stage 2.0 (TID 2, localhost, executor driver): org.apache.spark.SparkException: Python worker failed to connect back.
    at org.apache.spark.api.python.PythonWorkerFactory.createSimpleWorker(PythonWorkerFactory.scala:170)
    at org.apache.spark.api.python.PythonWorkerFactory.create(PythonWorkerFactory.scala:97)
    at org.apache.spark.SparkEnv.createPythonWorker(SparkEnv.scala:117)
    at org.apache.spark.api.python.BasePythonRunner.compute(PythonRunner.scala:108)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:65)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:121)
    at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:402)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:408)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.net.SocketTimeoutException: Accept timed out
    at java.net.DualStackPlainSocketImpl.waitForNewConnection(Native Method)
    at java.net.DualStackPlainSocketImpl.socketAccept(Unknown Source)
    at java.net.AbstractPlainSocketImpl.accept(Unknown Source)
    at java.net.PlainSocketImpl.accept(Unknown Source)
    at java.net.ServerSocket.implAccept(Unknown Source)
    at java.net.ServerSocket.accept(Unknown Source)
    at org.apache.spark.api.python.PythonWorkerFactory.createSimpleWorker(PythonWorkerFactory.scala:164)
</code>```

I went through the answers provided here:
Pyspark socket timeout exception after application running for a while. I tried changing the code to this as per the answers provided.

```<code>import pyspark as ps

conf = ps.SparkConf().setMaster("yarn-client").setAppName("sparK-mer")
conf.set("spark.executor.heartbeatInterval","3600s")
sc = ps.SparkContext('local[4]', '', conf=conf)
</code>```

I get the error saying Java gateway process exited before sending its port number while running this part sc = ps.SparkContext('local[4]', '', conf=conf).

Also tried like this, but still the same error which I received regarding Accept timed out.

```<code> parts = datanew.rdd.map(lambda l: l.split(","))
    datapysp = parts.map(lambda p: Row(uiid=p[0],title=(p[3].strip()),text=(p[4].strip())))
    schemaString = "uiid title text"
    fields = [StructField(field_name, StringType(), True) for  field_name in schemaString.split()]
    schema = StructType(fields)
    sqlContext.createDataFrame(datapysp,
    schema).show().config("sqlContext.executor.heartbeatInterval", "10000s")
    --added this but still the error is not being resolved.
</code>```

I would appreciate if any one could help me with this. I am using Windows 10 64 bit.

答:
First of all check your spark version with this snippet code:

```<code>print( "spark version=" ,SparkSession.builder.appName("test").getOrCreate().version)
</code>```

and pyspark version with pip command line:

```<code>pip show pyspark
</code>```

If the version of pyspark is greater then your spark version,
Then you can use older version of pyspark by using this snippet:

```<code>import pkg_resources
pkg_resources.require("pyspark==[older_version]")
</code>```

Or install new version of spark in your system

Body:
I am getting error while running pyspark in Jupyter Notebook using python 3.7 using this below code.

from pyspark import SparkContext
from pyspark.sql.session import SparkSession
from pyspark.sql import SQLContext
import pyspark as ps

conf = ps.SparkConf().setMaster("yarn-client").setAppName("sparK-mer")
conf.set("spark.executor.heartbeatInterval","3600s")
sc = SparkContext('local')
sqlContext = SQLContext(sc)
from pyspark.mllib.linalg import Vector, Vectors
from nltk.stem.wordnet import WordNetLemmatizer
from pyspark.ml.feature import RegexTokenizer, StopWordsRemover, Word2Vec

I am reading the csv file based on the following code:

datanew = sqlContext.read.format("csv") \
   .options(header='true', inferschema='true') \
   .load("C://Users//mypath//data.csv")

parts = datanew.rdd.map(lambda l: l.split(","))
datapysp = parts.map(lambda p: Row(uiid=p[0],title=(p[3].strip()),text=(p[4].strip())))
schemaString = "uiid title text"
fields = [StructField(field_name, StringType(), True) for  field_name in schemaString.split()]
schema = StructType(fields)
sqlContext.createDataFrame(datapysp, schema).show()

This is the error message, and I am receiving and there are columns mentioned UIID, Title and text.

Py4JJavaError: An error occurred while calling o74.showString.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 2.0 failed 1 times, most recent failure: Lost task 0.0 in stage 2.0 (TID 2, localhost, executor driver): org.apache.spark.SparkException: Python worker failed to connect back.
    at org.apache.spark.api.python.PythonWorkerFactory.createSimpleWorker(PythonWorkerFactory.scala:170)
    at org.apache.spark.api.python.PythonWorkerFactory.create(PythonWorkerFactory.scala:97)
    at org.apache.spark.SparkEnv.createPythonWorker(SparkEnv.scala:117)
    at org.apache.spark.api.python.BasePythonRunner.compute(PythonRunner.scala:108)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:65)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:121)
    at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:402)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:408)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.net.SocketTimeoutException: Accept timed out
    at java.net.DualStackPlainSocketImpl.waitForNewConnection(Native Method)
    at java.net.DualStackPlainSocketImpl.socketAccept(Unknown Source)
    at java.net.AbstractPlainSocketImpl.accept(Unknown Source)
    at java.net.PlainSocketImpl.accept(Unknown Source)
    at java.net.ServerSocket.implAccept(Unknown Source)
    at java.net.ServerSocket.accept(Unknown Source)
    at org.apache.spark.api.python.PythonWorkerFactory.createSimpleWorker(PythonWorkerFactory.scala:164)

I went through the answers provided here:
Pyspark socket timeout exception after application running for a while. I tried changing the code to this as per the answers provided.

import pyspark as ps

conf = ps.SparkConf().setMaster("yarn-client").setAppName("sparK-mer")
conf.set("spark.executor.heartbeatInterval","3600s")
sc = ps.SparkContext('local[4]', '', conf=conf)

I get the error saying Java gateway process exited before sending its port number while running this part sc = ps.SparkContext('local[4]', '', conf=conf).

Also tried like this, but still the same error which I received regarding Accept timed out.

 parts = datanew.rdd.map(lambda l: l.split(","))
    datapysp = parts.map(lambda p: Row(uiid=p[0],title=(p[3].strip()),text=(p[4].strip())))
    schemaString = "uiid title text"
    fields = [StructField(field_name, StringType(), True) for  field_name in schemaString.split()]
    schema = StructType(fields)
    sqlContext.createDataFrame(datapysp,
    schema).show().config("sqlContext.executor.heartbeatInterval", "10000s")
    --added this but still the error is not being resolved.

I would appreciate if any one could help me with this. I am using Windows 10 64 bit.

Body:
First of all check your spark version with this snippet code:

print( "spark version=" ,SparkSession.builder.appName("test").getOrCreate().version)

and pyspark version with pip command line:

pip show pyspark

If the version of pyspark is greater then your spark version,
Then you can use older version of pyspark by using this snippet:

import pkg_resources
pkg_resources.require("pyspark==[older_version]")

Or install new version of spark in your system


问:
Using a Group By and Count statement in WIQL (Azure Dev Ops)
I want to make a WIQL query to count the workitems from the type 'Bug', grouped by the title and the software version fields. But, there is no group by function in WIQL. Does anyone have an alternative to make this work in WIQL?

```<code>SELECT
    [System.Title],
    [System.State],
    count(*)
FROM workitems
WHERE
    [System.WorkItemType] = 'Bug'
    AND [System.State] <> ''
GROUP BY [System.Title], [Custom.ToolSoftwareVersion]
</code>```

The queries are used to create dashboards and overviews, ect.

答:
An alternative approach is to use a "Chart for Work Items" widget that provides a Pivot Table view.  You can choose aggregation types such as COUNT, SUM.

This operates similarly to Pivot Tables in Excel with numbers in the output rather than a chart.

Choose Chart Type:

Choose row and column axes

The result is presented as a table with "group by" / count style

Body:
I want to make a WIQL query to count the workitems from the type 'Bug', grouped by the title and the software version fields. But, there is no group by function in WIQL. Does anyone have an alternative to make this work in WIQL?

SELECT
    [System.Title],
    [System.State],
    count(*)
FROM workitems
WHERE
    [System.WorkItemType] = 'Bug'
    AND [System.State] <> ''
GROUP BY [System.Title], [Custom.ToolSoftwareVersion]

The queries are used to create dashboards and overviews, ect.


问:
Firebase currentUser and onAuthStateChanged
I am developing an app using react native, every time I refresh the app on the emulator in onAuthStateChanged and currentUser from firebase I get null.

I have read about waiting onAuthStateChanged to get a status update but I never do, so I guess I misconfigured something.

I am using expo 44, react 17, firebase 9.6.5 but in compat mode (planning in fully migrate later)

My first attempt of solution was trying to add persistence: firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL);

```<code>import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import "firebase/compat/firestore";
import "firebase/compat/functions";
import "firebase/compat/storage";
import AsyncStorage from "@react-native-async-storage/async-storage";

import { firebaseConfig } from "./firebase/firebaseConfig";

firebase.initializeApp(firebaseConfig);

firebase.firestore();
firebase.functions();
firebase.storage();
firebase.auth();

firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL);
firebase.auth().onAuthStateChanged(async (user) => {
    console.log("onAuthStateChanged called: ", user);
    if (user) {
        await AsyncStorage.setItem('@isLoggedIn', '1');
    } else {
        await AsyncStorage.setItem('@isLoggedIn', '0');
    }
});

export default firebase;
</code>```

But I get an error:

```<code>undefined is not an object (evaluating 'this.storage.setItem')
at node_modules/@firebase/auth/dist/esm2017/index-cff4f2fd.js:5248:0 in verifyBeforeUpdateEmail
at node_modules/@firebase/auth/dist/esm2017/index-cff4f2fd.js:5420:12 in _fromIdTokenResponse
at http://127.0.0.1:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:183132:41 in _set
at node_modules/@firebase/auth/dist/esm2017/index-cff4f2fd.js:1414:55 in newData.some$argument_0
at node_modules/@firebase/auth/dist/esm2017/index-cff4f2fd.js:2060:1 in <global>
at node_modules/@firebase/auth/dist/esm2017/index-cff4f2fd.js:2047:30 in _isIOS
at node_modules/@firebase/auth/dist/esm2017/index-cff4f2fd.js:1890:4 in PersistenceUserManager.create
at node_modules/@firebase/auth/dist/esm2017/index-cff4f2fd.js:1890:4 in PersistenceUserManager.create
</code>```

to Login I use:

```<code>userCredential = firebase
          .auth()
          .signInWithEmailAndPassword(data.email, this.state.password);
</code>```

答: I had this exact same issue. I solved it by adding "firebase": "^8.9.1" to package.json, running yarn install and changing the import import firebase from "firebase" (remove all the other imports you have). Apparently selective imports have a bug in v8, but at least it works well :)

Body:
I am developing an app using react native, every time I refresh the app on the emulator in onAuthStateChanged and currentUser from firebase I get null.

I have read about waiting onAuthStateChanged to get a status update but I never do, so I guess I misconfigured something.

I am using expo 44, react 17, firebase 9.6.5 but in compat mode (planning in fully migrate later)

My first attempt of solution was trying to add persistence: firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL);

import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import "firebase/compat/firestore";
import "firebase/compat/functions";
import "firebase/compat/storage";
import AsyncStorage from "@react-native-async-storage/async-storage";

import { firebaseConfig } from "./firebase/firebaseConfig";

firebase.initializeApp(firebaseConfig);

firebase.firestore();
firebase.functions();
firebase.storage();
firebase.auth();

firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL);
firebase.auth().onAuthStateChanged(async (user) => {
    console.log("onAuthStateChanged called: ", user);
    if (user) {
        await AsyncStorage.setItem('@isLoggedIn', '1');
    } else {
        await AsyncStorage.setItem('@isLoggedIn', '0');
    }
});

export default firebase;

But I get an error:

undefined is not an object (evaluating 'this.storage.setItem')
at node_modules/@firebase/auth/dist/esm2017/index-cff4f2fd.js:5248:0 in verifyBeforeUpdateEmail
at node_modules/@firebase/auth/dist/esm2017/index-cff4f2fd.js:5420:12 in _fromIdTokenResponse
at http://127.0.0.1:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:183132:41 in _set
at node_modules/@firebase/auth/dist/esm2017/index-cff4f2fd.js:1414:55 in newData.some$argument_0
at node_modules/@firebase/auth/dist/esm2017/index-cff4f2fd.js:2060:1 in <global>
at node_modules/@firebase/auth/dist/esm2017/index-cff4f2fd.js:2047:30 in _isIOS
at node_modules/@firebase/auth/dist/esm2017/index-cff4f2fd.js:1890:4 in PersistenceUserManager.create
at node_modules/@firebase/auth/dist/esm2017/index-cff4f2fd.js:1890:4 in PersistenceUserManager.create

to Login I use:

userCredential = firebase
          .auth()
          .signInWithEmailAndPassword(data.email, this.state.password);


问:
Loop through a list of dataframes to create dataframes in R
I have the following question and I have not been able to find an answer that works I have multiple dataframes (35 to be exact) and I want to add another dataframe containing demographics to each one of the 35 dataframes.

To make it simple, I have the following example:

```<code>df1 <- data.frame(ID = c(1:3), b = c('x', 'y', 'z'), c = c('gh', 'fg', 'xv'), df = c('z', 'x', 'y'))

df2 <- data.frame(ID = c(1:3), v = c('a', 'mm', 'xc'), hg = c('yty', 'zc', 'cx'), fd = c('z', 'x', 'y'))

df3 <- data.frame(ID = c(1:3, t = c('ae', 'yw', 'zs'), j = c('ewr', 'zd', 'x'), sd = c('z', 'x', 'y'))

df4 <- data.frame(ID = c(1:3), u = c('df', 'y', 'z'), k = c('df', 'zs', 'xf'), f = c('z', 'x', 'y'))
.
.
.
df(n) <- ...

demo <- data.frame(sex = c('m', 'm', 'f'), age = c('30', '50', '62'), vital_sts = c('a', 'a', 'd'))
</code>```

What I would like to do is to paste the demo dataframe to each one of the other frames. So I have tried:

```<code>dfList <- list(df1, df2,df3,df4...)

for (i in 1:length(dfList) {
     i <- merge(demo,i)
}
</code>```

However, when I check the dataframes they are not merged.
Any help will be greatly appreciated.
Thank you!

答:
You should give your demo data frame definitely an "ID" column as well! Then you do not have to hope that the demographics are correctly assigned to the observations, especially if the script is still changing during the work process. That may easily be done using transform (I simply use the consecutive ID's 1:3 here in the example).

```<code>res <- lapply(list(df1, df2, df3, df4), merge, transform(demo, ID=1:3))
res
# [[1]]
#   ID b  c df sex age vital_sts
# 1  1 x gh  z   m  30         a
# 2  2 y fg  x   m  50         a
# 3  3 z xv  y   f  62         d
#
# [[2]]
#   ID  v  hg fd sex age vital_sts
# 1  1  a yty  z   m  30         a
# 2  2 mm  zc  x   m  50         a
# 3  3 xc  cx  y   f  62         d
#
# [[3]]
#   ID  t   j sd sex age vital_sts
# 1  1 ae ewr  z   m  30         a
# 2  2 yw  zd  x   m  50         a
# 3  3 zs   x  y   f  62         d
#
# [[4]]
#   ID  u  k f sex age vital_sts
# 1  1 df df z   m  30         a
# 2  2  y zs x   m  50         a
# 3  3  z xf y   f  62         d
</code>```

If you have gazillions of data frames in your workspace, as it looks like,  you may list by pattern using mget(ls(pattern=)). (Or better yet, change your code to get them in a list in the first place.)

```<code>lapply(mget(ls(pat='^df\\d+')), merge, transform(demo, ID=1:3))
</code>```

Edit

If I understand you correctly, according to your comment you have a large data frame DAT from which you want to assemble smaller data frames of variable groups and merge the demo to them. In this case I would put the variable names of these groups in a named list vgroups. Next, lapply over it to simultaneously subset dat with "ID" concatenated and merge it to demo.

demo still should have an "ID", because you don't want to trust, all rows are sorted in the same order, just consider for example sort(c(3, 10, 1, 100)) vs. sort(as.character(c(3, 10, 1, 100))) or omitted rows for whatever reason etc.

```<code>demo <- transform(demo, ID=1:3)  ## identify demo observations

vgroups <- list(g1=c("b", "c", "df"), g2=c("v", "hg", "fd"), g3=c("t", "j", "sd"),
               g4=c("u", "k", "f"))

res1 <- lapply(vgroups, \(x) merge(demo, DAT[, c('ID', x)], by="ID"))
                          ## saying by ID is even more save --^
res1
# $g1
#   ID sex age vital_sts b  c df
# 1  1   m  30         a x gh  z
# 2  2   m  50         a y fg  x
# 3  3   f  62         d z xv  y
#
# $g2
#   ID sex age vital_sts  v  hg fd
# 1  1   m  30         a  a yty  z
# 2  2   m  50         a mm  zc  x
# 3  3   f  62         d xc  cx  y
#
# $g3
#   ID sex age vital_sts  t   j sd
# 1  1   m  30         a ae ewr  z
# 2  2   m  50         a yw  zd  x
# 3  3   f  62         d zs   x  y
#
# $g4
#   ID sex age vital_sts  u  k f
# 1  1   m  30         a df df z
# 2  2   m  50         a  y zs x
# 3  3   f  62         d  z xf y
</code>```

Access individual data frames:

```<code>res1$g1
#   ID sex age vital_sts b  c df
# 1  1   m  30         a x gh  z
# 2  2   m  50         a y fg  x
# 3  3   f  62         d z xv  y
</code>```

If you still want the individual data frames in your environment, use list2env:

```<code>list2env(res1)
ls()
# [1] "DAT"     "demo"    "res1"    "vgroups"
</code>```

Data:

```<code>DAT <- structure(list(ID = 1:3, b = c("x", "y", "z"), c = c("gh", "fg",
"xv"), df = c("z", "x", "y"), f = c("z", "x", "y"), fd = c("z",
"x", "y"), hg = c("yty", "zc", "cx"), j = c("ewr", "zd", "x"),
    k = c("df", "zs", "xf"), sd = c("z", "x", "y"), t = c("ae",
    "yw", "zs"), u = c("df", "y", "z"), v = c("a", "mm", "xc"
    ), x1 = c("gs", "gs", "gs"), x2 = c("cs", "cs", "cs"), x3 = c("tv",
    "tv", "tv"), x4 = c("fb", "fb", "fb")), row.names = c(NA,
-3L), class = "data.frame")

demo <- data.frame(sex = c('m', 'm', 'f'), age = c('30', '50', '62'), vital_sts = c('a', 'a', 'd'))
</code>```

Body:
I have the following question and I have not been able to find an answer that works I have multiple dataframes (35 to be exact) and I want to add another dataframe containing demographics to each one of the 35 dataframes.

To make it simple, I have the following example:

df1 <- data.frame(ID = c(1:3), b = c('x', 'y', 'z'), c = c('gh', 'fg', 'xv'), df = c('z', 'x', 'y'))

df2 <- data.frame(ID = c(1:3), v = c('a', 'mm', 'xc'), hg = c('yty', 'zc', 'cx'), fd = c('z', 'x', 'y'))

df3 <- data.frame(ID = c(1:3, t = c('ae', 'yw', 'zs'), j = c('ewr', 'zd', 'x'), sd = c('z', 'x', 'y'))

df4 <- data.frame(ID = c(1:3), u = c('df', 'y', 'z'), k = c('df', 'zs', 'xf'), f = c('z', 'x', 'y'))
.
.
.
df(n) <- ...

demo <- data.frame(sex = c('m', 'm', 'f'), age = c('30', '50', '62'), vital_sts = c('a', 'a', 'd'))

What I would like to do is to paste the demo dataframe to each one of the other frames. So I have tried:

dfList <- list(df1, df2,df3,df4...)

for (i in 1:length(dfList) {
     i <- merge(demo,i)
}

However, when I check the dataframes they are not merged.
Any help will be greatly appreciated.
Thank you!

Body:
You should give your demo data frame definitely an "ID" column as well! Then you do not have to hope that the demographics are correctly assigned to the observations, especially if the script is still changing during the work process. That may easily be done using transform (I simply use the consecutive ID's 1:3 here in the example).

res <- lapply(list(df1, df2, df3, df4), merge, transform(demo, ID=1:3))
res
# [[1]]
#   ID b  c df sex age vital_sts
# 1  1 x gh  z   m  30         a
# 2  2 y fg  x   m  50         a
# 3  3 z xv  y   f  62         d
#
# [[2]]
#   ID  v  hg fd sex age vital_sts
# 1  1  a yty  z   m  30         a
# 2  2 mm  zc  x   m  50         a
# 3  3 xc  cx  y   f  62         d
#
# [[3]]
#   ID  t   j sd sex age vital_sts
# 1  1 ae ewr  z   m  30         a
# 2  2 yw  zd  x   m  50         a
# 3  3 zs   x  y   f  62         d
#
# [[4]]
#   ID  u  k f sex age vital_sts
# 1  1 df df z   m  30         a
# 2  2  y zs x   m  50         a
# 3  3  z xf y   f  62         d

If you have gazillions of data frames in your workspace, as it looks like,  you may list by pattern using mget(ls(pattern=)). (Or better yet, change your code to get them in a list in the first place.)

lapply(mget(ls(pat='^df\\d+')), merge, transform(demo, ID=1:3))

Edit

If I understand you correctly, according to your comment you have a large data frame DAT from which you want to assemble smaller data frames of variable groups and merge the demo to them. In this case I would put the variable names of these groups in a named list vgroups. Next, lapply over it to simultaneously subset dat with "ID" concatenated and merge it to demo.

demo still should have an "ID", because you don't want to trust, all rows are sorted in the same order, just consider for example sort(c(3, 10, 1, 100)) vs. sort(as.character(c(3, 10, 1, 100))) or omitted rows for whatever reason etc.

demo <- transform(demo, ID=1:3)  ## identify demo observations

vgroups <- list(g1=c("b", "c", "df"), g2=c("v", "hg", "fd"), g3=c("t", "j", "sd"),
               g4=c("u", "k", "f"))

res1 <- lapply(vgroups, \(x) merge(demo, DAT[, c('ID', x)], by="ID"))
                          ## saying by ID is even more save --^
res1
# $g1
#   ID sex age vital_sts b  c df
# 1  1   m  30         a x gh  z
# 2  2   m  50         a y fg  x
# 3  3   f  62         d z xv  y
#
# $g2
#   ID sex age vital_sts  v  hg fd
# 1  1   m  30         a  a yty  z
# 2  2   m  50         a mm  zc  x
# 3  3   f  62         d xc  cx  y
#
# $g3
#   ID sex age vital_sts  t   j sd
# 1  1   m  30         a ae ewr  z
# 2  2   m  50         a yw  zd  x
# 3  3   f  62         d zs   x  y
#
# $g4
#   ID sex age vital_sts  u  k f
# 1  1   m  30         a df df z
# 2  2   m  50         a  y zs x
# 3  3   f  62         d  z xf y

Access individual data frames:

res1$g1
#   ID sex age vital_sts b  c df
# 1  1   m  30         a x gh  z
# 2  2   m  50         a y fg  x
# 3  3   f  62         d z xv  y

If you still want the individual data frames in your environment, use list2env:

list2env(res1)
ls()
# [1] "DAT"     "demo"    "res1"    "vgroups"

Data:

DAT <- structure(list(ID = 1:3, b = c("x", "y", "z"), c = c("gh", "fg",
"xv"), df = c("z", "x", "y"), f = c("z", "x", "y"), fd = c("z",
"x", "y"), hg = c("yty", "zc", "cx"), j = c("ewr", "zd", "x"),
    k = c("df", "zs", "xf"), sd = c("z", "x", "y"), t = c("ae",
    "yw", "zs"), u = c("df", "y", "z"), v = c("a", "mm", "xc"
    ), x1 = c("gs", "gs", "gs"), x2 = c("cs", "cs", "cs"), x3 = c("tv",
    "tv", "tv"), x4 = c("fb", "fb", "fb")), row.names = c(NA,
-3L), class = "data.frame")

demo <- data.frame(sex = c('m', 'm', 'f'), age = c('30', '50', '62'), vital_sts = c('a', 'a', 'd'))


问:
Finger swipe in Android application
I have created an application where in I have a page which contains for text and one 'Next' button and one 'Previous' button. Clicking 'Next' button, page shows some next text that is being takes from a list which contains a list of String text. 'Previous' button shows the last visited text.

It is working fine. But now I want to implement something new where swipe of finger by user would take to the next text or previous. Finger swipe as used while accepting a call.

答: Swipe to next view is the default behaviour for the Gallery class, you could start by giving this a try or extending it to meet your needs. Hope this helps!</p>

Title: Finger swipe in Android application


问:
Is there a Git alias for the remote tracking branch?
I know you can refer to the tip of the current branch in Git with the name HEAD.

Is there some sort of equivalent for referring to the tip of the remote tracking branch of the current branch?

Just so I don't have to type out remote/current-branch if there's something shorter.

答: @{upstream} or just @{u}, with a branch name in front if you're not referring to your current checkout.


问:
Python convert string holding nested json to dict
I have the following list (notice "keyE" has a dictionary as a string):

[
  {
    "keyA": "Example",
    "keyB": "{\"keyC\":2,\"keyD\":{\"keyE\":\"{\"name\":\"foo\"}\"},\"keyF\":0}"
  },
  {
    "keyA": "Example2",
    "keyB": "{\"keyC\":6,\"keyD\":{\"keyE\":\"{\"name\":\"bar\"}\"},\"keyF\":5}"
  }
]
```
<p>And I want to convert it to this (it can have any number of nested dictionaries and lists):</p>
<pre class="lang-json prettyprint-override"><code>[
  {
    "keyA": "Example",
    "keyB": {
      "keyC": 2,
      "keyD": {
        "keyE": {
          "name": "foo"
        }
      },
      "keyF": 0
    }
  },
  {
    "keyA": "Example2",
    "keyB": {
      "keyC": 6,
      "keyD": {
        "keyE": {
          "name": "bar"
        }
      },
      "keyF": 5
    }
  }
]
</code>```

So far, I have the following but I don't know what to do after the json.loads. I know I have to recursively call the function but not sure how.

import json

def convert(data_list: list) -> list:
  for i in range(len(data_list)):
    obj = data_list[i]

    for key, value in obj.items():
      if isinstance(value, str) and any(char in "{[]}" for char in value):
        try:
          data = json.loads(value)
          # What do I do here?
        except:
          continue
```

答:
Okay, here is recursive solution:

```<code>import json
from json import JSONDecodeError

data = [
  {
    "keyA": "Example",
    "keyB": "{\"keyC\":2,\"keyD\":{\"keyE\":\"{\\\"name\\\":\\\"foo\\\"}\"},\"keyF\":0}"
  },
  {
    "keyA": "Example2",
    "keyB": "{\"keyC\":6,\"keyD\":{\"keyE\":\"{\\\"name\\\":\\\"bar\\\"}\"},\"keyF\":5}"
  }
]

def rec_convert(data):

  for k, v in data.items():
    try:
      if type(v) == dict:
        rec_convert(v)
        continue
      data[k] = json.loads(v)
      rec_convert(data[k])
    except (JSONDecodeError, TypeError):
      continue

for el in data:
  rec_convert(el)

print("raw print:")

print(data)

print("pretty print")

print(json.dumps(data, indent=2))
</code>```

and output:

```<code>raw print:
[{'keyA': 'Example', 'keyB': {'keyC': 2, 'keyD': {'keyE': {'name': 'foo'}}, 'keyF': 0}}, {'keyA': 'Example2', 'keyB': {'keyC': 6, 'keyD': {'keyE': {'name': 'bar'}}, 'keyF': 5}}]
pretty print
[
  {
    "keyA": "Example",
    "keyB": {
      "keyC": 2,
      "keyD": {
        "keyE": {
          "name": "foo"
        }
      },
      "keyF": 0
    }
  },
  {
    "keyA": "Example2",
    "keyB": {
      "keyC": 6,
      "keyD": {
        "keyE": {
          "name": "bar"
        }
      },
      "keyF": 5
    }
  }
]
</code>```

Body:
I have the following list (notice "keyE" has a dictionary as a string):

[
  {
    "keyA": "Example",
    "keyB": "{\"keyC\":2,\"keyD\":{\"keyE\":\"{\"name\":\"foo\"}\"},\"keyF\":0}"
  },
  {
    "keyA": "Example2",
    "keyB": "{\"keyC\":6,\"keyD\":{\"keyE\":\"{\"name\":\"bar\"}\"},\"keyF\":5}"
  }
]

And I want to convert it to this (it can have any number of nested dictionaries and lists):

[
  {
    "keyA": "Example",
    "keyB": {
      "keyC": 2,
      "keyD": {
        "keyE": {
          "name": "foo"
        }
      },
      "keyF": 0
    }
  },
  {
    "keyA": "Example2",
    "keyB": {
      "keyC": 6,
      "keyD": {
        "keyE": {
          "name": "bar"
        }
      },
      "keyF": 5
    }
  }
]

So far, I have the following but I don't know what to do after the json.loads. I know I have to recursively call the function but not sure how.

import json

def convert(data_list: list) -> list:
  for i in range(len(data_list)):
    obj = data_list[i]

    for key, value in obj.items():
      if isinstance(value, str) and any(char in "{[]}" for char in value):
        try:
          data = json.loads(value)
          # What do I do here?
        except:
          continue

Body:
Okay, here is recursive solution:

import json
from json import JSONDecodeError

data = [
  {
    "keyA": "Example",
    "keyB": "{\"keyC\":2,\"keyD\":{\"keyE\":\"{\\\"name\\\":\\\"foo\\\"}\"},\"keyF\":0}"
  },
  {
    "keyA": "Example2",
    "keyB": "{\"keyC\":6,\"keyD\":{\"keyE\":\"{\\\"name\\\":\\\"bar\\\"}\"},\"keyF\":5}"
  }
]

def rec_convert(data):

  for k, v in data.items():
    try:
      if type(v) == dict:
        rec_convert(v)
        continue
      data[k] = json.loads(v)
      rec_convert(data[k])
    except (JSONDecodeError, TypeError):
      continue

for el in data:
  rec_convert(el)

print("raw print:")

print(data)

print("pretty print")

print(json.dumps(data, indent=2))

and output:

raw print:
[{'keyA': 'Example', 'keyB': {'keyC': 2, 'keyD': {'keyE': {'name': 'foo'}}, 'keyF': 0}}, {'keyA': 'Example2', 'keyB': {'keyC': 6, 'keyD': {'keyE': {'name': 'bar'}}, 'keyF': 5}}]
pretty print
[
  {
    "keyA": "Example",
    "keyB": {
      "keyC": 2,
      "keyD": {
        "keyE": {
          "name": "foo"
        }
      },
      "keyF": 0
    }
  },
  {
    "keyA": "Example2",
    "keyB": {
      "keyC": 6,
      "keyD": {
        "keyE": {
          "name": "bar"
        }
      },
      "keyF": 5
    }
  }
]