问:
feign.RetryableException: Connection refused (Connection refused) executing POST
I am using spring cloud to configure microservices. I used Jhipster to generate the application.

I have three applications JHipster-Registry, Gateway, and admin application

All three application are deployed on separate machine/ip-address. admin and gateway are configured with registry. Following is the gateway configuration

```<code>eureka:
    client:
        enabled: true
        healthcheck:
            enabled: true
        fetch-registry: true
        register-with-eureka: true
        instance-info-replication-interval-seconds: 10
        registry-fetch-interval-seconds: 10
        service-url:
            defaultZone: http://admin:${jhipster.registry.password}@ip-address:8080/jhipster-registry-3.1.0/eureka/
    instance:
        appname: applicationgateway
        instanceId: applicationgateway:${spring.application.instance-id:${random.value}}
        lease-renewal-interval-in-seconds: 5
        lease-expiration-duration-in-seconds: 10
        status-page-url-path: ${server.context-path:/}${management.context-path}/info
        health-check-url-path: ${server.context-path:/}${management.context-path}/health
        home-page-url-path: ${server.context-path:/}
        metadata-map:
            zone: primary # This is needed for the load balancer
            profile: ${spring.profiles.active}
            version: ${info.project.version}
        prefer-ip-address: true
</code>```

While the communication between admin to gateway is working fine, I am receiving the following error whenever gateway is trying to invoke an api from admin application. Since I am quite new to this requesting any help available.

```<code>feign.RetryableException: Connection refused (Connection refused) executing POST http://applicationadmin/applicationadmin-0.0.1-SNAPSHOT/api/notification
    at feign.FeignException.errorExecuting(FeignException.java:67)
    at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:104)
    at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:76)
    at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:103)
    at com.sun.proxy.$Proxy404.save(Unknown Source)
    at com.application.gateway.bll.impl.UserBllImpl.resendOTP(UserBllImpl.java:838)
    at com.application.gateway.bll.impl.UserBllImpl.addGhostUser(UserBllImpl.java:1141)
    at com.application.gateway.web.rest.UserRegisterRest.save(UserRegisterRest.java:536)
    at com.application.gateway.web.rest.UserRegisterRest$$FastClassBySpringCGLIB$$c32e2604.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)
    at com.application.gateway.aop.logging.LoggingAspect.logAround(LoggingAspect.java:85)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:629)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:618)
    at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:62)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
    at com.application.gateway.web.rest.UserRegisterRest$$EnhancerBySpringCGLIB$$83528812.save(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.codahale.metrics.servlet.AbstractInstrumentedFilter.doFilter(AbstractInstrumentedFilter.java:111)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:110)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at com.application.gateway.security.jwt.JWTFilter.doFilter(JWTFilter.java:43)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:115)
    at org.springframework.boot.web.support.ErrorPageFilter.access$000(ErrorPageFilter.java:59)
    at org.springframework.boot.web.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:90)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: Connection refused (Connection refused)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:463)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:558)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:242)
    at sun.net.www.http.HttpClient.New(HttpClient.java:339)
    at sun.net.www.http.HttpClient.New(HttpClient.java:357)
    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1220)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1156)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1050)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:984)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1334)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1309)
    at feign.Client$Default.convertAndSend(Client.java:133)
    at feign.Client$Default.execute(Client.java:73)
    at org.springframework.cloud.netflix.feign.ribbon.RetryableFeignLoadBalancer$1.doWithRetry(RetryableFeignLoadBalancer.java:92)
    at org.springframework.cloud.netflix.feign.ribbon.RetryableFeignLoadBalancer$1.doWithRetry(RetryableFeignLoadBalancer.java:77)
    at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:286)
    at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:163)
    at org.springframework.cloud.netflix.feign.ribbon.RetryableFeignLoadBalancer.execute(RetryableFeignLoadBalancer.java:77)
    at org.springframework.cloud.netflix.feign.ribbon.RetryableFeignLoadBalancer.execute(RetryableFeignLoadBalancer.java:48)
    at com.netflix.client.AbstractLoadBalancerAwareClient$1.call(AbstractLoadBalancerAwareClient.java:109)
    at com.netflix.loadbalancer.reactive.LoadBalancerCommand$3$1.call(LoadBalancerCommand.java:303)
    at com.netflix.loadbalancer.reactive.LoadBalancerCommand$3$1.call(LoadBalancerCommand.java:287)
    at rx.internal.util.ScalarSynchronousObservable$3.call(ScalarSynchronousObservable.java:231)
    at rx.internal.util.ScalarSynchronousObservable$3.call(ScalarSynchronousObservable.java:228)
    at rx.Observable.unsafeSubscribe(Observable.java:10211)
    at rx.internal.operators.OnSubscribeConcatMap$ConcatMapSubscriber.drain(OnSubscribeConcatMap.java:286)
    at rx.internal.operators.OnSubscribeConcatMap$ConcatMapSubscriber.onNext(OnSubscribeConcatMap.java:144)
    at com.netflix.loadbalancer.reactive.LoadBalancerCommand$1.call(LoadBalancerCommand.java:185)
    at com.netflix.loadbalancer.reactive.LoadBalancerCommand$1.call(LoadBalancerCommand.java:180)
    at rx.Observable.unsafeSubscribe(Observable.java:10211)
    at rx.internal.operators.OnSubscribeConcatMap.call(OnSubscribeConcatMap.java:94)
    at rx.internal.operators.OnSubscribeConcatMap.call(OnSubscribeConcatMap.java:42)
    at rx.Observable.unsafeSubscribe(Observable.java:10211)
    at rx.internal.operators.OperatorRetryWithPredicate$SourceSubscriber$1.call(OperatorRetryWithPredicate.java:127)
    at rx.internal.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.enqueue(TrampolineScheduler.java:73)
    at rx.internal.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.schedule(TrampolineScheduler.java:52)
    at rx.internal.operators.OperatorRetryWithPredicate$SourceSubscriber.onNext(OperatorRetryWithPredicate.java:79)
    at rx.internal.operators.OperatorRetryWithPredicate$SourceSubscriber.onNext(OperatorRetryWithPredicate.java:45)
    at rx.internal.util.ScalarSynchronousObservable$WeakSingleProducer.request(ScalarSynchronousObservable.java:276)
    at rx.Subscriber.setProducer(Subscriber.java:209)
    at rx.internal.util.ScalarSynchronousObservable$JustOnSubscribe.call(ScalarSynchronousObservable.java:138)
    at rx.internal.util.ScalarSynchronousObservable$JustOnSubscribe.call(ScalarSynchronousObservable.java:129)
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
    at rx.Observable.subscribe(Observable.java:10307)
    at rx.Observable.subscribe(Observable.java:10274)
    at rx.observables.BlockingObservable.blockForSingle(BlockingObservable.java:445)
    at rx.observables.BlockingObservable.single(BlockingObservable.java:342)
    at com.netflix.client.AbstractLoadBalancerAwareClient.executeWithLoadBalancer(AbstractLoadBalancerAwareClient.java:117)
    at org.springframework.cloud.netflix.feign.ribbon.LoadBalancerFeignClient.execute(LoadBalancerFeignClient.java:63)
    at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:97)
</code>```

答:
I had this error when I deploy my spring boot microservices (transfering data by openFeign) in docker, after changing the params by dynamic variables in both application.properties and docker-compose.yml, everything working properly.

For example in application.properties:

```<code>spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:${MYSQL_PORT:3306}/my_app_name
spring.datasource.username=${MYSQL_USER:ur_username}
spring.datasource.password=${MYSQL_PASSWORD:ur_password}
</code>```

In docker-compose.yml:

```<code>environment:
  MYSQL_HOST: my_mysql_container_name
  MYSQL_USER: ur_username
  MYSQL_PASSWORD: ur_password
  MYSQL_PORT: 3306
</code>```

Body:
I am using spring cloud to configure microservices. I used Jhipster to generate the application.

I have three applications JHipster-Registry, Gateway, and admin application

All three application are deployed on separate machine/ip-address. admin and gateway are configured with registry. Following is the gateway configuration

eureka:
    client:
        enabled: true
        healthcheck:
            enabled: true
        fetch-registry: true
        register-with-eureka: true
        instance-info-replication-interval-seconds: 10
        registry-fetch-interval-seconds: 10
        service-url:
            defaultZone: http://admin:${jhipster.registry.password}@ip-address:8080/jhipster-registry-3.1.0/eureka/
    instance:
        appname: applicationgateway
        instanceId: applicationgateway:${spring.application.instance-id:${random.value}}
        lease-renewal-interval-in-seconds: 5
        lease-expiration-duration-in-seconds: 10
        status-page-url-path: ${server.context-path:/}${management.context-path}/info
        health-check-url-path: ${server.context-path:/}${management.context-path}/health
        home-page-url-path: ${server.context-path:/}
        metadata-map:
            zone: primary # This is needed for the load balancer
            profile: ${spring.profiles.active}
            version: ${info.project.version}
        prefer-ip-address: true

While the communication between admin to gateway is working fine, I am receiving the following error whenever gateway is trying to invoke an api from admin application. Since I am quite new to this requesting any help available.

feign.RetryableException: Connection refused (Connection refused) executing POST http://applicationadmin/applicationadmin-0.0.1-SNAPSHOT/api/notification
    at feign.FeignException.errorExecuting(FeignException.java:67)
    at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:104)
    at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:76)
    at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:103)
    at com.sun.proxy.$Proxy404.save(Unknown Source)
    at com.application.gateway.bll.impl.UserBllImpl.resendOTP(UserBllImpl.java:838)
    at com.application.gateway.bll.impl.UserBllImpl.addGhostUser(UserBllImpl.java:1141)
    at com.application.gateway.web.rest.UserRegisterRest.save(UserRegisterRest.java:536)
    at com.application.gateway.web.rest.UserRegisterRest$$FastClassBySpringCGLIB$$c32e2604.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)
    at com.application.gateway.aop.logging.LoggingAspect.logAround(LoggingAspect.java:85)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:629)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:618)
    at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:62)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
    at com.application.gateway.web.rest.UserRegisterRest$$EnhancerBySpringCGLIB$$83528812.save(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.codahale.metrics.servlet.AbstractInstrumentedFilter.doFilter(AbstractInstrumentedFilter.java:111)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:110)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at com.application.gateway.security.jwt.JWTFilter.doFilter(JWTFilter.java:43)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:115)
    at org.springframework.boot.web.support.ErrorPageFilter.access$000(ErrorPageFilter.java:59)
    at org.springframework.boot.web.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:90)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: Connection refused (Connection refused)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:463)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:558)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:242)
    at sun.net.www.http.HttpClient.New(HttpClient.java:339)
    at sun.net.www.http.HttpClient.New(HttpClient.java:357)
    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1220)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1156)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1050)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:984)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1334)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1309)
    at feign.Client$Default.convertAndSend(Client.java:133)
    at feign.Client$Default.execute(Client.java:73)
    at org.springframework.cloud.netflix.feign.ribbon.RetryableFeignLoadBalancer$1.doWithRetry(RetryableFeignLoadBalancer.java:92)
    at org.springframework.cloud.netflix.feign.ribbon.RetryableFeignLoadBalancer$1.doWithRetry(RetryableFeignLoadBalancer.java:77)
    at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:286)
    at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:163)
    at org.springframework.cloud.netflix.feign.ribbon.RetryableFeignLoadBalancer.execute(RetryableFeignLoadBalancer.java:77)
    at org.springframework.cloud.netflix.feign.ribbon.RetryableFeignLoadBalancer.execute(RetryableFeignLoadBalancer.java:48)
    at com.netflix.client.AbstractLoadBalancerAwareClient$1.call(AbstractLoadBalancerAwareClient.java:109)
    at com.netflix.loadbalancer.reactive.LoadBalancerCommand$3$1.call(LoadBalancerCommand.java:303)
    at com.netflix.loadbalancer.reactive.LoadBalancerCommand$3$1.call(LoadBalancerCommand.java:287)
    at rx.internal.util.ScalarSynchronousObservable$3.call(ScalarSynchronousObservable.java:231)
    at rx.internal.util.ScalarSynchronousObservable$3.call(ScalarSynchronousObservable.java:228)
    at rx.Observable.unsafeSubscribe(Observable.java:10211)
    at rx.internal.operators.OnSubscribeConcatMap$ConcatMapSubscriber.drain(OnSubscribeConcatMap.java:286)
    at rx.internal.operators.OnSubscribeConcatMap$ConcatMapSubscriber.onNext(OnSubscribeConcatMap.java:144)
    at com.netflix.loadbalancer.reactive.LoadBalancerCommand$1.call(LoadBalancerCommand.java:185)
    at com.netflix.loadbalancer.reactive.LoadBalancerCommand$1.call(LoadBalancerCommand.java:180)
    at rx.Observable.unsafeSubscribe(Observable.java:10211)
    at rx.internal.operators.OnSubscribeConcatMap.call(OnSubscribeConcatMap.java:94)
    at rx.internal.operators.OnSubscribeConcatMap.call(OnSubscribeConcatMap.java:42)
    at rx.Observable.unsafeSubscribe(Observable.java:10211)
    at rx.internal.operators.OperatorRetryWithPredicate$SourceSubscriber$1.call(OperatorRetryWithPredicate.java:127)
    at rx.internal.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.enqueue(TrampolineScheduler.java:73)
    at rx.internal.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.schedule(TrampolineScheduler.java:52)
    at rx.internal.operators.OperatorRetryWithPredicate$SourceSubscriber.onNext(OperatorRetryWithPredicate.java:79)
    at rx.internal.operators.OperatorRetryWithPredicate$SourceSubscriber.onNext(OperatorRetryWithPredicate.java:45)
    at rx.internal.util.ScalarSynchronousObservable$WeakSingleProducer.request(ScalarSynchronousObservable.java:276)
    at rx.Subscriber.setProducer(Subscriber.java:209)
    at rx.internal.util.ScalarSynchronousObservable$JustOnSubscribe.call(ScalarSynchronousObservable.java:138)
    at rx.internal.util.ScalarSynchronousObservable$JustOnSubscribe.call(ScalarSynchronousObservable.java:129)
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
    at rx.Observable.subscribe(Observable.java:10307)
    at rx.Observable.subscribe(Observable.java:10274)
    at rx.observables.BlockingObservable.blockForSingle(BlockingObservable.java:445)
    at rx.observables.BlockingObservable.single(BlockingObservable.java:342)
    at com.netflix.client.AbstractLoadBalancerAwareClient.executeWithLoadBalancer(AbstractLoadBalancerAwareClient.java:117)
    at org.springframework.cloud.netflix.feign.ribbon.LoadBalancerFeignClient.execute(LoadBalancerFeignClient.java:63)
    at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:97)

Body:
I had this error when I deploy my spring boot microservices (transfering data by openFeign) in docker, after changing the params by dynamic variables in both application.properties and docker-compose.yml, everything working properly.

For example in application.properties:

spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:${MYSQL_PORT:3306}/my_app_name
spring.datasource.username=${MYSQL_USER:ur_username}
spring.datasource.password=${MYSQL_PASSWORD:ur_password}

In docker-compose.yml:

environment:
  MYSQL_HOST: my_mysql_container_name
  MYSQL_USER: ur_username
  MYSQL_PASSWORD: ur_password
  MYSQL_PORT: 3306


来源: stackexchange

问:
Encode and Decode a String using the repetition of characters along the string
I've been trying to tackle this problem but I haven't got any luck so far :( so any guidance would be awesome, especially since I'm just learning Python, so the problem is this:

Given a certain string, first you'll have to encode it using the following algorithm:

For every letter, strip the consecutive repetitions, if any, and add a number with the number of times it appears consecutively, including the first time.

After you've completed the encoding you'll have to create a function to decode it using the same criteria/assumptions.

Some examples of how it should work:

“Goooooooooddddd” => “G1o9d5”

“Oooo” => “O1o3”

“anagram” => “a1n1a1g1r1a1m1”

So far I have the following code for the encoding:

```<code>def encode(s) :

    i = 0
    while( i < len(s) - 1) :
        count = 1
        while s[i] == s[i + 1] :
            i += 1
            count += 1

            if i + 1 == len(s):
                break
        print(str(s[i]) + str(count),
                          end = "")
        i += 1
    print()

# Code for the driver
if __name__ == "__main__" :

    encode("Goooooooooddddd")
    encode("Oooo")
</code>```

With this I'm getting the needed output for the encoding part at least.

But I'm unable to actually do the "decoding" part by using this encoding as a starting point.

I know this question is quite silly/basic but I really can't get my head over it
Thanks in advance for the guidance/tips for this challenge problem

答:
Decoding would be very simple in python since it allows character multiplication:
It might be like:

```<code>def decode(s):
    a = list(s) # separate each character and number
    i = 0
    z = len(a)
    while i < z-1:   #This for block checks for any 2 digit numbers
        print(i, a[i])
        if a[i].isdigit() and a[i+1].isdigit():
            a[i] = a[i]+a[i+1]
            a.pop(i+1)
            print(a)
            z-=1
            try:
                if a[i+2].isdigit():
                    i-=1
            except IndexError:
                i-=1
        i+=1
    final_str = '' # the string that will have the value
    for i in range(0, len(a), 2):
        final_str += a[i]*int(a[i+1]) #a[i] is the character and int(a[i+1]) is the number of times.
                                      # They are multiplied and then added to the final string
    print(final_str) # The final string is printed

</code>```

Thanks to @Tobi208 for pointing out the bug.

ContentLicense: CC BY-SA 4.0

Body:
I've been trying to tackle this problem but I haven't got any luck so far :( so any guidance would be awesome, especially since I'm just learning Python, so the problem is this:

Given a certain string, first you'll have to encode it using the following algorithm:

For every letter, strip the consecutive repetitions, if any, and add a number with the number of times it appears consecutively, including the first time.

After you've completed the encoding you'll have to create a function to decode it using the same criteria/assumptions.

Some examples of how it should work:

“Goooooooooddddd” => “G1o9d5”

“Oooo” => “O1o3”

“anagram” => “a1n1a1g1r1a1m1”

So far I have the following code for the encoding:

def encode(s) :

    i = 0
    while( i < len(s) - 1) :
        count = 1
        while s[i] == s[i + 1] :
            i += 1
            count += 1

            if i + 1 == len(s):
                break
        print(str(s[i]) + str(count),
                          end = "")
        i += 1
    print()

# Code for the driver
if __name__ == "__main__" :

    encode("Goooooooooddddd")
    encode("Oooo")

With this I'm getting the needed output for the encoding part at least.

But I'm unable to actually do the "decoding" part by using this encoding as a starting point.

I know this question is quite silly/basic but I really can't get my head over it
Thanks in advance for the guidance/tips for this challenge problem

Body:
Decoding would be very simple in python since it allows character multiplication:
It might be like:

def decode(s):
    a = list(s) # separate each character and number
    i = 0
    z = len(a)
    while i < z-1:   #This for block checks for any 2 digit numbers
        print(i, a[i])
        if a[i].isdigit() and a[i+1].isdigit():
            a[i] = a[i]+a[i+1]
            a.pop(i+1)
            print(a)
            z-=1
            try:
                if a[i+2].isdigit():
                    i-=1
            except IndexError:
                i-=1
        i+=1
    final_str = '' # the string that will have the value
    for i in range(0, len(a), 2):
        final_str += a[i]*int(a[i+1]) #a[i] is the character and int(a[i+1]) is the number of times.
                                      # They are multiplied and then added to the final string
    print(final_str) # The final string is printed

Thanks to @Tobi208 for pointing out the bug.


问:
process items in Generic list/collections with Reflection
I have a generic class that I am using Reflection to pull out the properties of the type of the generic and looking for an attribute.  I am recursing into each property to do the same for each of their properties.  My issue is when I come to some sort of collection property (property that is a collection) or ICollection property.  I will not be able to cast the value returned from GetValue into a specific type (tried to cast into IEnumerable but does not work for generic IEnumerables).

Here is some code to help understand a little more:

```<code> public class NotificationMessageProcessor<T> : INotificationProcessor<T>
    {
          IList<string> availableTags = new List<string>();

          public string ReplaceNotificationTags<T>(string message, T instance)
          {

             LoadTagValues(instance);
             return ReplaceTags(message);

          }

          private string ReplaceTags(string message)
          {
             foreach (KeyValuePair<string, string> tagVal in tagValues)
             {
                 message = message.Replace(string.Format("<{0}>", tagVal.Key),     tagVal.Value);
             }
             return message;
          }

          private void LoadTagValues(object val)
          {
              Type elementType = val.GetType();
              PropertyInfo[] typeProperties = elementType.GetProperties();
              foreach (PropertyInfo prop in typeProperties)
              {

                 NotificationTag[] tags =      (NotificationTag[])prop.GetCustomAttributes(typeof(NotificationTag), false);
                if (tags != null && tags.Length > 0)
                {
                    string tagName = tags[0].TagName;
                    object propValue = prop.GetValue(val, null);
                    string propTypeString = prop.PropertyType.FullName;
                    tagName = prop.ReflectedType.Name + "." + tagName;
                    if (propValue != null)
                    {
                      tagValues.Add(tagName, propValue.ToString());
                    }

                    if (propValue != null)
                    {
                       if (!prop.PropertyType.IsPrimitive)
                       {
                         LoadTagValues(propValue);
                       }
                    }
                }
                else
                {
                   if (!prop.PropertyType.IsPrimitive)
                   {
                     object propValue = null;

                        if (prop.GetGetMethod().GetParameters().Count() == 0)
                        {
                            propValue = prop.GetValue(val, null);
                        }
                        else
                        {
                           //have a collection...need to process but do not know how many in collection....
                                propValue = prop.GetValue(val, new object[] { 0 });

                        }
                    if (propValue != null)
                    {
                        LoadTagValues(propValue);
                    }
                }
            }
        }
    }

 NotificationMessageProcessor<User> userProcessor = new NotificationMessageProcessor();
    userProcessor.ReplaceNotificationTags<User>(someMessage, instanceOfUser);
</code>```

The User object has the proper attributes

答: From what I understand, non-generic IEnumerable will do since you don't need the type information anyway.

OwnerDisplayName: CSharpAtl

ContentLicense: CC BY-SA 2.5

Body:
I have a generic class that I am using Reflection to pull out the properties of the type of the generic and looking for an attribute.  I am recursing into each property to do the same for each of their properties.  My issue is when I come to some sort of collection property (property that is a collection) or ICollection property.  I will not be able to cast the value returned from GetValue into a specific type (tried to cast into IEnumerable but does not work for generic IEnumerables).

Here is some code to help understand a little more:

 public class NotificationMessageProcessor<T> : INotificationProcessor<T>
    {
          IList<string> availableTags = new List<string>();

          public string ReplaceNotificationTags<T>(string message, T instance)
          {

             LoadTagValues(instance);
             return ReplaceTags(message);

          }

          private string ReplaceTags(string message)
          {
             foreach (KeyValuePair<string, string> tagVal in tagValues)
             {
                 message = message.Replace(string.Format("<{0}>", tagVal.Key),     tagVal.Value);
             }
             return message;
          }

          private void LoadTagValues(object val)
          {
              Type elementType = val.GetType();
              PropertyInfo[] typeProperties = elementType.GetProperties();
              foreach (PropertyInfo prop in typeProperties)
              {

                 NotificationTag[] tags =      (NotificationTag[])prop.GetCustomAttributes(typeof(NotificationTag), false);
                if (tags != null && tags.Length > 0)
                {
                    string tagName = tags[0].TagName;
                    object propValue = prop.GetValue(val, null);
                    string propTypeString = prop.PropertyType.FullName;
                    tagName = prop.ReflectedType.Name + "." + tagName;
                    if (propValue != null)
                    {
                      tagValues.Add(tagName, propValue.ToString());
                    }

                    if (propValue != null)
                    {
                       if (!prop.PropertyType.IsPrimitive)
                       {
                         LoadTagValues(propValue);
                       }
                    }
                }
                else
                {
                   if (!prop.PropertyType.IsPrimitive)
                   {
                     object propValue = null;

                        if (prop.GetGetMethod().GetParameters().Count() == 0)
                        {
                            propValue = prop.GetValue(val, null);
                        }
                        else
                        {
                           //have a collection...need to process but do not know how many in collection....
                                propValue = prop.GetValue(val, new object[] { 0 });

                        }
                    if (propValue != null)
                    {
                        LoadTagValues(propValue);
                    }
                }
            }
        }
    }

 NotificationMessageProcessor<User> userProcessor = new NotificationMessageProcessor();
    userProcessor.ReplaceNotificationTags<User>(someMessage, instanceOfUser);

The User object has the proper attributes

LastEditorDisplayName: CSharpAtl

OwnerDisplayName: Anton Gogolev


问:
PowerShell Remoting: Handling Verbose Messages
Is it possible to send the verbose output from a remote PowerShell session to the local console?</p>

答:
Not sure what you are doing, but the following does get the verbose output on your console:</p>

```<code>invoke-command -ComputerName comp -ScriptBlock {$verbosepreference="Continue";write-verbose "blah"}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Not sure what you are doing, but the following does get the verbose output on your console:

invoke-command -ComputerName comp -ScriptBlock {$verbosepreference="Continue";write-verbose "blah"}


问:
DRF: Full Example of ListSerializer like Django's Admin-Inline?
I'm trying to wrap my mind around DRF's ListSerializer in combination with a foreignkey-model. The aim is to have something similar to Django's admin-inline Formula. Unfortunately, I can not find a full example on the documentation or SO examples: two models, two serializers and a viewset.

Suppose we have a model bit like in the SO example DRF ListSerializer and ListField :

class Musician(models.Model):

    name = models.CharField(max_length=50)
    comment = models.TextField(blank=True)

class Album(models.Model):
    artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
```
<p>So I try to put them in serializers like that:</p>
<pre class="lang-py prettyprint-override"><code>class AlbumSerializer(serializers.ModelSerializer):

    class Meta:
        fields = 'artist', 'title'
        model = Album

class MusicianSerializer(serializers.ModelSerializer):

    class Meta:
        fields = 'name', 'comment', 'albums'
        model = Musician

    albums = serializers.ListSerializer(child=AlbumSerializer(), source='album_set')
</code>```

And then I want to build a ModelViewSet on it, so that I can work with it, just like in Django-Admin-Inline. But this is not working just like that:

class MusicianViewSet(viewsets.ModelViewSet):

    queryset = Musician.objects.all()
    serializer_class = MusicianSerializer
```

But it's difficult to test, the HTML front-end does work, and in the tests I got (in a slightly different situation) an error message something like:

{'album_set': [ErrorDetail(string='This field is required.', code='required')]}

which I could not understand, not even after digging hours in the source code.
So what am I missing? And ideally, what would be a full working example with POST, PUT and DESTROY, creating modifying oder deleting on child model objects?

[Edit: I'm using Django==4.0.1 and django-extensions==3.1.5]

答:
Ok so there were different mistakes, and here are some hints to split the problem.
First there were two mistakes in the serializers, we must not serialize the parent artist, and we shall add a create method to the Musician serializer:

class AlbumSerializer(serializers.ModelSerializer):

    class Meta:
        fields = 'title',
        model = Album

class MusicianSerializer(serializers.ModelSerializer):

    class Meta:
        fields = 'id', 'name', 'comment', 'albums',
        model = Musician

    albums = AlbumSerializer(many=True)

    def create(self, validated_data):
        album_data = validated_data.pop('albums')
        muse = Musician.objects.create(**validated_data)
        for alb in album_data:
            muse.albums.create(**alb)
        return muse
```
<p>This can be tested directly in tests, here are some hints both for relation serializing and indirectly for writing tests about the Serializer:
https://www.django-rest-framework.org/api-guide/relations/ .</p>
<p>With this, I could run a django script through the <code>runscript</code> django-extension command, both with <code>rest_framework.test.RequestsClient</code> and with <code>requests.Session</code> (in the later case, we are shall start the server with the <code>runserver</code> command).</p>
<p>The script could look like this:</p>
<pre class="lang-py prettyprint-override"><code>def run():
    client = requests.Session()
    client.auth = requests.auth.HTTPBasicAuth(username, password)

   TEST_DATA = {
       "name": "Miles Davis",
       "comment": "Great Stuff",
       "albums": [{"title": "B.B."}, {"title": "Don't know"}],
    }
    response = client.post(create_music_url, json=TEST_DATA)
</code>```

I found this useful to understand that the code is right and that the test was wrong, which I still can't get to work...

[Edit] Here are the error messages in the test using the rest_framework.test.APITestCase and its self.client and force_authenticate :

```<code>   response = self.client.post(music_url, json=TEST_DATA)
</code>```

The response.data is the following:
{'name': [ErrorDetail(string='This field is required.', code='required')], 'albums': [ErrorDetail(string='This field is required.', code='required')]}

and with

```<code>   response = self.client.post(music_url, TEST_DATA)
</code>```

I get
{'albums': [ErrorDetail(string='This field is required.', code='required')]}

Imho, these error messages are confusing to say the least...

Body:
I'm trying to wrap my mind around DRF's ListSerializer in combination with a foreignkey-model. The aim is to have something similar to Django's admin-inline Formula. Unfortunately, I can not find a full example on the documentation or SO examples: two models, two serializers and a viewset.

Suppose we have a model bit like in the SO example DRF ListSerializer and ListField :

class Musician(models.Model):

    name = models.CharField(max_length=50)
    comment = models.TextField(blank=True)

class Album(models.Model):
    artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)

So I try to put them in serializers like that:

class AlbumSerializer(serializers.ModelSerializer):

    class Meta:
        fields = 'artist', 'title'
        model = Album

class MusicianSerializer(serializers.ModelSerializer):

    class Meta:
        fields = 'name', 'comment', 'albums'
        model = Musician

    albums = serializers.ListSerializer(child=AlbumSerializer(), source='album_set')

And then I want to build a ModelViewSet on it, so that I can work with it, just like in Django-Admin-Inline. But this is not working just like that:

class MusicianViewSet(viewsets.ModelViewSet):

    queryset = Musician.objects.all()
    serializer_class = MusicianSerializer

But it's difficult to test, the HTML front-end does work, and in the tests I got (in a slightly different situation) an error message something like:

{'album_set': [ErrorDetail(string='This field is required.', code='required')]}

which I could not understand, not even after digging hours in the source code.
So what am I missing? And ideally, what would be a full working example with POST, PUT and DESTROY, creating modifying oder deleting on child model objects?

[Edit: I'm using Django==4.0.1 and django-extensions==3.1.5]

Body:
Ok so there were different mistakes, and here are some hints to split the problem.
First there were two mistakes in the serializers, we must not serialize the parent artist, and we shall add a create method to the Musician serializer:

class AlbumSerializer(serializers.ModelSerializer):

    class Meta:
        fields = 'title',
        model = Album

class MusicianSerializer(serializers.ModelSerializer):

    class Meta:
        fields = 'id', 'name', 'comment', 'albums',
        model = Musician

    albums = AlbumSerializer(many=True)

    def create(self, validated_data):
        album_data = validated_data.pop('albums')
        muse = Musician.objects.create(**validated_data)
        for alb in album_data:
            muse.albums.create(**alb)
        return muse

This can be tested directly in tests, here are some hints both for relation serializing and indirectly for writing tests about the Serializer:
https://www.django-rest-framework.org/api-guide/relations/ .

With this, I could run a django script through the runscript django-extension command, both with rest_framework.test.RequestsClient and with requests.Session (in the later case, we are shall start the server with the runserver command).

The script could look like this:

def run():
    client = requests.Session()
    client.auth = requests.auth.HTTPBasicAuth(username, password)

   TEST_DATA = {
       "name": "Miles Davis",
       "comment": "Great Stuff",
       "albums": [{"title": "B.B."}, {"title": "Don't know"}],
    }
    response = client.post(create_music_url, json=TEST_DATA)

I found this useful to understand that the code is right and that the test was wrong, which I still can't get to work...

[Edit] Here are the error messages in the test using the rest_framework.test.APITestCase and its self.client and force_authenticate :

   response = self.client.post(music_url, json=TEST_DATA)

The response.data is the following:
{'name': [ErrorDetail(string='This field is required.', code='required')], 'albums': [ErrorDetail(string='This field is required.', code='required')]}

and with

   response = self.client.post(music_url, TEST_DATA)

I get
{'albums': [ErrorDetail(string='This field is required.', code='required')]}

Imho, these error messages are confusing to say the least...


问:
Allow only numbers with dot in html
How can i allow only numbers and dot in input area using patterns and using button</p>
```<code><input type="text" id="amt" name="amount" pattern="[0-9-.]" title="numbers with dot allowed">
<input type="button" value="submit">
</code>```

答:
This will do:</p>
```<code>pattern="[0-9.]"
</code>```

Title: Allow only numbers with dot in html

Body:
How can i allow only numbers and dot in input area using patterns and using button

<input type="text" id="amt" name="amount" pattern="[0-9-.]" title="numbers with dot allowed">
<input type="button" value="submit">

Body:
This will do:

pattern="[0-9.]"


问:
Pytest: customize test discovery through command line
There are ways to configure pytest test discovery through configuration file .

I wonder if there are ways to configure pytest test discovery through command line options/args. In other words, can  I just pass some argument/switch to pytest command to achieve this?

答:
Every entry you put in the config file (so-called "inioption") can be passed from command line using the -o/--override-ini option. The -o option can be applied multiple times. E.g.

```<code>$ pytest -o python_files='check_*.py' \
         -o python_classes=Check \
         -o python_functions='*_check'
</code>```

Source: Configuration Options.

Body:
Every entry you put in the config file (so-called "inioption") can be passed from command line using the -o/--override-ini option. The -o option can be applied multiple times. E.g.

$ pytest -o python_files='check_*.py' \
         -o python_classes=Check \
         -o python_functions='*_check'

Source: Configuration Options.


问:
GDB script too slow, need help/suggestions
I am writing a gdb script to analyse a core file. The purpose of whom is as follows:

1] I am looking for packets which are scattered in the 64Mb space. The packet has a magic number of 4 bytes. Hence I have to read 4 bytes at a time.

2] I have to read a total of 64Mb of data starting from a given address.

3] Once i find the packet I should print the deatils of the packet and continue looking for other packets.

4] Hence in my script the main loop runs for 64*1024*1024/4 =16777216 times in the worse case.

Whats the problem:

The script is taking about 3 hours or more which is totally impractical.

I am assuming this is because its a interpreted language, also the number of loops is pretty large.

Any suggestions/improvements are welcome. Kindly help me here.

答:
the find command should do everything you want,
without having to loop every 4 bytes or so,
it stores the address of the last found packet in $_
(untested, but should be something to the effect of)

```<code>(gdb) python x = list()
(gdb) set $start_addr = 0x....
(gdb) set $last_end = $start_addr
(gdb) set $_ = $start_addr+1
(gdb) while $_ != $last_end
 >find $last_end, $start_addr + 64*1024*1024, 0x42
 >set $last_end = $_
 >python x.append(gdb.parse_and_eval("$_"))
 >end
(gdb) python print map(lambda(y): str(y), x)
</code>```

if you don't have python you can use set logging overwrite off,set logging on,print,set logging off

Body:
the find command should do everything you want,
without having to loop every 4 bytes or so,
it stores the address of the last found packet in $_
(untested, but should be something to the effect of)

(gdb) python x = list()
(gdb) set $start_addr = 0x....
(gdb) set $last_end = $start_addr
(gdb) set $_ = $start_addr+1
(gdb) while $_ != $last_end
 >find $last_end, $start_addr + 64*1024*1024, 0x42
 >set $last_end = $_
 >python x.append(gdb.parse_and_eval("$_"))
 >end
(gdb) python print map(lambda(y): str(y), x)

if you don't have python you can use set logging overwrite off,set logging on,print,set logging off


问:
Replace each line containing a specific word from the first file with the line from the second file
I have two txt files, the first one contains duplicated word "PACKAGES", i want to replace each "PACKAGES" word with a line from file 2

Ex of file 1:

```<code>NEW FUSTAT TOURS
City
USA
Address
napolean
PACKAGES
Test TOURS
City
UK
Address
napolean
PACKAGES
</code>```

Ex of file 2:

```<code>First Company
Second Company
</code>```

Expected Output:

```<code>NEW FUSTAT TOURS
City
USA
Address
napolean
First Company
Test TOURS
City
UK
Address
napolean
Second Company
</code>```

I tried:

```<code>with open("file1.txt", encoding="utf-8") as first, open("file2.txt", encoding="utf-8") as second:
        first_file = first.read()
        second_file = second.readline()
        print(first_file.replace('PACKAGES', second_file))
</code>```

Result:

```<code>NEW FUSTAT TOURS
City
USA
Addres
napolean
Phone Number
************
Email
***************
First Company
Test TOURS
City
UK
Addres
napolean
Phone Number
************
Email
***************
First Company
</code>```

Any kind of help please?

答:
Here's one way you could do it:

```<code>with open('file1.txt', encoding='utf-8') as f1:
    with open('file2.txt', encoding='utf-8') as f2:
        f2lines = iter(f2.readlines())
        for f1line in f1:
            if f1line.startswith('PACKAGES'):
                print(next(f2lines), end='')
            else:
                print(f1line, end='')
</code>```

Output:

```<code>NEW FUSTAT TOURS
City
USA
Address
napolean
First Company
Test TOURS
City
UK
Address
napolean
Second Company
</code>```

Body:
I have two txt files, the first one contains duplicated word "PACKAGES", i want to replace each "PACKAGES" word with a line from file 2

Ex of file 1:

NEW FUSTAT TOURS
City
USA
Address
napolean
PACKAGES
Test TOURS
City
UK
Address
napolean
PACKAGES

Ex of file 2:

First Company
Second Company

Expected Output:

NEW FUSTAT TOURS
City
USA
Address
napolean
First Company
Test TOURS
City
UK
Address
napolean
Second Company

I tried:

with open("file1.txt", encoding="utf-8") as first, open("file2.txt", encoding="utf-8") as second:
        first_file = first.read()
        second_file = second.readline()
        print(first_file.replace('PACKAGES', second_file))

Result:

NEW FUSTAT TOURS
City
USA
Addres
napolean
Phone Number
************
Email
***************
First Company
Test TOURS
City
UK
Addres
napolean
Phone Number
************
Email
***************
First Company

Any kind of help please?

Body:
Here's one way you could do it:

with open('file1.txt', encoding='utf-8') as f1:
    with open('file2.txt', encoding='utf-8') as f2:
        f2lines = iter(f2.readlines())
        for f1line in f1:
            if f1line.startswith('PACKAGES'):
                print(next(f2lines), end='')
            else:
                print(f1line, end='')

Output:

NEW FUSTAT TOURS
City
USA
Address
napolean
First Company
Test TOURS
City
UK
Address
napolean
Second Company


问:
TestNG Listener that clears tmp folder even for an aborted run via Jenkins?
I use Java Selenium WebDriver with TestNG for running my tests.

I am calling driver.quit() in my final test to make sure the files created in /tmp/ folder are deleted.

However, if there is an aborted run (via Jenkins), the contents in /tmp/ folder are not deleted.

Is there a testng listener or any other way I can make sure that tmp folder is cleared even if the run is aborted mid-run?

答:
If the issue introduced on Jenkins level (aborting action), I believe, more effective will be solve this also with Jenkins, not with TestNG Listener.

For declarative pipeline

```<code>pipeline {
    agent any

    stages {
        ...
    }
    post {
        aborted {
            script {
              echo 'cleanup on abort'
              // this will clean workspace
              // cleanWs()

              //or just delete 'tmp' directory
              dir ('tmp') {
                  deleteDir()
              }
            }
        }
    }
}
</code>```

Using Plugin

https://plugins.jenkins.io/postbuild-task/

Install plugin and setup shell script execution for the job like

```<code>rm -rf tmp
</code>```

Body:
If the issue introduced on Jenkins level (aborting action), I believe, more effective will be solve this also with Jenkins, not with TestNG Listener.

For declarative pipeline

pipeline {
    agent any

    stages {
        ...
    }
    post {
        aborted {
            script {
              echo 'cleanup on abort'
              // this will clean workspace
              // cleanWs()

              //or just delete 'tmp' directory
              dir ('tmp') {
                  deleteDir()
              }
            }
        }
    }
}

Using Plugin

https://plugins.jenkins.io/postbuild-task/

Install plugin and setup shell script execution for the job like

rm -rf tmp


问:
Kotlin Exception when mocking suspend function java.io.EOFException: Premature end of stream: expected 1 bytes
I use KTor and Kotlin Serialization library in my android project, along with mockk and junit.jupiter for unit testing. I've encountered a problem when mocking ktor's suspend function readText(). The following unit test tests that initErrorMessage() function returns correct error message.

Test class:

```<code>class ErrorTest {

    private val errorMessage = "objectId must be provided."
    private val errorCode = 2689
    private val correctResponseJson = "{\"code\":$errorCode,\"message\":\"$errorMessage\"}"
    // ResponseException class is from ktor library
    private val exceptionMock: ResponseException = mockk(relaxed = true)

    @Test
    fun `initErrorMessage should return correct error message`() = runTest {
        coEvery { exceptionMock.response.readText() } returns correctResponseJson // <-- here is the Error occurs

        val expectedError = errorMessage
        val actualError = initErrorMessage(exceptionMock)

        assertEquals(expectedError, actualError)
    }
}
</code>```

Method to test:

```<code>suspend fun initErrorMessage(cause: ResponseException): String {
    return try {
        val body = cause.response.readText()
        val jsonSerializer = JsonObject.serializer()
        val jsonObj = Json.decodeFromString(jsonSerializer, body)
        jsonObj["message"].toString()
    } catch (e: Exception) {
        ""
    }
}
</code>```

During execution of the first line in the test method I get an Error:

```<code>Premature end of stream: expected 1 bytes
java.io.EOFException: Premature end of stream: expected 1 bytes
    at io.ktor.utils.io.core.StringsKt.prematureEndOfStream(Strings.kt:492)
    at io.ktor.utils.io.core.internal.UnsafeKt.prepareReadHeadFallback(Unsafe.kt:78)
    at io.ktor.utils.io.core.internal.UnsafeKt.prepareReadFirstHead(Unsafe.kt:61)
    at io.ktor.utils.io.charsets.CharsetJVMKt.decode(CharsetJVM.kt:556)
    at io.ktor.utils.io.charsets.EncodingKt.decode(Encoding.kt:103)
    at io.ktor.utils.io.charsets.EncodingKt.decode$default(Encoding.kt:101)
    at io.ktor.client.statement.HttpStatementKt.readText(HttpStatement.kt:173)
    at io.ktor.client.statement.HttpStatementKt.readText$default(HttpStatement.kt:168)
    at com.example.android.http.error.ErrorTest$initErrorMessage should return correct error message$1$1.invokeSuspend(ErrorTest.kt:37)
    at com.example.android.http.error.ErrorTest$initErrorMessage should return correct error message$1$1.invoke(ErrorTest.kt)
    at com.example.android.http.error.ErrorTest$initErrorMessage should return correct error message$1$1.invoke(ErrorTest.kt)
    at io.mockk.impl.eval.RecordedBlockEvaluator$record$block$2$1.invokeSuspend(RecordedBlockEvaluator.kt:28)
    at io.mockk.impl.eval.RecordedBlockEvaluator$record$block$2$1.invoke(RecordedBlockEvaluator.kt)
    at io.mockk.InternalPlatformDsl$runCoroutine$1.invokeSuspend(InternalPlatformDsl.kt:20)
</code>```

How to mock this suspend method readText() without an Error?

答:
It turned out that the function readText() hasn't been mocked properly.
It is an extension function on HttpResponse and it has to be mocked using mockkStatic function, for example like this:

```<code>@BeforeEach
fun setup() {
    mockkStatic(HttpResponse::readText)
}
</code>```

setup() will be executed before each @Test, because it is marked with @BeforeEach annotation.

Body:
I use KTor and Kotlin Serialization library in my android project, along with mockk and junit.jupiter for unit testing. I've encountered a problem when mocking ktor's suspend function readText(). The following unit test tests that initErrorMessage() function returns correct error message.

Test class:

class ErrorTest {

    private val errorMessage = "objectId must be provided."
    private val errorCode = 2689
    private val correctResponseJson = "{\"code\":$errorCode,\"message\":\"$errorMessage\"}"
    // ResponseException class is from ktor library
    private val exceptionMock: ResponseException = mockk(relaxed = true)

    @Test
    fun `initErrorMessage should return correct error message`() = runTest {
        coEvery { exceptionMock.response.readText() } returns correctResponseJson // <-- here is the Error occurs

        val expectedError = errorMessage
        val actualError = initErrorMessage(exceptionMock)

        assertEquals(expectedError, actualError)
    }
}

Method to test:

suspend fun initErrorMessage(cause: ResponseException): String {
    return try {
        val body = cause.response.readText()
        val jsonSerializer = JsonObject.serializer()
        val jsonObj = Json.decodeFromString(jsonSerializer, body)
        jsonObj["message"].toString()
    } catch (e: Exception) {
        ""
    }
}

During execution of the first line in the test method I get an Error:

Premature end of stream: expected 1 bytes
java.io.EOFException: Premature end of stream: expected 1 bytes
    at io.ktor.utils.io.core.StringsKt.prematureEndOfStream(Strings.kt:492)
    at io.ktor.utils.io.core.internal.UnsafeKt.prepareReadHeadFallback(Unsafe.kt:78)
    at io.ktor.utils.io.core.internal.UnsafeKt.prepareReadFirstHead(Unsafe.kt:61)
    at io.ktor.utils.io.charsets.CharsetJVMKt.decode(CharsetJVM.kt:556)
    at io.ktor.utils.io.charsets.EncodingKt.decode(Encoding.kt:103)
    at io.ktor.utils.io.charsets.EncodingKt.decode$default(Encoding.kt:101)
    at io.ktor.client.statement.HttpStatementKt.readText(HttpStatement.kt:173)
    at io.ktor.client.statement.HttpStatementKt.readText$default(HttpStatement.kt:168)
    at com.example.android.http.error.ErrorTest$initErrorMessage should return correct error message$1$1.invokeSuspend(ErrorTest.kt:37)
    at com.example.android.http.error.ErrorTest$initErrorMessage should return correct error message$1$1.invoke(ErrorTest.kt)
    at com.example.android.http.error.ErrorTest$initErrorMessage should return correct error message$1$1.invoke(ErrorTest.kt)
    at io.mockk.impl.eval.RecordedBlockEvaluator$record$block$2$1.invokeSuspend(RecordedBlockEvaluator.kt:28)
    at io.mockk.impl.eval.RecordedBlockEvaluator$record$block$2$1.invoke(RecordedBlockEvaluator.kt)
    at io.mockk.InternalPlatformDsl$runCoroutine$1.invokeSuspend(InternalPlatformDsl.kt:20)

How to mock this suspend method readText() without an Error?

Body:
It turned out that the function readText() hasn't been mocked properly.
It is an extension function on HttpResponse and it has to be mocked using mockkStatic function, for example like this:

@BeforeEach
fun setup() {
    mockkStatic(HttpResponse::readText)
}

setup() will be executed before each @Test, because it is marked with @BeforeEach annotation.


问:
How do I install/use nd4j?
I've been working on a project for a while and determined that it would be made much faster with the use of nd4j.  I have spent many hours trying to use this library, but I always find more dependencies and errors.

I started in Processing, but when I discovered that nd4j suggested the use of Maven, I switched to Eclipse.  I'm not very familiar with Eclipse or Maven, so I'm sure there's some fairly easy way to get all of the dependencies for nd4j and I just haven't figured it out yet.

Does anyone know where can find all of the required jars for nd4j or how I can use it in Eclipse (or Processing)?

Again, I'm not familiar with Eclipse or Maven, so step by step instructions would be great.

Thanks so much!

If any further information would be useful, I would be happy to provide it.

答:
Nd4j itself is just a library. You don't really "install" it.
What I'm about to say is also in our docs at https://deeplearning4j.konduit.ai. If you can't find something, I would appreciate feedback on the github repo: https://github.com/eclipse/deeplearning4j/issues

All you do is include which backend you want to use. A backend is a library which implements the nd4j interface and interfaces with a native backend which consists of a combination of a c++ library and blas/lapack bindings.

Of note here is usually when folks are new to the library they sometimes just don't know maven. If you are not familiar with maven/gradle I would recommend you get familiar with them. We don't support downloading 1 off jars and trying to mix/match them on your own in eclipse. This is due to all the combinations of dependencies you can use to make the library fit your use case. Of course this has its own trade offs.

Learning maven is a bit outside the scope of this post but I would recommend the maven quickstart or the guide for your IDE. Eclipse/Intellij have great maven integration and I would suggest you learn it. Most of the java ecosystem assumes that you know this for consuming their libraries.

If maven/gradle is well understood then you need to pick whether to use CPU or GPU. For simplicity, I assume you will want to use a cpu backend. In that case, once you have maven/gradle setup use the latest version found on maven central. In this case, you'll want the nd4j-native-platform artifact. This will allow you to declare 1 line in your pom.xml that will configure/download all the dependencies for you. That will usually look like:

<dependency>
  <groupId>org.nd4j</groupId>
  <artifactId>nd4j-native-platform</artifactId>
  <version>1.0.0-M1.1</version>
</dependency>
```

I would look at maven central itself to see what the latest version will be at a given time though:
https://search.maven.org/artifact/org.nd4j/nd4j-native-platform/1.0.0-M1.1/jar

Title: How do I install/use nd4j?

Body:
Nd4j itself is just a library. You don't really "install" it.
What I'm about to say is also in our docs at https://deeplearning4j.konduit.ai. If you can't find something, I would appreciate feedback on the github repo: https://github.com/eclipse/deeplearning4j/issues

All you do is include which backend you want to use. A backend is a library which implements the nd4j interface and interfaces with a native backend which consists of a combination of a c++ library and blas/lapack bindings.

Of note here is usually when folks are new to the library they sometimes just don't know maven. If you are not familiar with maven/gradle I would recommend you get familiar with them. We don't support downloading 1 off jars and trying to mix/match them on your own in eclipse. This is due to all the combinations of dependencies you can use to make the library fit your use case. Of course this has its own trade offs.

Learning maven is a bit outside the scope of this post but I would recommend the maven quickstart or the guide for your IDE. Eclipse/Intellij have great maven integration and I would suggest you learn it. Most of the java ecosystem assumes that you know this for consuming their libraries.

If maven/gradle is well understood then you need to pick whether to use CPU or GPU. For simplicity, I assume you will want to use a cpu backend. In that case, once you have maven/gradle setup use the latest version found on maven central. In this case, you'll want the nd4j-native-platform artifact. This will allow you to declare 1 line in your pom.xml that will configure/download all the dependencies for you. That will usually look like:

<dependency>
  <groupId>org.nd4j</groupId>
  <artifactId>nd4j-native-platform</artifactId>
  <version>1.0.0-M1.1</version>
</dependency>

I would look at maven central itself to see what the latest version will be at a given time though:
https://search.maven.org/artifact/org.nd4j/nd4j-native-platform/1.0.0-M1.1/jar


问:
Fragment showing nothing when starting my app for first time
I have an app with bottom navigation fragment activity
I have placed text views and buttons on my home fragment.
further these fragments are placed in a frame layout.
when I launch my app my home fragment shows nothing just blank screen it loads everything when I
switch between fragments.

I want to fix this, so that when I launch my app everything that is on my home fragment shows up.

答:
because you didn't specify the first fragment to show,

in the onCreate you have to do this :

first checked the bottomNavigation item, that you want to start with :

```<code> bottomNavigation.getMenu().findItem(R.id.item).setChecked(true);
</code>```

then put the first fragment in frame layout

Body:
because you didn't specify the first fragment to show,

in the onCreate you have to do this :

first checked the bottomNavigation item, that you want to start with :

 bottomNavigation.getMenu().findItem(R.id.item).setChecked(true);

then put the first fragment in frame layout


问:
Regular expression for validating cyrillic
I have a php function to validate "City":

```<code>function validate_city($field) {
    if ($field == "") return "Enter city.<br />";
    else if (preg_match("/[^а-Яa-zA-z-]/", $field))
        return "City hame only from letters and -.<br />";
    return "";
}
</code>```

Every time, when I enter a cyrillic City name (for ex: "Минск") it returns:
City hame only from letters and -.
Variable $_POST['city'] looks like:
Ð�Ð¸Ð½Ñ�Ðº

In JS this code works correct, I think something is in encoding.....

答: I try to use ^[a-zA-Z\p{Cyrillic}\d\s\-]+$ in https://regex101.com/ and everything is ok.

Body:
I have a php function to validate "City":

function validate_city($field) {
    if ($field == "") return "Enter city.
";
    else if (preg_match("/[^а-Яa-zA-z-]/", $field))
        return "City hame only from letters and -.
";
    return "";
}

Every time, when I enter a cyrillic City name (for ex: "Минск") it returns:
City hame only from letters and -.
Variable $_POST['city'] looks like:
Ð�Ð¸Ð½Ñ�Ðº

In JS this code works correct, I think something is in encoding.....


问:
Search bar with VisNetwork Graph in Shiny
I have built a network graph with VisNetwork and Shiny. I am very pleased with the results.  What I would like to do is use a search bar (for example: http://projects.flowingdata.com/tut/interactive_network_demo/) to search the nodes in my data.

I am using shinydashboard.  So I tried to use the "sidebarSearchForm". However, when I run the app and try to use the search form, nothing is returned.

Here is my code for the ui:

```<code>ui <- dashboardPage(skin = "black",
  dashboardHeader(),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Network", tabName = "network", icon = icon("dashboard")),
      sidebarSearchForm(textId = "searchText", buttonId = "searchButton", label = "Search...")
   )
  ),
  dashboardBody(
    box(
      title = "Network",  status = "warning", solidHeader = TRUE, collapsible = TRUE,
      visNetworkOutput("network_proxy", height = 700)
    )
  )
)#end ui
</code>```

Here is the code for the server;

```<code>server <- function(input, output) {
  output$network_proxy <- renderVisNetwork({
    visNetwork(my.nodes, my.edges, height = "100%")
  })
  output$searchString <- renderText({
    if (input$searchButton == 0)
      return()
    isolate({input$searchString})
  })
} #end server
</code>```

答:
The above code from bthieurmel can be modified to the below to enable search that is not case sensitive:</p>
```<code>current_node <- nodes[grep(input$searchText, nodes$label, ignore.case = T), "id"]
</code>```

Body:
I have built a network graph with VisNetwork and Shiny. I am very pleased with the results.  What I would like to do is use a search bar (for example: http://projects.flowingdata.com/tut/interactive_network_demo/) to search the nodes in my data.

I am using shinydashboard.  So I tried to use the "sidebarSearchForm". However, when I run the app and try to use the search form, nothing is returned.

Here is my code for the ui:

ui <- dashboardPage(skin = "black",
  dashboardHeader(),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Network", tabName = "network", icon = icon("dashboard")),
      sidebarSearchForm(textId = "searchText", buttonId = "searchButton", label = "Search...")
   )
  ),
  dashboardBody(
    box(
      title = "Network",  status = "warning", solidHeader = TRUE, collapsible = TRUE,
      visNetworkOutput("network_proxy", height = 700)
    )
  )
)#end ui

Here is the code for the server;

server <- function(input, output) {
  output$network_proxy <- renderVisNetwork({
    visNetwork(my.nodes, my.edges, height = "100%")
  })
  output$searchString <- renderText({
    if (input$searchButton == 0)
      return()
    isolate({input$searchString})
  })
} #end server

Body:
The above code from bthieurmel can be modified to the below to enable search that is not case sensitive:

current_node <- nodes[grep(input$searchText, nodes$label, ignore.case = T), "id"]


问:
How to use Loguru defaults + and extra information?
I'm still reaseaching about Loguru, but I can't find an easy way to do this. I want to use the default options from Loguru, I believe they  are great, but I want to add information to it, I want to add the IP of a request that will be logged.

If I try this:

```<code>import sys
from loguru import logger
logger.info("This is log info!")
# This is directle from Loguru page
logger.add(sys.stderr, format="{extra[ip]} {extra[user]} {message}")
context_logger = logger.bind(ip="192.168.0.1", user="someone")
context_logger.info("Contextualize your logger easily")
context_logger.bind(user="someone_else").info("Inline binding of extra attribute")
context_logger.info("Use kwargs to add context during formatting: {user}", user="anybody")
</code>```

That logs this:

I know that with logger.remove(0) I will remove the default logs, but I want to use it to obtain something like this: 2022-02-03 15:16:54.920 | INFO     | __main__:<module>:79 - XXX.XXX.XX.X - Use kwargs to add context during formatting: anybody, with XXX.XXX.XX.X  being the IP. Using the default config (for color and the rest of thing) and adding a little thing to the format.

I'm trying to access the default configs, but I haven't been able to import them and use them with logger.add. I think I will have to configure everything from scratch.

Hope someone can help me, thanks.

答:
I made the same question in the Github Repository and this was the answer by Delgan (Loguru maintainer):

I think you simply need to add() your handler using a custom format containing the extra information. Here is an example:

```<code>logger_format = (
    "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
    "<level>{level: <8}</level> | "
    "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | "
    "{extra[ip]} {extra[user]} - <level>{message}</level>"
)
logger.configure(extra={"ip": "", "user": ""})  # Default values
logger.remove()
logger.add(sys.stderr, format=logger_format)
</code>```

Extra: if you want to use TRACE level use this when adding the configurations:

logger.add(sys.stderr, format=logger_format, level="TRACE")

Body:
I'm still reaseaching about Loguru, but I can't find an easy way to do this. I want to use the default options from Loguru, I believe they  are great, but I want to add information to it, I want to add the IP of a request that will be logged.

If I try this:

import sys
from loguru import logger
logger.info("This is log info!")
# This is directle from Loguru page
logger.add(sys.stderr, format="{extra[ip]} {extra[user]} {message}")
context_logger = logger.bind(ip="192.168.0.1", user="someone")
context_logger.info("Contextualize your logger easily")
context_logger.bind(user="someone_else").info("Inline binding of extra attribute")
context_logger.info("Use kwargs to add context during formatting: {user}", user="anybody")

That logs this:

I know that with logger.remove(0) I will remove the default logs, but I want to use it to obtain something like this: 2022-02-03 15:16:54.920 | INFO     | __main__:<module>:79 - XXX.XXX.XX.X - Use kwargs to add context during formatting: anybody, with XXX.XXX.XX.X  being the IP. Using the default config (for color and the rest of thing) and adding a little thing to the format.

I'm trying to access the default configs, but I haven't been able to import them and use them with logger.add. I think I will have to configure everything from scratch.

Hope someone can help me, thanks.

Body:
I made the same question in the Github Repository and this was the answer by Delgan (Loguru maintainer):

I think you simply need to add() your handler using a custom format containing the extra information. Here is an example:

logger_format = (
    "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
    "<level>{level: <8}</level> | "
    "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | "
    "{extra[ip]} {extra[user]} - <level>{message}</level>"
)
logger.configure(extra={"ip": "", "user": ""})  # Default values
logger.remove()
logger.add(sys.stderr, format=logger_format)

Extra: if you want to use TRACE level use this when adding the configurations:

logger.add(sys.stderr, format=logger_format, level="TRACE")


问:
Regex: ignore case sensitivity
How can I make the following regex ignore case sensitivity? It should match all the correct characters but ignore whether they are lower or uppercase.</p>

```<code>G[a-b].*
</code>```

Title: Regex: ignore case sensitivity

Body:
How can I make the following regex ignore case sensitivity? It should match all the correct characters but ignore whether they are lower or uppercase.

G[a-b].*

Body:
Kotlin:

"G[a-b].*".toRegex(RegexOption.IGNORE_CASE)


问:
List ALL Files on iPhone
in Objective C how would I get a list of ALL files on the iPhone?

is this even possible or can I only get files from a certain directory or known path?

答:
I am not sure why people are saying that your app can only see certain files inside of your sandbox.  As of iOS 2.x (the last time I tried something like this), you can use NSFileManager to list files in almost any directory.  Here is a little code to get all of the names of all files in a specific directory.

```<code>- (NSArray *)allFiles:(NSString *)aPath
    NSMutableArray * listing = [NSMutableArray array];
    NSArray * fileNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:aPath error:nil];
    if (!fileNames) return listing;
    for (NSString * file in fileNames) {
        NSString * absPath = [aPath stringByAppendingPathComponent:file];
        BOOL isDir = NO;
        if ([[NSFileManager defaultManager] fileExistsAtPath:absPath isDirectory:&isDir]) {
            if (isDir) {
                [listing addObject:absPath];
                [listing addObjectsFromArray:[self allFiles:absPath]];
            } else {
                [listing addObject:absPath];
            }
        }
    }
    return listing;
}
</code>```

This is an example of a very simple recursive function.  It could, of course be modified to work more efficiently with blocks as callbacks or even incorporate NSOperation.

Title: List ALL Files on iPhone

Body:
I am not sure why people are saying that your app can only see certain files inside of your sandbox.  As of iOS 2.x (the last time I tried something like this), you can use NSFileManager to list files in almost any directory.  Here is a little code to get all of the names of all files in a specific directory.

- (NSArray *)allFiles:(NSString *)aPath
    NSMutableArray * listing = [NSMutableArray array];
    NSArray * fileNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:aPath error:nil];
    if (!fileNames) return listing;
    for (NSString * file in fileNames) {
        NSString * absPath = [aPath stringByAppendingPathComponent:file];
        BOOL isDir = NO;
        if ([[NSFileManager defaultManager] fileExistsAtPath:absPath isDirectory:&isDir]) {
            if (isDir) {
                [listing addObject:absPath];
                [listing addObjectsFromArray:[self allFiles:absPath]];
            } else {
                [listing addObject:absPath];
            }
        }
    }
    return listing;
}

This is an example of a very simple recursive function.  It could, of course be modified to work more efficiently with blocks as callbacks or even incorporate NSOperation.