问:
How can I log SQL statements in Spring Boot?
I want to log SQL statements to a file.

I have the following properties in application.properties:

spring.datasource.url=...
spring.datasource.username=user
spring.datasource.password=1234
spring.datasource.driver-class-name=net.sourceforge.jtds.jdbc.Driver

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

security.ignored=true
security.basic.enabled=false

logging.level.org.springframework.web=INFO
logging.level.org.hibernate=INFO
logging.file=c:/temp/my-log/app.log
```
<p>When I run my application,</p>
<pre class="lang-none prettyprint-override"><code>cmd> mvn spring-boot:run
</code>```

I can see SQL statements in the console, but they don't appear in app.log. The file contains only basic logs from Spring.

What should I do to see SQL statements in the log file?

答:
Settings to avoid

You should not use this setting:

spring.jpa.show-sql=true
```
<p>The problem with <code>show-sql</code> is that the SQL statements are printed in the console, so there is no way to filter them, as you'd normally do with a Logging framework.</p>
<h2>Using Hibernate logging</h2>
<p>In your log configuration file, if you add the following logger:</p>
<pre class="lang-xml prettyprint-override"><code><logger name="org.hibernate.SQL" level="debug"/>
</code>```

Then, Hibernate will print the SQL statements when the JDBC PreparedStatement is created. That's why the statement will be logged using parameter placeholders:

INSERT INTO post (title, version, id) VALUES (?, ?, ?)
```
<p>If you want to log the bind parameter values, just add the following logger as well:</p>
<pre class="lang-xml prettyprint-override"><code><logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="trace"/>
</code>```

Once you set the BasicBinder logger, you will see that the bind parameter values are logged as well:

DEBUG [main]: o.h.SQL - insert into post (title, version, id) values (?, ?, ?)
TRACE [main]: o.h.t.d.s.BasicBinder - binding parameter [1] as [VARCHAR] - [High-Performance Java Persistence, part 1]
TRACE [main]: o.h.t.d.s.BasicBinder - binding parameter [2] as [INTEGER] - [0]
TRACE [main]: o.h.t.d.s.BasicBinder - binding parameter [3] as [BIGINT] - [1]
```
<h2>Using datasource-proxy</h2>
<p>The datasource-proxy OSS framework allows you to proxy the actual JDBC <code>DataSource</code>, as illustrated by the following diagram:</p>
<p><img src="https://i.stack.imgur.com/c67Gb.png" alt="DataSource-Proxy" /></p>
<p>You can define the <code>dataSource</code> bean that will be used by Hibernate as follows:</p>
```@Bean
public DataSource dataSource(DataSource actualDataSource) {
    SLF4JQueryLoggingListener loggingListener = new SLF4JQueryLoggingListener();
    loggingListener.setQueryLogEntryCreator(new InlineQueryLogEntryCreator());
    return ProxyDataSourceBuilder
        .create(actualDataSource)
        .name(DATA_SOURCE_PROXY_NAME)
        .listener(loggingListener)
        .build();
}
```
<p>Notice that the <code>actualDataSource</code> must be the <code>DataSource</code> defined by the connection pool you are using in your application.</p>
<p>Next, you need to set the <code>net.ttddyy.dsproxy.listener</code> log level to <code>debug</code> in your logging framework configuration file. For instance, if you're using Logback, you can add the following logger:</p>
<pre class="lang-xml prettyprint-override"><code><logger name="net.ttddyy.dsproxy.listener" level="debug"/>
</code>```

Once you enable datasource-proxy, the SQL statement are going to be logged as follows:

Name:DATA_SOURCE_PROXY, Time:6, Success:True,
Type:Prepared, Batch:True, QuerySize:1, BatchSize:3,
Query:["insert into post (title, version, id) values (?, ?, ?)"],
Params:[(Post no. 0, 0, 0), (Post no. 1, 0, 1), (Post no. 2, 0, 2)]
```

Body:
I want to log SQL statements to a file.

I have the following properties in application.properties:

spring.datasource.url=...
spring.datasource.username=user
spring.datasource.password=1234
spring.datasource.driver-class-name=net.sourceforge.jtds.jdbc.Driver

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

security.ignored=true
security.basic.enabled=false

logging.level.org.springframework.web=INFO
logging.level.org.hibernate=INFO
logging.file=c:/temp/my-log/app.log

When I run my application,

cmd> mvn spring-boot:run

I can see SQL statements in the console, but they don't appear in app.log. The file contains only basic logs from Spring.

What should I do to see SQL statements in the log file?

Body:
Settings to avoid

You should not use this setting:

spring.jpa.show-sql=true

The problem with show-sql is that the SQL statements are printed in the console, so there is no way to filter them, as you'd normally do with a Logging framework.

Using Hibernate logging

In your log configuration file, if you add the following logger:

<logger name="org.hibernate.SQL" level="debug"/>

Then, Hibernate will print the SQL statements when the JDBC PreparedStatement is created. That's why the statement will be logged using parameter placeholders:

INSERT INTO post (title, version, id) VALUES (?, ?, ?)

If you want to log the bind parameter values, just add the following logger as well:

<logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="trace"/>

Once you set the BasicBinder logger, you will see that the bind parameter values are logged as well:

DEBUG [main]: o.h.SQL - insert into post (title, version, id) values (?, ?, ?)
TRACE [main]: o.h.t.d.s.BasicBinder - binding parameter [1] as [VARCHAR] - [High-Performance Java Persistence, part 1]
TRACE [main]: o.h.t.d.s.BasicBinder - binding parameter [2] as [INTEGER] - [0]
TRACE [main]: o.h.t.d.s.BasicBinder - binding parameter [3] as [BIGINT] - [1]

Using datasource-proxy

The datasource-proxy OSS framework allows you to proxy the actual JDBC DataSource, as illustrated by the following diagram:

You can define the dataSource bean that will be used by Hibernate as follows:

@Bean
public DataSource dataSource(DataSource actualDataSource) {
    SLF4JQueryLoggingListener loggingListener = new SLF4JQueryLoggingListener();
    loggingListener.setQueryLogEntryCreator(new InlineQueryLogEntryCreator());
    return ProxyDataSourceBuilder
        .create(actualDataSource)
        .name(DATA_SOURCE_PROXY_NAME)
        .listener(loggingListener)
        .build();
}

Notice that the actualDataSource must be the DataSource defined by the connection pool you are using in your application.

Next, you need to set the net.ttddyy.dsproxy.listener log level to debug in your logging framework configuration file. For instance, if you're using Logback, you can add the following logger:

<logger name="net.ttddyy.dsproxy.listener" level="debug"/>

Once you enable datasource-proxy, the SQL statement are going to be logged as follows:

Name:DATA_SOURCE_PROXY, Time:6, Success:True,
Type:Prepared, Batch:True, QuerySize:1, BatchSize:3,
Query:["insert into post (title, version, id) values (?, ?, ?)"],
Params:[(Post no. 0, 0, 0), (Post no. 1, 0, 1), (Post no. 2, 0, 2)]


来源: stackexchange

问:
Non-zero exit status tidyverse install packages Rstudio
I have been roaming the internet trying to find a solution, but haven't found it yet.

My problem is: i can't install tidytext. I also found out I can't re-install tidyverse for some reason.

The error code is:

```<code>install.packages("tidytext")
WARNING: Rtools is required to build R packages but is not currently installed. Please download and install the appropriate version of Rtools before proceeding:

https://cran.rstudio.com/bin/windows/Rtools/
Installing package into ‘C:/Users/maria/OneDrive/Documents/R/win-library/3.4’
(as ‘lib’ is unspecified)
Warning in install.packages :
  dependency ‘ISOcodes’ is not available
also installing the dependency ‘stopwords’

  There is a binary version available but the source
  version is later:
          binary source needs_compilation
stopwords  0.9.0    1.0             FALSE

installing the source packages ‘stopwords’, ‘tidytext’

trying URL 'https://cran.rstudio.com/src/contrib/stopwords_1.0.tar.gz'
Content type 'application/x-gzip' length 104532 bytes (102 KB)
downloaded 102 KB

trying URL 'https://cran.rstudio.com/src/contrib/tidytext_0.2.2.tar.gz'
Content type 'application/x-gzip' length 3088493 bytes (2.9 MB)
downloaded 2.9 MB

ERROR: dependency 'ISOcodes' is not available for package 'stopwords'
* removing 'C:/Users/maria/OneDrive/Documents/R/win-library/3.4/stopwords'
In R CMD INSTALL
Warning in install.packages :
  running command '"C:/PROGRA~1/R/R-34~1.4/bin/x64/R" CMD INSTALL -l "C:\Users\maria\OneDrive\Documents\R\win-library\3.4" C:\Users\maria\AppData\Local\Temp\RtmpOUYnrR/downloaded_packages/stopwords_1.0.tar.gz' had status 1
Warning in install.packages :
  installation of package ‘stopwords’ had non-zero exit status
ERROR: dependency 'stopwords' is not available for package 'tidytext'
* removing 'C:/Users/maria/OneDrive/Documents/R/win-library/3.4/tidytext'
In R CMD INSTALL
Warning in install.packages :
  running command '"C:/PROGRA~1/R/R-34~1.4/bin/x64/R" CMD INSTALL -l "C:\Users\maria\OneDrive\Documents\R\win-library\3.4" C:\Users\maria\AppData\Local\Temp\RtmpOUYnrR/downloaded_packages/tidytext_0.2.2.tar.gz' had status 1
Warning in install.packages :
  installation of package ‘tidytext’ had non-zero exit status

The downloaded source packages are in
    ‘C:\Users\maria\AppData\Local\Temp\RtmpOUYnrR\downloaded_packages’
> install.packages("tidyverse")
Error in install.packages : Updating loaded packages

Restarting R session...

> install.packages("tidyverse")
WARNING: Rtools is required to build R packages but is not currently installed. Please download and install the appropriate version of Rtools before proceeding:

https://cran.rstudio.com/bin/windows/Rtools/
Installing package into ‘C:/Users/maria/OneDrive/Documents/R/win-library/3.4’
(as ‘lib’ is unspecified)
also installing the dependencies ‘ellipsis’, ‘vctrs’, ‘lifecycle’, ‘dplyr’, ‘haven’, ‘hms’, ‘purrr’, ‘rlang’, ‘tibble’, ‘tidyr’, ‘xml2’

  There are binary versions available but the source
  versions are later:
           binary source needs_compilation
ellipsis    0.1.0  0.3.0              TRUE
vctrs       0.1.0  0.2.2              TRUE
dplyr     0.8.0.1  0.8.4              TRUE
haven       2.1.0  2.2.0              TRUE
hms         0.4.2  0.5.3             FALSE
purrr       0.3.2  0.3.3              TRUE
rlang       0.3.4  0.4.4              TRUE
tibble      2.1.1  2.1.3              TRUE
tidyr       0.8.3  1.0.2              TRUE
xml2        1.2.0  1.2.2              TRUE
tidyverse   1.2.1  1.3.0             FALSE

  Binaries will be installed
trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/ellipsis_0.1.0.zip'
Content type 'application/zip' length 30847 bytes (30 KB)
downloaded 30 KB

trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/vctrs_0.1.0.zip'
Content type 'application/zip' length 499748 bytes (488 KB)
downloaded 488 KB

trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/dplyr_0.8.0.1.zip'
Content type 'application/zip' length 3029353 bytes (2.9 MB)
downloaded 2.9 MB

trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/haven_2.1.0.zip'
Content type 'application/zip' length 988500 bytes (965 KB)
downloaded 965 KB

trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/purrr_0.3.2.zip'
Content type 'application/zip' length 327437 bytes (319 KB)
downloaded 319 KB

trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/rlang_0.3.4.zip'
Content type 'application/zip' length 1080437 bytes (1.0 MB)
downloaded 1.0 MB

trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/tibble_2.1.1.zip'
Content type 'application/zip' length 238931 bytes (233 KB)
downloaded 233 KB

trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/tidyr_0.8.3.zip'
Content type 'application/zip' length 907112 bytes (885 KB)
downloaded 885 KB

trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/xml2_1.2.0.zip'
Content type 'application/zip' length 3543977 bytes (3.4 MB)
downloaded 3.4 MB

package ‘ellipsis’ successfully unpacked and MD5 sums checked
package ‘vctrs’ successfully unpacked and MD5 sums checked
package ‘dplyr’ successfully unpacked and MD5 sums checked
package ‘haven’ successfully unpacked and MD5 sums checked
package ‘purrr’ successfully unpacked and MD5 sums checked
package ‘rlang’ successfully unpacked and MD5 sums checked
package ‘tibble’ successfully unpacked and MD5 sums checked
package ‘tidyr’ successfully unpacked and MD5 sums checked
package ‘xml2’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\maria\AppData\Local\Temp\Rtmpi6CSjp\downloaded_packages
installing the source packages ‘lifecycle’, ‘hms’, ‘tidyverse’

trying URL 'https://cran.rstudio.com/src/contrib/lifecycle_0.1.0.tar.gz'
Content type 'application/x-gzip' length 150752 bytes (147 KB)
downloaded 147 KB

trying URL 'https://cran.rstudio.com/src/contrib/hms_0.5.3.tar.gz'
Content type 'application/x-gzip' length 134669 bytes (131 KB)
downloaded 131 KB

trying URL 'https://cran.rstudio.com/src/contrib/tidyverse_1.3.0.tar.gz'
Content type 'application/x-gzip' length 712837 bytes (696 KB)
downloaded 696 KB

* installing *source* package 'lifecycle' ...
** package 'lifecycle' successfully unpacked and MD5 sums checked
** R
** inst
** preparing package for lazy loading
Error in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]) :
  namespace 'rlang' 0.3.4 is being loaded, but >= 0.4.0 is required
ERROR: lazy loading failed for package 'lifecycle'
* removing 'C:/Users/maria/OneDrive/Documents/R/win-library/3.4/lifecycle'
In R CMD INSTALL
Warning in install.packages :
  running command '"C:/PROGRA~1/R/R-34~1.4/bin/x64/R" CMD INSTALL -l "C:\Users\maria\OneDrive\Documents\R\win-library\3.4" C:\Users\maria\AppData\Local\Temp\Rtmpi6CSjp/downloaded_packages/lifecycle_0.1.0.tar.gz' had status 1
Warning in install.packages :
  installation of package ‘lifecycle’ had non-zero exit status
* installing *source* package 'hms' ...
** package 'hms' successfully unpacked and MD5 sums checked
** R
** preparing package for lazy loading
Error in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]) :
  namespace 'vctrs' 0.1.0 is being loaded, but >= 0.2.1 is required
ERROR: lazy loading failed for package 'hms'
* removing 'C:/Users/maria/OneDrive/Documents/R/win-library/3.4/hms'
* restoring previous 'C:/Users/maria/OneDrive/Documents/R/win-library/3.4/hms'
In R CMD INSTALL
Warning in install.packages :
  running command '"C:/PROGRA~1/R/R-34~1.4/bin/x64/R" CMD INSTALL -l "C:\Users\maria\OneDrive\Documents\R\win-library\3.4" C:\Users\maria\AppData\Local\Temp\Rtmpi6CSjp/downloaded_packages/hms_0.5.3.tar.gz' had status 1
Warning in install.packages :
  installation of package ‘hms’ had non-zero exit status
* installing *source* package 'tidyverse' ...
** package 'tidyverse' successfully unpacked and MD5 sums checked
** R
** inst
** preparing package for lazy loading
Error in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]) :
  namespace 'haven' 2.1.0 is being loaded, but >= 2.2.0 is required
ERROR: lazy loading failed for package 'tidyverse'
* removing 'C:/Users/maria/OneDrive/Documents/R/win-library/3.4/tidyverse'
* restoring previous 'C:/Users/maria/OneDrive/Documents/R/win-library/3.4/tidyverse'
In R CMD INSTALL
Warning in install.packages :
  running command '"C:/PROGRA~1/R/R-34~1.4/bin/x64/R" CMD INSTALL -l "C:\Users\maria\OneDrive\Documents\R\win-library\3.4" C:\Users\maria\AppData\Local\Temp\Rtmpi6CSjp/downloaded_packages/tidyverse_1.3.0.tar.gz' had status 1
Warning in install.packages :
  installation of package ‘tidyverse’ had non-zero exit status
</code>```

I thought the issue was dependencies, but it's not in the error message/output.

Because of the Rtools warning, I have downloaded Rtools, which never was required before - but I get this:

```<code>> install.packages("Rtools")
WARNING: Rtools is required to build R packages but is not currently installed. Please download and install the appropriate version of Rtools before proceeding:

https://cran.rstudio.com/bin/windows/Rtools/
Installing package into ‘C:/Users/maria/OneDrive/Documents/R/win-library/3.4’
(as ‘lib’ is unspecified)
Warning in install.packages :
  package ‘Rtools’ is not available (for R version 3.4.4)
</code>```

My R / system info: [Default] [64-bit] C:\Program Files\R\R-3.4.4
I work on a Microsoft computer.

Hope someone knows what's what here!

Best,

Maria

答:
@MrFlick posted the answer in the section above:

I had the old version of R. Installed to R 3.6.0 and everything works.
I first only updated Rstudio, not R itself. It wasn't until I updated R that it worked.

Find the link here: https://cran.r-project.org/bin/windows/base/old/3.6.0/

ContentLicense: CC BY-SA 4.0

Body:
I have been roaming the internet trying to find a solution, but haven't found it yet.

My problem is: i can't install tidytext. I also found out I can't re-install tidyverse for some reason.

The error code is:

install.packages("tidytext")
WARNING: Rtools is required to build R packages but is not currently installed. Please download and install the appropriate version of Rtools before proceeding:

https://cran.rstudio.com/bin/windows/Rtools/
Installing package into ‘C:/Users/maria/OneDrive/Documents/R/win-library/3.4’
(as ‘lib’ is unspecified)
Warning in install.packages :
  dependency ‘ISOcodes’ is not available
also installing the dependency ‘stopwords’

  There is a binary version available but the source
  version is later:
          binary source needs_compilation
stopwords  0.9.0    1.0             FALSE

installing the source packages ‘stopwords’, ‘tidytext’

trying URL 'https://cran.rstudio.com/src/contrib/stopwords_1.0.tar.gz'
Content type 'application/x-gzip' length 104532 bytes (102 KB)
downloaded 102 KB

trying URL 'https://cran.rstudio.com/src/contrib/tidytext_0.2.2.tar.gz'
Content type 'application/x-gzip' length 3088493 bytes (2.9 MB)
downloaded 2.9 MB

ERROR: dependency 'ISOcodes' is not available for package 'stopwords'
* removing 'C:/Users/maria/OneDrive/Documents/R/win-library/3.4/stopwords'
In R CMD INSTALL
Warning in install.packages :
  running command '"C:/PROGRA~1/R/R-34~1.4/bin/x64/R" CMD INSTALL -l "C:\Users\maria\OneDrive\Documents\R\win-library\3.4" C:\Users\maria\AppData\Local\Temp\RtmpOUYnrR/downloaded_packages/stopwords_1.0.tar.gz' had status 1
Warning in install.packages :
  installation of package ‘stopwords’ had non-zero exit status
ERROR: dependency 'stopwords' is not available for package 'tidytext'
* removing 'C:/Users/maria/OneDrive/Documents/R/win-library/3.4/tidytext'
In R CMD INSTALL
Warning in install.packages :
  running command '"C:/PROGRA~1/R/R-34~1.4/bin/x64/R" CMD INSTALL -l "C:\Users\maria\OneDrive\Documents\R\win-library\3.4" C:\Users\maria\AppData\Local\Temp\RtmpOUYnrR/downloaded_packages/tidytext_0.2.2.tar.gz' had status 1
Warning in install.packages :
  installation of package ‘tidytext’ had non-zero exit status

The downloaded source packages are in
    ‘C:\Users\maria\AppData\Local\Temp\RtmpOUYnrR\downloaded_packages’
> install.packages("tidyverse")
Error in install.packages : Updating loaded packages

Restarting R session...

> install.packages("tidyverse")
WARNING: Rtools is required to build R packages but is not currently installed. Please download and install the appropriate version of Rtools before proceeding:

https://cran.rstudio.com/bin/windows/Rtools/
Installing package into ‘C:/Users/maria/OneDrive/Documents/R/win-library/3.4’
(as ‘lib’ is unspecified)
also installing the dependencies ‘ellipsis’, ‘vctrs’, ‘lifecycle’, ‘dplyr’, ‘haven’, ‘hms’, ‘purrr’, ‘rlang’, ‘tibble’, ‘tidyr’, ‘xml2’

  There are binary versions available but the source
  versions are later:
           binary source needs_compilation
ellipsis    0.1.0  0.3.0              TRUE
vctrs       0.1.0  0.2.2              TRUE
dplyr     0.8.0.1  0.8.4              TRUE
haven       2.1.0  2.2.0              TRUE
hms         0.4.2  0.5.3             FALSE
purrr       0.3.2  0.3.3              TRUE
rlang       0.3.4  0.4.4              TRUE
tibble      2.1.1  2.1.3              TRUE
tidyr       0.8.3  1.0.2              TRUE
xml2        1.2.0  1.2.2              TRUE
tidyverse   1.2.1  1.3.0             FALSE

  Binaries will be installed
trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/ellipsis_0.1.0.zip'
Content type 'application/zip' length 30847 bytes (30 KB)
downloaded 30 KB

trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/vctrs_0.1.0.zip'
Content type 'application/zip' length 499748 bytes (488 KB)
downloaded 488 KB

trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/dplyr_0.8.0.1.zip'
Content type 'application/zip' length 3029353 bytes (2.9 MB)
downloaded 2.9 MB

trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/haven_2.1.0.zip'
Content type 'application/zip' length 988500 bytes (965 KB)
downloaded 965 KB

trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/purrr_0.3.2.zip'
Content type 'application/zip' length 327437 bytes (319 KB)
downloaded 319 KB

trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/rlang_0.3.4.zip'
Content type 'application/zip' length 1080437 bytes (1.0 MB)
downloaded 1.0 MB

trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/tibble_2.1.1.zip'
Content type 'application/zip' length 238931 bytes (233 KB)
downloaded 233 KB

trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/tidyr_0.8.3.zip'
Content type 'application/zip' length 907112 bytes (885 KB)
downloaded 885 KB

trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/xml2_1.2.0.zip'
Content type 'application/zip' length 3543977 bytes (3.4 MB)
downloaded 3.4 MB

package ‘ellipsis’ successfully unpacked and MD5 sums checked
package ‘vctrs’ successfully unpacked and MD5 sums checked
package ‘dplyr’ successfully unpacked and MD5 sums checked
package ‘haven’ successfully unpacked and MD5 sums checked
package ‘purrr’ successfully unpacked and MD5 sums checked
package ‘rlang’ successfully unpacked and MD5 sums checked
package ‘tibble’ successfully unpacked and MD5 sums checked
package ‘tidyr’ successfully unpacked and MD5 sums checked
package ‘xml2’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\maria\AppData\Local\Temp\Rtmpi6CSjp\downloaded_packages
installing the source packages ‘lifecycle’, ‘hms’, ‘tidyverse’

trying URL 'https://cran.rstudio.com/src/contrib/lifecycle_0.1.0.tar.gz'
Content type 'application/x-gzip' length 150752 bytes (147 KB)
downloaded 147 KB

trying URL 'https://cran.rstudio.com/src/contrib/hms_0.5.3.tar.gz'
Content type 'application/x-gzip' length 134669 bytes (131 KB)
downloaded 131 KB

trying URL 'https://cran.rstudio.com/src/contrib/tidyverse_1.3.0.tar.gz'
Content type 'application/x-gzip' length 712837 bytes (696 KB)
downloaded 696 KB

* installing *source* package 'lifecycle' ...
** package 'lifecycle' successfully unpacked and MD5 sums checked
** R
** inst
** preparing package for lazy loading
Error in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]) :
  namespace 'rlang' 0.3.4 is being loaded, but >= 0.4.0 is required
ERROR: lazy loading failed for package 'lifecycle'
* removing 'C:/Users/maria/OneDrive/Documents/R/win-library/3.4/lifecycle'
In R CMD INSTALL
Warning in install.packages :
  running command '"C:/PROGRA~1/R/R-34~1.4/bin/x64/R" CMD INSTALL -l "C:\Users\maria\OneDrive\Documents\R\win-library\3.4" C:\Users\maria\AppData\Local\Temp\Rtmpi6CSjp/downloaded_packages/lifecycle_0.1.0.tar.gz' had status 1
Warning in install.packages :
  installation of package ‘lifecycle’ had non-zero exit status
* installing *source* package 'hms' ...
** package 'hms' successfully unpacked and MD5 sums checked
** R
** preparing package for lazy loading
Error in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]) :
  namespace 'vctrs' 0.1.0 is being loaded, but >= 0.2.1 is required
ERROR: lazy loading failed for package 'hms'
* removing 'C:/Users/maria/OneDrive/Documents/R/win-library/3.4/hms'
* restoring previous 'C:/Users/maria/OneDrive/Documents/R/win-library/3.4/hms'
In R CMD INSTALL
Warning in install.packages :
  running command '"C:/PROGRA~1/R/R-34~1.4/bin/x64/R" CMD INSTALL -l "C:\Users\maria\OneDrive\Documents\R\win-library\3.4" C:\Users\maria\AppData\Local\Temp\Rtmpi6CSjp/downloaded_packages/hms_0.5.3.tar.gz' had status 1
Warning in install.packages :
  installation of package ‘hms’ had non-zero exit status
* installing *source* package 'tidyverse' ...
** package 'tidyverse' successfully unpacked and MD5 sums checked
** R
** inst
** preparing package for lazy loading
Error in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]) :
  namespace 'haven' 2.1.0 is being loaded, but >= 2.2.0 is required
ERROR: lazy loading failed for package 'tidyverse'
* removing 'C:/Users/maria/OneDrive/Documents/R/win-library/3.4/tidyverse'
* restoring previous 'C:/Users/maria/OneDrive/Documents/R/win-library/3.4/tidyverse'
In R CMD INSTALL
Warning in install.packages :
  running command '"C:/PROGRA~1/R/R-34~1.4/bin/x64/R" CMD INSTALL -l "C:\Users\maria\OneDrive\Documents\R\win-library\3.4" C:\Users\maria\AppData\Local\Temp\Rtmpi6CSjp/downloaded_packages/tidyverse_1.3.0.tar.gz' had status 1
Warning in install.packages :
  installation of package ‘tidyverse’ had non-zero exit status

I thought the issue was dependencies, but it's not in the error message/output.

Because of the Rtools warning, I have downloaded Rtools, which never was required before - but I get this:

> install.packages("Rtools")
WARNING: Rtools is required to build R packages but is not currently installed. Please download and install the appropriate version of Rtools before proceeding:

https://cran.rstudio.com/bin/windows/Rtools/
Installing package into ‘C:/Users/maria/OneDrive/Documents/R/win-library/3.4’
(as ‘lib’ is unspecified)
Warning in install.packages :
  package ‘Rtools’ is not available (for R version 3.4.4)

My R / system info: [Default] [64-bit] C:\Program Files\R\R-3.4.4
I work on a Microsoft computer.

Hope someone knows what's what here!

Best,

Maria


问:
Three.js, unexpected position shift when scaling object
I'm trying to create a zoom box, so far I managed to translate the cursor positions from locale to world coordinates and create a box object around the cursor with the right uvs.

Here is the fiddle of my attempt :  https://jsfiddle.net/2ynfedvk/2/

Without scaling the box is perfectly centered around the cursor, but if you toggle the scaling checkbox to set the scale zoomMesh.scale.set(1.5, 1.5, 1), the box position shift the further you move the cursor from the scene center.

Am I messing any CSS like "transform origin" for three.js to center the scale around the object, is this the right approach the get this kind of zoom effect ?

I'm new to three.js and 3d in general, so thanks for any help.

答:
thanks for the answer, not quite what I was looking for (not only resize the square but also zoom in the image), but you pointed me in the right direction.

Like you said the positions coordinate are shifting with the scale, so I have to recalculate the new position relative to the scale.

Added these new lines, with new scale and offset variables :

```<code>if(scaleCheckBox.checked){
    const offset = scale - 1;
    zoomMesh.position.set(
        -(x1 * offset) - (size*scale)/2) -(size/2),
        -((y1 * offset) + (size*scale)/2) -(size/2)),
        0
    );
}
</code>```

Here is the working fiddle : https://jsfiddle.net/dc9f5v0m/

It's a bit messy, with a lot of recalculation (Especially to center the cursor around the square), but it gets the job done and the zoom effect can be achieved with any shape not only a square.

Thanks again for your help.

Body:
thanks for the answer, not quite what I was looking for (not only resize the square but also zoom in the image), but you pointed me in the right direction.

Like you said the positions coordinate are shifting with the scale, so I have to recalculate the new position relative to the scale.

Added these new lines, with new scale and offset variables :

if(scaleCheckBox.checked){
    const offset = scale - 1;
    zoomMesh.position.set(
        -(x1 * offset) - (size*scale)/2) -(size/2),
        -((y1 * offset) + (size*scale)/2) -(size/2)),
        0
    );
}

Here is the working fiddle : https://jsfiddle.net/dc9f5v0m/

It's a bit messy, with a lot of recalculation (Especially to center the cursor around the square), but it gets the job done and the zoom effect can be achieved with any shape not only a square.

Thanks again for your help.


问:
How to create a transparent control which works when on top of other controls?
I have a control (derived from System.Windows.Forms.Control) which needs to be transparent in some areas.  I have implemented this by using SetStyle():

```<code>public TransparentControl()
{
    SetStyle(ControlStyles.SupportsTransparentBackColor, true);
    this.BackColor = Color.Transparent.
}
</code>```

Now, this works if there are no controls between the form and the transparent control.  However, if there happens to be another control below the transparent control (which is the use case here), it does not work.  The intermediate control is not draw, but the form below does show through.  I can get the effect that I need by overriding CreateParams and setting the WS_EX_TRANSPARENT flasg like so:

```<code>protected override CreateParams CreateParams
{
    get
    {
        CreateParams cp = base.CreateParams;
        cp.ExStyle |= 0x20; // WS_EX_TRANSPARENT
        return cp;
    }
}
</code>```

The problem here is that it really slows down the painting of the control.  The control is already double buffered, so nothing to do there.  The performance hit is so bad that it is unacceptable.  Has anyone else encountered this problem?  All of the resources that I can find suggest using method #1, but again, that does not work in my case.

EDIT: I should note that I do have a workaround.  The child (transparent) controls could simply draw themselves onto the parent's Graphics object, but it is really ungly and I don't like the solution at all (though it may be all I have).

EDIT2:  So, following the advice that I got on how transparency works in .NET, I have implemented the IContainer interface in my user control which contains the transparent controls.  I have created a class which implements ISite, I add my child controls to the Components collection of the UserControl, the Container property lines up correctly in the debugger, but I still do not get a transparency effect.  Does anyone have any ideas?

答:
Drawing the siblings under the control is possible, but it's ugly. The code below works reasonably well for me, it expands on the code given in the link in Ed S.' answer.

Possible pitfalls:

DrawToBitmap was introduced with .net 2.0, so don't expect it to work with anything older than that. But even then something like this may be possible by sending WM_PRINT to the sibling control; AFAIK that's what DrawToBitmap does internally.

It may also have problems if you have controls under your control that make use of WS_EX_TRANSPARENT since according to msdn that window style fiddles with the painting order. I haven't got any controls that use this style so I can't tell.

I'm running XP SP3 with VS2010, therefore this approach may have additional problems on Vista or W7.

Here's the code:

```<code>if (Parent != null)
{
    float
        tx = -Left,
        ty = -Top;

    // make adjustments to tx and ty here if your control
    // has a non-client area, borders or similar

    e.Graphics.TranslateTransform(tx, ty);

    using (PaintEventArgs pea = new PaintEventArgs(e.Graphics,e.ClipRectangle))
    {
        InvokePaintBackground(Parent, pea);
        InvokePaint(Parent, pea);
    }

    e.Graphics.TranslateTransform(-tx, -ty);

    // loop through children of parent which are under ourselves
    int start = Parent.Controls.GetChildIndex(this);
    Rectangle rect = new Rectangle(Left, Top, Width, Height);
    for (int i = Parent.Controls.Count - 1; i > start; i--)
    {
        Control c = Parent.Controls[i];

        // skip ...
        // ... invisible controls
        // ... or controls that have zero width/height (Autosize Labels without content!)
        // ... or controls that don't intersect with ourselves
        if (!c.Visible || c.Width == 0 || c.Height == 0 || !rect.IntersectsWith(new Rectangle(c.Left, c.Top, c.Width, c.Height)))
            continue;

        using (Bitmap b = new Bitmap(c.Width, c.Height, e.Graphics))
        {
            c.DrawToBitmap(b, new Rectangle(0, 0, c.Width, c.Height));

            tx = c.Left - Left;
            ty = c.Top - Top;

            // make adjustments to tx and ty here if your control
            // has a non-client area, borders or similar

            e.Graphics.TranslateTransform(tx, ty);
            e.Graphics.DrawImageUnscaled(b, new Point(0, 0));
            e.Graphics.TranslateTransform(-tx, -ty);
        }
}
</code>```

OwnerDisplayName: Ed Swangren

ContentLicense: CC BY-SA 2.5

Body:
I have a control (derived from System.Windows.Forms.Control) which needs to be transparent in some areas.  I have implemented this by using SetStyle():

public TransparentControl()
{
    SetStyle(ControlStyles.SupportsTransparentBackColor, true);
    this.BackColor = Color.Transparent.
}

Now, this works if there are no controls between the form and the transparent control.  However, if there happens to be another control below the transparent control (which is the use case here), it does not work.  The intermediate control is not draw, but the form below does show through.  I can get the effect that I need by overriding CreateParams and setting the WS_EX_TRANSPARENT flasg like so:

protected override CreateParams CreateParams
{
    get
    {
        CreateParams cp = base.CreateParams;
        cp.ExStyle |= 0x20; // WS_EX_TRANSPARENT
        return cp;
    }
}

The problem here is that it really slows down the painting of the control.  The control is already double buffered, so nothing to do there.  The performance hit is so bad that it is unacceptable.  Has anyone else encountered this problem?  All of the resources that I can find suggest using method #1, but again, that does not work in my case.

EDIT: I should note that I do have a workaround.  The child (transparent) controls could simply draw themselves onto the parent's Graphics object, but it is really ungly and I don't like the solution at all (though it may be all I have).

EDIT2:  So, following the advice that I got on how transparency works in .NET, I have implemented the IContainer interface in my user control which contains the transparent controls.  I have created a class which implements ISite, I add my child controls to the Components collection of the UserControl, the Container property lines up correctly in the debugger, but I still do not get a transparency effect.  Does anyone have any ideas?

LastEditorDisplayName: Ed Swangren

Body:
Drawing the siblings under the control is possible, but it's ugly. The code below works reasonably well for me, it expands on the code given in the link in Ed S.' answer.

Possible pitfalls:

DrawToBitmap was introduced with .net 2.0, so don't expect it to work with anything older than that. But even then something like this may be possible by sending WM_PRINT to the sibling control; AFAIK that's what DrawToBitmap does internally.

It may also have problems if you have controls under your control that make use of WS_EX_TRANSPARENT since according to msdn that window style fiddles with the painting order. I haven't got any controls that use this style so I can't tell.

I'm running XP SP3 with VS2010, therefore this approach may have additional problems on Vista or W7.

Here's the code:

if (Parent != null)
{
    float
        tx = -Left,
        ty = -Top;

    // make adjustments to tx and ty here if your control
    // has a non-client area, borders or similar

    e.Graphics.TranslateTransform(tx, ty);

    using (PaintEventArgs pea = new PaintEventArgs(e.Graphics,e.ClipRectangle))
    {
        InvokePaintBackground(Parent, pea);
        InvokePaint(Parent, pea);
    }

    e.Graphics.TranslateTransform(-tx, -ty);

    // loop through children of parent which are under ourselves
    int start = Parent.Controls.GetChildIndex(this);
    Rectangle rect = new Rectangle(Left, Top, Width, Height);
    for (int i = Parent.Controls.Count - 1; i > start; i--)
    {
        Control c = Parent.Controls[i];

        // skip ...
        // ... invisible controls
        // ... or controls that have zero width/height (Autosize Labels without content!)
        // ... or controls that don't intersect with ourselves
        if (!c.Visible || c.Width == 0 || c.Height == 0 || !rect.IntersectsWith(new Rectangle(c.Left, c.Top, c.Width, c.Height)))
            continue;

        using (Bitmap b = new Bitmap(c.Width, c.Height, e.Graphics))
        {
            c.DrawToBitmap(b, new Rectangle(0, 0, c.Width, c.Height));

            tx = c.Left - Left;
            ty = c.Top - Top;

            // make adjustments to tx and ty here if your control
            // has a non-client area, borders or similar

            e.Graphics.TranslateTransform(tx, ty);
            e.Graphics.DrawImageUnscaled(b, new Point(0, 0));
            e.Graphics.TranslateTransform(-tx, -ty);
        }
}

ContentLicense: CC BY-SA 3.0


问:
Difference between kafka idempotent and transactional producer setup?
When setting up a kafka producer to use idempotent behaviour, and transactional behaviour:

I understand that for idempotency we set:
enable.idempotence=true
and that by changing this one flag on our producer, we are guaranteed exactly-once event delivery?

and for transactions, we must go further and set the transaction.id=<some value>
but by setting this value, it also sets idempotence to true?

Also, by setting one or both of the above to true, the producer will also set acks=all.

With the above should I be able to add 'exactly once delivery' by simply changing the enable idempotency setting? If i wanted to go further and enable transactional support, On the Consumer side, I would only need to change their setting, isolation.level=read_committed? Does this image reflect how to setup the producer in terms of EOS?

答:
Yes you understood the main concepts.

By enabling idempotence, the producer automatically sets acks to all and guarantees message delivery for the lifetime of the Producer instance.

By enabling transactions, the producer automatically enables idempotence (and acks=all). Transactions allow to group produce requests and offset commits and ensure all or nothing gets committed to Kafka.

When using transactions, you can configure if consumers should only see records from committed transactions by setting isolation.level to read_committed, otherwise by default they see all records including from discarded transactions.


答:
using dplyr  you might try this:

```<code>install.packages("dplyr")
library(dplyr)
mapoc_temp <- mapoc_temp %>%
              mutate(month_new = month.abb[as.numeric(gsub("M","",month))])
</code>```

The %>% is an indicator of the pipline. month.abb is something from base R that contains all month abbreviations (note that it is the abbreviations for the language your R is in, you can change that if you want see for example). By using gsub I delete the M that is in front of the numbers. These numbers are used to select the correct month in month.abb.

It results in:

```<code>   Longitude Latitude       Temp month year month_new
1  -43.54116 59.95063 -1.1657088    M1 2016       Jan
2  -43.54116 59.95063 -1.7090803    M1 2017       Jan
3  -43.54116 59.95063 -1.7090803    M1 2018       Jan
4  -43.54116 59.95063 -1.6484648    M2 2016       Feb
5  -43.54116 59.95063 -1.5090311    M2 2017       Feb
6  -43.54116 59.95063 -1.5090311    M2 2018       Feb
7  -43.54116 59.95063 -1.2948184    M3 2016       Mar
8  -43.54116 59.95063 -0.8193197    M3 2017       Mar
9  -43.54116 59.95063 -0.8193197    M3 2018       Mar
10 -43.54116 59.95063  0.9379213    M4 2016       Apr
</code>```

If you don't want it in a new variable, just change the month_new to month. But this is for display purposes that the month M# valuse are correctly converted.

Title: How To Properly change Strings To Month Abbreviations in R?

Body:
I have a dataframe which gives me months labelled as M1-M12 instead of Jan-Dec. I am trying to convert the M values to month abbreviations and I can't seem to work it out.
this is the dput for the original dataframe:

mapoc_temp = structure(list(Longitude = c(-43.5411605834961, -43.5411605834961,
-43.5411605834961, -43.5411605834961, -43.5411605834961, -43.5411605834961,
-43.5411605834961, -43.5411605834961, -43.5411605834961, -43.5411605834961,
-43.5411605834961, -43.5411605834961, -43.5411605834961, -43.5411605834961,
-43.5411605834961, -43.5411605834961, -43.5411605834961, -43.5411605834961,
-43.5411605834961, -43.5411605834961, -43.5411605834961, -43.5411605834961,
-43.5411605834961, -43.5411605834961, -43.5411605834961, -43.5411605834961,
-43.5411605834961, -43.5411605834961, -43.5411605834961, -43.5411605834961,
-43.5411605834961, -43.5411605834961, -43.5411605834961, -43.5411605834961,
-43.5411605834961, -43.5411605834961), Latitude = c(59.950626373291,
59.950626373291, 59.950626373291, 59.950626373291, 59.950626373291,
59.950626373291, 59.950626373291, 59.950626373291, 59.950626373291,
59.950626373291, 59.950626373291, 59.950626373291, 59.950626373291,
59.950626373291, 59.950626373291, 59.950626373291, 59.950626373291,
59.950626373291, 59.950626373291, 59.950626373291, 59.950626373291,
59.950626373291, 59.950626373291, 59.950626373291, 59.950626373291,
59.950626373291, 59.950626373291, 59.950626373291, 59.950626373291,
59.950626373291, 59.950626373291, 59.950626373291, 59.950626373291,
59.950626373291, 59.950626373291, 59.950626373291), Temp = c(-1.1657087802887,
-1.70908033847809, -1.70908033847809, -1.64846479892731, -1.50903105735779,
-1.50903105735779, -1.29481840133667, -0.819319725036621, -0.819319725036621,
0.937921285629272, -0.033661849796772, -0.033661849796772, 3.09912943840027,
3.3768904209137, 3.3768904209137, 5.44990491867065, 5.90848398208618,
5.90848398208618, 8.87255096435547, 7.57381582260132, 7.57381582260132,
9.52607250213623, 9.41888046264648, 9.41888046264648, 7.80030059814453,
7.23698377609253, 7.23698377609253, 3.53716945648193, 4.55290651321411,
4.55290651321411, 0.885161995887756, 1.48482501506805, 1.48482501506805,
-0.0936287492513657, 0.650709450244904, 0.650709450244904), month = c("M1",
"M1", "M1", "M2", "M2", "M2", "M3", "M3", "M3", "M4", "M4", "M4",
"M5", "M5", "M5", "M6", "M6", "M6", "M7", "M7", "M7", "M8", "M8",
"M8", "M9", "M9", "M9", "M10", "M10", "M10", "M11", "M11", "M11",
"M12", "M12", "M12"), year = c(2016, 2017, 2018, 2016, 2017,
2018, 2016, 2017, 2018, 2016, 2017, 2018, 2016, 2017, 2018, 2016,
2017, 2018, 2016, 2017, 2018, 2016, 2017, 2018, 2016, 2017, 2018,
2016, 2017, 2018, 2016, 2017, 2018, 2016, 2017, 2018)), row.names = c(NA,
-36L), class = "data.frame")

I've tried using the following code to change the M strings to months:

#Rename my months so they are abbreviated and not M1:M12
mapoc_temp$month = c(M1 = "Jan", M2 = "Feb", M3 = "Mar",
                     M4 = "Apr", M5 = "May", M6 = "Jun",
                     M7 = "Jul", M8 = "Aug", M9 = "Sep",
                     M10 = "Oct", M11 = "Nov", M12 = "Dec")

but when I use that code it gives me different months than my original ones for each of the rows, as you can see in this new dataframe I've posted:

mapoc_temp = structure(list(Longitude = c(-43.5411605834961, -43.5411605834961,
-43.5411605834961, -43.5411605834961, -43.5411605834961, -43.5411605834961,
-43.5411605834961, -43.5411605834961, -43.5411605834961, -43.5411605834961,
-43.5411605834961, -43.5411605834961, -43.5411605834961, -43.5411605834961,
-43.5411605834961, -43.5411605834961, -43.5411605834961, -43.5411605834961,
-43.5411605834961, -43.5411605834961, -43.5411605834961, -43.5411605834961,
-43.5411605834961, -43.5411605834961, -43.5411605834961, -43.5411605834961,
-43.5411605834961, -43.5411605834961, -43.5411605834961, -43.5411605834961,
-43.5411605834961, -43.5411605834961, -43.5411605834961, -43.5411605834961,
-43.5411605834961, -43.5411605834961), Latitude = c(59.950626373291,
59.950626373291, 59.950626373291, 59.950626373291, 59.950626373291,
59.950626373291, 59.950626373291, 59.950626373291, 59.950626373291,
59.950626373291, 59.950626373291, 59.950626373291, 59.950626373291,
59.950626373291, 59.950626373291, 59.950626373291, 59.950626373291,
59.950626373291, 59.950626373291, 59.950626373291, 59.950626373291,
59.950626373291, 59.950626373291, 59.950626373291, 59.950626373291,
59.950626373291, 59.950626373291, 59.950626373291, 59.950626373291,
59.950626373291, 59.950626373291, 59.950626373291, 59.950626373291,
59.950626373291, 59.950626373291, 59.950626373291), Temp = c(-1.1657087802887,
-1.70908033847809, -1.70908033847809, -1.64846479892731, -1.50903105735779,
-1.50903105735779, -1.29481840133667, -0.819319725036621, -0.819319725036621,
0.937921285629272, -0.033661849796772, -0.033661849796772, 3.09912943840027,
3.3768904209137, 3.3768904209137, 5.44990491867065, 5.90848398208618,
5.90848398208618, 8.87255096435547, 7.57381582260132, 7.57381582260132,
9.52607250213623, 9.41888046264648, 9.41888046264648, 7.80030059814453,
7.23698377609253, 7.23698377609253, 3.53716945648193, 4.55290651321411,
4.55290651321411, 0.885161995887756, 1.48482501506805, 1.48482501506805,
-0.0936287492513657, 0.650709450244904, 0.650709450244904), month = c("Jan",
"Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
"Nov", "Dec", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct", "Nov", "Dec", "Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), year = c(2016,
2017, 2018, 2016, 2017, 2018, 2016, 2017, 2018, 2016, 2017, 2018,
2016, 2017, 2018, 2016, 2017, 2018, 2016, 2017, 2018, 2016, 2017,
2018, 2016, 2017, 2018, 2016, 2017, 2018, 2016, 2017, 2018, 2016,
2017, 2018)), row.names = c(NA, -36L), class = "data.frame")

As you can see instead of assigning M1 - Jan, and M2 - Feb, and M3 - Mar etc. It gives me the abbreviated months in order no matter what the original value is. Does anyone know how to fix this?

Body:
using dplyr  you might try this:

install.packages("dplyr")
library(dplyr)
mapoc_temp <- mapoc_temp %>%
              mutate(month_new = month.abb[as.numeric(gsub("M","",month))])

The %>% is an indicator of the pipline. month.abb is something from base R that contains all month abbreviations (note that it is the abbreviations for the language your R is in, you can change that if you want see for example). By using gsub I delete the M that is in front of the numbers. These numbers are used to select the correct month in month.abb.

It results in:

   Longitude Latitude       Temp month year month_new
1  -43.54116 59.95063 -1.1657088    M1 2016       Jan
2  -43.54116 59.95063 -1.7090803    M1 2017       Jan
3  -43.54116 59.95063 -1.7090803    M1 2018       Jan
4  -43.54116 59.95063 -1.6484648    M2 2016       Feb
5  -43.54116 59.95063 -1.5090311    M2 2017       Feb
6  -43.54116 59.95063 -1.5090311    M2 2018       Feb
7  -43.54116 59.95063 -1.2948184    M3 2016       Mar
8  -43.54116 59.95063 -0.8193197    M3 2017       Mar
9  -43.54116 59.95063 -0.8193197    M3 2018       Mar
10 -43.54116 59.95063  0.9379213    M4 2016       Apr

If you don't want it in a new variable, just change the month_new to month. But this is for display purposes that the month M# valuse are correctly converted.


问:
Google Colab: No option to restart and clear all outputs?
I'm experienced with Jupyter Notebook and am coming over to Google Colaboratory. I noticed that Colab does not have an option to restart the runtime and clear all the outputs; is that correct?

In Jupyter Notebook, the option is under Kernel --> Restart & Clear Output.

However, in Google Colab, there is no such option under the Runtime menu:

When I click on Restart Runtime..., it only shows the following:

Any help would be appreciated.

答:
To clear outputs, go to 'EDIT' and 'clear all outputs'.

If you want to reset all packages, data files etc. installed, you have got to the runtime as you mentioned.
Hopefully, it helps. :)


问:
What does parameters limit and maxLevel mean in Neo4j apoc query?
By reading the official Neo4j documentation, I can't understand what does the two parameters limit and maxLevel mean in a apoc.path.subgraphnodes.

https://neo4j-contrib.github.io/neo4j-apoc-procedures/3.5/path-finding/path-expander/

Anyone can help me ?

Thanks in advance

答:
maxLevel is basically the depth of the expansion. maxLevel:2 means up to two expansions from the starting node.

limit limits the total results returned from the call, once this many results are found, then it will stop looking further.

So as an example, if we had a social graph, and you wanted to find the first 3 :Doctor nodes, within 10 expansions of you (this uses breadth first expansion by default), you might use something like:

```<code>MATCH (me:Person {id:12345})
CALL apoc.path.subgraphNodes(me, {maxLevel:10, limit:3, labelFilter:'Doctor'}) YIELD node
RETURN node
</code>```

And there might be thousands of :Doctor nodes within 10 hops, but because of the limit:3, once 3 are found it will stop trying to find more.

Body:
maxLevel is basically the depth of the expansion. maxLevel:2 means up to two expansions from the starting node.

limit limits the total results returned from the call, once this many results are found, then it will stop looking further.

So as an example, if we had a social graph, and you wanted to find the first 3 :Doctor nodes, within 10 expansions of you (this uses breadth first expansion by default), you might use something like:

MATCH (me:Person {id:12345})
CALL apoc.path.subgraphNodes(me, {maxLevel:10, limit:3, labelFilter:'Doctor'}) YIELD node
RETURN node

And there might be thousands of :Doctor nodes within 10 hops, but because of the limit:3, once 3 are found it will stop trying to find more.


问:
CORS error on request, with headers and webpack-dev-server proxy configured
I have a simple ReactJS+Typescript application (bundled with Webpack) that I've been designing for the last couple of days. Now, I was starting the backend connection part (not my field, nor my responsability in this context), with which I'm having some difficulties. The main problem is a CORS error on the browser. This is my setup:

```<code>    "webpack": "^4.30.0",
    "webpack-dev-server": "^3.3.1",
    "typescript": "^3.4.5",
    "react": "^16.8.6",
    "axios": "^0.18.0",
    Chrome version 74.0.3729.131 (64-bit)
</code>```

Without any type of suggestion or experiment, this is the error I encountered:

I've tried a couple of things to solve this problem, but none of them actually fixed it. They are as follows:

On my webpack.dev.ts configuration file, I configured the webpack proxy property. I configured it like this:

```<code>  devServer: {
    contentBase: path.join(__dirname, process.env.PUBLIC_PATH || '../dist'),
    compress: true,
    host: process.env.DEV_HOST || 'localhost',
    port: process.env.DEV_PORT || 8000,
    open: 'chrome',
    proxy: {
      '/api': {
        target: 'http://<ip>:8888',
        secure: false,
      },
    },
    headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': '*',
        'Access-Control-Allow-Methods': '*',
    },
  },
</code>```

The request to the backend is built as follows:

```<code>const config = {
  method: 'post',
  url: '/api/login',
  data: { password: password },
};
axios(config)
  .then(resp => console.log(resp))
  .catch(error => console.log(error));
</code>```

Please note that, for now, the password field is just a placeholder and is not validated on the backend, and as such, the Access-Control-Allow-Credentials header is not required.

To my big disappointment, the request doesn't seem to be using the proxy configured, since this is the error:

On the network tab, there's also no reference to the backend IP address. Please note that only in this case does the request show as a POST and not as an OPTIONS request.

Tried configuring axios with the headers required for CORS control on my side (client). This also didn't bring any solution to the table. This is what I came up with:

```<code>const config = {
  method: 'post',
  url: 'http://<ip>:8888/api/login',
  data: { password: password },
  headers: {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': '*',
    'Access-Control-Allow-Methods': '*',
  },
};
axios(config)
  .then(resp => console.log(resp))
  .catch(error => console.log(error));
</code>```

The result that appeared is similar to the one without any configuration (first image attached here).

Finally, I installed a Chrome extension for CORS, that (I suppose) attaches the Access-Control-Allow-Origin: * header to all requests. This is where things get interesting/weird. With this extension active (and without configuring it), even if I disable all the other previous options, the error changes:

I've also tried activating all three previous options at the same time, and this last error is what appears.

I'm not sure where to head next, or how to proceed from here. I'm avoiding requesting a change to the server API's headers, but I'm keeping that option open as a last resort.

I've tried to be thorough with the explanation and with what I want to achieve, but feel free to request more information.

Thanks in advance.

答:
Exposing an API backend server from the same origin the web application is loaded helps to get around the CORS restriction. It's where the webpack dev-server proxy comes in handy. First, make sure requests to the API address the proxy. If XMLHttpRequest's or fetches in source code address absolute URLs (as opposed to relative ones) use a flag that indicates a development mode to choose the proxy as the origin. For example:

```<code>fetch(isDevelopment ? '/api' : 'http://backend.server.com/api')
.then(response => processResponse(response));
</code>```

Second, configure the proxy to target the required API on the real backend server:

```<code>devServer: {
  proxy: {
    '/api': {
      target: 'http://backend.server.com'
    }
  }
}
</code>```

There are no cross-origin requests from a browser's viewpoint anymore. This configuration may be also enough for the server to respond properly (for instance Jetty 9 with its CORS filter set works for me just fine). On the other hand, browsers may send Origin headers even with same-origin requests. To prevent CORS issues on different backend servers, if there is any, change the Origin header to match the target URL like this:

```<code>devServer: {
  proxy: {
    '/api': {
      target: 'http://backend.server.com',
      onProxyReq: proxyReq => {
        if (proxyReq.getHeader('origin')) {
          proxyReq.setHeader('origin', 'http://backend.server.com');
        }
      }
    }
  }
}
</code>```

Refer to the documentation of dev-server and the http-proxy-middleware library it uses under the hood for more information. Also, TCP/HTTP sniffers like Wireshark are very helpful to understand what is sent where and what is sent in response.

Body:
I have a simple ReactJS+Typescript application (bundled with Webpack) that I've been designing for the last couple of days. Now, I was starting the backend connection part (not my field, nor my responsability in this context), with which I'm having some difficulties. The main problem is a CORS error on the browser. This is my setup:

    "webpack": "^4.30.0",
    "webpack-dev-server": "^3.3.1",
    "typescript": "^3.4.5",
    "react": "^16.8.6",
    "axios": "^0.18.0",
    Chrome version 74.0.3729.131 (64-bit)

Without any type of suggestion or experiment, this is the error I encountered:

I've tried a couple of things to solve this problem, but none of them actually fixed it. They are as follows:

On my webpack.dev.ts configuration file, I configured the webpack proxy property. I configured it like this:

  devServer: {
    contentBase: path.join(__dirname, process.env.PUBLIC_PATH || '../dist'),
    compress: true,
    host: process.env.DEV_HOST || 'localhost',
    port: process.env.DEV_PORT || 8000,
    open: 'chrome',
    proxy: {
      '/api': {
        target: 'http://<ip>:8888',
        secure: false,
      },
    },
    headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': '*',
        'Access-Control-Allow-Methods': '*',
    },
  },

The request to the backend is built as follows:

const config = {
  method: 'post',
  url: '/api/login',
  data: { password: password },
};
axios(config)
  .then(resp => console.log(resp))
  .catch(error => console.log(error));

Please note that, for now, the password field is just a placeholder and is not validated on the backend, and as such, the Access-Control-Allow-Credentials header is not required.

To my big disappointment, the request doesn't seem to be using the proxy configured, since this is the error:

On the network tab, there's also no reference to the backend IP address. Please note that only in this case does the request show as a POST and not as an OPTIONS request.

Tried configuring axios with the headers required for CORS control on my side (client). This also didn't bring any solution to the table. This is what I came up with:

const config = {
  method: 'post',
  url: 'http://<ip>:8888/api/login',
  data: { password: password },
  headers: {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': '*',
    'Access-Control-Allow-Methods': '*',
  },
};
axios(config)
  .then(resp => console.log(resp))
  .catch(error => console.log(error));

The result that appeared is similar to the one without any configuration (first image attached here).

Finally, I installed a Chrome extension for CORS, that (I suppose) attaches the Access-Control-Allow-Origin: * header to all requests. This is where things get interesting/weird. With this extension active (and without configuring it), even if I disable all the other previous options, the error changes:

I've also tried activating all three previous options at the same time, and this last error is what appears.

I'm not sure where to head next, or how to proceed from here. I'm avoiding requesting a change to the server API's headers, but I'm keeping that option open as a last resort.

I've tried to be thorough with the explanation and with what I want to achieve, but feel free to request more information.

Thanks in advance.

Body:
Exposing an API backend server from the same origin the web application is loaded helps to get around the CORS restriction. It's where the webpack dev-server proxy comes in handy. First, make sure requests to the API address the proxy. If XMLHttpRequest's or fetches in source code address absolute URLs (as opposed to relative ones) use a flag that indicates a development mode to choose the proxy as the origin. For example:

fetch(isDevelopment ? '/api' : 'http://backend.server.com/api')
.then(response => processResponse(response));

Second, configure the proxy to target the required API on the real backend server:

devServer: {
  proxy: {
    '/api': {
      target: 'http://backend.server.com'
    }
  }
}

There are no cross-origin requests from a browser's viewpoint anymore. This configuration may be also enough for the server to respond properly (for instance Jetty 9 with its CORS filter set works for me just fine). On the other hand, browsers may send Origin headers even with same-origin requests. To prevent CORS issues on different backend servers, if there is any, change the Origin header to match the target URL like this:

devServer: {
  proxy: {
    '/api': {
      target: 'http://backend.server.com',
      onProxyReq: proxyReq => {
        if (proxyReq.getHeader('origin')) {
          proxyReq.setHeader('origin', 'http://backend.server.com');
        }
      }
    }
  }
}

Refer to the documentation of dev-server and the http-proxy-middleware library it uses under the hood for more information. Also, TCP/HTTP sniffers like Wireshark are very helpful to understand what is sent where and what is sent in response.


问:
Why does mutating a value of a parent directive's scope in link not provide that mutated state to a child directive?
I have a parent directive being passed an array as the value for one of its attributes. The parent directive's job is render some components, and then send a modified version of that array to a child directive. The child directive needs to then render the modified array.

Adjusting this array in the parent directive's link function does not seem to propagate the change to the rendered child directive.

Why is this?

I am only a couple days into AngularJS and may have a fundamental misunderstanding of scope or lifecycle, though I'm not sure which.

The example below modifies an array of [1,2] provided to the parent directive by having the parent directive push 3 into it.

The parent directive renders a template containing the child directive and, what I had hoped to be, the mutated array.

The screen will render the unmutated array (rendered from the child directive) but console.log the mutated array (logged from the parent directive)

https://codesandbox.io/s/trusting-fire-k4so0?fontsize=14&hidenavigation=1&theme=dark

src/index.js

```<code>"use_strict";

var angular = require("angular");

angular
  .module("App", [])
  .controller("IgnorableController", [function(){}])
  .directive("parentIsolatedScope", [
    function() {
      return {
        restrict: "E",
        template:
          "<child-isolated-scope mutated-array='mutableArray'></child-isolated-scope>",
        scope: {
          mutableArray: "<"
        },
        link: function(scope) {
          scope.mutableArray.push(3);
          console.log(scope.mutableArray);
        }
      };
    }
  ])
  .directive("childIsolatedScope", [
    function() {
      return {
        restrict: "E",
        template: "<div>{{mutatedArray | json}}</div>",
        scope: {
          mutatedArray: "<"
        }
      };
    }
  ]);
</code>```

index.html

```<code><!DOCTYPE html>
<html ng-app="App">
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <script src="src/index.js"></script>
  </head>

  <body ng-controller="IgnorableController">
    <parent-isolated-scope mutable-array="[1,2]"></parent-isolated-scope>
  </body>
</html>
</code>```

答:
If you declare a variable for the initial array and use it to pass the array into the directive it will work as expected.

Can you provide an explanation as to why that's the case?

```<code><body ng-controller="IgnorableController">
    <parent-isolated-scope mutable-array="[1,2]"></parent-isolated-scope>
</body>
</code>```

When the binding is an AngularJS expression that resolves to an array, on every digest cycle the framework evaluates the expression and sets the isolate scope variable to that value. On each digest cycle, the framework sets the value anew replacing any mutations.

With a variable:

```<code><body ng-controller="IgnorableController" ng-init="x = [1,2]">
    <parent-isolated-scope mutable-array="x"></parent-isolated-scope>
</body>
</code>```

A reference to the variable is assigned to the isolate scope.

Be aware that any mutations to the contents of the reference will change the contents in both the child isolate scope and the parent scope. This can have unintended consequences for some designs.

Body:
I have a parent directive being passed an array as the value for one of its attributes. The parent directive's job is render some components, and then send a modified version of that array to a child directive. The child directive needs to then render the modified array.

Adjusting this array in the parent directive's link function does not seem to propagate the change to the rendered child directive.

Why is this?

I am only a couple days into AngularJS and may have a fundamental misunderstanding of scope or lifecycle, though I'm not sure which.

The example below modifies an array of [1,2] provided to the parent directive by having the parent directive push 3 into it.

The parent directive renders a template containing the child directive and, what I had hoped to be, the mutated array.

The screen will render the unmutated array (rendered from the child directive) but console.log the mutated array (logged from the parent directive)

https://codesandbox.io/s/trusting-fire-k4so0?fontsize=14&hidenavigation=1&theme=dark

src/index.js

"use_strict";

var angular = require("angular");

angular
  .module("App", [])
  .controller("IgnorableController", [function(){}])
  .directive("parentIsolatedScope", [
    function() {
      return {
        restrict: "E",
        template:
          "<child-isolated-scope mutated-array='mutableArray'></child-isolated-scope>",
        scope: {
          mutableArray: "<"
        },
        link: function(scope) {
          scope.mutableArray.push(3);
          console.log(scope.mutableArray);
        }
      };
    }
  ])
  .directive("childIsolatedScope", [
    function() {
      return {
        restrict: "E",
        template: "
{{mutatedArray | json}}
",
        scope: {
          mutatedArray: "<"
        }
      };
    }
  ]);

index.html

<!DOCTYPE html>

    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />

    <parent-isolated-scope mutable-array="[1,2]"></parent-isolated-scope>

Body:
If you declare a variable for the initial array and use it to pass the array into the directive it will work as expected.

Can you provide an explanation as to why that's the case?

<body ng-controller="IgnorableController">
    <parent-isolated-scope mutable-array="[1,2]"></parent-isolated-scope>
</body>

When the binding is an AngularJS expression that resolves to an array, on every digest cycle the framework evaluates the expression and sets the isolate scope variable to that value. On each digest cycle, the framework sets the value anew replacing any mutations.

With a variable:

<body ng-controller="IgnorableController" ng-init="x = [1,2]">
    <parent-isolated-scope mutable-array="x"></parent-isolated-scope>
</body>

A reference to the variable is assigned to the isolate scope.

Be aware that any mutations to the contents of the reference will change the contents in both the child isolate scope and the parent scope. This can have unintended consequences for some designs.


问:
HTML entities incorrectly encoding in API call
I am about to use Paxful API method for sending a message to trade:

```<code>String message = "Do NOT PRESS 'Paid' button, until your transfer get 'Success' status.";
paxfulService.sendMessage(tradeId, message);
</code>```

But here is what I see in the browser:

This is my fault, or Paxful API use unnecessary HTML encoding?

答:
The API you are using is re-encoding the single quotes back into their hex values.

In your original message string try using ' in the place of the single quotes you have.

Body:
I am about to use Paxful API method for sending a message to trade:

String message = "Do NOT PRESS 'Paid' button, until your transfer get 'Success' status.";
paxfulService.sendMessage(tradeId, message);

But here is what I see in the browser:

This is my fault, or Paxful API use unnecessary HTML encoding?

Body:
The API you are using is re-encoding the single quotes back into their hex values.

In your original message string try using &#39; in the place of the single quotes you have.


问:
How to merge 2 pdf vector image assets in Swift
I have two vector images. I want to merge them so the dots appear on top of the first image.
The solutions for regular png assets don't work, as they use the actual size of the image, and the combined image comes out very blurry.

One solution that I found was placing a second UIImageView (same size, centred) on top of the first one, but it seems really dumb.

I need to make this inside the app because I also want to have the squared coloured differently (change the tint of the vector), and then merged with the black border image. So I can have 3 assets in my project (square, border and dots).

答:
Figured out a way to do this in an extension to UIImageView. Surprised that I couldn't find this anywhere.</p>

```<code>extension UIImageView {

    func mergeTwoPDF(one: UIImage, two: UIImage) {
        UIGraphicsBeginImageContextWithOptions(self.frame.size, false, UIScreen.main.scale)
        let areaSize = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
        one.draw(in: areaSize, blendMode: .normal, alpha: 1.0)
        two.draw(in: areaSize, blendMode: .normal, alpha: 1.0)
        //If you want to merge more than 2 images, just add them to the func parameters and repeat the line above with them
        let mergedImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        self.image = mergedImage
    }
}
</code>```

Body:
Figured out a way to do this in an extension to UIImageView. Surprised that I couldn't find this anywhere.

extension UIImageView {

    func mergeTwoPDF(one: UIImage, two: UIImage) {
        UIGraphicsBeginImageContextWithOptions(self.frame.size, false, UIScreen.main.scale)
        let areaSize = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
        one.draw(in: areaSize, blendMode: .normal, alpha: 1.0)
        two.draw(in: areaSize, blendMode: .normal, alpha: 1.0)
        //If you want to merge more than 2 images, just add them to the func parameters and repeat the line above with them
        let mergedImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        self.image = mergedImage
    }
}


问:
Ionic React v5: Configure Project to Process Sass/Scss Files
I've create a test application with Ionic v5 w/React and I don't see any specifics in the documentation on how to configure Sass preprocessing. I have a couple sass files in the project structure, but they don't seem to be loading or being processed for that matter. I added node-sass to the package.json. Any help would be much appreciated. I used the Ionic Cli to created a blank app and added some .scss files to the project dir.</p>

答: So I figured it out. Turns that ionic looks at the themes directory for all style sheets, including scss sheets. So I simply place my scss files there, ran ionic serve and imported the base style sheet, import '/theme/styles.scss' into the "main" component and it worked. I could run ionic build command see that the scss files were processed and minified into a .css file.


问:
Looping through multiple pages of a JSON request (Guzzle, Laravel, PHP)
New dev here so I am sorry if this is a simple question or something like that but haven't been able to find exactly what I am looking for (it totally could be that I am not asking the question correctly either) Basically I have a paginated list coming back from an api and I am not sure what the logic would be to be able to cycle through those pages. Here is the code that I have so far that works perfectly for the first page lol.

```<code>    public function handle()
    {
        //This is the artisan command that runs on a timer and gets all the ticket and update fields that are needed and saves them to the database.
        $tickets = $this->pullTicketSummary();
        collect($tickets['data'])
            ->each(function ($currTicket) {

                $ticketRow = Tickets::query()->firstOrCreate(['ticket_id' => $currTicket['id']]);
                $ticketRow->status_id = $currTicket['status']['id'];
                $ticketRow->category_id = $currTicket['category']['id'];
                $ticketRow->user_id = $currTicket['assigned_to']['id'];
                $ticketRow->jira_issue_id = $currTicket['jira_issue_id'];
                $ticketRow->save();

                collect($currTicket['updates'])->each(function ($update) use ($currTicket){
                    $updateRow = Update::query()->firstOrCreate(['update_id' => $update['update_id']]);
                    $updateRow->ticket_id = $currTicket['id'];
                    $updateRow->assignee_change = $update['assignee_change'];
                });
            });
        Log::info('All tickets and updates were pulled successfully');
    }

    protected function pullTicketSummary()
    {       //Function makes the guzzle request and returns the response from the happyfox api
            $client = new Client();
            $request = $client->get('https://happyfox.com/api/1.1/json/tickets/?size=50&page=1',
                ['auth' => ['N/A']);
            $response = json_decode($request->getBody()->getContents(), true);
            return $response;

    }
</code>```

With the fact that I am new if this is something that has been answered before that I missed please just shoot me over a link or if you are aware of any documentation that would help me get to the answer on my own that would be awesome! thanks!

答:
Update your function to use the page number:

```<code>protected function pullTicketSummary($page)
{       //Function makes the guzzle request and returns the response from the happyfox api
        $client = new Client();
        $request = $client->get('https://happyfox.com/api/1.1/json/tickets/?size=50&page='.$page,
            ['auth' => ['N/A']);
        $response = json_decode($request->getBody()->getContents(), true);
        return $response;

}

//new function only to save the data from tickets variable. Necessary to reuse.
public function saveTicketsOrSomething($tickets)
{
    collect($tickets['data'])
        ->each(function ($currTicket) {

            $ticketRow = Tickets::query()->firstOrCreate(['ticket_id' => $currTicket['id']]);
            $ticketRow->status_id = $currTicket['status']['id'];
            $ticketRow->category_id = $currTicket['category']['id'];
            $ticketRow->user_id = $currTicket['assigned_to']['id'];
            $ticketRow->jira_issue_id = $currTicket['jira_issue_id'];
            $ticketRow->save();

            collect($currTicket['updates'])->each(function ($update) use ($currTicket){
                $updateRow = Update::query()->firstOrCreate(['update_id' => $update['update_id']]);
                $updateRow->ticket_id = $currTicket['id'];
                $updateRow->assignee_change = $update['assignee_change'];
            });
        });
}
</code>```

Then iterate until you finish all the pages:

```<code>    $tickets = $this->pullTicketSummary(1); //first time
    $numPages = $tickets['numPages']; //update here to get the actual value of number of pages
    $this->saveTicketsOrSomething($tickets);

    for ($i = 2; $i < $numPages; $i++) { //start on 2, cause we already have fetched page 1
        $tickets = $this->pullTicketSummary($i); //other pages
        $this->saveTicketsOrSomething($tickets);
    }
    Log::info('All tickets and updates were pulled successfully');
</code>```

Body:
New dev here so I am sorry if this is a simple question or something like that but haven't been able to find exactly what I am looking for (it totally could be that I am not asking the question correctly either) Basically I have a paginated list coming back from an api and I am not sure what the logic would be to be able to cycle through those pages. Here is the code that I have so far that works perfectly for the first page lol.

    public function handle()
    {
        //This is the artisan command that runs on a timer and gets all the ticket and update fields that are needed and saves them to the database.
        $tickets = $this->pullTicketSummary();
        collect($tickets['data'])
            ->each(function ($currTicket) {

                $ticketRow = Tickets::query()->firstOrCreate(['ticket_id' => $currTicket['id']]);
                $ticketRow->status_id = $currTicket['status']['id'];
                $ticketRow->category_id = $currTicket['category']['id'];
                $ticketRow->user_id = $currTicket['assigned_to']['id'];
                $ticketRow->jira_issue_id = $currTicket['jira_issue_id'];
                $ticketRow->save();

                collect($currTicket['updates'])->each(function ($update) use ($currTicket){
                    $updateRow = Update::query()->firstOrCreate(['update_id' => $update['update_id']]);
                    $updateRow->ticket_id = $currTicket['id'];
                    $updateRow->assignee_change = $update['assignee_change'];
                });
            });
        Log::info('All tickets and updates were pulled successfully');
    }

    protected function pullTicketSummary()
    {       //Function makes the guzzle request and returns the response from the happyfox api
            $client = new Client();
            $request = $client->get('https://happyfox.com/api/1.1/json/tickets/?size=50&page=1',
                ['auth' => ['N/A']);
            $response = json_decode($request->getBody()->getContents(), true);
            return $response;

    }

With the fact that I am new if this is something that has been answered before that I missed please just shoot me over a link or if you are aware of any documentation that would help me get to the answer on my own that would be awesome! thanks!

Body:
Update your function to use the page number:

protected function pullTicketSummary($page)
{       //Function makes the guzzle request and returns the response from the happyfox api
        $client = new Client();
        $request = $client->get('https://happyfox.com/api/1.1/json/tickets/?size=50&page='.$page,
            ['auth' => ['N/A']);
        $response = json_decode($request->getBody()->getContents(), true);
        return $response;

}

//new function only to save the data from tickets variable. Necessary to reuse.
public function saveTicketsOrSomething($tickets)
{
    collect($tickets['data'])
        ->each(function ($currTicket) {

            $ticketRow = Tickets::query()->firstOrCreate(['ticket_id' => $currTicket['id']]);
            $ticketRow->status_id = $currTicket['status']['id'];
            $ticketRow->category_id = $currTicket['category']['id'];
            $ticketRow->user_id = $currTicket['assigned_to']['id'];
            $ticketRow->jira_issue_id = $currTicket['jira_issue_id'];
            $ticketRow->save();

            collect($currTicket['updates'])->each(function ($update) use ($currTicket){
                $updateRow = Update::query()->firstOrCreate(['update_id' => $update['update_id']]);
                $updateRow->ticket_id = $currTicket['id'];
                $updateRow->assignee_change = $update['assignee_change'];
            });
        });
}

Then iterate until you finish all the pages:

    $tickets = $this->pullTicketSummary(1); //first time
    $numPages = $tickets['numPages']; //update here to get the actual value of number of pages
    $this->saveTicketsOrSomething($tickets);

    for ($i = 2; $i < $numPages; $i++) { //start on 2, cause we already have fetched page 1
        $tickets = $this->pullTicketSummary($i); //other pages
        $this->saveTicketsOrSomething($tickets);
    }
    Log::info('All tickets and updates were pulled successfully');


问:
Python: How to test, if a constructor is called with the right parameters
I have a function in python that creates an isntance of a Projectclass. If there is no data available, a default instance is created. The code in python is similar to this:

def create_project(data):
  try:
    if data:
      return module.Project(data)
    else:
      return DefaultProject()
  except:
    raise Exception("Can't create project.')
```

<p>I want to test, if the constructor of the <code>Project</code> class is called with the right parameter. I already test, if the constructor is called with the following test:</p>

```@mock.patch('module')
def test_create_to_return_created_project(self, module_mock):
    #arrange
    project = mock.MagicMock()
    module_mock.Project = mock.MagicMock(return_value = project)

    #act
    result = module.create_project('some_data')

    #assert
    self.assertEqual(result, project)
```

<p>Now I want to test, if the constructor of the <code>Project</code> class gets the right parameter value with the following code:</p>

```@mock.patch('module')
def test_create_project_with_right_parameter(self, module_mock):
  #arrange
  mockProject = mock.MagicMock()
  module_mock.Project = mockProject

  #act
  module.create_project('some_data')

  #assert
  mockProject.__init__.assert_called('some_data')
```

But the code results in the error:

Message: 'function' object has no attribute 'assert_called'

Does anybody know how to test, if the constructor of the Project class is called with the right parameter?

答:
The assertion you actually want to check is simply at the mock_project, and not the mock_project __init__.

refer to the link: Asserting that __init__ was called with right arguments

Body:
I have a function in python that creates an isntance of a Projectclass. If there is no data available, a default instance is created. The code in python is similar to this:

def create_project(data):
  try:
    if data:
      return module.Project(data)
    else:
      return DefaultProject()
  except:
    raise Exception("Can't create project.')

I want to test, if the constructor of the Project class is called with the right parameter. I already test, if the constructor is called with the following test:

@mock.patch('module')
def test_create_to_return_created_project(self, module_mock):
    #arrange
    project = mock.MagicMock()
    module_mock.Project = mock.MagicMock(return_value = project)

    #act
    result = module.create_project('some_data')

    #assert
    self.assertEqual(result, project)

Now I want to test, if the constructor of the Project class gets the right parameter value with the following code:

@mock.patch('module')
def test_create_project_with_right_parameter(self, module_mock):
  #arrange
  mockProject = mock.MagicMock()
  module_mock.Project = mockProject

  #act
  module.create_project('some_data')

  #assert
  mockProject.__init__.assert_called('some_data')

But the code results in the error:

Message: 'function' object has no attribute 'assert_called'

Does anybody know how to test, if the constructor of the Project class is called with the right parameter?


问:
Access id of first foreach loop in second loop when where condition is met
```<code>$data['customers'] = DB::table('master_customer')->where('ORG_ID', $user_org)->get();//customer table

$document_cat = DB::table('document_category')->get();//category table

foreach ($data['customers'] as $key => $value) {

    foreach ($document_cat as $key1 => $value1) {

        $docs = DB::table('master_documents')//docuements saved in this table
            ->where('cust_id', $value->id)
            ->get();
        $document_cat[$key1]->doc = $docs;

    }

    $data['customers'][$key]->documents = $document_cat;
}

print_r($data);
die;
</code>```

答:
Why you dont update eloquent relationships in models? If you do so it could be much easier.

MasterCustemer Model

```<code>public function masterDocuments()
{
    return $this->hasMany('App\correctfoldertoothermodel\MasterDocument','cust_id');
}

</code>```

MasterDocument Model

```<code>public function masterCustomer()
{
    return $this->belongsTo('App\correctfoldertoothermodel\MasterCustomer','cust_id');
}

public function documentCategory()
{
    return $this->belongsTo('App\correctfoldertoothermodel\DocumentCategory');
}

</code>```

DocumentCategory Model

```<code>public function masterDocuments()
{
    return $this->hasMany('App\correctfoldertoothermodel\MasterDocument');
}

</code>```

Of course you'll have to provide the correct table names in migration for auto implementation of fk or set tables in relationships too.

When it's done you could retrieve data like it:

```<code>$masterCustomers->with('masterDocuments.documentCategory')->get();
$masterCustomers->masterDocuments = $masterCustomers->masterDocuments->groupBy(function($item){
   return $item->documentCategory->name;
});
</code>```

The result will be a collection of customers with and property containing an another collection of categories with its documents.

Body:
Why you dont update eloquent relationships in models? If you do so it could be much easier.

MasterCustemer Model

public function masterDocuments()
{
    return $this->hasMany('App\correctfoldertoothermodel\MasterDocument','cust_id');
}

MasterDocument Model

public function masterCustomer()
{
    return $this->belongsTo('App\correctfoldertoothermodel\MasterCustomer','cust_id');
}

public function documentCategory()
{
    return $this->belongsTo('App\correctfoldertoothermodel\DocumentCategory');
}

DocumentCategory Model

public function masterDocuments()
{
    return $this->hasMany('App\correctfoldertoothermodel\MasterDocument');
}

Of course you'll have to provide the correct table names in migration for auto implementation of fk or set tables in relationships too.

When it's done you could retrieve data like it:

$masterCustomers->with('masterDocuments.documentCategory')->get();
$masterCustomers->masterDocuments = $masterCustomers->masterDocuments->groupBy(function($item){
   return $item->documentCategory->name;
});

The result will be a collection of customers with and property containing an another collection of categories with its documents.


问:
How to center vertically and horizontally a div using Bootstrap?
I have a problem with my CSS. I have a panel form in my index page and I want to move it in the middle of the page vertically and horizontally. But I don't know how to create a CSS for this.

Here's my sample code:

```<code><div class="login_header"></div>

<div class="container" style="text-align: center;">
    <div class="col-md-6 col-md-offset-3">
        <div class="panel_form panel panel-default">
            <div class="panel-content">
                <h1>test</h1>
            </div>
            <div class="panel-footer">
                <p>test</p>
            </div>
        </div>
    </div>
</div>

<footer class="footer"></footer>
</code>```

I have a CSS like this:

```<code>.login_header { min-height: 50px; background-color: #f5f5f5; }

.panel_form {
   /* I don't have an idea with this */
}

.footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 50px;
    background-color: #f5f5f5;
}
</code>```

I am not good enough in CSS that's why I need your help. That's all thanks.. :)

答:
Some of the other answers on this question use CSS hacks with tables and custom CSS classes. As the poster asked "How to center vertically and horizontally using Bootstrap", here is how to do that using only Bootstrap 4 utility classes:

Your Content

```

<p>Something of note is that due to the styling on the parent div, when adding additional elements in the same div, they will appear beside the first one, rather than below it. To fix this, just add an additional div inside the parent to reset the styling.</p>

<pre class="lang-html prettyprint-override"><code><div class="d-flex justify-content-md-center align-items-center vh-100">
    <div>
        <p>Content 1</p>
        <p>Content 2</p>
    </div>
</div>
</code>```

This does work with Bootstrap flex, I've found that it works best when placed inside a flex component like this, rather than wrapping the entire row.

Content 1

Content 2

```

Here is a breakdown of each class:

d-flex: Effectively display: flex, allows the div to grow or shrink depending on the amount of content.

justify-content-md-center: Justifies content in the center of the page, can also be replaced with justify-content-sm-center or justify-content-lg-center to change the breakpoint.

align-items-center: Centers the alignments of all items in a div.

vh-100: Sets the height of the div to 100vh, or 100 "vertical height". This ensures that the div is the correct height to allow for vertical alignment.

Body:
I have a problem with my CSS. I have a panel form in my index page and I want to move it in the middle of the page vertically and horizontally. But I don't know how to create a CSS for this.

Here's my sample code:

test

test

I have a CSS like this:

.login_header { min-height: 50px; background-color: #f5f5f5; }

.panel_form {
   /* I don't have an idea with this */
}

.footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 50px;
    background-color: #f5f5f5;
}

I am not good enough in CSS that's why I need your help. That's all thanks.. :)

Body:
Some of the other answers on this question use CSS hacks with tables and custom CSS classes. As the poster asked "How to center vertically and horizontally using Bootstrap", here is how to do that using only Bootstrap 4 utility classes:

<div class="d-flex justify-content-md-center align-items-center vh-100">
    <p>Your Content</p>
</div>

Something of note is that due to the styling on the parent div, when adding additional elements in the same div, they will appear beside the first one, rather than below it. To fix this, just add an additional div inside the parent to reset the styling.

<div class="d-flex justify-content-md-center align-items-center vh-100">
    <div>
        <p>Content 1</p>
        <p>Content 2</p>
    </div>
</div>

This does work with Bootstrap flex, I've found that it works best when placed inside a flex component like this, rather than wrapping the entire row.

<div class="container">
    <div class="row">
        <div class="col-md-6">
            <div class="d-flex justify-content-md-center align-items-center vh-100">
                 <p>Content 1</p>
            </div>
        </div>
        <div class="col-md-6">
            <div class="d-flex justify-content-md-center align-items-center vh-100">
                 <p>Content 2</p>
            </div>
        </div>
    </div>
</div>

Here is a breakdown of each class:

d-flex: Effectively display: flex, allows the div to grow or shrink depending on the amount of content.

justify-content-md-center: Justifies content in the center of the page, can also be replaced with justify-content-sm-center or justify-content-lg-center to change the breakpoint.

align-items-center: Centers the alignments of all items in a div.

vh-100: Sets the height of the div to 100vh, or 100 "vertical height". This ensures that the div is the correct height to allow for vertical alignment.


问:
How to get the next status for a specific period of time?
I am trying create a query that will add a column called NextStatus to the table whose value will be the Status of end date for specific period of time and a specific ID. The specified period is 18-Jan to 18-Feb. Thus, the NextStatus would be the Status on 18-Feb.

Here is sample of the data:

```<code>As_of_Dt  LoanID    Status
18-Jan  1410010957    C
18-Jan  1410011314    C
18-Feb  1410010957    F
18-Feb  1410011314    R

</code>```

So there would be a new column,

```<code>As_of_Dt  ID        Status   NextStatus
18-Jan   10957    C           F
18-Jan   11314    C           R
18-Feb   10957    F           F
18-Feb   11314    R           R
</code>```

As you can see the NextStatus for ID 10957 would be F and the NextStatus for ID 11314 would be R since on 18-Feb was R.

答:
This sounds like lead():

```<code>select t.*,
       lead(status, 1, status) over (partition by id order by as_of_dt) as nextstatus
from t;
</code>```

This uses the three-argument form of lead().  If there is not "next" row, then the third argument is the default value to return.

Body:
I am trying create a query that will add a column called NextStatus to the table whose value will be the Status of end date for specific period of time and a specific ID. The specified period is 18-Jan to 18-Feb. Thus, the NextStatus would be the Status on 18-Feb.

Here is sample of the data:

As_of_Dt  LoanID    Status
18-Jan  1410010957    C
18-Jan  1410011314    C
18-Feb  1410010957    F
18-Feb  1410011314    R

So there would be a new column,

As_of_Dt  ID        Status   NextStatus
18-Jan   10957    C           F
18-Jan   11314    C           R
18-Feb   10957    F           F
18-Feb   11314    R           R

As you can see the NextStatus for ID 10957 would be F and the NextStatus for ID 11314 would be R since on 18-Feb was R.

Body:
This sounds like lead():

select t.*,
       lead(status, 1, status) over (partition by id order by as_of_dt) as nextstatus
from t;

This uses the three-argument form of lead().  If there is not "next" row, then the third argument is the default value to return.


问:
WIPO search missing form data POST message
i am trying to search trough the WIPO brand register with python, but if i am checking the formdata which got send to the server i don't really understand what this is.

Form Data:

This is the formdata if i am searching for "Lumunu", where come these characters from?

Wipo URL: https://www.wipo.int/branddb/en/

答:
I started in the same way as you and found no solution using the POST method. After much research on Google almost without success I noticed that it is possible to make queries in JSON format directly on the URL. For example, if I am searching for the "alpina" brand, specifying Costa Rica as "country of origin" "CR", Holder Country Colombia "CO", and Goods/Services "leche" (milk in Spanish) you could get the URL like this:

```<code>import requests
url_base = 'http://www.wipo.int/branddb/en/?q='

query = {"searches": [
    {"te":"alpina","fi":"BRAND"},
    {'te': 'CR', "fi": 'OO'},
    {'te': 'CO', "fi": 'HOLC'},
    {"te": "leche", "fi": "GS"}
]}

url = url_base + str(query).replace(" ", "").replace("'", "\"")
print(url)

response = requests.get(URL)
print(response.status_code)

response.content
</code>```

I have not been able to find documentation, what I have achieved has been trial and error, but it works.

Body:
I started in the same way as you and found no solution using the POST method. After much research on Google almost without success I noticed that it is possible to make queries in JSON format directly on the URL. For example, if I am searching for the "alpina" brand, specifying Costa Rica as "country of origin" "CR", Holder Country Colombia "CO", and Goods/Services "leche" (milk in Spanish) you could get the URL like this:

import requests
url_base = 'http://www.wipo.int/branddb/en/?q='

query = {"searches": [
    {"te":"alpina","fi":"BRAND"},
    {'te': 'CR', "fi": 'OO'},
    {'te': 'CO', "fi": 'HOLC'},
    {"te": "leche", "fi": "GS"}
]}

url = url_base + str(query).replace(" ", "").replace("'", "\"")
print(url)

response = requests.get(URL)
print(response.status_code)

response.content

I have not been able to find documentation, what I have achieved has been trial and error, but it works.


问:
SQLite Getting multiple results with LIMIT 1
I have the following problem.

Part of a task is to determine the visitor(s) with the most money spent between 2000 and 2020.
It just looks like this.

```<code>SELECT UserEMail FROM Visitor
JOIN Ticket ON Visitor.UserEMail = Ticket.VisitorUserEMail
where Ticket.Date> date('2000-01-01') AND Ticket.Date < date ('2020-12-31')
Group by Ticket.VisitorUserEMail
order by SUM(Price) DESC;
</code>```

Is it possible to output more than one person if both have spent the same amount?

答:
Use a CTE that returns all the total prices for each email and with NOT EXISTS select the rows with the top total price:

```<code>WITH cte AS (
  SELECT VisitorUserEMail, SUM(Price) SumPrice
  FROM Ticket
  WHERE Date >= '2000-01-01' AND Date <= '2020-12-31'
  GROUP BY VisitorUserEMail
)
SELECT c.VisitorUserEMail
FROM cte c
WHERE NOT EXISTS (
  SELECT 1 FROM cte
  WHERE SumPrice > c.SumPrice
)
</code>```

or:

```<code>WITH cte AS (
  SELECT VisitorUserEMail, SUM(Price) SumPrice
  FROM Ticket
  WHERE Date >= '2000-01-01' AND Date <= '2020-12-31'
  GROUP BY VisitorUserEMail
)
SELECT VisitorUserEMail
FROM cte
WHERE SumPrice = (SELECT MAX(SumPrice) FROM cte)
</code>```

Note that you don't need the function date() because the result of date('2000-01-01') is '2000-01-01'.

Also I think that the conditions in the WHERE clause should include the =, right?

Body:
I have the following problem.

Part of a task is to determine the visitor(s) with the most money spent between 2000 and 2020.
It just looks like this.

SELECT UserEMail FROM Visitor
JOIN Ticket ON Visitor.UserEMail = Ticket.VisitorUserEMail
where Ticket.Date> date('2000-01-01') AND Ticket.Date < date ('2020-12-31')
Group by Ticket.VisitorUserEMail
order by SUM(Price) DESC;

Is it possible to output more than one person if both have spent the same amount?

Body:
Use a CTE that returns all the total prices for each email and with NOT EXISTS select the rows with the top total price:

WITH cte AS (
  SELECT VisitorUserEMail, SUM(Price) SumPrice
  FROM Ticket
  WHERE Date >= '2000-01-01' AND Date <= '2020-12-31'
  GROUP BY VisitorUserEMail
)
SELECT c.VisitorUserEMail
FROM cte c
WHERE NOT EXISTS (
  SELECT 1 FROM cte
  WHERE SumPrice > c.SumPrice
)

or:

WITH cte AS (
  SELECT VisitorUserEMail, SUM(Price) SumPrice
  FROM Ticket
  WHERE Date >= '2000-01-01' AND Date <= '2020-12-31'
  GROUP BY VisitorUserEMail
)
SELECT VisitorUserEMail
FROM cte
WHERE SumPrice = (SELECT MAX(SumPrice) FROM cte)

Note that you don't need the function date() because the result of date('2000-01-01') is '2000-01-01'.

Also I think that the conditions in the WHERE clause should include the =, right?