问:
Exception opening socket - MongoDB, Docker
I have Maven Multi-Module application(Spring Boot + MySql + MongoDB) with using docker image, but i can't get connection to MongoDB.

Thing is when local mongo instance "MongoDB Server on Windows Services"  is turned on and use spring.data.mongodb.host=localhost all is working fine.

But when I turn off mongo instance and try to go with:
spring.data.mongodb.host=$(MONGO_HOST) to use it with docker I'm getting error "Exception opening socket"

I start my application with execute command:
mvn install and tryed with docker-compose up --build

console

```<code>  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.5.1)

2021-09-25 12:19:22.635  INFO 8588 --- [           main] c.o.o.n.controller.NoteControllerTest    : Starting NoteControllerTest using Java 16.0.1 on AntonioPC with PID 8588 (started by ajago in D:\Programming\Eclipse-workspace\OC_Project10\Notes)
2021-09-25 12:19:22.642  INFO 8588 --- [           main] c.o.o.n.controller.NoteControllerTest    : No active profile set, falling back to default profiles: default
2021-09-25 12:19:23.776  INFO 8588 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2021-09-25 12:19:23.777  INFO 8588 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-09-25 12:19:23.824  INFO 8588 --- [           main] .RepositoryConfigurationExtensionSupport : Spring Data JPA - Could not safely identify store assignment for repository candidate interface com.openclassrooms.ocproject10.notes.repository.NoteRepository. If you want this repository to be a JPA repository, consider annotating your entities with one of these annotations: javax.persistence.Entity, javax.persistence.MappedSuperclass (preferred), or consider extending one of the following types with your repository: org.springframework.data.jpa.repository.JpaRepository.
2021-09-25 12:19:23.826  INFO 8588 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 36 ms. Found 0 JPA repository interfaces.
2021-09-25 12:19:24.093  INFO 8588 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2021-09-25 12:19:24.094  INFO 8588 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data MongoDB repositories in DEFAULT mode.
2021-09-25 12:19:24.126  INFO 8588 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 31 ms. Found 1 MongoDB repository interfaces.
2021-09-25 12:19:24.876  INFO 8588 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2021-09-25 12:19:25.458  INFO 8588 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2021-09-25 12:19:25.596  INFO 8588 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-09-25 12:19:25.685  INFO 8588 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.4.32.Final
2021-09-25 12:19:25.882  INFO 8588 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-09-25 12:19:26.112  INFO 8588 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2021-09-25 12:19:27.051  INFO 8588 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-09-25 12:19:27.065  INFO 8588 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-09-25 12:19:27.486  INFO 8588 --- [           main] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms'}
2021-09-25 12:19:27.586  INFO 8588 --- [localhost:27017] org.mongodb.driver.cluster               : Exception in monitor thread while connecting to server localhost:27017

com.mongodb.MongoSocketOpenException: Exception opening socket
        at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:70) ~[mongodb-driver-core-4.2.3.jar:na]
        at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:143) ~[mongodb-driver-core-4.2.3.jar:na]
        at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.lookupServerDescription(DefaultServerMonitor.java:188) ~[mongodb-driver-core-4.2.3.jar:na]
        at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:144) ~[mongodb-driver-core-4.2.3.jar:na]
        at java.base/java.lang.Thread.run(Thread.java:831) ~[na:na]
Caused by: java.net.ConnectException: Connection refused: no further information
        at java.base/sun.nio.ch.Net.pollConnect(Native Method) ~[na:na]
        at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:669) ~[na:na]
        at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:542) ~[na:na]
        at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597) ~[na:na]
        at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:333) ~[na:na]
        at java.base/java.net.Socket.connect(Socket.java:645) ~[na:na]
        at com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:107) ~[mongodb-driver-core-4.2.3.jar:na]
        at com.mongodb.internal.connection.SocketStream.initializeSocket(SocketStream.java:79) ~[mongodb-driver-core-4.2.3.jar:na]
        at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:65) ~[mongodb-driver-core-4.2.3.jar:na]
        ... 4 common frames omitted

2021-09-25 12:19:28.302  WARN 8588 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2021-09-25 12:19:28.988  INFO 8588 --- [           main] o.s.b.t.m.w.SpringBootMockServletContext : Initializing Spring TestDispatcherServlet ''
2021-09-25 12:19:28.988  INFO 8588 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : Initializing Servlet ''
2021-09-25 12:19:28.990  INFO 8588 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : Completed initialization in 2 ms
2021-09-25 12:19:29.018  INFO 8588 --- [           main] c.o.o.n.controller.NoteControllerTest    : Started NoteControllerTest in 7.33 seconds (JVM running for 9.77)
2021-09-25 12:19:29.380  INFO 8588 --- [           main] org.mongodb.driver.cluster               : Cluster description not yet available. Waiting for 30000 ms before timing out
</code>```

docker-compose.yml

```<code>version: '2'

services:
  reports:
    image: 'reports:latest'
    build:
      context: ./reports
    container_name: reports
    ports:
      - 8080:8080
    environment:
      - PATIENTS_URL=http://gps:8081
      - NOTES_URL=http://rewards:8082

  patients:
    image: 'patients:latest'
    build:
      context: ./patients
    container_name: patients
    ports:
      - 8081:8081
    environment:
      - MYSQL_HOST=db-mysql
    depends_on:
      - db-mysql

  notes:
    image: 'notes:latest'
    build:
      context: ./notes
    container_name: notes
    ports:
      - 8082:8082
    environment:
      - MONGO_HOST=mongodb
    depends_on:
      - mongodb

  db-mysql:
    image: mysql:latest
    container_name: mysql
    ports:
        - 3306:3306
    command: --innodb --init-file /data/application/init.sql
    volumes:
        - ./init.sql:/data/application/init.sql
    environment:
        MYSQL_DATABASE: project_10
        MYSQL_ROOT_USER: root
        MYSQL_ROOT_PASSWORD: Musapa1990..

  mongodb:
    image: mongo:latest
    container_name: mongodb
    network_mode: host
    restart: always
    ports:
        - 27017:27017
    environment:
        MONGO_INITDB_DATABASE: project_10
</code>```

application.properties

```<code># App config
logging.level.org.springframework=INFO
spring.application.name=P10_notes
server.port=8082

################### MongoDB Configuration ##########################
spring.data.mongodb.database=project_10
spring.data.mongodb.port=27017
#spring.data.mongodb.host=localhost
spring.data.mongodb.host=$(MONGO_HOST)
spring.data.mongodb.authentication-database=admin

# thymeleaf configurations for Auto reload Thymeleaf templates without restart
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=file:src/main/resources/templates/
</code>```

I read similar articles here and tried different things, but nothing helped me.

答:
If that not work then you can try that

change localhost and 127.0.0.1  it worked for me
like this

```<code>#spring.data.mongodb.host=localhost
spring.data.mongodb.host=127.0.0.1
</code>```

Body:
I have Maven Multi-Module application(Spring Boot + MySql + MongoDB) with using docker image, but i can't get connection to MongoDB.

Thing is when local mongo instance "MongoDB Server on Windows Services"  is turned on and use spring.data.mongodb.host=localhost all is working fine.

But when I turn off mongo instance and try to go with:
spring.data.mongodb.host=$(MONGO_HOST) to use it with docker I'm getting error "Exception opening socket"

I start my application with execute command:
mvn install and tryed with docker-compose up --build

console

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.5.1)

2021-09-25 12:19:22.635  INFO 8588 --- [           main] c.o.o.n.controller.NoteControllerTest    : Starting NoteControllerTest using Java 16.0.1 on AntonioPC with PID 8588 (started by ajago in D:\Programming\Eclipse-workspace\OC_Project10\Notes)
2021-09-25 12:19:22.642  INFO 8588 --- [           main] c.o.o.n.controller.NoteControllerTest    : No active profile set, falling back to default profiles: default
2021-09-25 12:19:23.776  INFO 8588 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2021-09-25 12:19:23.777  INFO 8588 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-09-25 12:19:23.824  INFO 8588 --- [           main] .RepositoryConfigurationExtensionSupport : Spring Data JPA - Could not safely identify store assignment for repository candidate interface com.openclassrooms.ocproject10.notes.repository.NoteRepository. If you want this repository to be a JPA repository, consider annotating your entities with one of these annotations: javax.persistence.Entity, javax.persistence.MappedSuperclass (preferred), or consider extending one of the following types with your repository: org.springframework.data.jpa.repository.JpaRepository.
2021-09-25 12:19:23.826  INFO 8588 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 36 ms. Found 0 JPA repository interfaces.
2021-09-25 12:19:24.093  INFO 8588 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2021-09-25 12:19:24.094  INFO 8588 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data MongoDB repositories in DEFAULT mode.
2021-09-25 12:19:24.126  INFO 8588 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 31 ms. Found 1 MongoDB repository interfaces.
2021-09-25 12:19:24.876  INFO 8588 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2021-09-25 12:19:25.458  INFO 8588 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2021-09-25 12:19:25.596  INFO 8588 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-09-25 12:19:25.685  INFO 8588 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.4.32.Final
2021-09-25 12:19:25.882  INFO 8588 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-09-25 12:19:26.112  INFO 8588 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2021-09-25 12:19:27.051  INFO 8588 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-09-25 12:19:27.065  INFO 8588 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-09-25 12:19:27.486  INFO 8588 --- [           main] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms'}
2021-09-25 12:19:27.586  INFO 8588 --- [localhost:27017] org.mongodb.driver.cluster               : Exception in monitor thread while connecting to server localhost:27017

com.mongodb.MongoSocketOpenException: Exception opening socket
        at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:70) ~[mongodb-driver-core-4.2.3.jar:na]
        at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:143) ~[mongodb-driver-core-4.2.3.jar:na]
        at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.lookupServerDescription(DefaultServerMonitor.java:188) ~[mongodb-driver-core-4.2.3.jar:na]
        at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:144) ~[mongodb-driver-core-4.2.3.jar:na]
        at java.base/java.lang.Thread.run(Thread.java:831) ~[na:na]
Caused by: java.net.ConnectException: Connection refused: no further information
        at java.base/sun.nio.ch.Net.pollConnect(Native Method) ~[na:na]
        at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:669) ~[na:na]
        at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:542) ~[na:na]
        at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597) ~[na:na]
        at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:333) ~[na:na]
        at java.base/java.net.Socket.connect(Socket.java:645) ~[na:na]
        at com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:107) ~[mongodb-driver-core-4.2.3.jar:na]
        at com.mongodb.internal.connection.SocketStream.initializeSocket(SocketStream.java:79) ~[mongodb-driver-core-4.2.3.jar:na]
        at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:65) ~[mongodb-driver-core-4.2.3.jar:na]
        ... 4 common frames omitted

2021-09-25 12:19:28.302  WARN 8588 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2021-09-25 12:19:28.988  INFO 8588 --- [           main] o.s.b.t.m.w.SpringBootMockServletContext : Initializing Spring TestDispatcherServlet ''
2021-09-25 12:19:28.988  INFO 8588 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : Initializing Servlet ''
2021-09-25 12:19:28.990  INFO 8588 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : Completed initialization in 2 ms
2021-09-25 12:19:29.018  INFO 8588 --- [           main] c.o.o.n.controller.NoteControllerTest    : Started NoteControllerTest in 7.33 seconds (JVM running for 9.77)
2021-09-25 12:19:29.380  INFO 8588 --- [           main] org.mongodb.driver.cluster               : Cluster description not yet available. Waiting for 30000 ms before timing out

docker-compose.yml

version: '2'

services:
  reports:
    image: 'reports:latest'
    build:
      context: ./reports
    container_name: reports
    ports:
      - 8080:8080
    environment:
      - PATIENTS_URL=http://gps:8081
      - NOTES_URL=http://rewards:8082

  patients:
    image: 'patients:latest'
    build:
      context: ./patients
    container_name: patients
    ports:
      - 8081:8081
    environment:
      - MYSQL_HOST=db-mysql
    depends_on:
      - db-mysql

  notes:
    image: 'notes:latest'
    build:
      context: ./notes
    container_name: notes
    ports:
      - 8082:8082
    environment:
      - MONGO_HOST=mongodb
    depends_on:
      - mongodb

  db-mysql:
    image: mysql:latest
    container_name: mysql
    ports:
        - 3306:3306
    command: --innodb --init-file /data/application/init.sql
    volumes:
        - ./init.sql:/data/application/init.sql
    environment:
        MYSQL_DATABASE: project_10
        MYSQL_ROOT_USER: root
        MYSQL_ROOT_PASSWORD: Musapa1990..

  mongodb:
    image: mongo:latest
    container_name: mongodb
    network_mode: host
    restart: always
    ports:
        - 27017:27017
    environment:
        MONGO_INITDB_DATABASE: project_10

application.properties

# App config
logging.level.org.springframework=INFO
spring.application.name=P10_notes
server.port=8082

################### MongoDB Configuration ##########################
spring.data.mongodb.database=project_10
spring.data.mongodb.port=27017
#spring.data.mongodb.host=localhost
spring.data.mongodb.host=$(MONGO_HOST)
spring.data.mongodb.authentication-database=admin

# thymeleaf configurations for Auto reload Thymeleaf templates without restart
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=file:src/main/resources/templates/

I read similar articles here and tried different things, but nothing helped me.

Body:
If that not work then you can try that

change localhost and 127.0.0.1  it worked for me
like this

#spring.data.mongodb.host=localhost
spring.data.mongodb.host=127.0.0.1


来源: stackexchange

问:
rules with temporary objects and args by reference
say I have a class:

```<code>class A
{
 public:
 A() {}
};
</code>```

and a function:

```<code>void x(const A & s) {}
</code>```

and I do:

```<code>x(A());
</code>```

could someone please explain to me the rules regarding passing temporary objects by reference? In terms of what the compiler allows, where you need const, if an implicit copy happens, etc. From playing around, it seems like you need the const which makes sense, but is there a formal rule regarding all this?

Thanks!

答: Herb Sutter does a fine job explaining it here: http://www.gotw.ca/gotw/081.htm</p>

OwnerDisplayName: Steve

ContentLicense: CC BY-SA 2.5

Body:
say I have a class:

class A
{
 public:
 A() {}
};

and a function:

void x(const A & s) {}

and I do:

x(A());

could someone please explain to me the rules regarding passing temporary objects by reference? In terms of what the compiler allows, where you need const, if an implicit copy happens, etc. From playing around, it seems like you need the const which makes sense, but is there a formal rule regarding all this?

Thanks!

OwnerDisplayName: Sasha

LastEditorDisplayName: Rich B


问:
Threaded ListView for Android
I'm working on an app that involves displaying comments from a website.  These comments are threaded on the original site, so I'd like to replicate that experience within the app.  I know that Android has an ExpandableListView, but it only does two levels and I was hoping for more.

Each top-level content would be aligned to the left.  Replies would be indented by x units, replies to the reply would be indented x*2 units, etc.

Additionally, I'd like the ability for the user (or even the application code) to minimize/maximize threads.  This would be particularly useful if the first comment has 8724 replies - you could just minimize the original comment instead of scrolling endlessly until you reach the second top-level comment.

What is the best way to present this multi-level list to the user?  Are there any native/third-party classes/libraries I can use, or would I be better of coding this list in HTML and displaying that to the user instead?

答:
I don't really think you should use a tree for displaying thread. Device screens are too small for this kind of widget. I would prefer multiple activities for displaying different levels of the thread. But I'm not a UI designer so my opinion may be far from the ideal solution.

EDIT: Here's an open-source tree-view widget: http://code.google.com/p/tree-view-list-android/.

ContentLicense: CC BY-SA 3.0

Title: Threaded ListView for Android


问:
PG::ConnectionBad Sidekiq could not translate host name
We are getting a lot of sentries issue with PG:ConnectionBad on Postgres in RDS AWS and Ruby on Rails

```<code>PG::ConnectionBad Sidekiq/BookingExtensionCheckWorker

could not translate host name “ls-XXXXXXXXXXXXfee44.XXXXXXXXX.eu-west-1.rds.amazonaws.com” to address: Name or service not known
</code>```

In two weeks ago, we have migrate a new database and we change endpoint in the RoR files api

new database endpoint,

```<code>ls-XXXXXXXXXXXXXXXf3d4a.XXXXXXXX.eu-west-1.rds.amazonaws.com
</code>```

It working fine with no issue between the new database and Ruby on Rails api. however, I get a lot of sentries issue said that sidekiq having an issue with connection database as they use old database address which it’s no longer used. I have to check sidekiq database; the code shows it’s connected to the new database. They keep go back to the old database when I run Ruby on rails.

Is there some way to find why sidekiq keep connection old database

答:
Sidekiq is background service. So when someone deployed he has used some sort of like. Right now you are getting issue you think is fine but actually most jobs are not running. Which you will noticed in few days.

How can you check jobs If you sidekiq setup. Probably following url will lead to all jobs.

```<code>your_url/sidekiq
</code>```

It will show you all jobs, I think you have option here to restart services. Just click to restart sidekiq. And everything would be fine.

How to start

As your sidekiq running with old configuration. So following steps could be dangrous, I think you must check how you have started your process. Otherwise following are some way people configure it and runt it.

```<code>systemctl restart sidekiq
</code>```

If this does not work, check your command your deployment guy has setup some sort of scripts inside /etc/init.d folder
Some time developer use following simple line to run sidekiq

```<code>bundle exec sidekiq -d -P tmp/sidekiq.pid -L log/sidekiq.log
</code>```

or

```<code>bundle exec sidekiqctl stop
</code>```

ContentLicense: CC BY-SA 4.0

Body:
We are getting a lot of sentries issue with PG:ConnectionBad on Postgres in RDS AWS and Ruby on Rails

PG::ConnectionBad Sidekiq/BookingExtensionCheckWorker

could not translate host name “ls-XXXXXXXXXXXXfee44.XXXXXXXXX.eu-west-1.rds.amazonaws.com” to address: Name or service not known

In two weeks ago, we have migrate a new database and we change endpoint in the RoR files api

new database endpoint,

ls-XXXXXXXXXXXXXXXf3d4a.XXXXXXXX.eu-west-1.rds.amazonaws.com

It working fine with no issue between the new database and Ruby on Rails api. however, I get a lot of sentries issue said that sidekiq having an issue with connection database as they use old database address which it’s no longer used. I have to check sidekiq database; the code shows it’s connected to the new database. They keep go back to the old database when I run Ruby on rails.

Is there some way to find why sidekiq keep connection old database

Body:
Sidekiq is background service. So when someone deployed he has used some sort of like. Right now you are getting issue you think is fine but actually most jobs are not running. Which you will noticed in few days.

How can you check jobs If you sidekiq setup. Probably following url will lead to all jobs.

your_url/sidekiq

It will show you all jobs, I think you have option here to restart services. Just click to restart sidekiq. And everything would be fine.

How to start

As your sidekiq running with old configuration. So following steps could be dangrous, I think you must check how you have started your process. Otherwise following are some way people configure it and runt it.

systemctl restart sidekiq

If this does not work, check your command your deployment guy has setup some sort of scripts inside /etc/init.d folder
Some time developer use following simple line to run sidekiq

bundle exec sidekiq -d -P tmp/sidekiq.pid -L log/sidekiq.log

or

bundle exec sidekiqctl stop


问:
How do you conditionally add a character string to certain values in a column?
I found that leading 0s had dropped from my data set at some point. Maybe someone had opened a CSV file and the leading 0s had fallen off or the data had been read in as an integer and the 0s had been removed. I'd been expecting all my ids to be 5 characters long and noticed an issue when some of them weren't.

TLDR: How do you conditionally add a string onto observations in a column?

Body:
v <- c(1, 11, 111, 1111, 11111)

sprintf("%05d", v)

# [1] "00001" "00011" "00111" "01111" "11111"


问:
deal with illegal move on Reinforcment Learning
I'm trying to create an agent to play 'nim' game.

(numbers are the 'id' associated to each links)

I created a gym env.

My observation space is:
Box(0,2, shape=(,144)) of type integer.

There are 144 possible links

0 = no link

1 = link connected by us

2 = link connected by opponent

My action space is:
Discrete(144)
We chose the number of the link to connect.

At the beginning all 144 link are possible to connect
And as the game goes on, links are connected and we can't play on a connected link.

My rewards are:

+100 if we connect a link

-1000 if opponent close a box

+1000 if we close a box

-10000 if opponent win the game

+10000 if we win the game

-100000000 if we make an inegal move

here is the code I use to train my agent :

```<code>env = DotsAndBoxesEnv()
state = env.reset()
model = A2C('MlpPolicy', env, verbose=1, tensorboard_log=logPath)
model.learn(total_timesteps=1000000)
</code>```

the problem is that the agent use to play only illegal moves when I train it.
to be more precise, he play the same number over and over.

How could I improve his training ?

答:
I had a similar problem in my custom multiplayer environment. What seemed to be the reason was that the opponent my agent was training against was an RNG, basically, which just chooses a random legal move. My guess is that random moves from the opponent give too little info for training and the nnet can't just figure out how to move.

What solved the problem for me was my decision to make the opponent a MiniMax algorithm, so it has at least some logic behind its behavior. That seemed to solve the issue with nnet choosing illegal moves after just 10 minutes of training.

Body:
I'm trying to create an agent to play 'nim' game.

(numbers are the 'id' associated to each links)

I created a gym env.

My observation space is:
Box(0,2, shape=(,144)) of type integer.

There are 144 possible links

0 = no link

1 = link connected by us

2 = link connected by opponent

My action space is:
Discrete(144)
We chose the number of the link to connect.

At the beginning all 144 link are possible to connect
And as the game goes on, links are connected and we can't play on a connected link.

My rewards are:

+100 if we connect a link

-1000 if opponent close a box

+1000 if we close a box

-10000 if opponent win the game

+10000 if we win the game

-100000000 if we make an inegal move

here is the code I use to train my agent :

env = DotsAndBoxesEnv()
state = env.reset()
model = A2C('MlpPolicy', env, verbose=1, tensorboard_log=logPath)
model.learn(total_timesteps=1000000)

the problem is that the agent use to play only illegal moves when I train it.
to be more precise, he play the same number over and over.

How could I improve his training ?


问:
Redux Saga authentication with router 6
I am porting an application from Router v2 to Router v6.

I am attempting to get authentication to work.

This bit of code gets hit when the user hits login

    sendLoginRequest(event) {

        // Prevent the page from unloading from the form submit
        event.preventDefault();

        // Don't do anything if the form is not valid
        if (!this.isFormValid()) {
            return;
        }

        // Make the request to the server to login
        this.props.login({
            emailAddress: this.state.emailAddress,
            password: this.state.password,
            onLoginSuccess: () => {
                ReactGA.event({
                    category: 'Login',
                    action: 'success',
                    label: 'From Login Page'
                });

                // Login was successful, send the user to the main page
                this.props.navigate('/');
            },
            onLoginFailure: (error) => {
                ReactGA.event({
                    category: 'Login',
                    action: 'failure',
                    label: 'From Login Page'
                });
                // Set an error message depending on the type of error
                this.setErrorMessage(error);
            }
        });
    }
```
<p>mapDisptachToProps</p>
<pre class="lang-js prettyprint-override"><code>    static mapDispatchToProps(dispatch) {
        return {
            login: (options) => dispatch({type: LOGIN, ...options}),
            getSettings: () => dispatch({type: GET_SETTINGS})
        };
    }
</code>```

It gets to this.props.login, and goes through the reducers, as I would expect.

However, none of the reducers I have match the above layout with the exception of the below, which exists in the sagas\authenticator.js

function* login() {
  while (true) {
    const {emailAddress, password, onLoginSuccess, onLoginFailure} = yield take(actions.LOGIN);

    try {

      // Make the request to login only if the user is not currently logged in
      const isLoggedIn = yield select(_isLoggedIn);
      if (!isLoggedIn) {
        yield call(actions.login, emailAddress, password);
        yield put({type: actions.GET_PROFILE});

        // Call the success callback if one is provided
        if (onLoginSuccess) {
          onLoginSuccess();
        }
      }
    } catch (error) {

      // Call the failure callback if one is provided
      if (onLoginFailure) {
        onLoginFailure(error);
      }
    }
  }
}
```

This contains some sort of reference to the above code blocks calls, this also however never gets hit.

What am I missing here? I get no errors of any kind, just a lack of functionality.

答:
What I needed to do in this scenario was ensure my fork strategy for Redux was changed from

export default function* root() {
    yield [
        fork(login),
        fork(logout),
        fork(isLoggedIn),
        fork(getProfile),
        fork(forgotPassword),
        fork(resetPassword)
    ];
}
```
<p>to</p>
<pre class="lang-js prettyprint-override"><code>export default function* root() {
    yield fork(login);
    yield fork(logout);
    yield fork(isLoggedIn);
    yield fork(getProfile);
    yield fork(forgotPassword);
    yield fork(resetPassword);
}
</code>```

and now the proper bit of code is being called and the API is being hit.

However I am unsure if this has other implications I'm perhaps unaware of, and will update this post when I learn more.

Title: Redux Saga authentication with router 6

Body:
I am porting an application from Router v2 to Router v6.

I am attempting to get authentication to work.

This bit of code gets hit when the user hits login

    sendLoginRequest(event) {

        // Prevent the page from unloading from the form submit
        event.preventDefault();

        // Don't do anything if the form is not valid
        if (!this.isFormValid()) {
            return;
        }

        // Make the request to the server to login
        this.props.login({
            emailAddress: this.state.emailAddress,
            password: this.state.password,
            onLoginSuccess: () => {
                ReactGA.event({
                    category: 'Login',
                    action: 'success',
                    label: 'From Login Page'
                });

                // Login was successful, send the user to the main page
                this.props.navigate('/');
            },
            onLoginFailure: (error) => {
                ReactGA.event({
                    category: 'Login',
                    action: 'failure',
                    label: 'From Login Page'
                });
                // Set an error message depending on the type of error
                this.setErrorMessage(error);
            }
        });
    }

mapDisptachToProps

    static mapDispatchToProps(dispatch) {
        return {
            login: (options) => dispatch({type: LOGIN, ...options}),
            getSettings: () => dispatch({type: GET_SETTINGS})
        };
    }

It gets to this.props.login, and goes through the reducers, as I would expect.

However, none of the reducers I have match the above layout with the exception of the below, which exists in the sagas\authenticator.js

function* login() {
  while (true) {
    const {emailAddress, password, onLoginSuccess, onLoginFailure} = yield take(actions.LOGIN);

    try {

      // Make the request to login only if the user is not currently logged in
      const isLoggedIn = yield select(_isLoggedIn);
      if (!isLoggedIn) {
        yield call(actions.login, emailAddress, password);
        yield put({type: actions.GET_PROFILE});

        // Call the success callback if one is provided
        if (onLoginSuccess) {
          onLoginSuccess();
        }
      }
    } catch (error) {

      // Call the failure callback if one is provided
      if (onLoginFailure) {
        onLoginFailure(error);
      }
    }
  }
}

This contains some sort of reference to the above code blocks calls, this also however never gets hit.

What am I missing here? I get no errors of any kind, just a lack of functionality.

Body:
What I needed to do in this scenario was ensure my fork strategy for Redux was changed from

export default function* root() {
    yield [
        fork(login),
        fork(logout),
        fork(isLoggedIn),
        fork(getProfile),
        fork(forgotPassword),
        fork(resetPassword)
    ];
}

to

export default function* root() {
    yield fork(login);
    yield fork(logout);
    yield fork(isLoggedIn);
    yield fork(getProfile);
    yield fork(forgotPassword);
    yield fork(resetPassword);
}

and now the proper bit of code is being called and the API is being hit.

However I am unsure if this has other implications I'm perhaps unaware of, and will update this post when I learn more.


问:
How to adjust Material UI Tooltip font size?
I implemented a tooltip with Material UI but the fontSize is too small. And I can't change it with a .scss.

import React from "react";
import "./InfoTooltip.scss";
import InfoIcon from '@material-ui/icons/Info';
import Tooltip from '@material-ui/core/Tooltip';

const InfoTooltip: React.FC<{ children?: any }> = ({ children }) => {
  const [label, ...rest] = children;
  return (

        <Tooltip title={label}>
          <InfoIcon style={{ fontSize: '24px' }} />
        </Tooltip>

      {rest}

  );
};

export default InfoTooltip;
```
<pre class="lang-css prettyprint-override"><code>.info-tooltip-container {
  .label-container {
    font-size: 18px;
  }
  label {
    font-size: 18px;
  }
}
</code>```

https://mui.com/material-ui/react-tooltip/

答:
Using MUI v5

This will change the font size for all tooltips within <ThemeProvider>

```<code>import React from "react";
import { createTheme, CssBaseline, ThemeProvider } from '@mui/material';

const theme = createTheme({
    components: {
        MuiTooltip: {
            styleOverrides: {
                tooltip: {
                    fontSize: '1em'
                }
            }
        }
    }
});

export default function App() {
    return <ThemeProvider theme={theme}>
        {/* Your app content */}
        <CssBaseline />
    </ThemeProvider>;
}
</code>```

Body:
I implemented a tooltip with Material UI but the fontSize is too small. And I can't change it with a .scss.

import React from "react";
import "./InfoTooltip.scss";
import InfoIcon from '@material-ui/icons/Info';
import Tooltip from '@material-ui/core/Tooltip';

const InfoTooltip: React.FC<{ children?: any }> = ({ children }) => {
  const [label, ...rest] = children;
  return (

        <Tooltip title={label}>
          <InfoIcon style={{ fontSize: '24px' }} />
        </Tooltip>

      {rest}

  );
};

export default InfoTooltip;

.info-tooltip-container {
  .label-container {
    font-size: 18px;
  }
  label {
    font-size: 18px;
  }
}

https://mui.com/material-ui/react-tooltip/

Body:
Using MUI v5

This will change the font size for all tooltips within <ThemeProvider>

import React from "react";
import { createTheme, CssBaseline, ThemeProvider } from '@mui/material';

const theme = createTheme({
    components: {
        MuiTooltip: {
            styleOverrides: {
                tooltip: {
                    fontSize: '1em'
                }
            }
        }
    }
});

export default function App() {
    return <ThemeProvider theme={theme}>
        {/* Your app content */}
        <CssBaseline />
    </ThemeProvider>;
}


问:
Docker bind user file ownership
It was provided to me an image that run a service with the root user.

I have the need to bind mount a directory where the service running in the container must create files that will be used as input files of another non-containerized service.

The problem is well know: the generated files keep UID and GID from the in-container user.

So, I tried with this config:

```<code>  myservice:
    image: "someonewho/liketorunwithroot: latest"
    user: "${UID}:${GID}"
    volumes:
       - type: bind
         source: /home/user/output
         target: /service/path/outputdir
       - type: bind
         source: /etc/passwd
         target: /etc/passwd
       - type: bind
         source: /etc/group
         target: /etc/group
    ports:
      - "80:80"
</code>```

doing like this, I can force the in-container user to use uid and gid that are the same of the user on the docker host, so I have no problem at all with the files generated under /service/path/outputdir.

But in this way the service is not working anymore, because the user with those ID can't read and write in other folders.

So I tried with the user namespace, forcing the range of subuid to one specif id (the same of the docker host user)

In this case I get this error:

docker: failed to register layer: Error processing tar file (exit status 1): Container ID 100 cannot be mapped to a host ID.

I can't manipulate the Dockerfile, nor the container, because it must be "portable".

Is there a solution?

答:
you should consider using docker volumes for storing the files, you can always backup, restore or migrate the data

  myservice:
    image: "someonewho/liketorunwithroot: latest"
    volumes:
       - output:/service/path/outputdir
    ports:
      - "80:80"
  volumes:
    output:
```
<p>and you get get the volume name with</p>
<pre class="lang-sh prettyprint-override"><code>docker volume ls --format '{{json .}}' | jq -r '.Name' | grep "$(basename $PWD)_output"
</code>```

Title: Docker bind user file ownership

Body:
It was provided to me an image that run a service with the root user.

I have the need to bind mount a directory where the service running in the container must create files that will be used as input files of another non-containerized service.

The problem is well know: the generated files keep UID and GID from the in-container user.

So, I tried with this config:

  myservice:
    image: "someonewho/liketorunwithroot: latest"
    user: "${UID}:${GID}"
    volumes:
       - type: bind
         source: /home/user/output
         target: /service/path/outputdir
       - type: bind
         source: /etc/passwd
         target: /etc/passwd
       - type: bind
         source: /etc/group
         target: /etc/group
    ports:
      - "80:80"

doing like this, I can force the in-container user to use uid and gid that are the same of the user on the docker host, so I have no problem at all with the files generated under /service/path/outputdir.

But in this way the service is not working anymore, because the user with those ID can't read and write in other folders.

So I tried with the user namespace, forcing the range of subuid to one specif id (the same of the docker host user)

In this case I get this error:

docker: failed to register layer: Error processing tar file (exit status 1): Container ID 100 cannot be mapped to a host ID.

I can't manipulate the Dockerfile, nor the container, because it must be "portable".

Is there a solution?

Body:
you should consider using docker volumes for storing the files, you can always backup, restore or migrate the data

  myservice:
    image: "someonewho/liketorunwithroot: latest"
    volumes:
       - output:/service/path/outputdir
    ports:
      - "80:80"
  volumes:
    output:

and you get get the volume name with

docker volume ls --format '{{json .}}' | jq -r '.Name' | grep "$(basename $PWD)_output"


问:
Google OAuth Button Not Functioning
I'm a relatively new JS user, and I'm trying to integrate Google OAuth into my web app, but for some reason it is not responsive. It appears on the app, but I cannot click it, even when I inspect the element. This is the code pertaining to OAuth in my app file

```<code>class App extends React.Component {
  responseGoogle=(response)=>{
    console.log(response);
    console.log(response.profileObj);
  }
  render(){
    return(
      <div className="App">
        <GoogleLogin
        clientId="MY CLIENT ID IS HERE AND CORRECT"
        buttonText="Login"
        onSuccess={this.responseGoogle}
        onFailure={this.responseGoogle}
        cookiePolicy={'single-host-origin'}
        />
</code>```

The button is greyed out on the app and also is labeled as "disabled" in the console when I inspect it. If anyone could help that would be greatly appreciated

答:
I was experiencing the same problem here.

It was resolved when I re-created google credentials.

Go to https://console.developers.google.com/apis, and in the Google Plus API, access credentials, and create a new credential for "Oauth Client Id".
In the "Application Type" select "Web Application".

Be sure to put the full address of where the API is being called in the "Authorized redirect URIs".

Finally, use the new "Client ID" that will be generated.

Alternatively,

I fixed this issue by whitelisting

http://localhost

and adding cookiePolicy

```<code><GoogleLogin
clientId={WEB_CLIENT_ID}
buttonText="Login with LF account"
onSuccess={this.responseGoogle}
onFailure={this.responseGoogle}
cookiePolicy={'single_host_origin'}
/>
</code>```

https://developers.google.com/identity/sign-in/web/reference#googleauththenoninit-onerror

Let me know if this helps you or require some more info.

Title: Google OAuth Button Not Functioning

Body:
I'm a relatively new JS user, and I'm trying to integrate Google OAuth into my web app, but for some reason it is not responsive. It appears on the app, but I cannot click it, even when I inspect the element. This is the code pertaining to OAuth in my app file

class App extends React.Component {
  responseGoogle=(response)=>{
    console.log(response);
    console.log(response.profileObj);
  }
  render(){
    return(

        <GoogleLogin
        clientId="MY CLIENT ID IS HERE AND CORRECT"
        buttonText="Login"
        onSuccess={this.responseGoogle}
        onFailure={this.responseGoogle}
        cookiePolicy={'single-host-origin'}
        />

The button is greyed out on the app and also is labeled as "disabled" in the console when I inspect it. If anyone could help that would be greatly appreciated

Body:
I was experiencing the same problem here.

It was resolved when I re-created google credentials.

Go to https://console.developers.google.com/apis, and in the Google Plus API, access credentials, and create a new credential for "Oauth Client Id".
In the "Application Type" select "Web Application".

Be sure to put the full address of where the API is being called in the "Authorized redirect URIs".

Finally, use the new "Client ID" that will be generated.

Alternatively,

I fixed this issue by whitelisting

http://localhost

and adding cookiePolicy

<GoogleLogin
clientId={WEB_CLIENT_ID}
buttonText="Login with LF account"
onSuccess={this.responseGoogle}
onFailure={this.responseGoogle}
cookiePolicy={'single_host_origin'}
/>

https://developers.google.com/identity/sign-in/web/reference#googleauththenoninit-onerror

Let me know if this helps you or require some more info.


问:
Typo3 download remote files and create a file object
How do I save a remote file to local storage in Typo3 v10.

Having the following code, no files are getting saved in fileadmin storage

```<code>private function saveFileFromUri($fileUrl)
    {
        $urlParts = parse_url($fileUrl);
        $pathParts = pathinfo($urlParts['path']);
        $fileName = $pathParts['basename'];

        $file = GeneralUtility::getUrl($fileUrl);
        $temporaryFile = GeneralUtility::tempnam('temp/' . $fileName);
        $storage = $this->defaultStorage->createFolder($pathParts['dirname']);

        if ($file === false) {
            $error = sprintf(
                'File %s could not be fetched.',
                $fileUrl
            );
            if (isset($report['message'])) {
                $error .= ' ' . sprintf(
                    'Reason: %s (code: %s)',
                    $report['message'],
                    $report['error'] ?? 0
                );
            }
            throw new \TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException(
                $error,
                1613555057
            );
        }
        \TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($file);

        GeneralUtility::writeFileToTypo3tempDir(
            $temporaryFile,
            $file
        );

        $fileObject = $storage->addFile(
            $temporaryFile,
            $storage,
            $fileName
        );

        \TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($fileObject);
    }
</code>```

What is the right way to save remote files in typo3 and create a fileObject?

答:
TYPO3 has an API to get or add files via the File Abstraction Layer (FAL).

This example adds a new file in the root folder of the default storage:

$storageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class);
$storage = $storageRepository->getDefaultStorage();
$newFile = $storage->addFile(
      '/tmp/temporary_file_name.ext',
      $storage->getRootLevelFolder(),
      'final_file_name.ext'
);
```

Please refer to the documentation for details.

Body:
How do I save a remote file to local storage in Typo3 v10.

Having the following code, no files are getting saved in fileadmin storage

private function saveFileFromUri($fileUrl)
    {
        $urlParts = parse_url($fileUrl);
        $pathParts = pathinfo($urlParts['path']);
        $fileName = $pathParts['basename'];

        $file = GeneralUtility::getUrl($fileUrl);
        $temporaryFile = GeneralUtility::tempnam('temp/' . $fileName);
        $storage = $this->defaultStorage->createFolder($pathParts['dirname']);

        if ($file === false) {
            $error = sprintf(
                'File %s could not be fetched.',
                $fileUrl
            );
            if (isset($report['message'])) {
                $error .= ' ' . sprintf(
                    'Reason: %s (code: %s)',
                    $report['message'],
                    $report['error'] ?? 0
                );
            }
            throw new \TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException(
                $error,
                1613555057
            );
        }
        \TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($file);

        GeneralUtility::writeFileToTypo3tempDir(
            $temporaryFile,
            $file
        );

        $fileObject = $storage->addFile(
            $temporaryFile,
            $storage,
            $fileName
        );

        \TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($fileObject);
    }

What is the right way to save remote files in typo3 and create a fileObject?

Body:
TYPO3 has an API to get or add files via the File Abstraction Layer (FAL).

This example adds a new file in the root folder of the default storage:

$storageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class);
$storage = $storageRepository->getDefaultStorage();
$newFile = $storage->addFile(
      '/tmp/temporary_file_name.ext',
      $storage->getRootLevelFolder(),
      'final_file_name.ext'
);

Please refer to the documentation for details.


问:
Count all members with a specific role with Discord Py
I'm almost new to programming. I wanted to add a function to my bot to count the amount of members with x role, it'll always be the same role. I've been trying to use role.members, but I get the error

NameError: name 'role' is not defined

Thank you!

答:
Copy me This is the simplest way ever</p>
```<code>import discord
from discord.ext import commands,tasks
intents = discord.Intents.default()
intents.members = True

#If without intents It will return 0 so it should be like this

bot = commands.Bot(command_prefix='?',intents=intents)

@bot.command()
#You can create any name
async def users_in_role(ctx,role: discord.Role):

  #this will give the length of the users in role in an embed
  embed = discord.Embed(description =
  f"**Users in role:**\n{len(role.members)}")
  await ctx.send(embed=embed)

@bot.event
async def on_ready():
  print('bot online')

#in the discord type ``?users_in_role @role_name`` example ``?users_in_role @Owner``

#for the discord token you should go to discord.dev and make an application and in the bot page create a bot and then copy its token

bot.run("BOT_TOKEN_HERE")
</code>```

Body:
Copy me This is the simplest way ever

import discord
from discord.ext import commands,tasks
intents = discord.Intents.default()
intents.members = True

#If without intents It will return 0 so it should be like this

bot = commands.Bot(command_prefix='?',intents=intents)

@bot.command()
#You can create any name
async def users_in_role(ctx,role: discord.Role):

  #this will give the length of the users in role in an embed
  embed = discord.Embed(description =
  f"**Users in role:**\n{len(role.members)}")
  await ctx.send(embed=embed)

@bot.event
async def on_ready():
  print('bot online')

#in the discord type ``?users_in_role @role_name`` example ``?users_in_role @Owner``

#for the discord token you should go to discord.dev and make an application and in the bot page create a bot and then copy its token

bot.run("BOT_TOKEN_HERE")


问:
How to set transition for 2 backgrounds in an element?
in this code:

```<code>    #p1 {
        background-image: url(backimgs/first/1.jpg), url(backimgs/first/2.jpg);
        background-color: #05080d;
        background-position: left top, left bottom;
        background-size: 100% 35%, 100% 65%;
    }
</code>```

I want when the page shows up, first show backimgs/first/1.jpg then after 1 sec show backimgs/first/2.jpg. how can I do it?

答:
You can't animate background-images. You can change it, but there won't be any smooth transition:

#p1 {
  background-image: url(backimgs/first/1.jpg), url(backimgs/first/2.jpg);
  background-color: #05080d;
  background-position: left top, left bottom;
  background-size: 100% 35%, 100% 65%;
  animation: change-bg;
  animation-duration: 1s;
}

@keyframes change-bg {
  0% {
    background-image: url(backimgs/first/1.jpg), url(backimgs/first/2.jpg);
    background-size: 100% 35%, 100% 65%;
  }
  100% {
    background-image: url(backimgs/first/2.jpg), url(backimgs/first/1.jpg);
    background-size: 100% 65%, 100% 35%;
  }
}
```

If you want a smooth transition - you can use ::before and ::after with a background and animate the opacity of them. Let me know with a comment if you need more info on this aproach, I'll edit the post and show, how it's done.

Body:
in this code:

    #p1 {
        background-image: url(backimgs/first/1.jpg), url(backimgs/first/2.jpg);
        background-color: #05080d;
        background-position: left top, left bottom;
        background-size: 100% 35%, 100% 65%;
    }

I want when the page shows up, first show backimgs/first/1.jpg then after 1 sec show backimgs/first/2.jpg. how can I do it?

Body:
You can't animate background-images. You can change it, but there won't be any smooth transition:

#p1 {
  background-image: url(backimgs/first/1.jpg), url(backimgs/first/2.jpg);
  background-color: #05080d;
  background-position: left top, left bottom;
  background-size: 100% 35%, 100% 65%;
  animation: change-bg;
  animation-duration: 1s;
}

@keyframes change-bg {
  0% {
    background-image: url(backimgs/first/1.jpg), url(backimgs/first/2.jpg);
    background-size: 100% 35%, 100% 65%;
  }
  100% {
    background-image: url(backimgs/first/2.jpg), url(backimgs/first/1.jpg);
    background-size: 100% 65%, 100% 35%;
  }
}

If you want a smooth transition - you can use ::before and ::after with a background and animate the opacity of them. Let me know with a comment if you need more info on this aproach, I'll edit the post and show, how it's done.


问:
How to group/split array of objects by weeks with start and end date
I have big array of objects.

```<code>let objectsList = [
    {name: 'Misha', surname: 'Borovuk', id: '1', createdProfile: '11/02/2022'}
    {name: 'Karina', surname: 'Burba', id: '2', createdProfile: '17/01/2022'}
    {name: 'Alina', surname: 'Shulan', id: '3', createdProfile: '05/01/2021'}
    {name: 'Sasha', surname: 'Uena', id: '4', createdProfile: '11/02/2021'}
    {name: 'Stepan', surname: 'German', id: '4', createdProfile: '08/02/2022'}
  ]
</code>```

And 2 dates let fromDate = '24/12/2021'; let toDate = '11/02/2022';
And i need to remove those objects which are not in range, and group those objects which are in range by weeks.
For instance result should look like this :

```<code>let result = [
  [
    {name: 'Karina', surname: 'Burba', id: '2', createdProfile: '17/01.2022'}
  ],
  [
    {name: 'Stepan', surname: 'German', id: '4', createdProfile: '08/02/2022'},
    {name: 'Misha', surname: 'Borovuk', id: '1', createdProfile: '11/02/2022'},
     // Because they addad on same weak
  ],
]

let dates = [
  [
   '17/01/2022',
   '23/01/2022'
  ],
  [
   '07/02/2022',
   '13/02/2022'
  ],
]
</code>```

But does anyone know is it possible to do without for loops, maybe with groupBy of forEach, map?
In order to not complicate application?
I was looking a lot and only found a few examples with lodash and groupBy

```<code>groupBy(objectsList, (dt) => moment(dt).week());
</code>```

But they all use only one from fromDate parameter and don't use toDate parameter.
And also this approach doesn't allow to get rid of those items which are not in range.
Sorry for not providing any code solutions, all my ideas have lots of nested loops and conditions.

答:
But does anyone know is it possible to do without for loops, maybe with groupBy of forEach, map?

You are probably looking for the filter method. It will return each item that passes a conditional test in its callback, the conditional test in your case being a date within two dates.

Here's a link.

Try something like

const results = objectsLists.filter(item => {
     return item.createdProfile.getTime() >= fromDate.getTime() &&
            item.createdProfile.getTime() <= toDate.getTime()
})
```

I don't recognize your date format and am not sure it will play nicely with JavaScript's built-in Date class. If possible, you should consider using that instead. If not, you could still use the filter method with a more convoluted conditional checking month/day/year positions in the createdProfile string.

Body:
I have big array of objects.

let objectsList = [
    {name: 'Misha', surname: 'Borovuk', id: '1', createdProfile: '11/02/2022'}
    {name: 'Karina', surname: 'Burba', id: '2', createdProfile: '17/01/2022'}
    {name: 'Alina', surname: 'Shulan', id: '3', createdProfile: '05/01/2021'}
    {name: 'Sasha', surname: 'Uena', id: '4', createdProfile: '11/02/2021'}
    {name: 'Stepan', surname: 'German', id: '4', createdProfile: '08/02/2022'}
  ]

And 2 dates let fromDate = '24/12/2021'; let toDate = '11/02/2022';
And i need to remove those objects which are not in range, and group those objects which are in range by weeks.
For instance result should look like this :

let result = [
  [
    {name: 'Karina', surname: 'Burba', id: '2', createdProfile: '17/01.2022'}
  ],
  [
    {name: 'Stepan', surname: 'German', id: '4', createdProfile: '08/02/2022'},
    {name: 'Misha', surname: 'Borovuk', id: '1', createdProfile: '11/02/2022'},
     // Because they addad on same weak
  ],
]

let dates = [
  [
   '17/01/2022',
   '23/01/2022'
  ],
  [
   '07/02/2022',
   '13/02/2022'
  ],
]

But does anyone know is it possible to do without for loops, maybe with groupBy of forEach, map?
In order to not complicate application?
I was looking a lot and only found a few examples with lodash and groupBy

groupBy(objectsList, (dt) => moment(dt).week());

But they all use only one from fromDate parameter and don't use toDate parameter.
And also this approach doesn't allow to get rid of those items which are not in range.
Sorry for not providing any code solutions, all my ideas have lots of nested loops and conditions.

Body:
But does anyone know is it possible to do without for loops, maybe with groupBy of forEach, map?

You are probably looking for the filter method. It will return each item that passes a conditional test in its callback, the conditional test in your case being a date within two dates.

Here's a link.

Try something like

const results = objectsLists.filter(item => {
     return item.createdProfile.getTime() >= fromDate.getTime() &&
            item.createdProfile.getTime() <= toDate.getTime()
})

I don't recognize your date format and am not sure it will play nicely with JavaScript's built-in Date class. If possible, you should consider using that instead. If not, you could still use the filter method with a more convoluted conditional checking month/day/year positions in the createdProfile string.


问:
URL is not opened in modal
I'm trying to make the URL content appear in the modal (let's assume it's www.google.it), only it doesn't open in the modal.

I tried to use window.location.href as shown in the code below, however this site opens in a new page and not in the modal.

Can anyone kindly help me?

// Get the modal
            var modal = document.getElementById("myModal");

            // Get the button that opens the modal
            var btn = document.getElementById("myBtn");

            // Get the  element that closes the modal
            var span = document.getElementsByClassName("close")[0];

            // When the user clicks the button, open the modal
            btn.onclick = function () {
                modal.style.display = "block";
                window.location.href="www.google.com";
            }

            // When the user clicks on  (x), close the modal
            span.onclick = function () {
                modal.style.display = "none";
            }

            // When the user clicks anywhere outside of the modal, close it
            window.onclick = function (event) {
                if (event.target == modal) {
                    modal.style.display = "none";
                }
            }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.modal {
            display: none;
            /* Hidden by default */
            position: fixed;
            /* Stay in place */
            z-index: 1;
            /* Sit on top */
            padding-top: 100px;
            /* Location of the box */
            left: 0;
            top: 0;
            width: 100%;
            /* Full width */
            height: 100%;
            /* Full height */
            overflow: auto;
            /* Enable scroll if needed */
            background-color: rgb(0, 0, 0);
            /* Fallback color */
            background-color: rgba(0, 0, 0, 0.4);
            /* Black w/ opacity */
        }

        /* Modal Content */
        .modal-content {
            background-color: #fefefe;
            margin: auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
        }

        /* The Close Button */
        .close {
            color: #aaaaaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .close:hover,
        .close:focus {
            color: #000;
            text-decoration: none;
            cursor: pointer;
        }</code>```

                <button id="myBtn">Open Modal</button>

                        ×

Some text in the Modal..

```

答:
As I am understanding your question may need to use an iframe in your model to show or open a URL.

window.location.href="www.google.com"; will redirect your page to the address you mentioned so I comment this line.

You can assign www.google.com to iframe src.

// Get the modal
            var modal = document.getElementById("myModal");

            // Get the button that opens the modal
            var btn = document.getElementById("myBtn");

            // Get the  element that closes the modal
            var span = document.getElementsByClassName("close")[0];

            // When the user clicks the button, open the modal
            btn.onclick = function () {
                modal.style.display = "block";
                //window.location.href="www.google.com";
            }

            // When the user clicks on  (x), close the modal
            span.onclick = function () {
                modal.style.display = "none";
            }

            // When the user clicks anywhere outside of the modal, close it
            window.onclick = function (event) {
                if (event.target == modal) {
                    modal.style.display = "none";
                }
            }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.modal {
            display: none;
            /* Hidden by default */
            position: fixed;
            /* Stay in place */
            z-index: 1;
            /* Sit on top */
            padding-top: 100px;
            /* Location of the box */
            left: 0;
            top: 0;
            width: 100%;
            /* Full width */
            height: 100%;
            /* Full height */
            overflow: auto;
            /* Enable scroll if needed */
            background-color: rgb(0, 0, 0);
            /* Fallback color */
            background-color: rgba(0, 0, 0, 0.4);
            /* Black w/ opacity */
        }

        /* Modal Content */
        .modal-content {
            background-color: #fefefe;
            margin: auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
        }

        /* The Close Button */
        .close {
            color: #aaaaaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .close:hover,
        .close:focus {
            color: #000;
            text-decoration: none;
            cursor: pointer;
        }</code>```

                <button id="myBtn">Open Modal</button>

                        ×

Some text in the Modal..

```

Title: URL is not opened in modal

Body:
I'm trying to make the URL content appear in the modal (let's assume it's www.google.it), only it doesn't open in the modal.

I tried to use window.location.href as shown in the code below, however this site opens in a new page and not in the modal.

Can anyone kindly help me?

// Get the modal
            var modal = document.getElementById("myModal");

            // Get the button that opens the modal
            var btn = document.getElementById("myBtn");

            // Get the  element that closes the modal
            var span = document.getElementsByClassName("close")[0];

            // When the user clicks the button, open the modal
            btn.onclick = function () {
                modal.style.display = "block";
                window.location.href="www.google.com";
            }

            // When the user clicks on  (x), close the modal
            span.onclick = function () {
                modal.style.display = "none";
            }

            // When the user clicks anywhere outside of the modal, close it
            window.onclick = function (event) {
                if (event.target == modal) {
                    modal.style.display = "none";
                }
            }

.modal {
            display: none;
            /* Hidden by default */
            position: fixed;
            /* Stay in place */
            z-index: 1;
            /* Sit on top */
            padding-top: 100px;
            /* Location of the box */
            left: 0;
            top: 0;
            width: 100%;
            /* Full width */
            height: 100%;
            /* Full height */
            overflow: auto;
            /* Enable scroll if needed */
            background-color: rgb(0, 0, 0);
            /* Fallback color */
            background-color: rgba(0, 0, 0, 0.4);
            /* Black w/ opacity */
        }

        /* Modal Content */
        .modal-content {
            background-color: #fefefe;
            margin: auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
        }

        /* The Close Button */
        .close {
            color: #aaaaaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .close:hover,
        .close:focus {
            color: #000;
            text-decoration: none;
            cursor: pointer;
        }

                <button id="myBtn">Open Modal</button>

                        ×

Some text in the Modal..

Body:
As I am understanding your question may need to use an iframe in your model to show or open a URL.

window.location.href="www.google.com"; will redirect your page to the address you mentioned so I comment this line.

You can assign www.google.com to iframe src.

// Get the modal
            var modal = document.getElementById("myModal");

            // Get the button that opens the modal
            var btn = document.getElementById("myBtn");

            // Get the <span> element that closes the modal
            var span = document.getElementsByClassName("close")[0];

            // When the user clicks the button, open the modal
            btn.onclick = function () {
                modal.style.display = "block";
                //window.location.href="www.google.com";
            }

            // When the user clicks on <span> (x), close the modal
            span.onclick = function () {
                modal.style.display = "none";
            }

            // When the user clicks anywhere outside of the modal, close it
            window.onclick = function (event) {
                if (event.target == modal) {
                    modal.style.display = "none";
                }
            }

.modal {
            display: none;
            /* Hidden by default */
            position: fixed;
            /* Stay in place */
            z-index: 1;
            /* Sit on top */
            padding-top: 100px;
            /* Location of the box */
            left: 0;
            top: 0;
            width: 100%;
            /* Full width */
            height: 100%;
            /* Full height */
            overflow: auto;
            /* Enable scroll if needed */
            background-color: rgb(0, 0, 0);
            /* Fallback color */
            background-color: rgba(0, 0, 0, 0.4);
            /* Black w/ opacity */
        }

        /* Modal Content */
        .modal-content {
            background-color: #fefefe;
            margin: auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
        }

        /* The Close Button */
        .close {
            color: #aaaaaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .close:hover,
        .close:focus {
            color: #000;
            text-decoration: none;
            cursor: pointer;
        }

<!-- Trigger/Open The Modal -->
                <button id="myBtn">Open Modal</button>

                <!-- The Modal -->
                <div id="myModal" class="modal">

                    <!-- Modal content -->
                    <div class="modal-content">
                        <span class="close">&times;</span>
                        <p>Some text in the Modal..</p>
                        <iframe src="https://www.w3schools.com" class="url" title="W3Schools Free Online Web Tutorials">
</iframe>
                    </div>

                </div>


问:
issue with counting lines of python file
I am traversing a directory, and if python file is found, trying to find the number of lines of code in it.
I am not really sure why I face the below issue.

```<code>for dirpath, dirnames, filenames in os.walk(APP_FOLDER):

    for file in filenames:
        if pathlib.Path(file).suffix == ".py":
            num_lines = len(open(file).readlines()) #causes issue
            print(
                f"Root:{dirpath}\n"
                f"file:{file}\n\n"
                f"lines: {num_lines}" //
            )
</code>```

Érror:

```<code>Traceback (most recent call last):
  File "C:\Users\XXXX\PycharmProjects\pythonProject1\main.py", line 11, in <module>
    num_lines = len(open(file).readlines())
FileNotFoundError: [Errno 2] No such file or directory:
</code>```

If i remove that line, the code works as expected. There is a single line code within. Any guidance here?

答:
file is the file's name, not its path, to get its full path, join the name with the directory path dirpath using os.path.join. Also, it is better to use a with statement when dealing with files since it automatically closes the file:

```<code>file_path = os.path.join(dirpath, file)

with open(file_path) as f:
    num_lines = len(f.readlines())
</code>```

Body:
I am traversing a directory, and if python file is found, trying to find the number of lines of code in it.
I am not really sure why I face the below issue.

for dirpath, dirnames, filenames in os.walk(APP_FOLDER):

    for file in filenames:
        if pathlib.Path(file).suffix == ".py":
            num_lines = len(open(file).readlines()) #causes issue
            print(
                f"Root:{dirpath}\n"
                f"file:{file}\n\n"
                f"lines: {num_lines}" //
            )

Érror:

Traceback (most recent call last):
  File "C:\Users\XXXX\PycharmProjects\pythonProject1\main.py", line 11, in <module>
    num_lines = len(open(file).readlines())
FileNotFoundError: [Errno 2] No such file or directory:

If i remove that line, the code works as expected. There is a single line code within. Any guidance here?

Body:
file is the file's name, not its path, to get its full path, join the name with the directory path dirpath using os.path.join. Also, it is better to use a with statement when dealing with files since it automatically closes the file:

file_path = os.path.join(dirpath, file)

with open(file_path) as f:
    num_lines = len(f.readlines())


问:
Platform types and jsr-305 annotations when using kotlin with project reactor
I am using project reactor with kotlin. As expected, since i am writing kotlin code that calls java code, all type signatures from project reactor's operators are showing up as platform types. e.g.

//here i is inferred as Int!
Mono.just(1).map { i -> i + 1 }
```
<p>Reading through project reactor's documentation, it seems like theres a way to assert that all types are non nullable and to have the types be inferred as non nullable types. https://projectreactor.io/docs/core/release/reference/#kotlin-null-safety</p>
<p><code>Kotlin support for JSR 305 annotations and Reactor nullability annotations provide null-safety for the whole Reactor API to Kotlin developers, with the advantage of dealing with null-related issues at compile time.</code></p>
<p>I have tried using the suggested compiler option with no luck. Using the following kotlin configuration, the type of <code>i</code> is still showing up as <code>Int!</code> while i would now expect it to be <code>Int</code>.</p>
<pre class="lang-kotlin prettyprint-override"><code>import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    kotlin("jvm") version "1.6.10"
    application
}

group = "me.stef"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

dependencies {
    testImplementation(kotlin("test"))
    implementation("io.projectreactor:reactor-core:3.4.14")
}

tasks.test {
    useJUnitPlatform()
}

tasks.withType<KotlinCompile> {
    kotlinOptions {
        jvmTarget = "1.8"
        freeCompilerArgs = listOf("-Xjsr305=strict")
    }
}

application {
    mainClass.set("MainKt")
}
</code>```

I am using the intelliJ IDEA Ultimate version 2021.3.2 with the kotlin plugin version 213-1.6.10-release-961-IJ6777.52

I am aware that i can use explicit type annotations to turn the platform types into nullable or non null types, but i would like avoid that if possible.

So my questions are:

Am i correctly interpreting the documentation in understanding that there's indeed a way to enforce non nullable types when using project reactor with kotlin?

If i have understood correctly, and the jsr305 compiler option is the way to achieve my goal, what could i be doing wrong?

If thats not the way to achieve my goal, how can i do it?

Could it be a problem with intellij?

答:
Actually the behaviour is by design because @NonNullApi which is applied to a package from where you are calling the method (map), doesn't have type use default qualifier, but only METHOD and PARAMETER. In particular, it means that the Kotlin compiler doesn't enhance types inside type argument positions, but only whole types in return type and value parameter positions.

It can be proved with the following code:

```<code>fun main() {
    // useless unsafe call before `get()` is reported because
    // the Kotlin compiler already enhanced the return type of `blockOptional` to not-null
    Mono.just(1).blockOptional()?.get()
}
</code>```

In your specific case, the lambda's value parameter i is mapped to T type argument of Function in map declaration which corresponds to type use position. That's why the Kotlin compiler doesn't enhance this type.

Note that the Kotlin compiler supports enhancing types from Java by default nullability annotations (including on a package ones) in type use positions. See the following compiler test.

So maybe it makes sense to create a feature request for reactor to expand scope of its NonNullApi annotation to type use positions.

Body:
I am using project reactor with kotlin. As expected, since i am writing kotlin code that calls java code, all type signatures from project reactor's operators are showing up as platform types. e.g.

//here i is inferred as Int!
Mono.just(1).map { i -> i + 1 }

Reading through project reactor's documentation, it seems like theres a way to assert that all types are non nullable and to have the types be inferred as non nullable types. https://projectreactor.io/docs/core/release/reference/#kotlin-null-safety

Kotlin support for JSR 305 annotations and Reactor nullability annotations provide null-safety for the whole Reactor API to Kotlin developers, with the advantage of dealing with null-related issues at compile time.

I have tried using the suggested compiler option with no luck. Using the following kotlin configuration, the type of i is still showing up as Int! while i would now expect it to be Int.

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    kotlin("jvm") version "1.6.10"
    application
}

group = "me.stef"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

dependencies {
    testImplementation(kotlin("test"))
    implementation("io.projectreactor:reactor-core:3.4.14")
}

tasks.test {
    useJUnitPlatform()
}

tasks.withType<KotlinCompile> {
    kotlinOptions {
        jvmTarget = "1.8"
        freeCompilerArgs = listOf("-Xjsr305=strict")
    }
}

application {
    mainClass.set("MainKt")
}

I am using the intelliJ IDEA Ultimate version 2021.3.2 with the kotlin plugin version 213-1.6.10-release-961-IJ6777.52

I am aware that i can use explicit type annotations to turn the platform types into nullable or non null types, but i would like avoid that if possible.

So my questions are:

Am i correctly interpreting the documentation in understanding that there's indeed a way to enforce non nullable types when using project reactor with kotlin?

If i have understood correctly, and the jsr305 compiler option is the way to achieve my goal, what could i be doing wrong?

If thats not the way to achieve my goal, how can i do it?

Could it be a problem with intellij?

Body:
Actually the behaviour is by design because @NonNullApi which is applied to a package from where you are calling the method (map), doesn't have type use default qualifier, but only METHOD and PARAMETER. In particular, it means that the Kotlin compiler doesn't enhance types inside type argument positions, but only whole types in return type and value parameter positions.

It can be proved with the following code:

fun main() {
    // useless unsafe call before `get()` is reported because
    // the Kotlin compiler already enhanced the return type of `blockOptional` to not-null
    Mono.just(1).blockOptional()?.get()
}

In your specific case, the lambda's value parameter i is mapped to T type argument of Function in map declaration which corresponds to type use position. That's why the Kotlin compiler doesn't enhance this type.

Note that the Kotlin compiler supports enhancing types from Java by default nullability annotations (including on a package ones) in type use positions. See the following compiler test.

So maybe it makes sense to create a feature request for reactor to expand scope of its NonNullApi annotation to type use positions.


问:
Trying to get only cells with certain initials but giving me syntax error? SQL
So my assignment question is to "Get a list of all books withdrawn by people with the initials 'B.W.'. Show a column for the first name, last name, initials, and the title of the book". I am trying to join these 3 tables as it is the only way to get this information, but Im having a hard time only displaying names with initials B.W. I get a syntax error saying:

"You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'JOIN withdrawals

When I remove my 'WHERE' statement (all of the second line), my syntax error goes away. How do I make this work?

Below is my code:

```<code> SELECT first_name, last_name, title FROM members
     WHERE first_name LIKE 'B%' AND last_name LIKE 'W%'
      JOIN withdrawals
        ON members.member_id  = withdrawals.member_id
         JOIN books
             ON withdrawals.book_id = books.book_id
</code>```

答:
There is a flow you have to follow when writing your SQL statements</p>
```<code>SELECT * FROM table
JOIN table2 ON
WHERE
GROUP BY
</code>```

Body:
So my assignment question is to "Get a list of all books withdrawn by people with the initials 'B.W.'. Show a column for the first name, last name, initials, and the title of the book". I am trying to join these 3 tables as it is the only way to get this information, but Im having a hard time only displaying names with initials B.W. I get a syntax error saying:

"You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'JOIN withdrawals

When I remove my 'WHERE' statement (all of the second line), my syntax error goes away. How do I make this work?

Below is my code:

 SELECT first_name, last_name, title FROM members
     WHERE first_name LIKE 'B%' AND last_name LIKE 'W%'
      JOIN withdrawals
        ON members.member_id  = withdrawals.member_id
         JOIN books
             ON withdrawals.book_id = books.book_id

Body:
There is a flow you have to follow when writing your SQL statements

SELECT * FROM table
JOIN table2 ON
WHERE
GROUP BY


问:
In CNN, should we have more layers with less filters or less layers with large number of filters?
I am trying to understand the effect of adding more layers vs the effect of increasing the number of filters in the existing layers in a CNN. Consider a CNN with 2 hidden layers and 64 filters each. Consider a second CNN with 4 hidden layers and 32 filters each. The kernel sizes are same in both CNNs. The number of parameters are also same in both cases.

Which one should I expect to perform better? I am thinking in terms of hyperparameter tuning, batch sizes, training time etc.

答:
In CNNs the deeper layers correspond to higher-level features in images. In the first layer, you are going to get low-level features such as edges, lines, etc. So the network uses these layers to create more complex features; using edges to find circles, using circles to find wheels, using wheels to find a car (I skipped a couple of steps but you get the gist).

So to answer your question, you need to consider how complex your problem is. If you are working on something like imagenet, you can expect model with more layers to have the edge. On the other hand, for problems like mnist, you don't need high-level features.


问:
inotifywait running daemon mode giving error Couldn't initialize inotify
I am running inotifywait (inotify-tools-3.14-1) in the daemon mode, however, it gave the following error and no watches are established.  Also, since it is within the while loop, there were many inotifywait daemon processes created.

I have no such problem if running with --monitor instead of --daemon.  Can someone help fixing it?  Thanks a lot.

"Couldn't initialize inotify.  Are you running Linux 2.6.13 or later, and was the
CONFIG_INOTIFY option enabled when your kernel was compiled?  If so,
something mysterious has gone wrong.  Please e-mail radu.voicilas@gmail.com
 and mention that you saw this message."

Below is the code:

```<code>while true  # run indefinitely
do
  inotifywait --daemon --outfile /tmp/daemon.log --event close_write --format '%w%f %e %T' --timefmt '%F %T' $folder |  while read eventInfo
     do
        call_another_fun $eventInfo
        break
     done
   done
</code>```

答:
You should increase the maximum amount of inotify instances.

```<code>sudo sysctl fs.inotify.max_user_instances=2048
</code>```

On my Desktop System the default of 128 Instances was to low for a few file-browsers, IDEs and electron apps. All of them have multiple inotify instances.

To make this permanent, add this line into /etc/sysctl.conf

```<code>fs.inotify.max_user_instances=2048
</code>```

Body:
I am running inotifywait (inotify-tools-3.14-1) in the daemon mode, however, it gave the following error and no watches are established.  Also, since it is within the while loop, there were many inotifywait daemon processes created.

I have no such problem if running with --monitor instead of --daemon.  Can someone help fixing it?  Thanks a lot.

"Couldn't initialize inotify.  Are you running Linux 2.6.13 or later, and was the
CONFIG_INOTIFY option enabled when your kernel was compiled?  If so,
something mysterious has gone wrong.  Please e-mail radu.voicilas@gmail.com
 and mention that you saw this message."

Below is the code:

while true  # run indefinitely
do
  inotifywait --daemon --outfile /tmp/daemon.log --event close_write --format '%w%f %e %T' --timefmt '%F %T' $folder |  while read eventInfo
     do
        call_another_fun $eventInfo
        break
     done
   done

Body:
You should increase the maximum amount of inotify instances.

sudo sysctl fs.inotify.max_user_instances=2048

On my Desktop System the default of 128 Instances was to low for a few file-browsers, IDEs and electron apps. All of them have multiple inotify instances.

To make this permanent, add this line into /etc/sysctl.conf

fs.inotify.max_user_instances=2048


问:
implicitly convert type problem
I have the following classes:

```<code>public class DictionaryBuilder<T> where T : IDictionary<string, object>, new()
{
    private List<Tuple<string, object>> values_ = new List<Tuple<string, object>>();

    public DictionaryBuilder<T> WithValue(string key, object obj)
    {
        values_.Add(Tuple.Create(key, obj));
        return this;
    }
    public static implicit operator T(DictionaryBuilder<T> builder)
    {
        return builder.Build();
    }
    public T Build()
    {
        var dict = new T();
        foreach (var value in values_)
        {
            dict.Add(value.Item1, value.Item2);
        }
        return dict;
    }
}

public static class Admin
{
    public static string IndexPath { get { return "Admin/Index"; } }
    public static DictionaryBuilder<RouteValueDictionary> IndexRoute
    {
        get
        {
            return new DictionaryBuilder<RouteValueDictionary>()
                .WithValue("controller", "Admin")
                .WithValue("action", "Index");
        }
    }
}
</code>```

And it is used like:

```<code>@Html.RouteLink("Admim",
    Admin.IndexRoute
        .WithValue("id",3),
    new DictionaryBuilder<Dictionary<string,object>>()
        .WithValue("class","AdminRouteLink")
</code>```

This is a bit of a mouthful, and the generics are obstructing the intent a little. I'd like to do this:

```<code>public class RouteValues : DictionaryBuilder<RouteValueDictionary> { }
public class HtmlValues : DictionaryBuilder<Dictionary<string,object>> { }

public static class Admin
{
    public static string IndexPath { get { return "Admin/Index"; } }
    public static RouteValues IndexRoute
    {
        get
        {
            return new RouteValues()
                .WithValue("controller", "Admin")
                .WithValue("action", "Index");
        }
    }
}

@Html.RouteLink("Admim",
    Admin.IndexRoute
        .WithValue("id",3),
    new HtmlValues()
        .WithValue("class","AdminRouteLink")
</code>```

Unfortunately, I'm getting a conversion error I'm afraid I don't fully understand:

```<code>Cannot implicitly convert type
'ControllerActionExporter
    .DictionaryBuilder<System.Web.Routing.RouteValueDictionary>'
to
'ControllerActionExporter.RouteValues'.
An explicit conversion exists (are you missing a cast?)

        return new RouteValues()
            .WithValue("controller", "Admin")
            .WithValue("action", "Index"); //error occurs on this line
</code>```

What am I doing wrong, and how do I correct the problem?

答:
The problem is that WithValue returns a DictionaryBuilder<T>, but the IndexRoute property returns the more specific type RouteValues. Try changing your property to return the DictionaryBuilder<T>:

```<code>public static DictionaryBuilder<RouteValueDictionary> IndexRoute
{
    get
    {
        return new RouteValues()
            .WithValue("controller", "Admin")
            .WithValue("action", "Index");
    }
}
</code>```

An alternative to this would be to create a generic extension method to the DictionaryBuilder<T> class that returns the same type as the one that was passed in:

```<code>public static T WithValue(this T builder, string key, object obj)
{
        builder.WithValue(key, obj);
        return builder;
}
</code>```

Title: implicitly convert type problem

Body:
I have the following classes:

public class DictionaryBuilder<T> where T : IDictionary<string, object>, new()
{
    private List<Tuple<string, object>> values_ = new List<Tuple<string, object>>();

    public DictionaryBuilder<T> WithValue(string key, object obj)
    {
        values_.Add(Tuple.Create(key, obj));
        return this;
    }
    public static implicit operator T(DictionaryBuilder<T> builder)
    {
        return builder.Build();
    }
    public T Build()
    {
        var dict = new T();
        foreach (var value in values_)
        {
            dict.Add(value.Item1, value.Item2);
        }
        return dict;
    }
}

public static class Admin
{
    public static string IndexPath { get { return "Admin/Index"; } }
    public static DictionaryBuilder<RouteValueDictionary> IndexRoute
    {
        get
        {
            return new DictionaryBuilder<RouteValueDictionary>()
                .WithValue("controller", "Admin")
                .WithValue("action", "Index");
        }
    }
}

And it is used like:

@Html.RouteLink("Admim",
    Admin.IndexRoute
        .WithValue("id",3),
    new DictionaryBuilder<Dictionary<string,object>>()
        .WithValue("class","AdminRouteLink")

This is a bit of a mouthful, and the generics are obstructing the intent a little. I'd like to do this:

public class RouteValues : DictionaryBuilder<RouteValueDictionary> { }
public class HtmlValues : DictionaryBuilder<Dictionary<string,object>> { }

public static class Admin
{
    public static string IndexPath { get { return "Admin/Index"; } }
    public static RouteValues IndexRoute
    {
        get
        {
            return new RouteValues()
                .WithValue("controller", "Admin")
                .WithValue("action", "Index");
        }
    }
}

@Html.RouteLink("Admim",
    Admin.IndexRoute
        .WithValue("id",3),
    new HtmlValues()
        .WithValue("class","AdminRouteLink")

Unfortunately, I'm getting a conversion error I'm afraid I don't fully understand:

Cannot implicitly convert type
'ControllerActionExporter
    .DictionaryBuilder<System.Web.Routing.RouteValueDictionary>'
to
'ControllerActionExporter.RouteValues'.
An explicit conversion exists (are you missing a cast?)

        return new RouteValues()
            .WithValue("controller", "Admin")
            .WithValue("action", "Index"); //error occurs on this line

What am I doing wrong, and how do I correct the problem?

Body:
The problem is that WithValue returns a DictionaryBuilder<T>, but the IndexRoute property returns the more specific type RouteValues. Try changing your property to return the DictionaryBuilder<T>:

public static DictionaryBuilder<RouteValueDictionary> IndexRoute
{
    get
    {
        return new RouteValues()
            .WithValue("controller", "Admin")
            .WithValue("action", "Index");
    }
}

An alternative to this would be to create a generic extension method to the DictionaryBuilder<T> class that returns the same type as the one that was passed in:

public static T WithValue(this T builder, string key, object obj)
{
        builder.WithValue(key, obj);
        return builder;
}