问:
configuration Pycharm/odoo 12
i have a problem with the configuration of odoo 12 with pycharm on Windows 10 ( Python 3.6)

This is the error :

```<code>"C:\Program Files (x86)\Odoo 12.0\python\python.exe" "C:/Program Files (x86)/Odoo 12.0/server/odoo-bin"
ERROR: couldn't create the logfile directory. Logging to the standard output.
2020-02-19 10:20:28,596 8216 INFO ? odoo: Odoo version 12.0-20200203
2020-02-19 10:20:28,597 8216 INFO ? odoo: Using configuration file at C:\Program Files (x86)\Odoo 12.0\server\odoo.conf
2020-02-19 10:20:28,597 8216 INFO ? odoo: addons paths: ['c:\\users\\asus\\appdata\\local\\openerp s.a\\odoo\\addons\\12.0', 'c:\\program files (x86)\\odoo 12.0\\server\\odoo\\addons', 'C:\\Program Files (x86)\\Odoo 12.0\\server\\odoo\\addons']
2020-02-19 10:20:28,598 8216 INFO ? odoo: database: root@localhost:5432
2020-02-19 10:20:30,813 8216 INFO ? odoo.addons.base.models.ir_actions_report: Will use the Wkhtmltopdf binary at C:\Program Files (x86)\Odoo 12.0\thirdparty\wkhtmltopdf.exe
2020-02-19 10:20:32,873 8216 INFO ? odoo.service.server: HTTP service (werkzeug) running on DESKTOP-GPEAI9D:8069
</code>```

and thanks =)

答:
If you are using pycharm then do setting like this.

Script path: PathOfodoo-binFile

Parameters: --config=pathToConfFile

Title: configuration Pycharm/odoo 12

Body:
i have a problem with the configuration of odoo 12 with pycharm on Windows 10 ( Python 3.6)

This is the error :

"C:\Program Files (x86)\Odoo 12.0\python\python.exe" "C:/Program Files (x86)/Odoo 12.0/server/odoo-bin"
ERROR: couldn't create the logfile directory. Logging to the standard output.
2020-02-19 10:20:28,596 8216 INFO ? odoo: Odoo version 12.0-20200203
2020-02-19 10:20:28,597 8216 INFO ? odoo: Using configuration file at C:\Program Files (x86)\Odoo 12.0\server\odoo.conf
2020-02-19 10:20:28,597 8216 INFO ? odoo: addons paths: ['c:\\users\\asus\\appdata\\local\\openerp s.a\\odoo\\addons\\12.0', 'c:\\program files (x86)\\odoo 12.0\\server\\odoo\\addons', 'C:\\Program Files (x86)\\Odoo 12.0\\server\\odoo\\addons']
2020-02-19 10:20:28,598 8216 INFO ? odoo: database: root@localhost:5432
2020-02-19 10:20:30,813 8216 INFO ? odoo.addons.base.models.ir_actions_report: Will use the Wkhtmltopdf binary at C:\Program Files (x86)\Odoo 12.0\thirdparty\wkhtmltopdf.exe
2020-02-19 10:20:32,873 8216 INFO ? odoo.service.server: HTTP service (werkzeug) running on DESKTOP-GPEAI9D:8069

and thanks =)


来源: stackexchange

问:
Why does from scipy import spatial work, while scipy.spatial doesn't work after import scipy?
I would like to use scipy.spatial.distance.cosine in my code. I can import the spatial submodule if I do something like import scipy.spatial or from scipy import spatial, but if I simply import scipy calling scipy.spatial.distance.cosine(...) results in the following error: AttributeError: 'module' object has no attribute 'spatial'.

What is wrong with the second approach?

答: Use scipy version 1.2.1 to solve this issue......</p>

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
oracle query taking more execution time in oracle when i m using AND condition
This below query taking more execution time when in filtering with AND Condition TD.A97 = '4408' ,and apart from them I m joining two table and two synonyms can u help me to reduce execution time  for this query.</p>

```<code>SELECT DISTINCT TC.CUS_ACNT_NBR ,
                TC.CUS_ACNT_ROLE_CD ,
                TD.F_DOCNUMBER,
                TD.A45,
                HD.SHPMNT_NBR,
                HD.SHPMNT_ID
FROM   TDOC_CUS_ACNT TC
       INNER JOIN TDOC TD ON TD.F_DOCNUMBER = TC.F_DOCNUMBER
       INNER JOIN DWH_SHIPMENT_DIM HD ON TD.A45 = HD.SHPMNT_NBR
       INNER JOIN DWH_INVOICE_CHARGE_FACT ICF ON HD.shpmnt_dim_key = ICF.shipment_dim_fk
WHERE  TC.CUS_ACNT_ROLE_CD in ('BILL','SHPR','THRD')
AND    TD.A97 = '4408' ;
</code>```

答:
One way you can use to reduce execution time is to use parallel hints in your query.

```<code> ALTER TABLE  T PARALLEL 4;

 SELECT  /*+ parallel(4) */    DISTINCT TC.CUS_ACNT_NBR ...
</code>```

oracle docs

Body:
This below query taking more execution time when in filtering with AND Condition TD.A97 = '4408' ,and apart from them I m joining two table and two synonyms can u help me to reduce execution time  for this query.

SELECT DISTINCT TC.CUS_ACNT_NBR ,
                TC.CUS_ACNT_ROLE_CD ,
                TD.F_DOCNUMBER,
                TD.A45,
                HD.SHPMNT_NBR,
                HD.SHPMNT_ID
FROM   TDOC_CUS_ACNT TC
       INNER JOIN TDOC TD ON TD.F_DOCNUMBER = TC.F_DOCNUMBER
       INNER JOIN DWH_SHIPMENT_DIM HD ON TD.A45 = HD.SHPMNT_NBR
       INNER JOIN DWH_INVOICE_CHARGE_FACT ICF ON HD.shpmnt_dim_key = ICF.shipment_dim_fk
WHERE  TC.CUS_ACNT_ROLE_CD in ('BILL','SHPR','THRD')
AND    TD.A97 = '4408' ;

Body:
One way you can use to reduce execution time is to use parallel hints in your query.

 ALTER TABLE  T PARALLEL 4;

 SELECT  /*+ parallel(4) */    DISTINCT TC.CUS_ACNT_NBR ...

oracle docs


问:
Cloning repository from AWS Codecommit
I am currently using SSH Key to clone repository from AWS Codecommit to my local machine. My

```<code>ssh git-codecommit.us-east-2.amazonaws.com
</code>```

has successfully connected.

My problem is that when I run this:

```<code>git clone ssh://git-codecommit.us-east-2.amazonaws.com.amazonaws.com/v1/repos/Project
</code>```

it is cloning my project but after 100% of cloning, I keep getting this error

```<code>remote: Counting objects: 1024, done.
client_loop: send disconnect: Connection reset by peer KiB/s
fatal: the remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed
</code>```

I cannot find answers around google and hoping that someone will help me with this. What is the possible causes of these error? Thank you in advance!

答:
Try increasing the buffer

```<code>git config --global ssh.postBuffer 1048576000
</code>```

If it doesn't work then use TortoiseGit software,
It helped me when I faced the same problem like yours

Title: Cloning repository from AWS Codecommit

Body:
I am currently using SSH Key to clone repository from AWS Codecommit to my local machine. My

ssh git-codecommit.us-east-2.amazonaws.com

has successfully connected.

My problem is that when I run this:

git clone ssh://git-codecommit.us-east-2.amazonaws.com.amazonaws.com/v1/repos/Project

it is cloning my project but after 100% of cloning, I keep getting this error

remote: Counting objects: 1024, done.
client_loop: send disconnect: Connection reset by peer KiB/s
fatal: the remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed

I cannot find answers around google and hoping that someone will help me with this. What is the possible causes of these error? Thank you in advance!

Body:
Try increasing the buffer

git config --global ssh.postBuffer 1048576000

If it doesn't work then use TortoiseGit software,
It helped me when I faced the same problem like yours


问:
Dashed border animation in css3 animation
I saw this article http://tympanus.net/Tutorials/BorderAnimationSVG/

I want to add this in my WP blog. So that each new post div have this animation on its border. But problem is that its in SVG. Is there anyway i can make this animation work without using SVG and also i don't want to use javascript.

Lets say code is:

.go {
  width: 900px;
  height: 200px;
  border: 8px dashed;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="go"></div></code>```

答:
Animating a pseudo-element worked better for my round button:

.border {
    position: relative;
    border: 0;
    height: 4rem;
    width: 4rem;
    border-radius: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.border:before {
  content: " ";
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  border-radius: 100%;
  border: 2px dashed limegreen;
  animation: rotate 20s linear infinite;
}

@keyframes rotate {
  0% { transform: rotate(0deg) }
  100% { transform: rotate(360deg) }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="border"> hello </div></code>```

Body:
Animating a pseudo-element worked better for my round button:

.border {
    position: relative;
    border: 0;
    height: 4rem;
    width: 4rem;
    border-radius: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.border:before {
  content: " ";
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  border-radius: 100%;
  border: 2px dashed limegreen;
  animation: rotate 20s linear infinite;
}

@keyframes rotate {
  0% { transform: rotate(0deg) }
  100% { transform: rotate(360deg) }
}

<div class="border"> hello </div>


问:
Extract value in Python
My Code:

```<code>import requests
import json

web_page = requests.get("http://api.bart.gov/api/etd.aspx?cmd=etd&orig=mont&key=MW9S-E7SL-26DU-VV8V&json=y")
response = web_page.text
parsed_json = json.loads(response)
#print(parsed_json)

print(parsed_json['root']['date'])
print(parsed_json['root']['time'])
print(parsed_json['root']['station']['name'])

</code>```

How to extract value of destination and minutes from below in Python.

```<code>[{'name': 'Montgomery St.', 'abbr': 'MONT', 'etd': [{'destination': 'Daly City', 'abbreviation': 'DALY', 'limited': '0', 'estimate': [{'minutes': '39', 'platform': '1', 'direction': 'South', 'length': '10', 'color': 'WHITE', 'hexcolor': '#ffffff', 'bikeflag': '1', 'delay': '220'}]}, {'destination': 'SF Airport', 'abbreviation': 'SFIA', 'limited': '0', 'estimate': [{'minutes': '16', 'platform': '1', 'direction': 'South', 'length': '10', 'color': 'YELLOW', 'hexcolor': '#ffff33', 'bikeflag': '1', 'delay': '132'}, {'minutes': '26', 'platform': '1', 'direction': 'South', 'length': '10', 'color': 'BLUE', 'hexcolor': '#0099cc', 'bikeflag': '1', 'delay': '69'}]}]}]

</code>```

答:
The problem is in parsed_json['root']['station']['name']. parsed_json['root']['station'] is a list, not a dict, so it doesn't have name key. You need to use index 0 or iterate over it

```<code>for station in parsed_json['root']['station']:
    for etd in station['etd']:
        for estimate in etd['estimate']:
            print(etd['destination'], estimate['minutes'])
</code>```

Output

```<code>Daly City 35
SF Airport 16
SF Airport 26
</code>```

Title: Extract value in Python

Body:
My Code:

import requests
import json

web_page = requests.get("http://api.bart.gov/api/etd.aspx?cmd=etd&orig=mont&key=MW9S-E7SL-26DU-VV8V&json=y")
response = web_page.text
parsed_json = json.loads(response)
#print(parsed_json)

print(parsed_json['root']['date'])
print(parsed_json['root']['time'])
print(parsed_json['root']['station']['name'])

How to extract value of destination and minutes from below in Python.

[{'name': 'Montgomery St.', 'abbr': 'MONT', 'etd': [{'destination': 'Daly City', 'abbreviation': 'DALY', 'limited': '0', 'estimate': [{'minutes': '39', 'platform': '1', 'direction': 'South', 'length': '10', 'color': 'WHITE', 'hexcolor': '#ffffff', 'bikeflag': '1', 'delay': '220'}]}, {'destination': 'SF Airport', 'abbreviation': 'SFIA', 'limited': '0', 'estimate': [{'minutes': '16', 'platform': '1', 'direction': 'South', 'length': '10', 'color': 'YELLOW', 'hexcolor': '#ffff33', 'bikeflag': '1', 'delay': '132'}, {'minutes': '26', 'platform': '1', 'direction': 'South', 'length': '10', 'color': 'BLUE', 'hexcolor': '#0099cc', 'bikeflag': '1', 'delay': '69'}]}]}]

Body:
The problem is in parsed_json['root']['station']['name']. parsed_json['root']['station'] is a list, not a dict, so it doesn't have name key. You need to use index 0 or iterate over it

for station in parsed_json['root']['station']:
    for etd in station['etd']:
        for estimate in etd['estimate']:
            print(etd['destination'], estimate['minutes'])

Output

Daly City 35
SF Airport 16
SF Airport 26


问:
print result after submitting in laravel
how can I create a submit button that can show the pdf result of my form to print it directly?
this is my code below

```<code><form method="post" action="{{ url('dashboard/generate') }}" enctype="multipart/form-data" id="form-ui">
                {{ csrf_field() }}
                  <div class="col-md-6 col-xs-12">
                    <label for="exampleInputEmail1">Distributor</label>
                    <select name="distributor" id="type" class="form-control">
                      <option value="">Choose Distributor</option>
                      @foreach ($distributor as $item)
                      <option value="{{ $item->id }}">{{ $item->name }}</option>
                      @endforeach
                    </select>
                  </div>

                  <div class="col-md-6 col-xs-12">
                    <label for="exampleInputEmail1">Select Event</label>
                    <select name="event" id="type" class="form-control">
                      <option value="">Choose Event</option>
                      @foreach ($event as $item)
                      <option value="{{ $item->id }}">({{ $item->events->date }}, {{ $item->time }}, {{ $item->events->stage }})-{{ $item->title }}</option>
                      @endforeach
                    </select>
                  </div>

                  <div class="col-md-12 col-xs-12" style="margin-top: 10px;">
                    <button class="btn btn-success" type="submit" onclick="myFunction()">SUBMIT</button>
                  </div>
                </form>
<script>
  function myFunction() {
    window.print();
  }
</script>
</code>```

but it just print the current page (the form page). any advice i can try?

答:
try this onsubmit jquery event

```<code><div class="col-md-12 col-xs-12" style="margin-top: 10px;">
 <button class="btn btn-success" type="submit" name="submit">SUBMIT</button>
</div>

<script>
 $(document).ready(function(){
   $('body').on('submit', '.formsubmit', function(e) {
   alert(1);
 });
</code>```

Body:
how can I create a submit button that can show the pdf result of my form to print it directly?
this is my code below

<form method="post" action="{{ url('dashboard/generate') }}" enctype="multipart/form-data" id="form-ui">
                {{ csrf_field() }}

                    Distributor
                    <select name="distributor" id="type" class="form-control">
                      <option value="">Choose Distributor</option>
                      @foreach ($distributor as $item)
                      <option value="{{ $item->id }}">{{ $item->name }}</option>
                      @endforeach
                    </select>

                    Select Event
                    <select name="event" id="type" class="form-control">
                      <option value="">Choose Event</option>
                      @foreach ($event as $item)
                      <option value="{{ $item->id }}">({{ $item->events->date }}, {{ $item->time }}, {{ $item->events->stage }})-{{ $item->title }}</option>
                      @endforeach
                    </select>

                    <button class="btn btn-success" type="submit" onclick="myFunction()">SUBMIT</button>

                </form>

but it just print the current page (the form page). any advice i can try?

Body:
try this onsubmit jquery event

<div class="col-md-12 col-xs-12" style="margin-top: 10px;">
 <button class="btn btn-success" type="submit" name="submit">SUBMIT</button>
</div>

<script>
 $(document).ready(function(){
   $('body').on('submit', '.formsubmit', function(e) {
   alert(1);
 });


问:
Batching requests over HTTP2
Is it possible to get a better throughput from our servers, if we make one large HTTP request, as opposed to multiple smaller HTTP requests over HTTP2.

As per my understanding it should not produce any significant difference in performance since with HTTP2 we can have multiple requests multiplexed over one TCP connection.

答:
Yes at a network level one large request will be more efficient than multiple small requests. This is due to the overhead of making a network request.

This is also why concatenating CSS and JavaScript and spriting for images were recommended under HTTP/1.1 so the amount of data sent was the same, but the amount of requests was considerably lower. In fact due to the way compression like gzip works the amount of data was often smaller when sending large requests.

HTTP/2 was designed to make the costs of HTTP requests a lot smaller though the reuse of a single TCP connection using multiplexing. In theory this would allow us to give up concatenation and spriting. The reality has been a little less than perfect though - usually due to browser inefficiencies rather than HTTP/2’s fault. The bottleneck has just moved and we need to optimise browsers for the new world. So, for now, some level of concenation and spriting is still recommended.

Getting back to your question, then yes it should have single effects at that network level and in fact HTTP/1.1 and HTTP/2 may even be similar in performance if you do this.

However beyond the network level you may discover other reasons not to bundle into fewer files. If you have one large JavaScript file for example then the browser must wait for it all to be downloaded before it can be parsed, compiled and run. You may be better getting smaller, more important JavaScript downloaded first. Similarly with image spriting you may be waiting for the entire sprite file to download before a single image is display.

Then there are the caching implications. Changing a single line of JS or adding a single image to the image Sprite requires creating a whole new large file, meaning the older one cannot be used and the whole thing needs to be downloaded again in its entirety.

Plus having large files can be more complicated to implemented and managed. They require a build step (maybe not a big deal as many sites do) and creating and managing image sprites through CSS is often more difficult.

Also if using this to stick with HTTP/1.1, then you may be missing out on are the other benefits of HTTP/2 including HPACK header compression and HTTP/2 push (though this is also more tricky to get right than initially thought/hoped!).

It’s a fascinating topic that I’ve spent a lot of time on, and best advice (as always!) is to understand the technology and test, test, test!

Title: Batching requests over HTTP2


问:
Can not horizontally align the div with text-align?
I want align the div horizontally.

.d1 {
  margin-left: 1rem;
  margin-right: 1rem;
  font-size: 0;
  text-align: justify;
}

.d1::after {
  content: '';
  font-size: 0;
  line-height: 0;
  height: 0;
  width: 100%;
  display: inline-block;
}

.dd {
  display: inline-block;
  position: relative;
  font-size: initial;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="d1">
  <div class="dd">aa</div>
  <div class="dd">bb</div>
</div></code>```

but it can not justify the div and align is left. Why?

答:
Please specify how you want to align the div's along the horizontal axis.
For now, I have aligned them adjacent to each other on the left side.</p>

```<code><div class="d1">
  <div class="dd">aa</div>
  <div class="dd">bb</div>
</div>

.d1 {
 display: flex;
}
.dd{
  margin: 1rem; //to provide space in between
}
</code>```

Body:
I want align the div horizontally.

.d1 {
  margin-left: 1rem;
  margin-right: 1rem;
  font-size: 0;
  text-align: justify;
}

.d1::after {
  content: '';
  font-size: 0;
  line-height: 0;
  height: 0;
  width: 100%;
  display: inline-block;
}

.dd {
  display: inline-block;
  position: relative;
  font-size: initial;
}

aa

bb

but it can not justify the div and align is left. Why?

Body:
Please specify how you want to align the div's along the horizontal axis.
For now, I have aligned them adjacent to each other on the left side.

<div class="d1">
  <div class="dd">aa</div>
  <div class="dd">bb</div>
</div>

.d1 {
 display: flex;
}
.dd{
  margin: 1rem; //to provide space in between
}


问:
Fill blank values with data from following columns
Having a dataframe like this:

```<code>data.frame(id = c(1,2,3,4), text1 = c("sth","","another",""), text2 = c("more","another","add",""), text3 = c("final","and","where","all"))
</code>```

How is it possible to detect if in the text1 column a row is blank and fill the blank with a value exist in text2, text3 or text4 column and leave from this NA after the process

Example of expected output

```<code>data.frame(id = c(1,2,3,4), text1 = c("sth","another","another","all"), text2 = c("more","","add",""), text3 = c("final","and","where",""))
</code>```

答:
At this stage, why not also a dplyr approach? Admittedly, with a sparkle of base R in the middle

df <- data.frame(id = c(1,2,3,4),
                 text1 = c("sth","","another",""),
                 text2 = c("more","another","add",""),
                 text3 = c("final","and","where","all"))

library("dplyr")
library("tidyr")

df_filled <- df %>%
    pivot_longer(cols = starts_with("text"),
                 names_to = "text_id",
                 values_to = "value") %>%
    mutate(value = as.character(value)) %>%
    group_by(id) %>%
    mutate(value = if_else(value=="", as.character(NA), value)) %>%
    mutate(previously_missing = value) %>%
    tidyr::fill(value, .direction = "downup")

df_filled$value[which(is.na(df_filled$previously_missing)&df_filled$text_id!="text3")+1] <- NA

df_filled %>%
    ungroup() %>%
    pivot_wider(id_cols = id,
                names_from = "text_id",
                values_from = "value")
#> # A tibble: 4 x 4
#>      id text1   text2 text3
#>   <dbl> <chr>   <chr> <chr>
#> 1     1 sth     more  final
#> 2     2 another <NA>  and
#> 3     3 another add   where
#> 4     4 all     <NA>  <NA>
```

Created on 2020-02-19 by the reprex package (v0.3.0)

Body:
Having a dataframe like this:

data.frame(id = c(1,2,3,4), text1 = c("sth","","another",""), text2 = c("more","another","add",""), text3 = c("final","and","where","all"))

How is it possible to detect if in the text1 column a row is blank and fill the blank with a value exist in text2, text3 or text4 column and leave from this NA after the process

Example of expected output

data.frame(id = c(1,2,3,4), text1 = c("sth","another","another","all"), text2 = c("more","","add",""), text3 = c("final","and","where",""))

Body:
At this stage, why not also a dplyr approach? Admittedly, with a sparkle of base R in the middle

df <- data.frame(id = c(1,2,3,4),
                 text1 = c("sth","","another",""),
                 text2 = c("more","another","add",""),
                 text3 = c("final","and","where","all"))

library("dplyr")
library("tidyr")

df_filled <- df %>%
    pivot_longer(cols = starts_with("text"),
                 names_to = "text_id",
                 values_to = "value") %>%
    mutate(value = as.character(value)) %>%
    group_by(id) %>%
    mutate(value = if_else(value=="", as.character(NA), value)) %>%
    mutate(previously_missing = value) %>%
    tidyr::fill(value, .direction = "downup")

df_filled$value[which(is.na(df_filled$previously_missing)&df_filled$text_id!="text3")+1] <- NA

df_filled %>%
    ungroup() %>%
    pivot_wider(id_cols = id,
                names_from = "text_id",
                values_from = "value")
#> # A tibble: 4 x 4
#>      id text1   text2 text3
#>   <dbl> <chr>   <chr> <chr>
#> 1     1 sth     more  final
#> 2     2 another <NA>  and
#> 3     3 another add   where
#> 4     4 all     <NA>  <NA>

Created on 2020-02-19 by the reprex package (v0.3.0)


问:
How to extract floats from vector columns in PySpark?
My Spark DataFrame has data in the following format:

The printSchema() shows that each column is of the type vector.

I tried to get the values out of [ and ] using the code below (for 1 columns col1):

```<code>from pyspark.sql.functions import udf
from pyspark.sql.types import FloatType

firstelement=udf(lambda v:float(v[0]),FloatType())
df.select(firstelement('col1')).show()
</code>```

However, how can I apply it to all columns of df?

答:
As I understand your problem, you do not required to use UDF to change Vector into normal Float Type. Use pyspark predefined function concat_ws for it.

```<code>>>> from pyspark.sql.functions import *
>>> df.show()
+------+
|   num|
+------+
| [211]|
|[3412]|
| [121]|
| [121]|
|  [34]|
|[1441]|
+------+

>>> df.printSchema()
root
 |-- num: array (nullable = true)
 |    |-- element: string (containsNull = true)

>>> df.withColumn("num", concat_ws("", col("num"))).show()
+----+
| num|
+----+
| 211|
|3412|
| 121|
| 121|
|  34|
|1441|
+----+
</code>```

Body:
My Spark DataFrame has data in the following format:

The printSchema() shows that each column is of the type vector.

I tried to get the values out of [ and ] using the code below (for 1 columns col1):

from pyspark.sql.functions import udf
from pyspark.sql.types import FloatType

firstelement=udf(lambda v:float(v[0]),FloatType())
df.select(firstelement('col1')).show()

However, how can I apply it to all columns of df?

Body:
As I understand your problem, you do not required to use UDF to change Vector into normal Float Type. Use pyspark predefined function concat_ws for it.

>>> from pyspark.sql.functions import *
>>> df.show()
+------+
|   num|
+------+
| [211]|
|[3412]|
| [121]|
| [121]|
|  [34]|
|[1441]|
+------+

>>> df.printSchema()
root
 |-- num: array (nullable = true)
 |    |-- element: string (containsNull = true)

>>> df.withColumn("num", concat_ws("", col("num"))).show()
+----+
| num|
+----+
| 211|
|3412|
| 121|
| 121|
|  34|
|1441|
+----+


问:
Could not download maven-fail-safe-plugin. Giving me an error message
I have created a new maven project with serenity framework. I am getting this error in my new maven project

Plugin org.apache.maven.plugins:maven-failsafe-plugin:2.22.1 or one of
  its dependencies could not be resolved: Failed to read artifact
  descriptor for
  org.apache.maven.plugins:maven-failsafe-plugin:jar:2.22.1: Could not
  transfer artifact
  org.apache.maven.plugins:maven-failsafe-plugin:pom:2.22.1 from/to
  central (http://jcenter.bintray.com): Authorization failed for
  http://jcenter.bintray.com/org/apache/maven/plugins/maven-failsafe-plugin/2.22.1/maven-failsafe-plugin-2.22.1.pom
  403 Forbidden

答:
I found this way, just delete these line below in pom.xml and it's worked:

<repositories>
  <repository>
    <snapshots>
      <enabled>false</enabled>
    </snapshots>
    <id>central</id>
    <name>bintray</name>
    <url>http://jcenter.bintray.com</url>
  </repository>
</repositories>
<pluginRepositories>
  <pluginRepository>
    <snapshots>
      <enabled>false</enabled>
    </snapshots>
    <id>central</id>
    <name>bintray-plugins</name>
    <url>http://jcenter.bintray.com</url>
  </pluginRepository>
</pluginRepositories>
```


问:
WPF: How to smooth out a ColorAnimation with the starting point as Transparent?
I'm animating the background of a button at the control template level, but since the initial background color is set to Transparent, I'm noticing a weird effect where the transition jumps from Transparent => some white/gray intermediate => my desired color.

Here is a gif showing the effect:

Button Style (XAML)

```<code> <Style x:Key="btn-style"
         TargetType="Button">
    <Setter Property="Foreground"
            Value="Black" />
    <Setter Property="Background"
            Value="Transparent" />
    <Setter Property="Padding"
            Value="15,0,15,0" />
    <Setter Property="BorderBrush"
            Value="Transparent" />
    <Setter Property="BorderThickness"
            Value="0" />
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="{x:Type ButtonBase}">
          <Border x:Name="PART_Border"
                  Background="{TemplateBinding Background}"
                  BorderBrush="{TemplateBinding BorderBrush}"
                  BorderThickness="{TemplateBinding BorderThickness}"
                  Padding="{TemplateBinding Padding}">
            <ContentPresenter x:Name="PART_ContentHost"
                              HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                              VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
          </Border>
          <ControlTemplate.Triggers>
            <MultiTrigger>
              <MultiTrigger.Conditions>
                <Condition Property="IsMouseOver"
                           Value="True" />
              </MultiTrigger.Conditions>
              <MultiTrigger.EnterActions>
                <BeginStoryboard>
                  <Storyboard>

                    <ColorAnimation Duration="0:0:0.125"
                                    Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)"
                                    From="Transparent"
                                    To="#ff0000">
                      <ColorAnimation.EasingFunction>
                        <ExponentialEase EasingMode="EaseInOut"
                                         Exponent="2" />
                      </ColorAnimation.EasingFunction>
                    </ColorAnimation>
                  </Storyboard>
                </BeginStoryboard>
              </MultiTrigger.EnterActions>
              <MultiTrigger.ExitActions>
                <BeginStoryboard>
                  <Storyboard>
                    <ColorAnimation Duration="0:0:0.125"
                                    Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)"
                                    From="#ff0000"
                                    To="Transparent">
                      <ColorAnimation.EasingFunction>
                        <ExponentialEase EasingMode="EaseInOut"
                                         Exponent="2" />
                      </ColorAnimation.EasingFunction>
                    </ColorAnimation>

                  </Storyboard>
                </BeginStoryboard>
              </MultiTrigger.ExitActions>
            </MultiTrigger>
          </ControlTemplate.Triggers>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>
</code>```

Things I've Tried

Setting the DesiredFrameRate="60" definitely makes it smoother, but the intermediate "Gray" flash is still present.

Not specifying the EasingFunction has the same behavior

答:
You see some white because Colors.Transparent is defined as transparent white , i.e. #00FFFFFF.

You may animate to/from a fully transparent red:

```<code><ColorAnimation Storyboard.TargetProperty="Background.Color"
                From="#00ff0000" To="#ffff0000"
                Duration="0:0:0.125">
    ...
</ColorAnimation>
</code>```

Body:
I'm animating the background of a button at the control template level, but since the initial background color is set to Transparent, I'm noticing a weird effect where the transition jumps from Transparent => some white/gray intermediate => my desired color.

Here is a gif showing the effect:

Button Style (XAML)

Things I've Tried

Setting the DesiredFrameRate="60" definitely makes it smoother, but the intermediate "Gray" flash is still present.

Not specifying the EasingFunction has the same behavior

Body:
You see some white because Colors.Transparent is defined as transparent white , i.e. #00FFFFFF.

You may animate to/from a fully transparent red:

<ColorAnimation Storyboard.TargetProperty="Background.Color"
                From="#00ff0000" To="#ffff0000"
                Duration="0:0:0.125">
    ...
</ColorAnimation>


问:
Load custom dataset like Mnist ( Tensorflow Python )
I'm experimenting with a clustering model from https://github.com/astirn/IIC
(already tried to contact him about this)

It uses Mnist Dataset like in most research papers.
In here they first define the dataset name as 'mnist' which is enough for tensorflow to import mnist from their standard online datasets.
Then he loads the dataset using the tensorflow_dataset.load() function

I have created a tfrecord file for my dataset and now I just need to replace the part where the beforementioned script points to "mnist" (line 1 in code below) and instead point to my local dataset.

Do I just replace 'mnist' with the file path in the first line???

Code from actual training model file:

```<code>if __name__ == '__main__':
# pick a data set
    DATA_SET = 'mnist'

# define splits
    DS_CONFIG = {
        # mnist data set parameters
        'mnist': {
            'batch_size': 700,
            'num_repeats': 5,
            'mdl_input_dims': [24, 24, 1]}
    }

# load the data set
    TRAIN_SET, TEST_SET, SET_INFO = load(data_set_name=DATA_SET, **DS_CONFIG[DATA_SET])

# configure the common model elements
    MDL_CONFIG = {
    # mist hyper-parameters
        'mnist': {
            'num_classes': SET_INFO.features['label'].num_classes,
            'learning_rate': 1e-4,
            'num_repeats': DS_CONFIG[DATA_SET]['num_repeats'],
            'save_dir': None},
    }
</code>```

Code from 'data preparation file' where he calls the dataset with tensorflor_dataset.load as tfds.load :

```<code>def load(data_set_name, **kwargs):
    """
    :param data_set_name: data set name--call tfds.list_builders() for options
    :return:
        train_ds: TensorFlow Dataset object for the training data
        test_ds: TensorFlow Dataset object for the testing data
        info: data set info object
    """
    # get data and its info
    ds, info = tfds.load(name=data_set_name, split=tfds.Split.ALL, with_info=True)
</code>```

thanks for the help

答:
According to docs, you need to use download parameter as False and data_dir with the name of directory:

```<code>ds, info = tfds.load(name=data_set_name, split=tfds.Split.ALL, with_info=True, download=False, data_dir="/path/to/file")
</code>```

Body:
I'm experimenting with a clustering model from https://github.com/astirn/IIC
(already tried to contact him about this)

It uses Mnist Dataset like in most research papers.
In here they first define the dataset name as 'mnist' which is enough for tensorflow to import mnist from their standard online datasets.
Then he loads the dataset using the tensorflow_dataset.load() function

I have created a tfrecord file for my dataset and now I just need to replace the part where the beforementioned script points to "mnist" (line 1 in code below) and instead point to my local dataset.

Do I just replace 'mnist' with the file path in the first line???

Code from actual training model file:

if __name__ == '__main__':
# pick a data set
    DATA_SET = 'mnist'

# define splits
    DS_CONFIG = {
        # mnist data set parameters
        'mnist': {
            'batch_size': 700,
            'num_repeats': 5,
            'mdl_input_dims': [24, 24, 1]}
    }

# load the data set
    TRAIN_SET, TEST_SET, SET_INFO = load(data_set_name=DATA_SET, **DS_CONFIG[DATA_SET])

# configure the common model elements
    MDL_CONFIG = {
    # mist hyper-parameters
        'mnist': {
            'num_classes': SET_INFO.features['label'].num_classes,
            'learning_rate': 1e-4,
            'num_repeats': DS_CONFIG[DATA_SET]['num_repeats'],
            'save_dir': None},
    }

Code from 'data preparation file' where he calls the dataset with tensorflor_dataset.load as tfds.load :

def load(data_set_name, **kwargs):
    """
    :param data_set_name: data set name--call tfds.list_builders() for options
    :return:
        train_ds: TensorFlow Dataset object for the training data
        test_ds: TensorFlow Dataset object for the testing data
        info: data set info object
    """
    # get data and its info
    ds, info = tfds.load(name=data_set_name, split=tfds.Split.ALL, with_info=True)

thanks for the help

Body:
According to docs, you need to use download parameter as False and data_dir with the name of directory:

ds, info = tfds.load(name=data_set_name, split=tfds.Split.ALL, with_info=True, download=False, data_dir="/path/to/file")


问:
Date format and time zone JS
I would like to explain my problem of the day.

In the following code, everything works properly. The problem is I receive the "created" in the following format:

```<code>"created": "2020-02-18T13:45:01.652Z"
</code>```

but I would only like to recover the time if possible without the seconds:

```<code>postbackend = () => {
  const config = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      ...this.state,
      items: newItems,
      created: new
      Date().toISOString()
    }),
  };
  const url = entrypoint + "/alluserpls";
  fetch(url, config)
    .then(res => res.json())
    .then(res => {
      if (res.error) {
        alert(res.error);
      } else {
        alert(`ajouté avec l'ID ${res}!`);
      }
    }).catch(e => {
      console.error(e);
    }).finally(() => this.setState({ redirect: true }));
}
</code>```

Do you have an idea of how to fix this? Neff

答:
I would suggest you use moments js for anything to do with dates in javascript.

moment("2020-02-18T13:45:01.652Z").format('YYYY-MM-DD HH:mm') // 2020-02-18 19:15
```

Title: Date format and time zone JS

Body:
I would like to explain my problem of the day.

In the following code, everything works properly. The problem is I receive the "created" in the following format:

"created": "2020-02-18T13:45:01.652Z"

but I would only like to recover the time if possible without the seconds:

postbackend = () => {
  const config = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      ...this.state,
      items: newItems,
      created: new
      Date().toISOString()
    }),
  };
  const url = entrypoint + "/alluserpls";
  fetch(url, config)
    .then(res => res.json())
    .then(res => {
      if (res.error) {
        alert(res.error);
      } else {
        alert(`ajouté avec l'ID ${res}!`);
      }
    }).catch(e => {
      console.error(e);
    }).finally(() => this.setState({ redirect: true }));
}

Do you have an idea of how to fix this? Neff


问:
Scala Spark code for creating GCP Publisher throws: java.lang.NoSuchMethodError: com.google.common.base.Preconditions.checkArgument
Iam trying to publish messages to a topic in GCP's Pub/Sub using Spark Scala using IntelliJ. Here is the code:
GcpPublish.scala

```<code>val publisher = Publisher.newBuilder(s"projects/projectid/topics/test")
                .setCredentialsProvider(FixedCredentialsProvider
                .create(ServiceAccountCredentials
                .fromStream(new FileInputStream("gs://credsfiles/projectid.json"))))
                .build()

publisher.publish(PubsubMessage
         .newBuilder
         .setData(ByteString.copyFromUtf8(JSONData.toString()))
         .build())
</code>```

And this is the build.sbt:

```<code>name := "TryingSomething"

version := "1.0"

scalaVersion := "2.11.12"

val sparkVersion = "2.3.2"

libraryDependencies ++= Seq(
  "org.apache.spark" %% "spark-core" % "2.3.2" % "provided",
  "org.apache.spark" %% "spark-sql" % "2.3.2" ,
  "com.google.cloud" % "google-cloud-bigquery" % "1.106.0",
  "org.apache.beam" % "beam-sdks-java-core" % "2.19.0" ,
  "org.apache.beam" % "beam-runners-google-cloud-dataflow-java" % "2.19.0",
  "com.typesafe.scala-logging" %% "scala-logging" % "3.1.0" ,
  "org.apache.beam" % "beam-sdks-java-extensions-google-cloud-platform-core" % "2.19.0" ,
  "org.apache.beam" % "beam-sdks-java-io-google-cloud-platform" % "2.19.0" ,
  "com.google.apis" % "google-api-services-bigquery" % "v2-rev456-1.25.0" ,
  "com.google.cloud" % "google-cloud-pubsub" % "1.102.1",
  "com.google.guava" % "guava" % "28.2-jre",
  "org.apache.httpcomponents" % "httpclient" % "4.5.11"
)

assemblyMergeStrategy in assembly := {
  case PathList("META-INF", xs @ _*) => MergeStrategy.discard
  case _ => MergeStrategy.first
}
</code>```

but when I create the fat jar and run it on the Dataprocs cluster I get the below error:

```<code>Exception in thread "main" java.lang.NoSuchMethodError: com.google.common.base.Preconditions.checkArgument(ZLjava/lang/String;I)V
    at com.google.api.gax.grpc.InstantiatingGrpcChannelProvider$Builder.setPoolSize(InstantiatingGrpcChannelProvider.java:527)
    at com.google.api.gax.grpc.InstantiatingGrpcChannelProvider$Builder.setChannelsPerCpu(InstantiatingGrpcChannelProvider.java:546)
    at com.google.api.gax.grpc.InstantiatingGrpcChannelProvider$Builder.setChannelsPerCpu(InstantiatingGrpcChannelProvider.java:535)
    at com.google.cloud.pubsub.v1.Publisher$Builder.<init>(Publisher.java:633)
    at com.google.cloud.pubsub.v1.Publisher$Builder.<init>(Publisher.java:588)
    at com.google.cloud.pubsub.v1.Publisher.newBuilder(Publisher.java:584)
</code>```

I followed the solutions stated here and added the guava and httpcomponents dependencies but I still get the same exception.

I even changed the code to instantiate the Publisher to:

```<code>val publisher = Publisher.newBuilder(s"projects/projectid/topics/test").build()
</code>```

But this gives the same error as well.

Any suggestions what could cause this error?

答:
The problem was that both Spark and Hadoop injected their own versions of guava that is also present in the Google Pubsub package. I got around this by adding shade rules in the build.sbt file:

```<code>assemblyShadeRules in assembly := Seq(
  ShadeRule.rename("com.google.common.**" -> "repackaged.com.google.common.@1").inAll,
  ShadeRule.rename("com.google.protobuf.**" -> "repackaged.com.google.protobuf.@1").inAll,
  ShadeRule.rename("io.netty.**" -> "repackaged.io.netty.@1").inAll
)
</code>```

The shade rule for com.google.common and com.google.protobuf is the one which solves the guava dependencies. I added the others for later dependency conflicts I encountered on the way.

Body:
Iam trying to publish messages to a topic in GCP's Pub/Sub using Spark Scala using IntelliJ. Here is the code:
GcpPublish.scala

val publisher = Publisher.newBuilder(s"projects/projectid/topics/test")
                .setCredentialsProvider(FixedCredentialsProvider
                .create(ServiceAccountCredentials
                .fromStream(new FileInputStream("gs://credsfiles/projectid.json"))))
                .build()

publisher.publish(PubsubMessage
         .newBuilder
         .setData(ByteString.copyFromUtf8(JSONData.toString()))
         .build())

And this is the build.sbt:

name := "TryingSomething"

version := "1.0"

scalaVersion := "2.11.12"

val sparkVersion = "2.3.2"

libraryDependencies ++= Seq(
  "org.apache.spark" %% "spark-core" % "2.3.2" % "provided",
  "org.apache.spark" %% "spark-sql" % "2.3.2" ,
  "com.google.cloud" % "google-cloud-bigquery" % "1.106.0",
  "org.apache.beam" % "beam-sdks-java-core" % "2.19.0" ,
  "org.apache.beam" % "beam-runners-google-cloud-dataflow-java" % "2.19.0",
  "com.typesafe.scala-logging" %% "scala-logging" % "3.1.0" ,
  "org.apache.beam" % "beam-sdks-java-extensions-google-cloud-platform-core" % "2.19.0" ,
  "org.apache.beam" % "beam-sdks-java-io-google-cloud-platform" % "2.19.0" ,
  "com.google.apis" % "google-api-services-bigquery" % "v2-rev456-1.25.0" ,
  "com.google.cloud" % "google-cloud-pubsub" % "1.102.1",
  "com.google.guava" % "guava" % "28.2-jre",
  "org.apache.httpcomponents" % "httpclient" % "4.5.11"
)

assemblyMergeStrategy in assembly := {
  case PathList("META-INF", xs @ _*) => MergeStrategy.discard
  case _ => MergeStrategy.first
}

but when I create the fat jar and run it on the Dataprocs cluster I get the below error:

Exception in thread "main" java.lang.NoSuchMethodError: com.google.common.base.Preconditions.checkArgument(ZLjava/lang/String;I)V
    at com.google.api.gax.grpc.InstantiatingGrpcChannelProvider$Builder.setPoolSize(InstantiatingGrpcChannelProvider.java:527)
    at com.google.api.gax.grpc.InstantiatingGrpcChannelProvider$Builder.setChannelsPerCpu(InstantiatingGrpcChannelProvider.java:546)
    at com.google.api.gax.grpc.InstantiatingGrpcChannelProvider$Builder.setChannelsPerCpu(InstantiatingGrpcChannelProvider.java:535)
    at com.google.cloud.pubsub.v1.Publisher$Builder.<init>(Publisher.java:633)
    at com.google.cloud.pubsub.v1.Publisher$Builder.<init>(Publisher.java:588)
    at com.google.cloud.pubsub.v1.Publisher.newBuilder(Publisher.java:584)

I followed the solutions stated here and added the guava and httpcomponents dependencies but I still get the same exception.

I even changed the code to instantiate the Publisher to:

val publisher = Publisher.newBuilder(s"projects/projectid/topics/test").build()

But this gives the same error as well.

Any suggestions what could cause this error?

Body:
The problem was that both Spark and Hadoop injected their own versions of guava that is also present in the Google Pubsub package. I got around this by adding shade rules in the build.sbt file:

assemblyShadeRules in assembly := Seq(
  ShadeRule.rename("com.google.common.**" -> "repackaged.com.google.common.@1").inAll,
  ShadeRule.rename("com.google.protobuf.**" -> "repackaged.com.google.protobuf.@1").inAll,
  ShadeRule.rename("io.netty.**" -> "repackaged.io.netty.@1").inAll
)

The shade rule for com.google.common and com.google.protobuf is the one which solves the guava dependencies. I added the others for later dependency conflicts I encountered on the way.


问:
While loop not properly working on device, it works well in the emulator
While loop not properly work in device , it works well in emulator. What will be an issue? Below is my code,</p>

```<code> val query = database?.createAllDocumentsQuery()
    query?.startKey = "refill-device-SERIAL-AB121-0"
    query?.endKey = "refill-device-SERIAL-AB121-7"
    var result: QueryEnumerator? = null
    result = query?.run()
    val it = result
    if (it != null) {
        while (it.hasNext()) {
            val row = it.next()
            if (row.documentId.startsWith("refill-device-SERIAL-")) {
                obj = JSONObject(row.document.properties)
                val canisters = gson.fromJson(obj.toString(), Canisters::class.java)
                arrayList.add(canisters)
            }
        }
        canistersArrayList.postValue(arrayList)
    }
</code>```

答:
You have to use thread or asynctask for long running operations. Sometime this long running operations works fine on emulator but fails on real device. Do you have any logs in logcat if yes please post them as well.

AsyncTask will look like this

```<code>class queryTask() : AsyncTask<Void, Void, ArrayList>() {
    override fun doInBackground(vararg params: Void?): String? {
      val query = database?.createAllDocumentsQuery()
    query?.startKey = "refill-device-SERIAL-AB121-0"
    query?.endKey = "refill-device-SERIAL-AB121-7"
    var result: QueryEnumerator? = null
    result = query?.run()
    val it = result
    if (it != null) {
        while (it.hasNext()) {
            val row = it.next()
            if (row.documentId.startsWith("refill-device-SERIAL-")) {
                obj = JSONObject(row.document.properties)
                val canisters = gson.fromJson(obj.toString(), Canisters::class.java)
                arrayList.add(canisters)
            }
        }

        return arrayList
    }
    }

    override fun onPreExecute() {
        super.onPreExecute()

    }

    override fun onPostExecute(result: ArrayList?) {
        super.onPostExecute(result)
        canistersArrayList.postValue(result)

    }
}
</code>```

And execute it like

```<code>queryTask().execute()
</code>```

Body:
While loop not properly work in device , it works well in emulator. What will be an issue? Below is my code,

 val query = database?.createAllDocumentsQuery()
    query?.startKey = "refill-device-SERIAL-AB121-0"
    query?.endKey = "refill-device-SERIAL-AB121-7"
    var result: QueryEnumerator? = null
    result = query?.run()
    val it = result
    if (it != null) {
        while (it.hasNext()) {
            val row = it.next()
            if (row.documentId.startsWith("refill-device-SERIAL-")) {
                obj = JSONObject(row.document.properties)
                val canisters = gson.fromJson(obj.toString(), Canisters::class.java)
                arrayList.add(canisters)
            }
        }
        canistersArrayList.postValue(arrayList)
    }

Body:
You have to use thread or asynctask for long running operations. Sometime this long running operations works fine on emulator but fails on real device. Do you have any logs in logcat if yes please post them as well.

AsyncTask will look like this

class queryTask() : AsyncTask<Void, Void, ArrayList>() {
    override fun doInBackground(vararg params: Void?): String? {
      val query = database?.createAllDocumentsQuery()
    query?.startKey = "refill-device-SERIAL-AB121-0"
    query?.endKey = "refill-device-SERIAL-AB121-7"
    var result: QueryEnumerator? = null
    result = query?.run()
    val it = result
    if (it != null) {
        while (it.hasNext()) {
            val row = it.next()
            if (row.documentId.startsWith("refill-device-SERIAL-")) {
                obj = JSONObject(row.document.properties)
                val canisters = gson.fromJson(obj.toString(), Canisters::class.java)
                arrayList.add(canisters)
            }
        }

        return arrayList
    }
    }

    override fun onPreExecute() {
        super.onPreExecute()

    }

    override fun onPostExecute(result: ArrayList?) {
        super.onPostExecute(result)
        canistersArrayList.postValue(result)

    }
}

And execute it like

queryTask().execute()


问:
How do I implement graceful termination in Java?
Say for instance I have my application running in a Linux terminal and I press "CTRL+C" on my keyboard to kill the process it will terminate the Java program.

Is there any way to catch this "request" in my Java application so I can shut it down gracefully and release all resources/write logs. I have several different threads running if it makes a difference to the response.

I know you have have an addShutDownHook, but as written in the Java documentation, it isn't called under certain circumstances, like the kill signal from "CTRL+C" in linux...are there any other ways?

```<code>Runtime.getRuntime().addShutdownHook(new Thread()
{
    public void run ()
    {
        // TODO: implement graceful shutdown here.
    }
});
</code>```

答:
This works for me, capturing SIGINT/Ctrl-C on Linux:</p>

```<code>public class TestShutdownHook
{
    public static void main(final String[] args) throws InterruptedException
    {
        Runtime.getRuntime().addShutdownHook(new Thread()
        {
            @Override
            public void run()
            {
                System.out.println("Shutdown hook ran!");
            }
        });

        while (true)
        {
            Thread.sleep(1000);
        }
    }
}
</code>```

Body:
Say for instance I have my application running in a Linux terminal and I press "CTRL+C" on my keyboard to kill the process it will terminate the Java program.

Is there any way to catch this "request" in my Java application so I can shut it down gracefully and release all resources/write logs. I have several different threads running if it makes a difference to the response.

I know you have have an addShutDownHook, but as written in the Java documentation, it isn't called under certain circumstances, like the kill signal from "CTRL+C" in linux...are there any other ways?

Runtime.getRuntime().addShutdownHook(new Thread()
{
    public void run ()
    {
        // TODO: implement graceful shutdown here.
    }
});

Body:
This works for me, capturing SIGINT/Ctrl-C on Linux:

public class TestShutdownHook
{
    public static void main(final String[] args) throws InterruptedException
    {
        Runtime.getRuntime().addShutdownHook(new Thread()
        {
            @Override
            public void run()
            {
                System.out.println("Shutdown hook ran!");
            }
        });

        while (true)
        {
            Thread.sleep(1000);
        }
    }
}


问:
How to urlencode UTC datetime strings?
I am using python's urllib.parse.urlencode to encode a request body to make a 'get' request for a url. I am running into trouble when encoding a UTC datetime string.

The endpoints expects the date to look like:
begin=2004-01-01T00:00:00&end=2019-04-21T00:00:00

but after using urlencode, the date payload looks like:
begin=2020-02-04T17%3A00%3A00&end=2020-02-04T20%3A00%3A00

The format of the first half of the UTC datetime looks okay, (YYYY-MM-DDT), but second half is screwed up. It SHOULD look like T00:00:00 but does not.

I am passing a dictionary of parameters into the urlencode function:

params = {
        'begin':'2020-02-04T17:00:00',
        'end':'2020-02-04T20:00:00',
}
return urlencode(params, doseq=True)

How can I encode the date in the correct format? Please let me know if there is anything else I can provide to help you all. Thank you.

答:
%3A is : when urlencoded.

Hence begin=2020-02-04T17:00:00&end=2020-02-04T20:00:00 when encoded will be begin=2020-02-04T17%3A00%3A00&end=2020-02-04T20%3A00%3A00, as stated in your question.

The format is correct and there is nothing wrong with your code.

Title: How to urlencode UTC datetime strings?


问:
Select columns together with the sum()
I have a problem in getting the columns and I also want to get the sum of total_amount.

```<code>CREATE TABLE purchase (
    id int,
    sheet_number varchar(255),
    total_amount decimal(23,6),
    transaction_status int
);

INSERT INTO purchase (id, sheet_number, total_amount, transaction_status)
VALUES (
    '1', 'PO10010000001', '120.18', 1,
    '2', 'PO10010000002', '87.23', 1,
    '3', 'PO10010000003', '53.56', 3,
    '4', 'PO10010000004', '150.28', 4,
    '5', 'PO10010000005', '160.53' 3,
);
</code>```

I want to get the columns and also the sum of this total_amount with respect (group by) of transaction_status.

I've created a SQL query like this but it doesn't work with the expected one.

Here is the SQL query that I've made:

```<code>SELECT
    id,
    sheet_number,
    transaction_status,
    sum(total_amount) AS total FROM purchase
GROUP BY transaction_status, id, sheet_number
</code>```

I think the problem because I listed the other columns/attributes in the GROUP BY clause.

But I needed it because it will prompt an error message that the column is not valid since it is not contained in the group by clause.

The expected SQL query is like this (but I can't since there will be a prompt error):

```<code>SELECT
    id,
    sheet_number,
    transaction_status,
    sum(total_amount) AS total FROM purchase
GROUP BY transaction_status
</code>```

The expected result will be:

```<code>[id],[sheet_number],[total],[transaction_status]

[1],[PO10010000001],[207.41],[1],
[2],[PO10010000002],[207.41],[1],
[3],[PO10010000003],[214.09],[3],
[4],[PO10010000004],[150.28],[4],
[5],[PO10010000005],[214.09],[3]
</code>```

I just want to get all the same columns but I can get also the sum of total_amount.

答:
You can try the inner join to get the output as shown below.

Here I have taken total amount group by transaction status and done joining with actual table based on the transaction status column.

```<code>SELECT purchase.id
    ,purchase.sheet_number
    ,b.total AS total_amount
    ,purchase.transaction_status
FROM purchase
INNER JOIN (
    SELECT transaction_status
        ,SUM(total_amount) AS total
    FROM purchase
    GROUP BY transaction_status
    ) b ON purchase.transaction_status = b.transaction_status
</code>```

Here is the db<>fiddle demo.

Title: Select columns together with the sum()

Body:
I have a problem in getting the columns and I also want to get the sum of total_amount.

CREATE TABLE purchase (
    id int,
    sheet_number varchar(255),
    total_amount decimal(23,6),
    transaction_status int
);

INSERT INTO purchase (id, sheet_number, total_amount, transaction_status)
VALUES (
    '1', 'PO10010000001', '120.18', 1,
    '2', 'PO10010000002', '87.23', 1,
    '3', 'PO10010000003', '53.56', 3,
    '4', 'PO10010000004', '150.28', 4,
    '5', 'PO10010000005', '160.53' 3,
);

I want to get the columns and also the sum of this total_amount with respect (group by) of transaction_status.

I've created a SQL query like this but it doesn't work with the expected one.

Here is the SQL query that I've made:

SELECT
    id,
    sheet_number,
    transaction_status,
    sum(total_amount) AS total FROM purchase
GROUP BY transaction_status, id, sheet_number

I think the problem because I listed the other columns/attributes in the GROUP BY clause.

But I needed it because it will prompt an error message that the column is not valid since it is not contained in the group by clause.

The expected SQL query is like this (but I can't since there will be a prompt error):

SELECT
    id,
    sheet_number,
    transaction_status,
    sum(total_amount) AS total FROM purchase
GROUP BY transaction_status

The expected result will be:

[id],[sheet_number],[total],[transaction_status]

[1],[PO10010000001],[207.41],[1],
[2],[PO10010000002],[207.41],[1],
[3],[PO10010000003],[214.09],[3],
[4],[PO10010000004],[150.28],[4],
[5],[PO10010000005],[214.09],[3]

I just want to get all the same columns but I can get also the sum of total_amount.

Body:
You can try the inner join to get the output as shown below.

Here I have taken total amount group by transaction status and done joining with actual table based on the transaction status column.

SELECT purchase.id
    ,purchase.sheet_number
    ,b.total AS total_amount
    ,purchase.transaction_status
FROM purchase
INNER JOIN (
    SELECT transaction_status
        ,SUM(total_amount) AS total
    FROM purchase
    GROUP BY transaction_status
    ) b ON purchase.transaction_status = b.transaction_status

Here is the db<>fiddle demo.


问:
Identifying lines ending in capital letters with AWK and using them as record separators
This is a smaller representative version of a data file that I need to parse and divide into chunks with awk based on the roman numeral of each chunk.

```<code>I
   Apple
   II
Banana

   III
   Mango
IV
Durian
Lemon

   IV
      Papaya
       V
</code>```

This seemed like an easy task with awk, so I tried
gawk -v RS="[A-Z]+$" '{print $0}' blah.txt to use lines that end with one or more capital letters (thus indicating lines with Roman Numerals) as record separators.

Surprisingly the program outputted the entire data file. Where did I go wrong?
Even more surprisingly, if I place an exit after the print statement, it still prints the entire file (indicating that the whole file is considered as one record)

I am using GNU AWK 4.1.3 on a Linux Mint machine.

NOTE: The specific use case I have in mind is to extract an arbitrary Shakespearean sonnet by number from the text file at http://www.gutenberg.org/cache/epub/1041/pg1041.txt (after removing the boilerplate header and footer data )

答:
The $ is the culprit - GNU awk treats the entire file as a single string for the purpose of matching a RS regular expression, and $ thus only matches at the end of the file (This is noted in the manual). Try replacing it with \>, which matches end of word, not end of string (And \< to match the start of a word, so that only things like I and IV are matched):

```<code>$ awk -v RS='\\<[A-Z]+\\>' '{print $0}' input.txt

   Apple

Banana

   Mango

Durian
Lemon

      Papaya
</code>```

You'll have to deal with all the extra newlines and whitespace, of course.

Body:
This is a smaller representative version of a data file that I need to parse and divide into chunks with awk based on the roman numeral of each chunk.

I
   Apple
   II
Banana

   III
   Mango
IV
Durian
Lemon

   IV
      Papaya
       V

This seemed like an easy task with awk, so I tried
gawk -v RS="[A-Z]+$" '{print $0}' blah.txt to use lines that end with one or more capital letters (thus indicating lines with Roman Numerals) as record separators.

Surprisingly the program outputted the entire data file. Where did I go wrong?
Even more surprisingly, if I place an exit after the print statement, it still prints the entire file (indicating that the whole file is considered as one record)

I am using GNU AWK 4.1.3 on a Linux Mint machine.

NOTE: The specific use case I have in mind is to extract an arbitrary Shakespearean sonnet by number from the text file at http://www.gutenberg.org/cache/epub/1041/pg1041.txt (after removing the boilerplate header and footer data )

Body:
The $ is the culprit - GNU awk treats the entire file as a single string for the purpose of matching a RS regular expression, and $ thus only matches at the end of the file (This is noted in the manual). Try replacing it with \>, which matches end of word, not end of string (And \< to match the start of a word, so that only things like I and IV are matched):

$ awk -v RS='\\<[A-Z]+\\>' '{print $0}' input.txt

   Apple

Banana

   Mango

Durian
Lemon

      Papaya

You'll have to deal with all the extra newlines and whitespace, of course.


问:
Trying to execute SQL commands only if value doesn't exists in a column
I'm trying to execute SQL commands in case value doesn't exist in a column,

What this script actually trying to achieve is to insert into the t_bridge table a new set of values.

I saw this answer but I get this error - if not valid in this position.

it looks like I'm in the wrong direction here, and I'm missing something pretty crucial.

```<code>IF EXISTS (SELECT * FROM t_bridge WHERE serial_number = 1234)
BEGIN
    -- don't do anyting
END
ELSE
BEGIN
    insert into t_bridge
    values (
           ID
          ,app_id
          ,1
          ,'SAN-2-H-5G-EU V4'
          ,470  /
          ,29569
          ,35
          ,HARDWARE_VERSION
          ,SOFTWARE_VERSION
          ,'MEN4'
          ,DESCRIPTION
          ,DETAILS
          ,1234
          ,STATUS
          ,INSTALL_DATE
          ,LAST_CONNECTED_DATE
          ,STATUS_CHANGED_DATE
          ,ERASED
          ,999
          ,LOCATION_ID
          ,unix_timestamp(now())*1000
          ,unix_timestamp(now())*1000
          ,NULL
          ,NULL
          ,SITE_ID
          ,CONNECTION_TYPE
          ,NETWORK_NAME
          ,2
          ,ICCID
          ,DATA_PLAN_VALID_DATE
          ,1
          ,NULL
          ,'automatically'
          );

    insert into t_chap_token (BRIDGE_ID,BRIDGE_SERIAL_NUMBER,TOKEN)
     VALUES (
     (select id from t_bridge where SERIAL_NUMBER = 1234)
     ,'1234'
     ,'XXXXXXXXXXX='
END
</code>```

答:
So since I'm not too familiar with SQL scripts,
It turns out I needed to create and run it inside of a procedure.

So this is the way to do it:

```<code>DROP procedure IF EXISTS `PROCEDURE_NAME`;

DELIMITER $$
USE `DB_NAME`$$
CREATE PROCEDURE `PROCEDURE_NAME`()
BEGIN
     IF EXISTS (SELECT * FROM t_bridge WHERE serial_number = 1234)
BEGIN
    -- don't do anyting
END
ELSE
BEGIN
    insert into t_bridge
    values (
           ID
          ,app_id
          ,1
          ,'SAN-2-H-5G-EU V4'
          ,470  /
          ,29569
          ,35
          ,HARDWARE_VERSION
          ,SOFTWARE_VERSION
          ,'MEN4'
          ,DESCRIPTION
          ,DETAILS
          ,1234
          ,STATUS
          ,INSTALL_DATE
          ,LAST_CONNECTED_DATE
          ,STATUS_CHANGED_DATE
          ,ERASED
          ,999
          ,LOCATION_ID
          ,unix_timestamp(now())*1000
          ,unix_timestamp(now())*1000
          ,NULL
          ,NULL
          ,SITE_ID
          ,CONNECTION_TYPE
          ,NETWORK_NAME
          ,2
          ,ICCID
          ,DATA_PLAN_VALID_DATE
          ,1
          ,NULL
          ,'automatically'
          );

    insert into t_chap_token (BRIDGE_ID,BRIDGE_SERIAL_NUMBER,TOKEN)
     VALUES (
     (select id from t_bridge where SERIAL_NUMBER = 1234)
     ,'1234'
     ,'XXXXXXXXXXX='
END
</code>```

Body:
I'm trying to execute SQL commands in case value doesn't exist in a column,

What this script actually trying to achieve is to insert into the t_bridge table a new set of values.

I saw this answer but I get this error - if not valid in this position.

it looks like I'm in the wrong direction here, and I'm missing something pretty crucial.

IF EXISTS (SELECT * FROM t_bridge WHERE serial_number = 1234)
BEGIN
    -- don't do anyting
END
ELSE
BEGIN
    insert into t_bridge
    values (
           ID
          ,app_id
          ,1
          ,'SAN-2-H-5G-EU V4'
          ,470  /
          ,29569
          ,35
          ,HARDWARE_VERSION
          ,SOFTWARE_VERSION
          ,'MEN4'
          ,DESCRIPTION
          ,DETAILS
          ,1234
          ,STATUS
          ,INSTALL_DATE
          ,LAST_CONNECTED_DATE
          ,STATUS_CHANGED_DATE
          ,ERASED
          ,999
          ,LOCATION_ID
          ,unix_timestamp(now())*1000
          ,unix_timestamp(now())*1000
          ,NULL
          ,NULL
          ,SITE_ID
          ,CONNECTION_TYPE
          ,NETWORK_NAME
          ,2
          ,ICCID
          ,DATA_PLAN_VALID_DATE
          ,1
          ,NULL
          ,'automatically'
          );

    insert into t_chap_token (BRIDGE_ID,BRIDGE_SERIAL_NUMBER,TOKEN)
     VALUES (
     (select id from t_bridge where SERIAL_NUMBER = 1234)
     ,'1234'
     ,'XXXXXXXXXXX='
END

Body:
So since I'm not too familiar with SQL scripts,
It turns out I needed to create and run it inside of a procedure.

So this is the way to do it:

DROP procedure IF EXISTS `PROCEDURE_NAME`;

DELIMITER $$
USE `DB_NAME`$$
CREATE PROCEDURE `PROCEDURE_NAME`()
BEGIN
     IF EXISTS (SELECT * FROM t_bridge WHERE serial_number = 1234)
BEGIN
    -- don't do anyting
END
ELSE
BEGIN
    insert into t_bridge
    values (
           ID
          ,app_id
          ,1
          ,'SAN-2-H-5G-EU V4'
          ,470  /
          ,29569
          ,35
          ,HARDWARE_VERSION
          ,SOFTWARE_VERSION
          ,'MEN4'
          ,DESCRIPTION
          ,DETAILS
          ,1234
          ,STATUS
          ,INSTALL_DATE
          ,LAST_CONNECTED_DATE
          ,STATUS_CHANGED_DATE
          ,ERASED
          ,999
          ,LOCATION_ID
          ,unix_timestamp(now())*1000
          ,unix_timestamp(now())*1000
          ,NULL
          ,NULL
          ,SITE_ID
          ,CONNECTION_TYPE
          ,NETWORK_NAME
          ,2
          ,ICCID
          ,DATA_PLAN_VALID_DATE
          ,1
          ,NULL
          ,'automatically'
          );

    insert into t_chap_token (BRIDGE_ID,BRIDGE_SERIAL_NUMBER,TOKEN)
     VALUES (
     (select id from t_bridge where SERIAL_NUMBER = 1234)
     ,'1234'
     ,'XXXXXXXXXXX='
END


问:
Adding Braintree plugin breaks social login on Flutter
I am facing a really strange problem and would appreciate any help - currently I have an app that has social login using flutter_facebook_login (3.0.0) for Facebook and google_sign_in (4.1.1) for Google.

They are working fine, but when I add one specific plugin - flutter_braintree (or braintree_payment), it stops working and never returns the result of facebookLogin.logIn(['email']) or googleSignIn.signIn();

I would be very appreciative if you can help me with this issue, because I am out of ideas. The moment I remove the Braintree plugin, the social login starts working fine immediately. I have no explanation why this is happening as I think they have nothing in common.

EDIT: I have a little progress on the issue. Might be that the Braintree overrides something that Facebook uses to do the login and return a result. A friend of mine told me that it might be the onActivityResult function that is overridden and Facebook never reaches it. Any ideas?

答:
It seems a problem with the last version of the FlutterBraintree (0.5.3+1).
I forced it to stay at version 0.5.3 and it works.
I reported an issue on the FlutterBraintree repository

https://github.com/Pikaju/FlutterBraintree/issues/16


问:
Incorporate hyperlink and link in script for Google spreadsheet
I am currently trying desperately to include a hyperlink in my script that, after executing the script, the hyperlink as it is here should be placed in cell C16. The same would be for C17-C19 and in G19 again.

```<code>function AlteFahrerdatenLeeren(){
  var sheet=SpreadsheetApp.getActiveSheet();
  var destination="C7:C15";
  sheet.getRange(destination).setValue("");
  var sheet1=SpreadsheetApp.getActiveSheet();
  var destination="C20";
  sheet1.getRange(destination).setValue("");
  var sheet2=SpreadsheetApp.getActiveSheet();
  var destination="G6:G7";
  sheet2.getRange(destination).setValue("");
  var sheet3=SpreadsheetApp.getActiveSheet();
  var destination="G9";
  sheet3.getRange(destination).setValue("");
  var sheet4=SpreadsheetApp.getActiveSheet();
  var destination="G11:G17";
  sheet4.getRange(destination).setValue("");
  var sheet5=SpreadsheetApp.getActiveSheet();
  var destination="G20";
  sheet5.getRange(destination).setValue("");
  var sheet5=SpreadsheetApp.getActiveSheet();
  var destination="N16:N17";
  sheet5.getRange(destination).setValue("");
  var sheet6=SpreadsheetApp.getActiveSheet();
  var destination="Q10:R10";
  sheet6.getRange(destination).setValue("");
  var sheet7=SpreadsheetApp.getActiveSheet();
  var destination="S6";
  sheet7.getRange(destination).setValue("");
  var sheet8=SpreadsheetApp.getActiveSheet();
  var destination="O22:S32";
  sheet8.getRange(destination).setValue("");
  var sheet9=SpreadsheetApp.getActiveSheet();
  var destination="G35:S50";
  sheet9.getRange(destination).setValue("");
  var sheet10=SpreadsheetApp.getActiveSheet();
  var destination="B53:S91";
  sheet10.getRange(destination).setValue("");
  **var SS=SpreadsheetApp.getActiveSheet();
  var sheet=ss.getRange(C16).setValue(HYPERLINK("https://erfurter-fernverkehrs-logistic.de/";"Neu"));**
}
</code>```

Furthermore what I ask myself. Is there a way to test a link in a script that he can get the last missing data from C20 via a button and then link to the website?

Help is very much appreciated. I'm completely new to the area.

enter image description here As here in the pictures, the ticks in the boxes are inside. But with my script I want to remove the tick so that there are only the empty boxes. And the range would be: K22: L32.

Sorry for the bad translation. Since I can't speak English myself, I had to do it via Google Translate.

答:
You have to use setFormula instead of setValue:

sheet.getRange('C16').setFormula('=HYPERLINK("https://erfurter-fernverkehrs-logistic.de/";"Neu")');
```

<p>Also, you don't need to repeat this every time. You only have to do it once:</p>

<pre class="lang-js prettyprint-override"><code>var sheet=SpreadsheetApp.getActiveSheet();
</code>```

Reference:

Range.setFormula(formula)

Body:
I am currently trying desperately to include a hyperlink in my script that, after executing the script, the hyperlink as it is here should be placed in cell C16. The same would be for C17-C19 and in G19 again.

function AlteFahrerdatenLeeren(){
  var sheet=SpreadsheetApp.getActiveSheet();
  var destination="C7:C15";
  sheet.getRange(destination).setValue("");
  var sheet1=SpreadsheetApp.getActiveSheet();
  var destination="C20";
  sheet1.getRange(destination).setValue("");
  var sheet2=SpreadsheetApp.getActiveSheet();
  var destination="G6:G7";
  sheet2.getRange(destination).setValue("");
  var sheet3=SpreadsheetApp.getActiveSheet();
  var destination="G9";
  sheet3.getRange(destination).setValue("");
  var sheet4=SpreadsheetApp.getActiveSheet();
  var destination="G11:G17";
  sheet4.getRange(destination).setValue("");
  var sheet5=SpreadsheetApp.getActiveSheet();
  var destination="G20";
  sheet5.getRange(destination).setValue("");
  var sheet5=SpreadsheetApp.getActiveSheet();
  var destination="N16:N17";
  sheet5.getRange(destination).setValue("");
  var sheet6=SpreadsheetApp.getActiveSheet();
  var destination="Q10:R10";
  sheet6.getRange(destination).setValue("");
  var sheet7=SpreadsheetApp.getActiveSheet();
  var destination="S6";
  sheet7.getRange(destination).setValue("");
  var sheet8=SpreadsheetApp.getActiveSheet();
  var destination="O22:S32";
  sheet8.getRange(destination).setValue("");
  var sheet9=SpreadsheetApp.getActiveSheet();
  var destination="G35:S50";
  sheet9.getRange(destination).setValue("");
  var sheet10=SpreadsheetApp.getActiveSheet();
  var destination="B53:S91";
  sheet10.getRange(destination).setValue("");
  **var SS=SpreadsheetApp.getActiveSheet();
  var sheet=ss.getRange(C16).setValue(HYPERLINK("https://erfurter-fernverkehrs-logistic.de/";"Neu"));**
}

Furthermore what I ask myself. Is there a way to test a link in a script that he can get the last missing data from C20 via a button and then link to the website?

Help is very much appreciated. I'm completely new to the area.

enter image description here As here in the pictures, the ticks in the boxes are inside. But with my script I want to remove the tick so that there are only the empty boxes. And the range would be: K22: L32.

Sorry for the bad translation. Since I can't speak English myself, I had to do it via Google Translate.

Body:
You have to use setFormula instead of setValue:

sheet.getRange('C16').setFormula('=HYPERLINK("https://erfurter-fernverkehrs-logistic.de/";"Neu")');

Also, you don't need to repeat this every time. You only have to do it once:

var sheet=SpreadsheetApp.getActiveSheet();

Reference:

Range.setFormula(formula)


问:
How to simulate a click on a Font Awesome Icon using Jest?
I'm testing through Jest and am trying to test the click on a Font Awesome Icon. I've tried different ways to find the 'node', but I get the error that "Method “simulate” is meant to be run on 1 node. 0 found instead." Any insight would be helpful.

The error I get when I try different inputs to component.find() is: Method “simulate” is meant to be run on 1 node. 0 found instead.

StringEditor

```<code>const clearInput = () => {
    onRemove()
}

render (
    ...
    <FontAwesomeIcon icon={['fal', 'times-circle']} className="clear-button"
    onClick={clearInput} /> : null`
)
</code>```

onRemove is a callback function.

```<code>it('should call clearInput thus onRemove', () =>{

    const onRemove= jest.fn()
    const component = mount(<StringEditor {...defaultProps}  onRemove={onRemove} />)
    component.find('<dont know what to put>').simulate('click')
    expect(saveValueFn).toBeCalled()
})
</code>```

答:
Try this:</p>

```<code>it('should call clearInput thus onRemove', () =>{
    const onRemove= jest.fn()
    const component = mount(<StringEditor {...defaultProps}  onRemove={onRemove} />)
    component.find({ className: "clear-button" }).simulate('click');
    expect(clearInput).toHaveBeenCalled();
})
</code>```

Body:
I'm testing through Jest and am trying to test the click on a Font Awesome Icon. I've tried different ways to find the 'node', but I get the error that "Method “simulate” is meant to be run on 1 node. 0 found instead." Any insight would be helpful.

The error I get when I try different inputs to component.find() is: Method “simulate” is meant to be run on 1 node. 0 found instead.

StringEditor

const clearInput = () => {
    onRemove()
}

render (
    ...
    <FontAwesomeIcon icon={['fal', 'times-circle']} className="clear-button"
    onClick={clearInput} /> : null`
)

onRemove is a callback function.

it('should call clearInput thus onRemove', () =>{

    const onRemove= jest.fn()
    const component = mount(<StringEditor {...defaultProps}  onRemove={onRemove} />)
    component.find('<dont know what to put>').simulate('click')
    expect(saveValueFn).toBeCalled()
})

Body:
Try this:

it('should call clearInput thus onRemove', () =>{
    const onRemove= jest.fn()
    const component = mount(<StringEditor {...defaultProps}  onRemove={onRemove} />)
    component.find({ className: "clear-button" }).simulate('click');
    expect(clearInput).toHaveBeenCalled();
})


问:
Count products and sum prices from different tables
I have these three tables:

```<code>Products
ID      NAME
1       Notebook
2       Keyboard

Base1
PRODUCT_ID    PRICE
1             2
1             2
1             2
2             3

Base2
PRODUCT_ID    PRICE
1             2
1             2
1             2
1             2
2             3
2             3
</code>```

What I need is to get a list of all products with number of occurences and sum proces, like this:

```<code>ID     NAME       Base1_count  Base1_SumPrice     Base2_count  Base2_SumPrice
1      Notebook   3            6                  4            8
2      Keyboard   1            3                  2            6
</code>```

How to write proper MySQL query?

答:
```<code>SELECT p.ID, p.NAME,
     sum(CASE WHEN b.Base_Name = 'Base1' THEN 1 ELSE 0 END) Base1_count,
     sum(CASE WHEN b.Base_Name = 'Base1' THEN b.PRICE ELSE 0 END) Base1_SumPrice,
     sum(CASE WHEN b.Base_Name = 'Base2' THEN 1 ELSE 0 END) Base1_count,
     sum(CASE WHEN b.Base_Name = 'Base2' THEN b.PRICE ELSE 0 END) Base1_SumPrice
  FROM Products p
  LEFT JOIN (SELECT 'Base1' Base_Name, b1.*
             UNION ALL
             SELECT 'Base2' Base_Name, b2.*) b
         ON p.ID=b.PRODUCT_ID
GROUP BY p.ID, p.Name
</code>```

Body:
I have these three tables:

Products
ID      NAME
1       Notebook
2       Keyboard

Base1
PRODUCT_ID    PRICE
1             2
1             2
1             2
2             3

Base2
PRODUCT_ID    PRICE
1             2
1             2
1             2
1             2
2             3
2             3

What I need is to get a list of all products with number of occurences and sum proces, like this:

ID     NAME       Base1_count  Base1_SumPrice     Base2_count  Base2_SumPrice
1      Notebook   3            6                  4            8
2      Keyboard   1            3                  2            6

How to write proper MySQL query?


问:
How to multiply array elements by condition
I have a array and want to multiply the elements greater than 9 by 2 and lesser than or equal to 9 by 3.

```<code>  List<Integer> list = Arrays.asList(3, 6, 9, 12, 15);
  list.stream().map(number -> number * 3).forEach(System.out::println);
</code>```

This one multiplies everything by 3 , where

```<code>list.stream().filter(number -> number>3).map(number -> number * 3).forEach(System.out::println);
</code>```

this one multiplies but also filters.

I want 3 ,6 ,9 multiplied by 3 and 12, 15 multiplied by 2.

Any help is appreciated.

答:
You can combine the filter and map steps:

```<code>list.stream()
    .map(n -> n > 9 ? n * 2 : n * 3)
    .forEach(System.out::println);
</code>```

Body:
I have a array and want to multiply the elements greater than 9 by 2 and lesser than or equal to 9 by 3.

  List<Integer> list = Arrays.asList(3, 6, 9, 12, 15);
  list.stream().map(number -> number * 3).forEach(System.out::println);

This one multiplies everything by 3 , where

list.stream().filter(number -> number>3).map(number -> number * 3).forEach(System.out::println);

this one multiplies but also filters.

I want 3 ,6 ,9 multiplied by 3 and 12, 15 multiplied by 2.

Any help is appreciated.

Body:
You can combine the filter and map steps:

list.stream()
    .map(n -> n > 9 ? n * 2 : n * 3)
    .forEach(System.out::println);


问:
How to group all the related data and return as a values dict in django?
I have 3 models:

```<code>class City(models.Model):
    name = models.CharField(max_length=150)

class Person(models.Model):
    name = models.CharField(max_length=150)
    city = models.ForeignKey(
        City, related_name="persons", on_delete=models.PROTECT)

class Fruit(models.Model):
    quantity = models.IntegerField()
    price = models.IntegerField()
    person = models.ForeignKey(Person, related_name="fruits")
    city = models.ForeignKey(City, related_name="fruits")
</code>```

I want to group all the data based on city and get total price of fruits city wise and total quantity citywise as well as person wise.

I want my result something like:

```<code>{'city': 'XYZ', 'total_fruits': 20, 'total_price': 123, 'persons': [{'name': 'foo', 'total_fruits': 5}, {'name': 'bar', 'total_fruits': 6}]}
</code>```

I have tried something like:

```<code>queryset = City.objects.annotate(total_price = Sum('persons__fruits__price'), total_fruits= Count('persons__fruits'))

city_list = []
for city in queryset:
   abc = {'name': city.name, 'total_fruits':company.total_fruits,
          'total_price':company.total_price}
   persons = city.persons.annotate(total_fruits= Count('fruits')).values('name','total_fruits')
   abc.update({'persons':persons })
   city_list.append(abc)
</code>```

Which is not much efficient.
I want to remove this loop and minimize the queries.
Thanks in advance. Let me know where I am wrong.

答:
You can reduce it to two queries:</p>

```<code>city_qs = City.objects.annotate(total_price = Sum('persons__fruits__price'), total_fruits=Count('persons__fruits')).prefetch_related('persons')

person_qs = Person.objects.annotate(total_fruits=Count('fruits')).values('name','total_fruits')

city_list = []
for city in city_qs:
    for person_id in city.persons:
         person_data = person_qs[person_id]
    ...
    city_list.append(abc)
</code>```

Body:
I have 3 models:

class City(models.Model):
    name = models.CharField(max_length=150)

class Person(models.Model):
    name = models.CharField(max_length=150)
    city = models.ForeignKey(
        City, related_name="persons", on_delete=models.PROTECT)

class Fruit(models.Model):
    quantity = models.IntegerField()
    price = models.IntegerField()
    person = models.ForeignKey(Person, related_name="fruits")
    city = models.ForeignKey(City, related_name="fruits")

I want to group all the data based on city and get total price of fruits city wise and total quantity citywise as well as person wise.

I want my result something like:

{'city': 'XYZ', 'total_fruits': 20, 'total_price': 123, 'persons': [{'name': 'foo', 'total_fruits': 5}, {'name': 'bar', 'total_fruits': 6}]}

I have tried something like:

queryset = City.objects.annotate(total_price = Sum('persons__fruits__price'), total_fruits= Count('persons__fruits'))

city_list = []
for city in queryset:
   abc = {'name': city.name, 'total_fruits':company.total_fruits,
          'total_price':company.total_price}
   persons = city.persons.annotate(total_fruits= Count('fruits')).values('name','total_fruits')
   abc.update({'persons':persons })
   city_list.append(abc)

Which is not much efficient.
I want to remove this loop and minimize the queries.
Thanks in advance. Let me know where I am wrong.

Body:
You can reduce it to two queries:

city_qs = City.objects.annotate(total_price = Sum('persons__fruits__price'), total_fruits=Count('persons__fruits')).prefetch_related('persons')

person_qs = Person.objects.annotate(total_fruits=Count('fruits')).values('name','total_fruits')

city_list = []
for city in city_qs:
    for person_id in city.persons:
         person_data = person_qs[person_id]
    ...
    city_list.append(abc)


问:
Azure Log Insights - How to aggregate events per hour
I am trying to monitor Azure ASR VM Disk churn & throughput processing.

I can get the last hours worth of VM Churn & Upload rate with the following query:

```<code>Perf
| where ObjectName == "ASRAnalytics"
| where InstanceName contains "VMName"
| where TimeGenerated >= ago(1h)
| project TimeGenerated, CounterName, Churn_MBps = todouble(CounterValue)/5242880
| render timechart
</code>```

This will only get me either a line chart showing what the VM upload activity looked like, or a table of values with columns TimeGenerated, Countername, Churn_MBps

How can I aggregate these values into a single value per counter name (SourceVmThrpRate,SourceVmCurnRate) that will show me the total aggregate Churn or Thrp for the total hour?

答:
Kusto Query has aggregated functions; like count(), avg(), max(), etc - you can read more about Aggregated Functions.

I hope below updated query helps; I have added summarize but I have not validated result as I will have different data.

| summarize avg(Churn_MBps) by bin(TimeGenerated, 1h), CounterName

```<code>Perf
| where ObjectName == "ASRAnalytics"
| where InstanceName contains "VMName"
| where TimeGenerated >= ago(1h)
| project TimeGenerated, CounterName, Churn_MBps = todouble(CounterValue) / 5242880
| summarize avg(Churn_MBps) by bin(TimeGenerated, 1h), CounterName
| render timechart
</code>```

Body:
I am trying to monitor Azure ASR VM Disk churn & throughput processing.

I can get the last hours worth of VM Churn & Upload rate with the following query:

Perf
| where ObjectName == "ASRAnalytics"
| where InstanceName contains "VMName"
| where TimeGenerated >= ago(1h)
| project TimeGenerated, CounterName, Churn_MBps = todouble(CounterValue)/5242880
| render timechart

This will only get me either a line chart showing what the VM upload activity looked like, or a table of values with columns TimeGenerated, Countername, Churn_MBps

How can I aggregate these values into a single value per counter name (SourceVmThrpRate,SourceVmCurnRate) that will show me the total aggregate Churn or Thrp for the total hour?

Body:
Kusto Query has aggregated functions; like count(), avg(), max(), etc - you can read more about Aggregated Functions.

I hope below updated query helps; I have added summarize but I have not validated result as I will have different data.

| summarize avg(Churn_MBps) by bin(TimeGenerated, 1h), CounterName

Perf
| where ObjectName == "ASRAnalytics"
| where InstanceName contains "VMName"
| where TimeGenerated >= ago(1h)
| project TimeGenerated, CounterName, Churn_MBps = todouble(CounterValue) / 5242880
| summarize avg(Churn_MBps) by bin(TimeGenerated, 1h), CounterName
| render timechart


问:
_CastError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast)
Want to ask again ... try implementing the data API stored in a local database ...
the form of the JSON API The object in which there is a JSON Array ... there was an error when wanting to load data from the API to Local database ... roughly this is an error because of "the wrong model or what

Api Service

```<code>class MealApiProvider {
  Future<List<Categories>> getAllMeal() async {
    var url = "https://www.themealdb.com/api/json/v1/1/categories.php";
    Response response = await Dio().get(url);
    print("Hasil Respon ${response.data}");
    return (response.data as List).map((employee) {
      print('Inserting $employee');
      DBProvider.db.insertMeals(Categories.fromJson(employee));
    }).toList();
  }
}
</code>```

Model

```<code>class DataMeal {
  final List<Categories> categories;

  DataMeal({this.categories});

  @override
  String toString() {
    return 'DataMeal{categories: $categories}';
  }

  factory DataMeal.fromJson(Map<String, dynamic> json) {
    return DataMeal(
      categories: List<Categories>.from(
        json["categories"].map(
          (categories) {
            return Categories.fromJson(categories);
          },
        ),
      ),
    );
  }

  Map<String, dynamic> toJson() => {
        "categories": List<dynamic>.from(
          categories.map(
            (x) => x.toJson(),
          ),
        ),
      };
}
</code>```

Local DB

```<code>  initDB() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    final String path = join(documentsDirectory.path, '$nameDatabase');
    print('insert database $path');

    return await openDatabase(path, version: 1, onOpen: (db) {},
        onCreate: (Database db, int version) async {
      await db.execute('CREATE TABLE $nameTable('
          'idCategory,'
          'strCategory TEXT,'
          'strCategoryThumb TEXT,'
          'strCategoryDescription TEXT'
          ')');
    });
  }

  insertMeals(DataMeal newMeal) async {
    await deleteAllMeal();
    final Database db = await database;
    final res = await db.insert("$nameTable", newMeal.toJson());
    print("inserting data $res");
    return res;
  }
</code>```

Error

return (response.data as List).map((employee)

Respon Data

答:
Your response contains map at the begining !
Try this

```<code>class MealApiProvider {
  Future<List<Categories>> getAllMeal() async {
    var url = "https://www.themealdb.com/api/json/v1/1/categories.php";
    Response response = await Dio().get(url);
    print("Hasil Respon ${response.data}");
    //***Change below line****
    return (response.data['categories'] as List).map((employee) {
      print('Inserting $employee');
      DBProvider.db.insertMeals(Categories.fromJson(employee));
    }).toList();
  }
}
</code>```

instead of

```<code>class MealApiProvider {
  Future<List<Categories>> getAllMeal() async {
    var url = "https://www.themealdb.com/api/json/v1/1/categories.php";
    Response response = await Dio().get(url);
    print("Hasil Respon ${response.data}");
    //*** I change the below line !
    return (response.data as List).map((employee) {
      print('Inserting $employee');
      DBProvider.db.insertMeals(Categories.fromJson(employee));
    }).toList();
  }
}
</code>```

Body:
Want to ask again ... try implementing the data API stored in a local database ...
the form of the JSON API The object in which there is a JSON Array ... there was an error when wanting to load data from the API to Local database ... roughly this is an error because of "the wrong model or what

Api Service

class MealApiProvider {
  Future<List<Categories>> getAllMeal() async {
    var url = "https://www.themealdb.com/api/json/v1/1/categories.php";
    Response response = await Dio().get(url);
    print("Hasil Respon ${response.data}");
    return (response.data as List).map((employee) {
      print('Inserting $employee');
      DBProvider.db.insertMeals(Categories.fromJson(employee));
    }).toList();
  }
}

Model

class DataMeal {
  final List<Categories> categories;

  DataMeal({this.categories});

  @override
  String toString() {
    return 'DataMeal{categories: $categories}';
  }

  factory DataMeal.fromJson(Map<String, dynamic> json) {
    return DataMeal(
      categories: List<Categories>.from(
        json["categories"].map(
          (categories) {
            return Categories.fromJson(categories);
          },
        ),
      ),
    );
  }

  Map<String, dynamic> toJson() => {
        "categories": List<dynamic>.from(
          categories.map(
            (x) => x.toJson(),
          ),
        ),
      };
}

Local DB

  initDB() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    final String path = join(documentsDirectory.path, '$nameDatabase');
    print('insert database $path');

    return await openDatabase(path, version: 1, onOpen: (db) {},
        onCreate: (Database db, int version) async {
      await db.execute('CREATE TABLE $nameTable('
          'idCategory,'
          'strCategory TEXT,'
          'strCategoryThumb TEXT,'
          'strCategoryDescription TEXT'
          ')');
    });
  }

  insertMeals(DataMeal newMeal) async {
    await deleteAllMeal();
    final Database db = await database;
    final res = await db.insert("$nameTable", newMeal.toJson());
    print("inserting data $res");
    return res;
  }

Error

return (response.data as List).map((employee)

Respon Data

Body:
Your response contains map at the begining !
Try this

class MealApiProvider {
  Future<List<Categories>> getAllMeal() async {
    var url = "https://www.themealdb.com/api/json/v1/1/categories.php";
    Response response = await Dio().get(url);
    print("Hasil Respon ${response.data}");
    //***Change below line****
    return (response.data['categories'] as List).map((employee) {
      print('Inserting $employee');
      DBProvider.db.insertMeals(Categories.fromJson(employee));
    }).toList();
  }
}

instead of

class MealApiProvider {
  Future<List<Categories>> getAllMeal() async {
    var url = "https://www.themealdb.com/api/json/v1/1/categories.php";
    Response response = await Dio().get(url);
    print("Hasil Respon ${response.data}");
    //*** I change the below line !
    return (response.data as List).map((employee) {
      print('Inserting $employee');
      DBProvider.db.insertMeals(Categories.fromJson(employee));
    }).toList();
  }
}


问:
Syncing a random variable in ruby
I am making a simple Tic tac toe game where the rows are represented by three arrays and columns are items in those arrays. For my computer choice I use two separate functions to get the row and column.

```<code>$first = ["-","-","-"]
$secound = ["-","-","-"]
$third = ["-","-","-"]
def get_row
    row = nil
    case rand(3)
    when 0
        row = $first
    when 1
        row = $secound
    else
        row = $third
    end
    row
end
def get_col
    col = nil
    case rand(3)
    when 0
        col = 0
    when 1
        col = 1
    else
        col = 2
    end
    col
end
</code>```

I then use a third function that keeps generating a new "guess" until it finds an empty spot, at which point it marks an 0.

```<code>def computer_guess
    temp = false
    try = get_row[get_col]
    while temp == false
        if try == "-"
           get_row[get_col] = "O"
            temp = true
        else
            try = get_row[get_col]
        end
    end
end
</code>```

My problem is that i cant return the guess to the same position that i check for validity. Is the there a way to sync these or do i need a different approach?

答:
The problem with your approach is that get_row[get_col] returns a random element every time it is called, so likewise get_row[get_col] = "O" will set a random element to "O". You inspect one element and then set another.

You could fix this quickly by modifying the retrieved element in-place:

```<code>if try == "-"
  try.replace("O")
  # ...
</code>```

But semantically, I don't like that fix very much. Thinking of a tic-tac-toe board, I'd rather assign an "O" to the free spot than transforming the existing placeholder from "-" into "O".

Did you notice that your get_row method returns an array whereas get_col returns an index? I think this mixture of arrays and indices makes your code a bit convoluted.

It's much easier (in my opinion) to access both, row and column via an index.

To do so, you could put your three rows into another array:

```<code>$board = [
  ['-', '-', '-'],
  ['-', '-', '-'],
  ['-', '-', '-']
]
</code>```

The first row can be accessed via $board[0] and its first element via $board[0][0]. To set an element you'd use: $board[1][2] = 'O' (this sets the middle row's right-most element to "O"). Of course, you can also use variables, e.g. $board[row][col].

With this two-dimensional array, your computer_guess could be rewritten using just two random indices: (get_row and get_col aren't needed anymore)

```<code>def computer_guess
  loop do
    row = rand(3)                # random row index
    col = rand(3)                # random column index
    if $board[row][col] == '-'   # if corresponding spot is "-"
      $board[row][col] = 'O'     #    set that spot to "O"
      break                      #    and break out of the loop
    end
  end
end
</code>```

Note however that "blindly" guessing spots until you find a free one might not be the best approach.

Instead, you could generate a list of "free" spots. This can be done by first generating an array of all coordinates1 and then select-ing those row/col pairs whose spot is "-":

```<code>def free_spots
  coordinates = [0, 1, 2].product([0, 1, 2])
  coordinates.select { |row, col| $board[row][col] == '-' }
end
</code>```

Now you just have to chose a random pair (via sample) and set the corresponding spot to "O":

```<code>def computer_guess
  row, col = free_spots.sample
  $board[row][col] = 'O'
end
</code>```

1 Array#product returns the Cartesian product of the given arrays. It's an easy way to get all pairs:

```<code>[0, 1, 2].product([0, 1, 2])
#=> [[0, 0], [0, 1], [0, 2],
#    [1, 0], [1, 1], [1, 2],
#    [2, 0], [2, 1], [2, 2]]
</code>```

Title: Syncing a random variable in ruby

Body:
I am making a simple Tic tac toe game where the rows are represented by three arrays and columns are items in those arrays. For my computer choice I use two separate functions to get the row and column.

$first = ["-","-","-"]
$secound = ["-","-","-"]
$third = ["-","-","-"]
def get_row
    row = nil
    case rand(3)
    when 0
        row = $first
    when 1
        row = $secound
    else
        row = $third
    end
    row
end
def get_col
    col = nil
    case rand(3)
    when 0
        col = 0
    when 1
        col = 1
    else
        col = 2
    end
    col
end

I then use a third function that keeps generating a new "guess" until it finds an empty spot, at which point it marks an 0.

def computer_guess
    temp = false
    try = get_row[get_col]
    while temp == false
        if try == "-"
           get_row[get_col] = "O"
            temp = true
        else
            try = get_row[get_col]
        end
    end
end

My problem is that i cant return the guess to the same position that i check for validity. Is the there a way to sync these or do i need a different approach?

Body:
The problem with your approach is that get_row[get_col] returns a random element every time it is called, so likewise get_row[get_col] = "O" will set a random element to "O". You inspect one element and then set another.

You could fix this quickly by modifying the retrieved element in-place:

if try == "-"
  try.replace("O")
  # ...

But semantically, I don't like that fix very much. Thinking of a tic-tac-toe board, I'd rather assign an "O" to the free spot than transforming the existing placeholder from "-" into "O".

Did you notice that your get_row method returns an array whereas get_col returns an index? I think this mixture of arrays and indices makes your code a bit convoluted.

It's much easier (in my opinion) to access both, row and column via an index.

To do so, you could put your three rows into another array:

$board = [
  ['-', '-', '-'],
  ['-', '-', '-'],
  ['-', '-', '-']
]

The first row can be accessed via $board[0] and its first element via $board[0][0]. To set an element you'd use: $board[1][2] = 'O' (this sets the middle row's right-most element to "O"). Of course, you can also use variables, e.g. $board[row][col].

With this two-dimensional array, your computer_guess could be rewritten using just two random indices: (get_row and get_col aren't needed anymore)

def computer_guess
  loop do
    row = rand(3)                # random row index
    col = rand(3)                # random column index
    if $board[row][col] == '-'   # if corresponding spot is "-"
      $board[row][col] = 'O'     #    set that spot to "O"
      break                      #    and break out of the loop
    end
  end
end

Note however that "blindly" guessing spots until you find a free one might not be the best approach.

Instead, you could generate a list of "free" spots. This can be done by first generating an array of all coordinates1 and then select-ing those row/col pairs whose spot is "-":

def free_spots
  coordinates = [0, 1, 2].product([0, 1, 2])
  coordinates.select { |row, col| $board[row][col] == '-' }
end

Now you just have to chose a random pair (via sample) and set the corresponding spot to "O":

def computer_guess
  row, col = free_spots.sample
  $board[row][col] = 'O'
end

1 Array#product returns the Cartesian product of the given arrays. It's an easy way to get all pairs:

[0, 1, 2].product([0, 1, 2])
#=> [[0, 0], [0, 1], [0, 2],
#    [1, 0], [1, 1], [1, 2],
#    [2, 0], [2, 1], [2, 2]]