问:
Docker, Springboot and Mysql : com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure
I try to run a Springboot app with mysql connection on Docker. Without docker, it works well. But when I try to deploy on a container, I have com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure.
I use this docker-compose:

```<code>version: '3'
services:
  nginx:
   container_name: nginx
   image: nginx:latest
   restart: always
   ports:
   - 80:80
   - 443:443
   volumes:
   - ./nginx/conf.d:/etc/nginx/conf.d
   depends_on:
   - spring-boot-app

  mysql:
   container_name: mysql
   image: mysql:latest
   environment:
    MYSQL_ROOT_PASSWORD: "rootpass"
    MYSQL_DATABASE: "db"
    MYSQL_USER: "user"
    MYSQL_PASSWORD: "pass"
   ports:
   - "1306:3306"
   volumes:
   - ./data/:/var/lib/mysql
   networks:
   - mysql-db
   restart: always

  spring-boot-app:
    container_name: spring-boot-app
    image: spring-boot-app
    build:
      context: ./spring-boot-app
      dockerfile: Dockerfile
    ports:
      - "8080:8080"
    depends_on:
      - mysql
    networks:
      - mysql-db
    restart: always

networks:
  mysql-db:
      driver: bridge
</code>```

Here is the Dockerfile for springboot app:

```<code>FROM openjdk:11
COPY target/spring-boot-app.jar /spring-boot-app/spring-boot-app.jar
ENTRYPOINT [ "java", "-jar", "-Dspring.profiles.active=prod","/spring-boot-app/spring-boot-app.jar" ]
</code>```

And finally, here is application.properties:

```<code>spring.datasource.url = jdbc:mysql://mysql:1306/db
spring.datasource.username = user
spring.datasource.password = pass

# Show or not log for each sql query
spring.jpa.show-sql = true

# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update

# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)

# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

server.port=8080
</code>```

I don't think this is a port problem because i tried to set mysql to default port (3306), and it still doesn't work.

If it can help, here is docker ps :

```<code>CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                  PORTS                                      NAMES
08ea16361c61        nginx:latest        "nginx -g 'daemon of…"   1 second ago        Up Less than a second   0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp   nginx
52ef8d5c2127        spring-boot-app     "java -jar -Dspring.…"   3 seconds ago       Up 1 second             0.0.0.0:8080->8080/tcp                     spring-boot-app
7bbcdc1fae3c        mysql:latest        "docker-entrypoint.s…"   4 seconds ago       Up 3 seconds            33060/tcp, 0.0.0.0:1306->3306/tcp          mysql
</code>```

Edit : full stacktrace :

```ubuntu@ubuntu:~/Documents/SpringBoot$ docker-compose up
Creating network "springboot_mysql-db" with driver "bridge"
Creating mysql ... done
Creating spring-boot-app ... done
Attaching to mysql, spring-boot-app
mysql              | 2019-05-27T21:50:19.645920Z 0 [Warning] [MY-011070] [Server] 'Disabling symbolic links using --skip-symbolic-links (or equivalent) is the default. Consider not using this option as it' is deprecated and will be removed in a future release.
mysql              | 2019-05-27T21:50:19.645986Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.16) starting as process 1
mysql              | 2019-05-27T21:50:20.451523Z 0 [System] [MY-010229] [Server] Starting crash recovery...
mysql              | 2019-05-27T21:50:20.466040Z 0 [System] [MY-010232] [Server] Crash recovery finished.
mysql              | 2019-05-27T21:50:20.544487Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
mysql              | 2019-05-27T21:50:20.551894Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
mysql              | 2019-05-27T21:50:20.584210Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.16'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server - GPL.
mysql              | 2019-05-27T21:50:20.682338Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: '/var/run/mysqld/mysqlx.sock' bind-address: '::' port: 33060
spring-boot-app    |
spring-boot-app    |   .   ____          _            __ _ _
spring-boot-app    |  /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
spring-boot-app    | ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
spring-boot-app    |  \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
spring-boot-app    |   '  |____| .__|_| |_|_| |_\__, | / / / /
spring-boot-app    |  =========|_|==============|___/=/_/_/_/
spring-boot-app    |  :: Spring Boot ::        (v2.1.5.RELEASE)
spring-boot-app    |
spring-boot-app    | 2019-05-27 21:50:22.884  INFO 1 --- [           main] com.jv.demo.DemoApplication              : Starting DemoApplication v0.0.1-SNAPSHOT on c69469fd7461 with PID 1 (/spring-boot-app/spring-boot-app.jar started by root in /)
spring-boot-app    | 2019-05-27 21:50:22.903  INFO 1 --- [           main] com.jv.demo.DemoApplication              : The following profiles are active: prod
spring-boot-app    | 2019-05-27 21:50:25.152  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
spring-boot-app    | 2019-05-27 21:50:25.378  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 205ms. Found 1 repository interfaces.
spring-boot-app    | 2019-05-27 21:50:26.313  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$e43b97d] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
spring-boot-app    | 2019-05-27 21:50:27.043  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
spring-boot-app    | 2019-05-27 21:50:27.195  INFO 1 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
spring-boot-app    | 2019-05-27 21:50:27.196  INFO 1 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.19]
spring-boot-app    | 2019-05-27 21:50:27.472  INFO 1 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
spring-boot-app    | 2019-05-27 21:50:27.472  INFO 1 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 4316 ms
spring-boot-app    | 2019-05-27 21:50:27.928  INFO 1 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
spring-boot-app    | 2019-05-27 21:50:29.226 ERROR 1 --- [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Exception during pool initialization.
spring-boot-app    |
spring-boot-app    | com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
spring-boot-app    |
spring-boot-app    | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
spring-boot-app    |    at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:835) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:455) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:199) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:136) ~[HikariCP-3.2.0.jar!/:na]
spring-boot-app    |    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:369) ~[HikariCP-3.2.0.jar!/:na]
spring-boot-app    |    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:198) ~[HikariCP-3.2.0.jar!/:na]
spring-boot-app    |    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:467) ~[HikariCP-3.2.0.jar!/:na]
spring-boot-app    |    at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:541) ~[HikariCP-3.2.0.jar!/:na]
spring-boot-app    |    at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-3.2.0.jar!/:na]
spring-boot-app    |    at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-3.2.0.jar!/:na]
spring-boot-app    |    at org.springframework.jdbc.datasource.DataSourceUtils.fetchConnection(DataSourceUtils.java:157) ~[spring-jdbc-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:115) ~[spring-jdbc-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:78) ~[spring-jdbc-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:319) ~[spring-jdbc-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:356) ~[spring-jdbc-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.boot.autoconfigure.orm.jpa.DatabaseLookup.getDatabase(DatabaseLookup.java:73) ~[spring-boot-autoconfigure-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at org.springframework.boot.autoconfigure.orm.jpa.JpaProperties.determineDatabase(JpaProperties.java:142) ~[spring-boot-autoconfigure-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.jpaVendorAdapter(JpaBaseConfiguration.java:113) ~[spring-boot-autoconfigure-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration$$EnhancerBySpringCGLIB$$2d1a7bec.CGLIB$jpaVendorAdapter$5(<generated>) ~[spring-boot-autoconfigure-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration$$EnhancerBySpringCGLIB$$2d1a7bec$$FastClassBySpringCGLIB$$cb57d9da.invoke(<generated>) ~[spring-boot-autoconfigure-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration$$EnhancerBySpringCGLIB$$2d1a7bec.jpaVendorAdapter(<generated>) ~[spring-boot-autoconfigure-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
spring-boot-app    |    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
spring-boot-app    |    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
spring-boot-app    |    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
spring-boot-app    |    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:456) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1248) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1168) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:509) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1248) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1168) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:509) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105) ~[spring-context-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) ~[spring-boot-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) ~[spring-boot-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) ~[spring-boot-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) ~[spring-boot-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at com.jv.demo.DemoApplication.main(DemoApplication.java:10) ~[classes!/:0.0.1-SNAPSHOT]
spring-boot-app    |    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
spring-boot-app    |    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
spring-boot-app    |    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
spring-boot-app    |    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
spring-boot-app    |    at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48) ~[spring-boot-app.jar:0.0.1-SNAPSHOT]
spring-boot-app    |    at org.springframework.boot.loader.Launcher.launch(Launcher.java:87) ~[spring-boot-app.jar:0.0.1-SNAPSHOT]
spring-boot-app    |    at org.springframework.boot.loader.Launcher.launch(Launcher.java:50) ~[spring-boot-app.jar:0.0.1-SNAPSHOT]
spring-boot-app    |    at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51) ~[spring-boot-app.jar:0.0.1-SNAPSHOT]
spring-boot-app    | Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure
spring-boot-app    |
spring-boot-app    | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
spring-boot-app    |    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:na]
spring-boot-app    |    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:na]
spring-boot-app    |    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:na]
spring-boot-app    |    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490) ~[na:na]
spring-boot-app    |    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:167) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:91) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.NativeSession.connect(NativeSession.java:152) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:955) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:825) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    ... 84 common frames omitted
spring-boot-app    | Caused by: java.net.ConnectException: Connection refused (Connection refused)
spring-boot-app    |    at java.base/java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:na]
spring-boot-app    |    at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399) ~[na:na]
spring-boot-app    |    at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242) ~[na:na]
spring-boot-app    |    at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224) ~[na:na]
spring-boot-app    |    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:403) ~[na:na]
spring-boot-app    |    at java.base/java.net.Socket.connect(Socket.java:591) ~[na:na]
spring-boot-app    |    at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:155) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:65) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    ... 87 common frames omitted
spring-boot-app    |
spring-boot-app    | 2019-05-27 21:50:29.234  WARN 1 --- [           main] o.s.b.a.orm.jpa.DatabaseLookup           : Unable to determine jdbc url from datasource
spring-boot-app    |
spring-boot-app    | org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta-data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
```

答:
As your Spring Boot application is also launched in a docker image, you can't used the port exposed by docker, but instead you need to use the original port of the image.

In application.properties you need to use:

```<code>spring.datasource.url = jdbc:mysql://mysql:3306/db
</code>```

Body:
I try to run a Springboot app with mysql connection on Docker. Without docker, it works well. But when I try to deploy on a container, I have com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure.
I use this docker-compose:

version: '3'
services:
  nginx:
   container_name: nginx
   image: nginx:latest
   restart: always
   ports:
   - 80:80
   - 443:443
   volumes:
   - ./nginx/conf.d:/etc/nginx/conf.d
   depends_on:
   - spring-boot-app

  mysql:
   container_name: mysql
   image: mysql:latest
   environment:
    MYSQL_ROOT_PASSWORD: "rootpass"
    MYSQL_DATABASE: "db"
    MYSQL_USER: "user"
    MYSQL_PASSWORD: "pass"
   ports:
   - "1306:3306"
   volumes:
   - ./data/:/var/lib/mysql
   networks:
   - mysql-db
   restart: always

  spring-boot-app:
    container_name: spring-boot-app
    image: spring-boot-app
    build:
      context: ./spring-boot-app
      dockerfile: Dockerfile
    ports:
      - "8080:8080"
    depends_on:
      - mysql
    networks:
      - mysql-db
    restart: always

networks:
  mysql-db:
      driver: bridge

Here is the Dockerfile for springboot app:

FROM openjdk:11
COPY target/spring-boot-app.jar /spring-boot-app/spring-boot-app.jar
ENTRYPOINT [ "java", "-jar", "-Dspring.profiles.active=prod","/spring-boot-app/spring-boot-app.jar" ]

And finally, here is application.properties:

spring.datasource.url = jdbc:mysql://mysql:1306/db
spring.datasource.username = user
spring.datasource.password = pass

# Show or not log for each sql query
spring.jpa.show-sql = true

# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update

# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)

# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

server.port=8080

I don't think this is a port problem because i tried to set mysql to default port (3306), and it still doesn't work.

If it can help, here is docker ps :

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                  PORTS                                      NAMES
08ea16361c61        nginx:latest        "nginx -g 'daemon of…"   1 second ago        Up Less than a second   0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp   nginx
52ef8d5c2127        spring-boot-app     "java -jar -Dspring.…"   3 seconds ago       Up 1 second             0.0.0.0:8080->8080/tcp                     spring-boot-app
7bbcdc1fae3c        mysql:latest        "docker-entrypoint.s…"   4 seconds ago       Up 3 seconds            33060/tcp, 0.0.0.0:1306->3306/tcp          mysql

Edit : full stacktrace :

ubuntu@ubuntu:~/Documents/SpringBoot$ docker-compose up
Creating network "springboot_mysql-db" with driver "bridge"
Creating mysql ... done
Creating spring-boot-app ... done
Attaching to mysql, spring-boot-app
mysql              | 2019-05-27T21:50:19.645920Z 0 [Warning] [MY-011070] [Server] 'Disabling symbolic links using --skip-symbolic-links (or equivalent) is the default. Consider not using this option as it' is deprecated and will be removed in a future release.
mysql              | 2019-05-27T21:50:19.645986Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.16) starting as process 1
mysql              | 2019-05-27T21:50:20.451523Z 0 [System] [MY-010229] [Server] Starting crash recovery...
mysql              | 2019-05-27T21:50:20.466040Z 0 [System] [MY-010232] [Server] Crash recovery finished.
mysql              | 2019-05-27T21:50:20.544487Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
mysql              | 2019-05-27T21:50:20.551894Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
mysql              | 2019-05-27T21:50:20.584210Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.16'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server - GPL.
mysql              | 2019-05-27T21:50:20.682338Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: '/var/run/mysqld/mysqlx.sock' bind-address: '::' port: 33060
spring-boot-app    |
spring-boot-app    |   .   ____          _            __ _ _
spring-boot-app    |  /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
spring-boot-app    | ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
spring-boot-app    |  \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
spring-boot-app    |   '  |____| .__|_| |_|_| |_\__, | / / / /
spring-boot-app    |  =========|_|==============|___/=/_/_/_/
spring-boot-app    |  :: Spring Boot ::        (v2.1.5.RELEASE)
spring-boot-app    |
spring-boot-app    | 2019-05-27 21:50:22.884  INFO 1 --- [           main] com.jv.demo.DemoApplication              : Starting DemoApplication v0.0.1-SNAPSHOT on c69469fd7461 with PID 1 (/spring-boot-app/spring-boot-app.jar started by root in /)
spring-boot-app    | 2019-05-27 21:50:22.903  INFO 1 --- [           main] com.jv.demo.DemoApplication              : The following profiles are active: prod
spring-boot-app    | 2019-05-27 21:50:25.152  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
spring-boot-app    | 2019-05-27 21:50:25.378  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 205ms. Found 1 repository interfaces.
spring-boot-app    | 2019-05-27 21:50:26.313  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$e43b97d] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
spring-boot-app    | 2019-05-27 21:50:27.043  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
spring-boot-app    | 2019-05-27 21:50:27.195  INFO 1 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
spring-boot-app    | 2019-05-27 21:50:27.196  INFO 1 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.19]
spring-boot-app    | 2019-05-27 21:50:27.472  INFO 1 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
spring-boot-app    | 2019-05-27 21:50:27.472  INFO 1 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 4316 ms
spring-boot-app    | 2019-05-27 21:50:27.928  INFO 1 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
spring-boot-app    | 2019-05-27 21:50:29.226 ERROR 1 --- [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Exception during pool initialization.
spring-boot-app    |
spring-boot-app    | com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
spring-boot-app    |
spring-boot-app    | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
spring-boot-app    |    at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:835) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:455) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:199) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:136) ~[HikariCP-3.2.0.jar!/:na]
spring-boot-app    |    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:369) ~[HikariCP-3.2.0.jar!/:na]
spring-boot-app    |    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:198) ~[HikariCP-3.2.0.jar!/:na]
spring-boot-app    |    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:467) ~[HikariCP-3.2.0.jar!/:na]
spring-boot-app    |    at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:541) ~[HikariCP-3.2.0.jar!/:na]
spring-boot-app    |    at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-3.2.0.jar!/:na]
spring-boot-app    |    at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-3.2.0.jar!/:na]
spring-boot-app    |    at org.springframework.jdbc.datasource.DataSourceUtils.fetchConnection(DataSourceUtils.java:157) ~[spring-jdbc-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:115) ~[spring-jdbc-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:78) ~[spring-jdbc-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:319) ~[spring-jdbc-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:356) ~[spring-jdbc-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.boot.autoconfigure.orm.jpa.DatabaseLookup.getDatabase(DatabaseLookup.java:73) ~[spring-boot-autoconfigure-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at org.springframework.boot.autoconfigure.orm.jpa.JpaProperties.determineDatabase(JpaProperties.java:142) ~[spring-boot-autoconfigure-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.jpaVendorAdapter(JpaBaseConfiguration.java:113) ~[spring-boot-autoconfigure-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration$$EnhancerBySpringCGLIB$$2d1a7bec.CGLIB$jpaVendorAdapter$5(<generated>) ~[spring-boot-autoconfigure-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration$$EnhancerBySpringCGLIB$$2d1a7bec$$FastClassBySpringCGLIB$$cb57d9da.invoke(<generated>) ~[spring-boot-autoconfigure-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration$$EnhancerBySpringCGLIB$$2d1a7bec.jpaVendorAdapter(<generated>) ~[spring-boot-autoconfigure-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
spring-boot-app    |    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
spring-boot-app    |    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
spring-boot-app    |    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
spring-boot-app    |    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:456) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1248) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1168) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:509) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1248) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1168) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:509) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105) ~[spring-context-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]
spring-boot-app    |    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) ~[spring-boot-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) ~[spring-boot-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) ~[spring-boot-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) ~[spring-boot-2.1.5.RELEASE.jar!/:2.1.5.RELEASE]
spring-boot-app    |    at com.jv.demo.DemoApplication.main(DemoApplication.java:10) ~[classes!/:0.0.1-SNAPSHOT]
spring-boot-app    |    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
spring-boot-app    |    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
spring-boot-app    |    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
spring-boot-app    |    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
spring-boot-app    |    at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48) ~[spring-boot-app.jar:0.0.1-SNAPSHOT]
spring-boot-app    |    at org.springframework.boot.loader.Launcher.launch(Launcher.java:87) ~[spring-boot-app.jar:0.0.1-SNAPSHOT]
spring-boot-app    |    at org.springframework.boot.loader.Launcher.launch(Launcher.java:50) ~[spring-boot-app.jar:0.0.1-SNAPSHOT]
spring-boot-app    |    at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51) ~[spring-boot-app.jar:0.0.1-SNAPSHOT]
spring-boot-app    | Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure
spring-boot-app    |
spring-boot-app    | The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
spring-boot-app    |    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:na]
spring-boot-app    |    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:na]
spring-boot-app    |    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:na]
spring-boot-app    |    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490) ~[na:na]
spring-boot-app    |    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:167) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:91) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.NativeSession.connect(NativeSession.java:152) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:955) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:825) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    ... 84 common frames omitted
spring-boot-app    | Caused by: java.net.ConnectException: Connection refused (Connection refused)
spring-boot-app    |    at java.base/java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:na]
spring-boot-app    |    at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399) ~[na:na]
spring-boot-app    |    at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242) ~[na:na]
spring-boot-app    |    at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224) ~[na:na]
spring-boot-app    |    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:403) ~[na:na]
spring-boot-app    |    at java.base/java.net.Socket.connect(Socket.java:591) ~[na:na]
spring-boot-app    |    at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:155) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:65) ~[mysql-connector-java-8.0.16.jar!/:8.0.16]
spring-boot-app    |    ... 87 common frames omitted
spring-boot-app    |
spring-boot-app    | 2019-05-27 21:50:29.234  WARN 1 --- [           main] o.s.b.a.orm.jpa.DatabaseLookup           : Unable to determine jdbc url from datasource
spring-boot-app    |
spring-boot-app    | org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta-data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

Body:
As your Spring Boot application is also launched in a docker image, you can't used the port exposed by docker, but instead you need to use the original port of the image.

In application.properties you need to use:

spring.datasource.url = jdbc:mysql://mysql:3306/db


来源: stackexchange

问:
How to fix matplotlib installation errors
I do not know how to fix this, any help is appreciated. Thanks in advance
-J

I have tried various ways of installing and importing matplotlib (though command prompt, the text editor I've been using (geany). and neither option has worked. I've also installed the .whl file from https://matplotlib.org/ and it still has not worked (gives the same error)

I originally used the code:

import matplotlib.pyplot as plt
```

<p>in my text editor (<em>geany</em>) to install <em>matplotlib</em> but this gave the error shown below</p>

<p><strong><em>Expected Results:</em></strong></p>

<p>I expect it to import and install the right version of matplotlib (I think the right version for me is matplotlib 3.0 because I'm using python 3.7).</p>

<p><strong><em>Actual Results:</em></strong></p>

<p>When I type 'python -m pip install -U matplotlib' into my command prompt (I'm on windows 10, using python 3.7) it displays: </p>

```WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))': /simple/matplotlib/
```

<p>and repeats the message for a total of 5 times then displays: </p>

```Could not fetch URL https://pypi.org/simple/matplotlib/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/matplotlib/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))) - skipping
```

<p>and finishes with the error: </p>

```ERROR: Could not find a version that satisfies the requirement matplotlib (from versions: none)
ERROR: No matching distribution found for matplotlib
```

I have tried to fix this SSLError but I haven't made any progress in this simply because I don't know where to start.

Thanks again for any help

答:
This could happen if you're behind a firewall and console is blocked from internet. You can download the package to local and run

```<code>python -m pip --install -e /path/to/package/folder
</code>```

or download the wheel file and run

```<code>python -m pip install /path/to/wheel_file.whl
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I do not know how to fix this, any help is appreciated. Thanks in advance
-J

I have tried various ways of installing and importing matplotlib (though command prompt, the text editor I've been using (geany). and neither option has worked. I've also installed the .whl file from https://matplotlib.org/ and it still has not worked (gives the same error)

I originally used the code:

import matplotlib.pyplot as plt

in my text editor (geany) to install matplotlib but this gave the error shown below

Expected Results:

I expect it to import and install the right version of matplotlib (I think the right version for me is matplotlib 3.0 because I'm using python 3.7).

Actual Results:

When I type 'python -m pip install -U matplotlib' into my command prompt (I'm on windows 10, using python 3.7) it displays:

WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))': /simple/matplotlib/

and repeats the message for a total of 5 times then displays:

Could not fetch URL https://pypi.org/simple/matplotlib/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/matplotlib/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))) - skipping

and finishes with the error:

ERROR: Could not find a version that satisfies the requirement matplotlib (from versions: none)
ERROR: No matching distribution found for matplotlib

I have tried to fix this SSLError but I haven't made any progress in this simply because I don't know where to start.

Thanks again for any help

Body:
This could happen if you're behind a firewall and console is blocked from internet. You can download the package to local and run

python -m pip --install -e /path/to/package/folder

or download the wheel file and run

python -m pip install /path/to/wheel_file.whl


问:
running JavaScript on a file:/// page (opened with Chrome on Windows 7)
the idea:
I'd like to make a very lightweight alternative to Windows Explorer for sorting and viewing my pictures, and the best approach (if it is possible) that I can think of is using javascript and jQuery to parse the html that is generated when I enter a file:/// url into Chrome.

possible approach:
The only way I can think to do this is to have a html page linking to my script, with an iframe containing the file:/// generated page, then accessing the list of files from there.

EDIT example of the possible approach. explore.js would have a script that accesses DOM elements inside myFrame and generates a custom view of the directory

```<code><!DOCTYPE html>
<html>
  <head>
    <script src="explore.js" type="text/javascript"></script>
    <title>My Explorer</title>
  </head>
  <body>
    <iframe id="myFrame" src="file:///c:/my/pics/directory"></iframe>
  </body>
</html>
</code>```

questons:
I've played around a little with no success - is it possible to access an iframe in this way (and how would this be approached)? Is there another approach that would give me something with similar simplicity, customizability and portability?

答: Through some explorations I've found that Chrome's current behaviour is not to allow access to the DOM of an iframe from the local domain, regardless of whether the parent frame is local. I'll have to look at another approach.</p>

ContentLicense: CC BY-SA 2.5

Body:
the idea:
I'd like to make a very lightweight alternative to Windows Explorer for sorting and viewing my pictures, and the best approach (if it is possible) that I can think of is using javascript and jQuery to parse the html that is generated when I enter a file:/// url into Chrome.

possible approach:
The only way I can think to do this is to have a html page linking to my script, with an iframe containing the file:/// generated page, then accessing the list of files from there.

EDIT example of the possible approach. explore.js would have a script that accesses DOM elements inside myFrame and generates a custom view of the directory

<!DOCTYPE html>

    <title>My Explorer</title>

questons:
I've played around a little with no success - is it possible to access an iframe in this way (and how would this be approached)? Is there another approach that would give me something with similar simplicity, customizability and portability?

ContentLicense: CC BY-SA 3.0


问:
Stub function does not executed when executing test using sinon and mocha
I'm trying to mock a function in order to pass tests using sinon and mocha.

app.js:

```<code>const express = require('express');
const { isValid } = require('./utils/index');

const config = require('./config.json')[process.env.NODE_ENV || 'development']

const app = express();

app.get('/', (req, res)=> {

    const url = config.url;
   try {
    const validUrl = isValid(url)
    .then(() => {
        return res.redirect(`https://${url}`);
    })
    .catch(() => {
        return res.status(400).send('Unable to redirect to the given url');
    })
   } catch(error) {
      return res.send('Internal Server Error')
   }

})

const port = process.env.port || 3000;

const server = app.listen(port, ()=> {
    console.log('server listens on 127.0.0.1:3000');
})

module.exports = {server, app};
</code>```

config.json:

```<code>{
"development": {
    "url": "www.stackoverflow.com"
},
"test": {
    "url": "www.stackoverflow.com"
}

}
</code>```

utils/index.js:

```<code>const http = require('http');

module.exports.isValid = (url) => {
    const options = {
        method: 'HEAD',
        host: url
    }
const promise = new Promise((resolve, reject) => {
    const req = http.request(options, () => {
        return resolve(true)
    })
    req.on('error', () => {
        return reject(new Error('Not valid'))
    })

    req.end();
})

return promise;
}
</code>```

test/index.js:

```<code>const request = require('supertest');
const chai = require('chai');
const sinon = require('sinon');
const index = require('../utils/index')
const { expect } = chai;

const { server } = require('../app');
const {url} = require('../config.json')['test'];

describe('isValid Test', () => {

    it('Should redirects an error when the url is not valid', async() => {

        const stub = sinon.stub(index, 'isValid');
        stub.withArgs(url).returns(Promise.reject(new Error('Not Valid')));
        const { status } = await request(server).get('/');

        expect(status).to.equal(400);

    })
})
</code>```

When I execute the test I got this error:

```<code>    (node:23622) UnhandledPromiseRejectionWarning: Error: Not Valid
    at Context.it (/home/hs/perso/mockTests/chaiMock/test/index.js:17:52)
    at callFn (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runnable.js:387:21)
    at Test.Runnable.run (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runnable.js:379:7)
    at Runner.runTest (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:535:10)
    at /home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:653:12
    at next (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:447:14)
    at /home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:457:7
    at next (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:362:14)
    at Immediate.<anonymous> (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:425:5)
    at runCallback (timers.js:705:18)
    at tryOnImmediate (timers.js:676:5)
    at processImmediate (timers.js:658:5)
(node:23622) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:23622) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
url:  www.stackoverflow.com
    1) Should redirects an error when the url is not valid

  0 passing (122ms)
  1 failing

  1) isValid Test
       Should redirects an error when the url is not valid:

      AssertionError: expected 302 to equal 400
      + expected - actual

      -302
      +400

      at Context.it (test/index.js:22:27)
      at process._tickCallback (internal/process/next_tick.js:68:7)
</code>```

答: Try to check the value you are send at "host" on your request, I believe you are hitting at "www.stackoverflow.com" and getting a http code 400 that's why you are getting an error on your test</p>

Body:
I'm trying to mock a function in order to pass tests using sinon and mocha.

app.js:

const express = require('express');
const { isValid } = require('./utils/index');

const config = require('./config.json')[process.env.NODE_ENV || 'development']

const app = express();

app.get('/', (req, res)=> {

    const url = config.url;
   try {
    const validUrl = isValid(url)
    .then(() => {
        return res.redirect(`https://${url}`);
    })
    .catch(() => {
        return res.status(400).send('Unable to redirect to the given url');
    })
   } catch(error) {
      return res.send('Internal Server Error')
   }

})

const port = process.env.port || 3000;

const server = app.listen(port, ()=> {
    console.log('server listens on 127.0.0.1:3000');
})

module.exports = {server, app};

config.json:

{
"development": {
    "url": "www.stackoverflow.com"
},
"test": {
    "url": "www.stackoverflow.com"
}

}

utils/index.js:

const http = require('http');

module.exports.isValid = (url) => {
    const options = {
        method: 'HEAD',
        host: url
    }
const promise = new Promise((resolve, reject) => {
    const req = http.request(options, () => {
        return resolve(true)
    })
    req.on('error', () => {
        return reject(new Error('Not valid'))
    })

    req.end();
})

return promise;
}

test/index.js:

const request = require('supertest');
const chai = require('chai');
const sinon = require('sinon');
const index = require('../utils/index')
const { expect } = chai;

const { server } = require('../app');
const {url} = require('../config.json')['test'];

describe('isValid Test', () => {

    it('Should redirects an error when the url is not valid', async() => {

        const stub = sinon.stub(index, 'isValid');
        stub.withArgs(url).returns(Promise.reject(new Error('Not Valid')));
        const { status } = await request(server).get('/');

        expect(status).to.equal(400);

    })
})

When I execute the test I got this error:

    (node:23622) UnhandledPromiseRejectionWarning: Error: Not Valid
    at Context.it (/home/hs/perso/mockTests/chaiMock/test/index.js:17:52)
    at callFn (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runnable.js:387:21)
    at Test.Runnable.run (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runnable.js:379:7)
    at Runner.runTest (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:535:10)
    at /home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:653:12
    at next (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:447:14)
    at /home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:457:7
    at next (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:362:14)
    at Immediate.<anonymous> (/home/hs/perso/mockTests/chaiMock/node_modules/mocha/lib/runner.js:425:5)
    at runCallback (timers.js:705:18)
    at tryOnImmediate (timers.js:676:5)
    at processImmediate (timers.js:658:5)
(node:23622) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:23622) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
url:  www.stackoverflow.com
    1) Should redirects an error when the url is not valid

  0 passing (122ms)
  1 failing

  1) isValid Test
       Should redirects an error when the url is not valid:

      AssertionError: expected 302 to equal 400
      + expected - actual

      -302
      +400

      at Context.it (test/index.js:22:27)
      at process._tickCallback (internal/process/next_tick.js:68:7)


问:
how to create file object in js?
I get from the server an object that should represent a file, and it looks like this:

```<code>name: "סריקה0252.pdf",
url: "https:XYZ/ABC/1/סריקה0252_28-05-2019_11:24:40.pdf"
</code>```

Now, I want to convert it to a file of JavaScript ,

Is it possible to do so?

答:
```<code>function urlToBlob(url){
 return new Promise((resolve,reject)=>{
    var xhr = new XMLHttpRequest();
    xhr.open( "GET", url, true );
    xhr.responseType = "blob";
    xhr.onload = function( e ) {
        resolve(this.response)
    };
    xhr.onerror = function( error ){
        reject(error)
    }
    xhr.send();
 })
}
let fileUrl = "https:XYZ/ABC/1/סריקה0252_28-05-2019_11:24:40.pdf"
urlToBlob(fileUrl).then(function(blob){
  console.log(blob)
  // you will get blob object of that file here
})
</code>```

Here is the function to convert it. this will load the file first to the local. once it will be loaded, it will return blob object as return type is defined as a blob.

Title: how to create file object in js?

Body:
I get from the server an object that should represent a file, and it looks like this:

name: "סריקה0252.pdf",
url: "https:XYZ/ABC/1/סריקה0252_28-05-2019_11:24:40.pdf"

Now, I want to convert it to a file of JavaScript ,

Is it possible to do so?

Body:
function urlToBlob(url){
 return new Promise((resolve,reject)=>{
    var xhr = new XMLHttpRequest();
    xhr.open( "GET", url, true );
    xhr.responseType = "blob";
    xhr.onload = function( e ) {
        resolve(this.response)
    };
    xhr.onerror = function( error ){
        reject(error)
    }
    xhr.send();
 })
}
let fileUrl = "https:XYZ/ABC/1/סריקה0252_28-05-2019_11:24:40.pdf"
urlToBlob(fileUrl).then(function(blob){
  console.log(blob)
  // you will get blob object of that file here
})

Here is the function to convert it. this will load the file first to the local. once it will be loaded, it will return blob object as return type is defined as a blob.


问:
spark.createDataFrame creates a DF but df.collect.foreach(println) fails with RuntimeException
Spark version: Scala 2.12.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_211)

In the following code, spark.createDataFrame creates a DF but the dataframe is useless (I can't print it or do anything with it).

val fieldSeparator = '\u001D' // 1D = group separator; 21 = !; 7C = |;
val recordSeparator = '\u001E' // 1E = record separator

val myRDD = dataSet.toDF().rdd.take(10)
    .map(r => r.mkString(fieldSeparator.toString))
val schema = new StructType()
    .add("displayname", StringType, true)
    .add("reputation", IntegerType, true)
    .add("numberOfPosts", LongType, true)
    .add("score", DoubleType, true)

println("---------- Creating DF from RDD: --------------")
val df = spark.createDataFrame(
    spark.sparkContext
         .parallelize(myRDD.map(r => r.split(fieldSeparator.toString)))
         .map(a => Row.fromSeq(a)),
    schema
)
println("---------- Successfully created DF from RDD (?) --------------")

println(df.getClass) // this prints: class org.apache.spark.sql.Dataset
df.printSchema()
/*
   root
   |-- displayname: string (nullable = true)
   |-- reputation: integer (nullable = true)
   |-- numberOfPosts: long (nullable = true)
   |-- score: double (nullable = true)
*/
myRDD.foreach(println) // prints all records correctly
df.collect.foreach(println)
// this fails with error: RuntimeException: java.lang.String is not a valid
// external type for schema of int ???
```

The result should be same as myRDD.foreach(println) which works fine.

答:
Let's first create a minimal, reproducible instance of your problem. BTW, this is what you should try to do each time you ask a question ;-)

// A RDD of string
val rdd = sc.parallelize(Seq("oli,15,56,0.5", "you,45,49987787,0.4"))

// your schema
val schema = new StructType()
    .add("displayname", StringType, true)
    .add("reputation", IntegerType, true)
    .add("numberOfPosts", LongType, true)
    .add("score", DoubleType, true)

// Now, let's try to create a dataframe
val rddOfRows = rdd.map(_.split(",")).map(Row.fromSeq(_))
val df = spark.createDataFrame(rddOfRows, schema)
// we can print its schema
df.printSchema
root
 |-- displayname: string (nullable = true)
 |-- reputation: integer (nullable = true)
 |-- numberOfPosts: long (nullable = true)
 |-- score: double (nullable = true)

// but show triggers the exception you mentioned
df.show
  java.lang.RuntimeException: java.lang.String is not a valid external type for
  schema of int
```

<p>Why? You need to remember that spark is lazy. As long as you do not collect or write data, spark does nothing. When you use <code>createDataFrame</code>, nothing happens. This is why you do not get any errors. When you print the schema, spark simply prints the schema you provided. Yet, when I call <code>show</code>, I ask spark to do something and it triggers all the dependent computations.</p>

<p>The problem you see is that spark is expecting an int, but you provide a string. Spark does not cast your data when creating the dataframe. You have several possibilities to solve your problem. One solution could be to cast the fields beforehand like this:</p>

<pre class="lang-scala prettyprint-override"><code>val rddOfRow = rdd
  .map(_.split(","))
  .map(_ match { case Array(a, b, c, d) => (a, b.toInt, c.toLong, d.toDouble) })
  .map(Row.fromTuple(_))
// and the rest of the code remains unchanged
</code>```

Body:
Spark version: Scala 2.12.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_211)

In the following code, spark.createDataFrame creates a DF but the dataframe is useless (I can't print it or do anything with it).

val fieldSeparator = '\u001D' // 1D = group separator; 21 = !; 7C = |;
val recordSeparator = '\u001E' // 1E = record separator

val myRDD = dataSet.toDF().rdd.take(10)
    .map(r => r.mkString(fieldSeparator.toString))
val schema = new StructType()
    .add("displayname", StringType, true)
    .add("reputation", IntegerType, true)
    .add("numberOfPosts", LongType, true)
    .add("score", DoubleType, true)

println("---------- Creating DF from RDD: --------------")
val df = spark.createDataFrame(
    spark.sparkContext
         .parallelize(myRDD.map(r => r.split(fieldSeparator.toString)))
         .map(a => Row.fromSeq(a)),
    schema
)
println("---------- Successfully created DF from RDD (?) --------------")

println(df.getClass) // this prints: class org.apache.spark.sql.Dataset
df.printSchema()
/*
   root
   |-- displayname: string (nullable = true)
   |-- reputation: integer (nullable = true)
   |-- numberOfPosts: long (nullable = true)
   |-- score: double (nullable = true)
*/
myRDD.foreach(println) // prints all records correctly
df.collect.foreach(println)
// this fails with error: RuntimeException: java.lang.String is not a valid
// external type for schema of int ???

The result should be same as myRDD.foreach(println) which works fine.

Body:
Let's first create a minimal, reproducible instance of your problem. BTW, this is what you should try to do each time you ask a question ;-)

// A RDD of string
val rdd = sc.parallelize(Seq("oli,15,56,0.5", "you,45,49987787,0.4"))

// your schema
val schema = new StructType()
    .add("displayname", StringType, true)
    .add("reputation", IntegerType, true)
    .add("numberOfPosts", LongType, true)
    .add("score", DoubleType, true)

// Now, let's try to create a dataframe
val rddOfRows = rdd.map(_.split(",")).map(Row.fromSeq(_))
val df = spark.createDataFrame(rddOfRows, schema)
// we can print its schema
df.printSchema
root
 |-- displayname: string (nullable = true)
 |-- reputation: integer (nullable = true)
 |-- numberOfPosts: long (nullable = true)
 |-- score: double (nullable = true)

// but show triggers the exception you mentioned
df.show
  java.lang.RuntimeException: java.lang.String is not a valid external type for
  schema of int

Why? You need to remember that spark is lazy. As long as you do not collect or write data, spark does nothing. When you use createDataFrame, nothing happens. This is why you do not get any errors. When you print the schema, spark simply prints the schema you provided. Yet, when I call show, I ask spark to do something and it triggers all the dependent computations.

The problem you see is that spark is expecting an int, but you provide a string. Spark does not cast your data when creating the dataframe. You have several possibilities to solve your problem. One solution could be to cast the fields beforehand like this:

val rddOfRow = rdd
  .map(_.split(","))
  .map(_ match { case Array(a, b, c, d) => (a, b.toInt, c.toLong, d.toDouble) })
  .map(Row.fromTuple(_))
// and the rest of the code remains unchanged


问:
Facing error while running Docker on Tensorflow serving image
I have trained a Tensorflow Object detection model. I am trying to make a REST request using the tensorflow serving image on docker. (following instruction from https://github.com/tensorflow/serving )

```<code>TESTDATA="$(pwd)/serving/tensorflow_serving/servables/tensorflow/testdata/"

 docker run -t --rm -p 8501:8501 \
    -v "$TESTDATA/my_model:/models/work_place_safety" \
     -e MODEL_NAME=work_place_safety \
     tensorflow/serving &
</code>```

I am facing below error message-

$ C:\Program Files\Docker\Docker\Resources\bin\docker.exe: Error response from daemon: Mount denied:
The source path "C:/Users/Desktop/models/serving/tensorflow_serving/servables/tensorflow/testdata/saved_model_work_place_safety;C"
doesn't exist and is not known to Docker.
See 'C:\Program Files\Docker\Docker\Resources\bin\docker.exe run --help'.

I wonder why its including ";C" at the end of source path and throwing an error.

Any Help is much appreciated.

Thanks

答:
What is the value of my_model. Is it saved_model_work_place_safety.

Are you sure that your Saved Objection Detection Model is in the Folder, saved_model_work_place_safety and that Folder is in the path, $(pwd)/serving/tensorflow_serving/servables/tensorflow/testdata/?

If it is not inside testdata, you should mention the correct path, where saved_model_work_place_safety is present.

Folder structure should be something like this =>

saved_model_work_place_safety => 00000123 or 1556272508 or 1 => .pb file and Variables Folder.

Body:
I have trained a Tensorflow Object detection model. I am trying to make a REST request using the tensorflow serving image on docker. (following instruction from https://github.com/tensorflow/serving )

TESTDATA="$(pwd)/serving/tensorflow_serving/servables/tensorflow/testdata/"

 docker run -t --rm -p 8501:8501 \
    -v "$TESTDATA/my_model:/models/work_place_safety" \
     -e MODEL_NAME=work_place_safety \
     tensorflow/serving &

I am facing below error message-

$ C:\Program Files\Docker\Docker\Resources\bin\docker.exe: Error response from daemon: Mount denied:
The source path "C:/Users/Desktop/models/serving/tensorflow_serving/servables/tensorflow/testdata/saved_model_work_place_safety;C"
doesn't exist and is not known to Docker.
See 'C:\Program Files\Docker\Docker\Resources\bin\docker.exe run --help'.

I wonder why its including ";C" at the end of source path and throwing an error.

Any Help is much appreciated.

Thanks


问:
How to reverse sort a map and send it to model in go lang
I want to send a reverse order of a list of books that are stored in a map and send this to a model instead of the map in its current order.

I need to display a list in reverse order of date entered which is pubDate so that the webpage (model) displays the most recently added books instead of the books added first.

I have tried many various sort methods listed but I do not know how I would send this to the model.  For example, I tried
import "sort"

```<code>var m map[int]string
var keys []int
for k := range m {
    keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
    fmt.Println("Key:", k, "Value:", m[k])
}
</code>```

I also tried
sort.Slice(ad, func(i, j int) bool {

```<code>    return ad[i].date.Before(ad[j].date)})
</code>```

there are many others but I can not seem to get any working.

```<code>type Book struct {
    ID     int64  `json:"id"`
    Title  string `json:"title"`
    Author string `json:"author"`
    pubDate time.Time `json:"pubDate"`
}

var bookModels = map[string]*Book{}

s := res.NewService("library")

    // Add handlers for "library.book.$id" models
    s.Handle(
        "book.$id",
        res.Access(res.AccessGranted),
        res.GetModel(getBookHandler),
        res.Set(setBookHandler),
    )

    // Add handlers for "library.books" collection
    s.Handle(
        "books",
        res.Access(res.AccessGranted),
        res.GetCollection(getBooksHandler),
        res.New(newBookHandler),
        res.Call("delete", deleteBookHandler),
    )

func getBookHandler(r res.ModelRequest) {

    book := bookModels[r.ResourceName()]
    if book == nil {
        r.NotFound()
        return
    }
    r.Model(book)
}
</code>```

Mainly I get errors that the map does not allow indexing, or the wrong type, or cant access the fields, etc...  How can you use a map and send it to a model and ensure that you have the most recent items listed first on the web page?

答: maps in go are always returned in a random order unless you use a key to access a value. so you can not reverse the order of a map because there is no order in the first place</p>

Body:
I want to send a reverse order of a list of books that are stored in a map and send this to a model instead of the map in its current order.

I need to display a list in reverse order of date entered which is pubDate so that the webpage (model) displays the most recently added books instead of the books added first.

I have tried many various sort methods listed but I do not know how I would send this to the model.  For example, I tried
import "sort"

var m map[int]string
var keys []int
for k := range m {
    keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
    fmt.Println("Key:", k, "Value:", m[k])
}

I also tried
sort.Slice(ad, func(i, j int) bool {

    return ad[i].date.Before(ad[j].date)})

there are many others but I can not seem to get any working.

type Book struct {
    ID     int64  `json:"id"`
    Title  string `json:"title"`
    Author string `json:"author"`
    pubDate time.Time `json:"pubDate"`
}

var bookModels = map[string]*Book{}

s := res.NewService("library")

    // Add handlers for "library.book.$id" models
    s.Handle(
        "book.$id",
        res.Access(res.AccessGranted),
        res.GetModel(getBookHandler),
        res.Set(setBookHandler),
    )

    // Add handlers for "library.books" collection
    s.Handle(
        "books",
        res.Access(res.AccessGranted),
        res.GetCollection(getBooksHandler),
        res.New(newBookHandler),
        res.Call("delete", deleteBookHandler),
    )

func getBookHandler(r res.ModelRequest) {

    book := bookModels[r.ResourceName()]
    if book == nil {
        r.NotFound()
        return
    }
    r.Model(book)
}

Mainly I get errors that the map does not allow indexing, or the wrong type, or cant access the fields, etc...  How can you use a map and send it to a model and ensure that you have the most recent items listed first on the web page?


问:
becomeFirstResponder slows down app
I have two textfields for username and password and a submit button. When the submit button is pressed a check is performed to see if the username and password was typed or not. If not it shows an alert message and the field whose value was not entered becomes the first responder.

```<code>-(IBAction)loginPressed:(id)sender {

    if ([username.text length] == 0)
    {
        [self showAlert:@"Invalid Username/ Password"];
       [username becomeFirstResponder];
        return;
    }

    if ([password.text length] == 0)
    {
        [self showAlert:@"Invalid Username/ Password"];
      [password becomeFirstResponder];
        return;
    }
}
</code>```

I observed that on clicking the button, the button remains selected for about 1.5 seconds and then the alert is shown. If I comment out the becomeFirstResponder method, it works without any pause. However I need becomeFirstResponder to be there. How do I speed things up using this?

答: Switch the ordering of becomeFirstResponder and showAlert.</p>

Title: becomeFirstResponder slows down app

Body:
I have two textfields for username and password and a submit button. When the submit button is pressed a check is performed to see if the username and password was typed or not. If not it shows an alert message and the field whose value was not entered becomes the first responder.

-(IBAction)loginPressed:(id)sender {

    if ([username.text length] == 0)
    {
        [self showAlert:@"Invalid Username/ Password"];
       [username becomeFirstResponder];
        return;
    }

    if ([password.text length] == 0)
    {
        [self showAlert:@"Invalid Username/ Password"];
      [password becomeFirstResponder];
        return;
    }
}

I observed that on clicking the button, the button remains selected for about 1.5 seconds and then the alert is shown. If I comment out the becomeFirstResponder method, it works without any pause. However I need becomeFirstResponder to be there. How do I speed things up using this?


问:
How do we represent the Python/numpy function "zeros_like" in Julia language
I am a bit new to Julia but I have some knowledge in Python. I am now learning Julia and I want to know how to represent the Python function "zeros_like" from Numpy in Julia.
The python code is below:

import numpy as np
a = [3] #vector of one number
b = np.zeros_like(a)
```

答:
Base.zero function returns the zero element (the "additive identity element" in the doc) for the type of its input argument:

```<code>julia> a = [3]
1-element Array{Int64,1}:
 3

julia> zero(a)
1-element Array{Int64,1}:
 0
</code>```

or

```<code>julia> zeros(Int, size(a))
1-element Array{Int64,1}:
 0
</code>```

Body:
Base.zero function returns the zero element (the "additive identity element" in the doc) for the type of its input argument:

julia> a = [3]
1-element Array{Int64,1}:
 3

julia> zero(a)
1-element Array{Int64,1}:
 0

or

julia> zeros(Int, size(a))
1-element Array{Int64,1}:
 0


问:
Parsing CSV file and get a value of the filed from it
Question regarding Mule 4 and DWL syntax.
I have a file listener that is expecting a csv file.

let say the file is in this format

value1, value2, value3, value4

Then I have a "var" message processor and in there need to assign the value of value3 (third field) to a variable.
How can I dod that?
Your help is appreciated.

答:
If you only have the one line you can access the first row using index 0: [0], then access the third field using index 2 [2]. Indexes start at 0.

Note, if your CSV does NOT have a header row, make sure to add this to the file:listener outputMimeType="application/csv;header=false" to let dw know there is no header row:

```<code><flow name="csv">
        <file:listener directory="/path/to/dir"  outputMimeType="application/csv;header=false" >
            <scheduling-strategy >
                <fixed-frequency frequency="100000" />
            </scheduling-strategy>
        </file:listener>

        <logger level="INFO" message="#[payload]" />
        <set-variable value="#[output application/java --- payload[0][2] as String]" variableName="myVar" />

        <logger level="INFO" message="#[vars.myVar]" />
    </flow>
</code>```

Also note you can use the transform component to set-variables also for more complex transformations where better formatting is required:

```<code><ee:transform>
            <ee:variables>
                <ee:set-variable variableName="myVar" ><![CDATA[%dw 2.0
output application/java
---
payload[0][2] as String]]></ee:set-variable>
            </ee:variables>
        </ee:transform>
</code>```

Body:
If you only have the one line you can access the first row using index 0: [0], then access the third field using index 2 [2]. Indexes start at 0.

Note, if your CSV does NOT have a header row, make sure to add this to the file:listener outputMimeType="application/csv;header=false" to let dw know there is no header row:

<flow name="csv">
        <file:listener directory="/path/to/dir"  outputMimeType="application/csv;header=false" >
            <scheduling-strategy >
                <fixed-frequency frequency="100000" />
            </scheduling-strategy>
        </file:listener>

        <logger level="INFO" message="#[payload]" />
        <set-variable value="#[output application/java --- payload[0][2] as String]" variableName="myVar" />

        <logger level="INFO" message="#[vars.myVar]" />
    </flow>

Also note you can use the transform component to set-variables also for more complex transformations where better formatting is required:

<ee:transform>
            <ee:variables>
                <ee:set-variable variableName="myVar" ><![CDATA[%dw 2.0
output application/java
---
payload[0][2] as String]]></ee:set-variable>
            </ee:variables>
        </ee:transform>


问:
Can you "line-break" a table using CSS by width or number of columns?
I have an HTML table with 17 columns over 2 header rows and 1 body row. On most desktop views, this table fits nicely with my design, but on small screens the table overhangs its parent element and a significant amount of horizontal scroll is created.

I was wondering if there's a way in CSS/HTML/JS to catch a table going over a certain width, or counting a number of columns (or any other sensible way of doing it), and causing it to 'break' over into a new line, the same way a line break would be added to a paragraph. I want to catch this programatically (rather than just rewriting the table to multiple tables) as the large-screen experience is dramatically better without this hypothetical column-line break.

Ideally I'd like to keep the css definitions of table-cell etc (as in, not just make everything display: block and be done with it).

To add to the complications, some of the header cells in the top row span two columns. I'm hoping a solution can be found that either doesn't break those cells, or copies the text in the cell to both columns after a break is made.

This is all inside the Foundation 6 framework, if there's any tools there that I've missed. I tried using Foundation's
, but it doesn't work - it only shows the body row, I think because some of the header cells span multiple columns.

答:
You can try to use css-grid with media-query

More

Example

```<code>HTML
<ul>
 <li>A</li>
 <li>B</li>
 <li>C</li>
 <li>D</li>
 <li>E</li>
 <li>F</li>
</ul>

CSS
ul {
 display: grid;
 grid-template-columns: 140px 140px 140px 140px;
 grid-gap: 10px;
}

@media only screen and (max-width: 800px) {
 ul {
  grid-template-columns: 200px 200px;
 }
</code>```

}

Body:
You can try to use css-grid with media-query

More

Example

HTML
<ul>
 <li>A</li>
 <li>B</li>
 <li>C</li>
 <li>D</li>
 <li>E</li>
 <li>F</li>
</ul>

CSS
ul {
 display: grid;
 grid-template-columns: 140px 140px 140px 140px;
 grid-gap: 10px;
}

@media only screen and (max-width: 800px) {
 ul {
  grid-template-columns: 200px 200px;
 }

}