问:
Spring @Autowired not work in @Endpoint
I want to create some Web service through Spring framework, but I found something wrong, @Autowired  not work in @Endpoint. Please see my code:

```<code>    @Endpoint
    public class VideoEndpoint
    {
        private VideoService videoService;
        @Autowired
        public VideoEndpoint(VideoService videoService)
        {
            this.videoService=videoService;
        }

        @PayloadRoot(namespace = "http://www.skysoft.top/ws/video", localPart = "GetVideoRequest")
        @ResponsePayload
        public GetVideoResponse findVideoById(@RequestPayload GetVideoRequest request)
                throws Exception
        {
            GetVideoResponse response = new GetVideoResponse();
            Video video=videoService.getVideoByAid(request.getAid());
            response.setVideo(video);
            return response;
        }
    }

    public interface VideoService {

        List<Video> getVideoList();
        Video getVideoByAid(long aid);
    }

    @Service("videoService")
    @Transactional
    public class VideoServiceImpl implements VideoService {
        private final Logger LOG = LoggerFactory.getLogger(this.getClass());
        @Autowired
        private VideoDao videoDao;
        @Autowired
        private RedisCache cache;

        @Override
        public List<Video> getVideoList() {
            String cache_key=RedisCache.CAHCENAME+"|getVideoList";
            //先去缓存中取
            List<Video> result_cache=cache.getListCache(cache_key, Video.class);
            if(result_cache==null){
                //缓存中没有再去数据库取，并插入缓存（缓存时间为60秒）
                result_cache=videoDao.queryAll();
                cache.putListCacheWithExpireTime(cache_key, result_cache, RedisCache.CAHCETIME);
                LOG.info("put cache with key:"+cache_key);
            }else{
                LOG.info("get cache with key:"+cache_key);
            }
            return result_cache;
        }
    @Override
        public Video getVideoByAid(long aid) {
            return videoDao.queryByAid(aid);
        }

    }
    This is my Spring-ws-servelet.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:sws="http://www.springframework.org/schema/web-services"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd">
        <context:annotation-config/>
        <!-- 自动扫描@Endpoint注解 -->
        <!--<bean class="org.springframework.remoting.jaxws.SimpleJaxWsServiceExporter" />-->
        <!--<context:component-scan base-package="com.yingjun.ssm.service" />-->
        <context:component-scan base-package="com.yingjun.ssm.ws.endpoint" />
        <!-- 开启Spring WebService的注解自动扫描驱动 -->
        <sws:annotation-driven/>
        <!-- 动态WSDL的配置 -->
        <sws:dynamic-wsdl id="video" portTypeName="VideoOperation" locationUri="/webservice/video"
                          targetNamespace="http://www.skysoft.top/ws/video">
            <sws:xsd location="classpath:wsdl/video.xsd" />
        </sws:dynamic-wsdl>

    </beans>

This is my web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
    http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">

    <!--配置DispatcherServlet -->
    <servlet>
        <servlet-name>spring-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 配置SpringMVC需要加载的配置文件 spring-xxx.xml -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/spring-*.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-dispatcher</servlet-name>
        <!--默认匹配所有的请求 -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- druid -->
    <servlet>
        <servlet-name>DruidStatView</servlet-name>
        <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>DruidStatView</servlet-name>
        <url-pattern>/druid/*</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>DruidWebStatFilter</filter-name>
        <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
        <init-param>
            <param-name>exclusions</param-name>
            <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>DruidWebStatFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>spring-ws</servlet-name>
        <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/spring-ws-servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-ws</servlet-name>
        <url-pattern>/webservice/*</url-pattern>
    </servlet-mapping>
</web-app>

 This is my spring-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:sws="http://www.springframework.org/schema/web-services"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd">
    <context:annotation-config/>
    <!-- 自动扫描@Endpoint注解 -->
    <!--<bean class="org.springframework.remoting.jaxws.SimpleJaxWsServiceExporter" />-->
    <!--<context:component-scan base-package="com.yingjun.ssm.service" />-->
    <context:component-scan base-package="com.yingjun.ssm.ws.endpoint" />
    <!-- 开启Spring WebService的注解自动扫描驱动 -->
    <sws:annotation-driven/>
    <!-- 动态WSDL的配置 -->
    <sws:dynamic-wsdl id="video" portTypeName="VideoOperation" locationUri="/webservice/video"
                      targetNamespace="http://www.skysoft.top/ws/video">
        <sws:xsd location="classpath:wsdl/video.xsd" />
    </sws:dynamic-wsdl>

</beans>
</code>```

I request the Web service through SoapUI, but it always go wrong:

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'videoEndpoint' defined in file [C:\Users\PAN\IdeaProjects\beauty_ssm\target\beauty_ssm_0.0.1-SNAPSHOT_20170603\WEB-INF\classes\com\yingjun\ssm\ws\endpoint\VideoEndpoint.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [com.yingjun.ssm.service.VideoService]: : No qualifying bean of type [com.yingjun.ssm.service.VideoService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.yingjun.ssm.service.VideoService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:633)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:681)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:552)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:779)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:133)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1347)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.yingjun.ssm.service.VideoService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1326)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1072)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:967)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:813)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
    ... 39 common frames omitted
20:38:34.634 [http-nio-8080-exec-7] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@552e7868: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,videoEndpoint,org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping#0,org.springframework.ws.soap.server.endpoint.mapping.SoapActionAnnotationMethodEndpointMapping#0,org.springframework.ws.soap.addressing.server.AnnotationActionEndpointMapping#0,org.springframework.ws.server.endpoint.adapter.method.dom.DomPayloadMethodProcessor#0,org.springframework.ws.server.endpoint.adapter.method.SourcePayloadMethodProcessor#0,org.springframework.ws.server.endpoint.adapter.method.jaxb.XmlRootElementPayloadMethodProcessor#0,org.springframework.ws.server.endpoint.adapter.method.jaxb.JaxbElementPayloadMethodProcessor#0,org.springframework.ws.server.endpoint.adapter.DefaultMethodEndpointAdapter#0,org.springframework.ws.soap.server.endpoint.SoapFaultAnnotationExceptionResolver#0,org.springframework.ws.soap.server.endpoint.SimpleSoapExceptionResolver#0,org.springframework.xml.xsd.SimpleXsdSchema#0,video,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor]; root of factory hierarchy
20:38:34.635 [http-nio-8080-exec-7] ERROR o.s.w.t.h.MessageDispatcherServlet - Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'videoEndpoint' defined in file [C:\Users\PAN\IdeaProjects\beauty_ssm\target\beauty_ssm_0.0.1-SNAPSHOT_20170603\WEB-INF\classes\com\yingjun\ssm\ws\endpoint\VideoEndpoint.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [com.yingjun.ssm.service.VideoService]: : No qualifying bean of type [com.yingjun.ssm.service.VideoService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.yingjun.ssm.service.VideoService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:633)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:681)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:552)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:779)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:133)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1347)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.yingjun.ssm.service.VideoService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1326)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1072)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:967)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:813)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
    ... 39 common frames omitted
</code>```

I have found many solutions, but not working.

答:
I'm not an expert but i think that your end point class is not aware of your applicationContext. put this at the top of your web.xml

```<code><listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring-*.xml</param-value>
</context-param>
</code>```

Every *-servlet.xml file that you define will have a different context, the ‘contextLoaderListener‘ will create a parent context so you can share Beans between contexts.

if that does not work try adding this to your Spring-ws-servelet.xml inside the <beans> tag

```<code><import resource="spring-service.xml"/>
</code>```

Title: Spring @Autowired not work in @Endpoint

Body:
I want to create some Web service through Spring framework, but I found something wrong, @Autowired  not work in @Endpoint. Please see my code:

    @Endpoint
    public class VideoEndpoint
    {
        private VideoService videoService;
        @Autowired
        public VideoEndpoint(VideoService videoService)
        {
            this.videoService=videoService;
        }

        @PayloadRoot(namespace = "http://www.skysoft.top/ws/video", localPart = "GetVideoRequest")
        @ResponsePayload
        public GetVideoResponse findVideoById(@RequestPayload GetVideoRequest request)
                throws Exception
        {
            GetVideoResponse response = new GetVideoResponse();
            Video video=videoService.getVideoByAid(request.getAid());
            response.setVideo(video);
            return response;
        }
    }

    public interface VideoService {

        List<Video> getVideoList();
        Video getVideoByAid(long aid);
    }

    @Service("videoService")
    @Transactional
    public class VideoServiceImpl implements VideoService {
        private final Logger LOG = LoggerFactory.getLogger(this.getClass());
        @Autowired
        private VideoDao videoDao;
        @Autowired
        private RedisCache cache;

        @Override
        public List<Video> getVideoList() {
            String cache_key=RedisCache.CAHCENAME+"|getVideoList";
            //先去缓存中取
            List<Video> result_cache=cache.getListCache(cache_key, Video.class);
            if(result_cache==null){
                //缓存中没有再去数据库取，并插入缓存（缓存时间为60秒）
                result_cache=videoDao.queryAll();
                cache.putListCacheWithExpireTime(cache_key, result_cache, RedisCache.CAHCETIME);
                LOG.info("put cache with key:"+cache_key);
            }else{
                LOG.info("get cache with key:"+cache_key);
            }
            return result_cache;
        }
    @Override
        public Video getVideoByAid(long aid) {
            return videoDao.queryByAid(aid);
        }

    }
    This is my Spring-ws-servelet.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:sws="http://www.springframework.org/schema/web-services"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd">
        <context:annotation-config/>

        <context:component-scan base-package="com.yingjun.ssm.ws.endpoint" />

        <sws:annotation-driven/>

        <sws:dynamic-wsdl id="video" portTypeName="VideoOperation" locationUri="/webservice/video"
                          targetNamespace="http://www.skysoft.top/ws/video">
            <sws:xsd location="classpath:wsdl/video.xsd" />
        </sws:dynamic-wsdl>

    </beans>

This is my web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
    http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">

    <servlet>
        <servlet-name>spring-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/spring-*.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-dispatcher</servlet-name>

        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>DruidStatView</servlet-name>
        <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>DruidStatView</servlet-name>
        <url-pattern>/druid/*</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>DruidWebStatFilter</filter-name>
        <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
        <init-param>
            <param-name>exclusions</param-name>
            <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>DruidWebStatFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>spring-ws</servlet-name>
        <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/spring-ws-servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-ws</servlet-name>
        <url-pattern>/webservice/*</url-pattern>
    </servlet-mapping>
</web-app>

 This is my spring-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:sws="http://www.springframework.org/schema/web-services"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd">
    <context:annotation-config/>

    <context:component-scan base-package="com.yingjun.ssm.ws.endpoint" />

    <sws:annotation-driven/>

    <sws:dynamic-wsdl id="video" portTypeName="VideoOperation" locationUri="/webservice/video"
                      targetNamespace="http://www.skysoft.top/ws/video">
        <sws:xsd location="classpath:wsdl/video.xsd" />
    </sws:dynamic-wsdl>

</beans>

I request the Web service through SoapUI, but it always go wrong:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'videoEndpoint' defined in file [C:\Users\PAN\IdeaProjects\beauty_ssm\target\beauty_ssm_0.0.1-SNAPSHOT_20170603\WEB-INF\classes\com\yingjun\ssm\ws\endpoint\VideoEndpoint.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [com.yingjun.ssm.service.VideoService]: : No qualifying bean of type [com.yingjun.ssm.service.VideoService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.yingjun.ssm.service.VideoService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:633)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:681)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:552)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:779)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:133)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1347)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.yingjun.ssm.service.VideoService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1326)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1072)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:967)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:813)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
    ... 39 common frames omitted
20:38:34.634 [http-nio-8080-exec-7] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@552e7868: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,videoEndpoint,org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping#0,org.springframework.ws.soap.server.endpoint.mapping.SoapActionAnnotationMethodEndpointMapping#0,org.springframework.ws.soap.addressing.server.AnnotationActionEndpointMapping#0,org.springframework.ws.server.endpoint.adapter.method.dom.DomPayloadMethodProcessor#0,org.springframework.ws.server.endpoint.adapter.method.SourcePayloadMethodProcessor#0,org.springframework.ws.server.endpoint.adapter.method.jaxb.XmlRootElementPayloadMethodProcessor#0,org.springframework.ws.server.endpoint.adapter.method.jaxb.JaxbElementPayloadMethodProcessor#0,org.springframework.ws.server.endpoint.adapter.DefaultMethodEndpointAdapter#0,org.springframework.ws.soap.server.endpoint.SoapFaultAnnotationExceptionResolver#0,org.springframework.ws.soap.server.endpoint.SimpleSoapExceptionResolver#0,org.springframework.xml.xsd.SimpleXsdSchema#0,video,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor]; root of factory hierarchy
20:38:34.635 [http-nio-8080-exec-7] ERROR o.s.w.t.h.MessageDispatcherServlet - Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'videoEndpoint' defined in file [C:\Users\PAN\IdeaProjects\beauty_ssm\target\beauty_ssm_0.0.1-SNAPSHOT_20170603\WEB-INF\classes\com\yingjun\ssm\ws\endpoint\VideoEndpoint.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [com.yingjun.ssm.service.VideoService]: : No qualifying bean of type [com.yingjun.ssm.service.VideoService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.yingjun.ssm.service.VideoService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:633)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:681)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:552)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:779)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:133)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1347)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.yingjun.ssm.service.VideoService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1326)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1072)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:967)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:813)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
    ... 39 common frames omitted

I have found many solutions, but not working.

Body:
I'm not an expert but i think that your end point class is not aware of your applicationContext. put this at the top of your web.xml

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring-*.xml</param-value>
</context-param>

Every *-servlet.xml file that you define will have a different context, the ‘contextLoaderListener‘ will create a parent context so you can share Beans between contexts.

if that does not work try adding this to your Spring-ws-servelet.xml inside the <beans> tag

<import resource="spring-service.xml"/>


来源: stackexchange

问:
How to use aws autoscaling to scale based on a single instance of a autoscaling group?
Is there a way to decide on the scaling activity of an autoscaling group based on metrics collected for a single instance among the multiple instances of an autoscaling group?

I'm tried to scale up based on alarm set for an instance which is one among the multiple instances of an autoscaling group but as I try to configure the autscaling under the cloudwatch alarm for the instance, autoscaling group doesn't show up.

As you can see in the below image Autoscaling group is not listed.

答:
Auto Scaling provides a way of adding and removing (scaling-out and scaling-in) Amazon EC2 instances. It works by launching new instances and terminating instances.

Auto Scaling groups can be scaled by executing a Scaling Policy, that tells Auto Scaling whether to add or remove instances, and how many -- eg +1, -1, +50%.

The scaling policy can be triggered by an Amazon CloudWatch alarm, a schedule or manually via an API/CLI call.

When triggering a scaling policy from Amazon CloudWatch, the metrics will be based on an aggregation of the Auto Scaling group -- for example, average CPU Utilization or maximum Network Out. The metrics are calculated from the entire Auto Scaling group, not a single instance. This makes sense -- imagine an Auto Scaling group with two instances where one is at 100% CPU and the other is 0% CPU. On average, they are at 50% CPU, so there is no need to scale. It would not make sense to base the scaling action on the metrics of a single instance.

So, to answer your question, how could you decide on the scaling activity of an autoscaling group based on metrics collected for a single instance among the multiple instances of an autoscaling group? You create an Amazon CloudWatch alarm that triggers on the metrics of a single instance. The alarm can trigger an Amazon SNS topic, and you could write an AWS Lambda function that subscribes to that topic. Your Lambda function can then trigger a Scaling Policy that changes the Desired Capacity of the Auto Scaling group.

However, I would recommend against this idea. Auto Scaling could for example, decide to scale-in and might remove the instance you are specifically monitoring. Your Auto Scaling group would then not scale anymore. Also, one instance is unlikely to represent the work level of the entire Auto Scaling group. It is better to scale based upon a metric that takes into account all instances in the Auto Scaling group, or some measure of the amount of 'work' being done or awaiting work, such as the size of an Amazon SQS queue that contains work to be processed.

ContentLicense: CC BY-SA 3.0


问:
Converting Caffe caffe::Datum to OpenCV cv::Mat in C++
I'm doing some debugging and so I'm dumping image files to look at the predictions and transformations.

I can create a caffe::Datum from cv::Mat:

```<code>cv::Mat matrix;
// ... initialize matrix
caffe::Datum datum;
caffe::CVMatToDatum(matrix, &datum)
</code>```

but how do I create a cv::Mat from caffe::Datum?  The following code gives the fatal exception "Datum not encoded":

```<code>caffe::Datum datum;
// ... initialize datum
cv::Mat matrix;
matrix = DecodeDatumToCVMat(datum, true);
</code>```

答:
You can use following functions.

```<code>cv::Mat DatumToCVMat(const Datum& datum){
int datum_channels = datum.channels();
int datum_height = datum.height();
int datum_width = datum.width();

string strData = datum.data();
cv::Mat cv_img;
if (strData.size() != 0)
{
    cv_img.create(datum_height, datum_width, CV_8UC(datum_channels));
    const string& data = datum.data();
    std::vector<char> vec_data(data.c_str(), data.c_str() + data.size());

    for (int h = 0; h < datum_height; ++h) {
        uchar* ptr = cv_img.ptr<uchar>(h);
        int img_index = 0;
        for (int w = 0; w < datum_width; ++w) {
            for (int c = 0; c < datum_channels; ++c) {
                int datum_index = (c * datum_height + h) * datum_width + w;
                ptr[img_index++] = static_cast<uchar>(vec_data[datum_index]);
            }
        }
    }
}
else
{
    cv_img.create(datum_height, datum_width, CV_32FC(datum_channels));
    for (int h = 0; h < datum_height; ++h) {
        float* ptr = cv_img.ptr<float>(h);
        int img_index = 0;
        for (int w = 0; w < datum_width; ++w) {
            for (int c = 0; c < datum_channels; ++c) {
                ptr[img_index++] = static_cast<float>(datum.float_data(img_index));
            }
        }
    }
}
return cv_img;
</code>```

}

all code :
http://lab.deepaivision.com/2017/06/opencv-mat-caffe-datum-datum-mat.html

Body:
I'm doing some debugging and so I'm dumping image files to look at the predictions and transformations.

I can create a caffe::Datum from cv::Mat:

cv::Mat matrix;
// ... initialize matrix
caffe::Datum datum;
caffe::CVMatToDatum(matrix, &datum)

but how do I create a cv::Mat from caffe::Datum?  The following code gives the fatal exception "Datum not encoded":

caffe::Datum datum;
// ... initialize datum
cv::Mat matrix;
matrix = DecodeDatumToCVMat(datum, true);

Body:
You can use following functions.

cv::Mat DatumToCVMat(const Datum& datum){
int datum_channels = datum.channels();
int datum_height = datum.height();
int datum_width = datum.width();

string strData = datum.data();
cv::Mat cv_img;
if (strData.size() != 0)
{
    cv_img.create(datum_height, datum_width, CV_8UC(datum_channels));
    const string& data = datum.data();
    std::vector<char> vec_data(data.c_str(), data.c_str() + data.size());

    for (int h = 0; h < datum_height; ++h) {
        uchar* ptr = cv_img.ptr<uchar>(h);
        int img_index = 0;
        for (int w = 0; w < datum_width; ++w) {
            for (int c = 0; c < datum_channels; ++c) {
                int datum_index = (c * datum_height + h) * datum_width + w;
                ptr[img_index++] = static_cast<uchar>(vec_data[datum_index]);
            }
        }
    }
}
else
{
    cv_img.create(datum_height, datum_width, CV_32FC(datum_channels));
    for (int h = 0; h < datum_height; ++h) {
        float* ptr = cv_img.ptr<float>(h);
        int img_index = 0;
        for (int w = 0; w < datum_width; ++w) {
            for (int c = 0; c < datum_channels; ++c) {
                ptr[img_index++] = static_cast<float>(datum.float_data(img_index));
            }
        }
    }
}
return cv_img;

}

all code :
http://lab.deepaivision.com/2017/06/opencv-mat-caffe-datum-datum-mat.html


问:
Adjusting flexbox grid for large and small screen sizes
I did two layouts.

First one is for medium & large screens, the last one is for max-width 736px device resolution.

Here is vanilla implementation with flexbox (without mobile adaptation)

And here is with bootstrap, I can then merge, because it is using flexboxes also

```<code><div class="d-flex gutters">
    <div class="bigger-cell">
        <div class="hero">
            I'm Hero!
        </div>
    </div>
    <div class="cell">
        <div class="hero">
            I'm Hero!
        </div>
    </div>
</div>

<div class="d-flex gutters">
    <div class="cell">
        <div class="hero">
            I'm Hero!
        </div>
    </div>
    <div class="cell">
        <div class="hero">
            I'm Hero!
        </div>
    </div>
    <div class="cell">
        <div class="hero">
            I'm Hero!
        </div>
    </div>
</div>
</code>```

答:
The layouts you want (both large and small screens) can be achieved efficiently with flexbox.

Your code can be simplified substantially.

https://jsfiddle.net/kmsxpk3q/

html, body {
  background: linear-gradient(#ade3e8, #b4b4b4) no-repeat;
  height: 100%;
}

body {
  font-family: 'Raleway', sans-serif;
  font-size: 22px;
  font-weight: 600;
  text-transform: uppercase;
  color: #FFF;
}

.d-flex {
  display: flex;
  flex-wrap: wrap;
  text-align: center;
}

.d-flex>div {
  margin: 5px;
}

.hero {
  flex: 0 0 calc(33.33% - 10px);
  padding: 30px 0;
  background: #7e58b7;
  border-radius: 3px;
}

.hero:first-child {
  flex-basis: calc(66.66% - 10px);
}

@media (max-width: 736px) {
  .hero {
    flex-basis: calc(50% - 10px);
  }
  .hero:first-child {
    flex-grow: 1;
  }
}

* {
  box-sizing: border-box;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="d-flex">
  <div class="hero">I'm Hero!</div>
  <div class="hero">I'm Hero!</div>
  <div class="hero">I'm Hero!</div>
  <div class="hero">I'm Hero!</div>
  <div class="hero">I'm Hero!</div>
</div></code>```

Body:
I did two layouts.

First one is for medium & large screens, the last one is for max-width 736px device resolution.

Here is vanilla implementation with flexbox (without mobile adaptation)

And here is with bootstrap, I can then merge, because it is using flexboxes also

            I'm Hero!

            I'm Hero!

            I'm Hero!

            I'm Hero!

            I'm Hero!

Body:
The layouts you want (both large and small screens) can be achieved efficiently with flexbox.

Your code can be simplified substantially.

https://jsfiddle.net/kmsxpk3q/

html, body {
  background: linear-gradient(#ade3e8, #b4b4b4) no-repeat;
  height: 100%;
}

body {
  font-family: 'Raleway', sans-serif;
  font-size: 22px;
  font-weight: 600;
  text-transform: uppercase;
  color: #FFF;
}

.d-flex {
  display: flex;
  flex-wrap: wrap;
  text-align: center;
}

.d-flex>div {
  margin: 5px;
}

.hero {
  flex: 0 0 calc(33.33% - 10px);
  padding: 30px 0;
  background: #7e58b7;
  border-radius: 3px;
}

.hero:first-child {
  flex-basis: calc(66.66% - 10px);
}

@media (max-width: 736px) {
  .hero {
    flex-basis: calc(50% - 10px);
  }
  .hero:first-child {
    flex-grow: 1;
  }
}

* {
  box-sizing: border-box;
}

<div class="d-flex">
  <div class="hero">I'm Hero!</div>
  <div class="hero">I'm Hero!</div>
  <div class="hero">I'm Hero!</div>
  <div class="hero">I'm Hero!</div>
  <div class="hero">I'm Hero!</div>
</div>


问:
Loadrunner : use parameter from list as array element number to get random array value
I want to use a random number from a list to select the particular element of a parameter array and use it elsewhere in the script as a parameter e.g.

Array is sspaidlist
My random integer from a parameter list is {GenRandomSSPAID}, which i want to use as the element of the sspaidlist array and save to is RandomSSPAID

```<code>lr_save_string(lr_eval_string("sspaidlist_{GenRandomSSPAID}"),"RandomSSPAID");
</code>```

This just gets me the actual value "sspaidlist" and not the array.

I've also tried

```<code>sprintf(RandomSSPAID, "{sspaidlist_%d}", lr_eval_string("{GenRandomSSPAID}"));
</code>```

but this seems to set RandomSSPAID to 0

The idea is to get 3 unique values - so 3 different array elements, I can't get the same value twice. I've offloaded the randomness to the loadrunner parameter functions, so I will always get a unique number with {GenRandomSSPAID}.

答:
First convert your "GenRandomSSPAID" to integer as below:

i = atoi(lr_eval_string("{GenRandomSSPAID}"));

Now use sprintf to save it into RandomSSPAID as below:

sprintf(RandomSSPAID, "{sspaidlist_%d}", i);

You should be able to see value now.

Body:
I want to use a random number from a list to select the particular element of a parameter array and use it elsewhere in the script as a parameter e.g.

Array is sspaidlist
My random integer from a parameter list is {GenRandomSSPAID}, which i want to use as the element of the sspaidlist array and save to is RandomSSPAID

lr_save_string(lr_eval_string("sspaidlist_{GenRandomSSPAID}"),"RandomSSPAID");

This just gets me the actual value "sspaidlist" and not the array.

I've also tried

sprintf(RandomSSPAID, "{sspaidlist_%d}", lr_eval_string("{GenRandomSSPAID}"));

but this seems to set RandomSSPAID to 0

The idea is to get 3 unique values - so 3 different array elements, I can't get the same value twice. I've offloaded the randomness to the loadrunner parameter functions, so I will always get a unique number with {GenRandomSSPAID}.


问:
C++ Declare array of unspecified length with string elements
What I'm trying to do here is quite simple. But some way, some how I'm missing something. I'm trying to "pre-declare" an array with strictly string elements in such a way that I can update the array contents during a specific period (periodically). So here are the snippets:

```<code>string ShotBox[] = {}; //"Pre-Declare" array that could contain as many elements here
</code>```

Then I have a loop within my Update container. Snippet's:

```<code>for (int i = 0; i < sizeof(ShotBox) - 1; i++){
            std::string soa = sPath;
            std::string so = soa + ShotBox[i];
            char *cstr = new char[so.length() + 1];
            strcpy(cstr, so.c_str());
            scPath = cstr;
}
</code>```

All is fine with everything except the fact that whichever way I try to "pre-declare", I get a memory access violation. In this very exact snippets, the exact error is: an empty array is invalid for an array with unspecified bound.

I tried using "vector" but can't seem to work around it. What's the way to solve this? Please I don't want libraries. I need direct short methods or something of such.

答:
Use std::vector<std::string>.

The vector manages an internal array.

```<code>std::vector<std::string> ShotBox; // (empty)

ShotBox.push_back(a_string); // add a string to the internal array

std::cout << ShotBox[0] << '\n'; // print first element
</code>```

Body:
What I'm trying to do here is quite simple. But some way, some how I'm missing something. I'm trying to "pre-declare" an array with strictly string elements in such a way that I can update the array contents during a specific period (periodically). So here are the snippets:

string ShotBox[] = {}; //"Pre-Declare" array that could contain as many elements here

Then I have a loop within my Update container. Snippet's:

for (int i = 0; i < sizeof(ShotBox) - 1; i++){
            std::string soa = sPath;
            std::string so = soa + ShotBox[i];
            char *cstr = new char[so.length() + 1];
            strcpy(cstr, so.c_str());
            scPath = cstr;
}

All is fine with everything except the fact that whichever way I try to "pre-declare", I get a memory access violation. In this very exact snippets, the exact error is: an empty array is invalid for an array with unspecified bound.

I tried using "vector" but can't seem to work around it. What's the way to solve this? Please I don't want libraries. I need direct short methods or something of such.

Body:
Use std::vector<std::string>.

The vector manages an internal array.

std::vector<std::string> ShotBox; // (empty)

ShotBox.push_back(a_string); // add a string to the internal array

std::cout << ShotBox[0] << '\n'; // print first element


问:
How to secure access to AWS Elasticsearch from a mobile application
I'm building a mobile app that requires access to an AWS Elasticsearch  (ES) cluster and would like to make sure only the app can make queries.

Assuming I'm not going to distribute AWS user credentials with my mobile application, what would be a secure way to allow read access to an AWS Elasticsearch cluster?

Reading this AWS post I gathered that I can setup a reverse proxy to sign my requests to Elasticsearch. If I follow this route, how would I secure access to the EC2 instance port where the proxy is listening to?

答:
For mobile applications what you want to set up is Web Identity Federation.  This is will give users temporary credentials to access aws resources needed for your mobile application.

http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc.html

Setting up
http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc_manual.html

Article from Amazon on Web Identity Federation with Mobile Applications

https://aws.amazon.com/articles/4617974389850313


问:
What is the point of encrypting web.config if user can just decrypt it?
Oi, some vendor is telling my bosses that not encrypting the web.config is big security hole. This sounds like bunk to me. I mean, if someone compromises the server aren't we screwed anyways?</p>

答: There was a recently released security hole in ASP.net that would have allowed a remote user to access any file in the web root, including web.config, without accessing the entire server. Additionally, there may be login information in the web.config that allows compromising one server to compromise another.</p>

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
Retrieving div "value" to javascript
So, im trying to code a simple sliding puzzle and got really stuck.
I've got a 3x3 sqare with diffrent "values"

Now, im trying to move the number to the blank space and vice versa.

So my question is how can i, in the easiest possible manner, change my 'test' text to the value of the clicked div ?

All answers and tips are truely appreciated

-Karlsen

EDIT :

Added full code, its a bit more understanding now i think :

          var counter = 0;
     var lastClickedDiv;

     function show(tag, alt1, alt2, alt3, alt4) {
       if (alt1 && document.getElementById(alt1).innerHTML == '') {
         document.getElementById(alt1).innerHTML = 'test';
         tag.innerHTML = '';
       }

       if (alt2 && document.getElementById(alt2).innerHTML == '') {
         document.getElementById(alt2).innerHTML = 'test1';
         tag.innerHTML = '';
       }

       if (alt3 && document.getElementById(alt3).innerHTML == '') {
         document.getElementById(alt3).innerHTML = 'test2';
         tag.innerHTML = '';
       }

       if (alt4 && document.getElementById(alt4).innerHTML == '') {
         document.getElementById(alt4).innerHTML = 'test3';
         tag.innerHTML = '';
       }
     }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  div.container {
   display: flex;
   height: 28vh;
  }
   div.number {
    color: black;
    background-color: rgb(140,0,0);
    margin: 10px;
    border: 10px solid black;
    display: flex;
    flex: 1;
    font-size: 500%;
    text-align: center;
    flex-direction: column;
    justify-content: center;
   }</code>```

<!DOCTYPE html>

 Sliding Puzzle

8

5

4

6

7

2

1

3

```

答:
You had an extra "." as @DASH suggested at line 4 in javascript, and you have a missing ' at line 4 in in the HTML.

I added a bit of CSS to see better if you don't mind.

function show(tag, alt1, alt2, alt3, alt4) {
  if (alt1 && document.getElementById(alt1).innerHTML == '') {
    document.getElementById(alt1).innerHTML = 'test';
    tag.innerHTML = '';
  }

  if (alt2 && document.getElementById(alt2).innerHTML == '') {
    document.getElementById(alt2).innerHTML = 'test1';
    tag.innerHTML = '';
  }

  if (alt3 && document.getElementById(alt3).innerHTML == '') {
    document.getElementById(alt3).innerHTML = 'test2';
    tag.innerHTML = '';
  }

  if (alt4 && document.getElementById(alt4).innerHTML == '') {
    document.getElementById(alt4).innerHTML = 'test3';
    tag.innerHTML = '';
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  display: flex;
  width: 200px;
  background-color: beige;
  justify-content: space-around;
}

.number {
  flex-basis: 100%;
  height: 50px;
  margin: 5px;
  border: 1px solid black;
  cursor: pointer;
}</code>```

8

5

4

6

7

2

1

3

```

Title: Retrieving div "value" to javascript

Body:
So, im trying to code a simple sliding puzzle and got really stuck.
I've got a 3x3 sqare with diffrent "values"

Now, im trying to move the number to the blank space and vice versa.

So my question is how can i, in the easiest possible manner, change my 'test' text to the value of the clicked div ?

All answers and tips are truely appreciated

-Karlsen

EDIT :

Added full code, its a bit more understanding now i think :

          var counter = 0;
     var lastClickedDiv;

     function show(tag, alt1, alt2, alt3, alt4) {
       if (alt1 && document.getElementById(alt1).innerHTML == '') {
         document.getElementById(alt1).innerHTML = 'test';
         tag.innerHTML = '';
       }

       if (alt2 && document.getElementById(alt2).innerHTML == '') {
         document.getElementById(alt2).innerHTML = 'test1';
         tag.innerHTML = '';
       }

       if (alt3 && document.getElementById(alt3).innerHTML == '') {
         document.getElementById(alt3).innerHTML = 'test2';
         tag.innerHTML = '';
       }

       if (alt4 && document.getElementById(alt4).innerHTML == '') {
         document.getElementById(alt4).innerHTML = 'test3';
         tag.innerHTML = '';
       }
     }

  div.container {
   display: flex;
   height: 28vh;
  }
   div.number {
    color: black;
    background-color: rgb(140,0,0);
    margin: 10px;
    border: 10px solid black;
    display: flex;
    flex: 1;
    font-size: 500%;
    text-align: center;
    flex-direction: column;
    justify-content: center;
   }

<!DOCTYPE html>

 Sliding Puzzle

8

5

4

6

7

2

1

3

Body:
You had an extra "." as @DASH suggested at line 4 in javascript, and you have a missing ' at line 4 in in the HTML.

I added a bit of CSS to see better if you don't mind.

function show(tag, alt1, alt2, alt3, alt4) {
  if (alt1 && document.getElementById(alt1).innerHTML == '') {
    document.getElementById(alt1).innerHTML = 'test';
    tag.innerHTML = '';
  }

  if (alt2 && document.getElementById(alt2).innerHTML == '') {
    document.getElementById(alt2).innerHTML = 'test1';
    tag.innerHTML = '';
  }

  if (alt3 && document.getElementById(alt3).innerHTML == '') {
    document.getElementById(alt3).innerHTML = 'test2';
    tag.innerHTML = '';
  }

  if (alt4 && document.getElementById(alt4).innerHTML == '') {
    document.getElementById(alt4).innerHTML = 'test3';
    tag.innerHTML = '';
  }
}

.container {
  display: flex;
  width: 200px;
  background-color: beige;
  justify-content: space-around;
}

.number {
  flex-basis: 100%;
  height: 50px;
  margin: 5px;
  border: 1px solid black;
  cursor: pointer;
}

<div class="container">
  <div id="a1" class="number" onclick="show(this, 'a2', 'b1')">8</div>
  <div id="a2" class="number" onclick="show(this, 'a1', 'a3', 'b2')">5</div>
  <div id="a3" class="number" onclick="show(this, 'a2', 'b3')">4</div>
</div>

<div class="container">
  <div id="b1" class="number" onclick="show(this, 'a1', 'b2', 'c1')">6</div>
  <div id="b2" class="number" onclick="show(this, 'a2', 'b1', 'b3', 'c2')">7</div>
  <div id="b3" class="number" onclick="show(this, 'a3', 'b2', 'c3')">2</div>
</div>

<div class="container">
  <div id="c1" class="number" onclick="show(this, 'b1', 'c2')">1</div>
  <div id="c2" class="number" onclick="show(this, 'c1', 'b2', 'c3')">3</div>
  <div id="c3" class="number" onclick="show(this, 'c2', 'b3')"></div>
</div>


问:
Nested/looping ajax function either makes php fail, or succeeds and makes website ui freeze
I have a php site. Once the page has loaded, ajax is run, then on success of that ajax, it loops through an array and runs ajax for each item in the array.

When I do it as i normally would (without using 'async: false', the website UI works as expected, but the backend PHP processing is a jumble and fails. However when I set asynch to false for AJAX, the UI freezes but the backend processing runs perfectly.

How can I get ajax to run by iterating through an array, but making sure it has completed before continuing the loop?

Here is my overly-simplified javascript/ajax structure:

```<code>//run once
$.ajax({ url: '/functions/myfile.php',
         data: { blahblahblah },
         type: 'post',
         success: function(data){
             var ajaxIDToConvert = [(array contents)];
             var arrayLength = ajaxIDToConvert.length;
             //loops
                 for (var i = 0; i < arrayLength; i++) {
                     var meh = ajaxIDToConvert[i];

                     $.ajax({ url : '/functions/myfile.php',
                              type : 'post',
                              async: false,
                              data : { blahblahblah},
                              success : function(convertdata) {
                                  var convertResponse = JSON.parse(convertdata);
                              },
                              error: function (err) {
                              }
                            });
                 }
         },
         error: function (err) {

                         }
});
</code>```

Heres a sample of my PHP log output when not using 'async false', as you can see the php code fails:

File to convert: 527
Converting started for 527: Sat 06:30:06pm

File to convert: 523
Converting started for 523: Sat 06:30:06pm

File to convert: 522
Converting started for 522: Sat 06:30:06pm

File to convert: 524
Converting started for 524: Sat 06:30:06pm

File to convert: 526
Converting started for 526: Sat 06:30:06pm

File to convert: 525
Converting started for 525: Sat 06:30:06pm

Converting ended for 522: Sat 06:30:38pm
522 Not Created
Converting
  ended for 524: Sat 06:30:39pm
524 Not Created

File to convert: 528
 Converting started for 528: Sat 06:30:39pm

File to convert: 529
 Converting started for 529: Sat 06:30:39pm
  Converting ended for 525: Sat 06:30:40pm
525 Not Created
 Converting
  ended for 523: Sat 06:30:42pm
523 Not Created

and here is a sample of the PHP output when using 'asynch: false':

(It produces the desired result...but the web page freezes while this is running)

File to convert: 522
Converting started for 522: Sat 06:33:03pm

  Converting ended for 522: Sat 06:33:12pm
522 Created Successfully

File to convert: 523
 Converting started for 523: Sat 06:33:13pm

  Converting ended for 523: Sat 06:33:22pm
 523 Created Successfully

File to convert: 524
 Converting started for 524: Sat 06:33:22pm

  Converting ended for 524: Sat 06:33:32pm
 524 Created Successfully

File to convert: 525
 Converting started for 525: Sat 06:33:32pm

  Converting ended for 525: Sat 06:33:42pm
525 Created Successfully

File to convert: 526
 Converting started for 526: Sat 06:33:42pm

  Converting ended for 526: Sat 06:33:52pm
 526 Created Successfully

I've also tried doing the following within the success brackets of the first ajax, but it results in the same php execution problems as the first php output above:

```<code>var promises = [];
for (var i = 0; i < $total_files; i++){
   /* $.ajax returns a promise*/
   var request = $.ajax({
        /* your ajax config*/
   })

   promises.push( request);
}

$.when.apply(null, promises).done(function(){
   alert('All done')
})
</code>```

答:
Try something like this:</p>

```<code>var ajaxIDsToConvert = [1, 2, 3];
var deferred = $.Deferred();
var promise = deferred.promise();

$.each(ajaxIDsToConvert, function(index, id) {
    promise = promise.pipe(function () {
      return $.ajax({
        // do required actions with `id` variable
      });
    });
});

deferred.resolve();
</code>```

Body:
I have a php site. Once the page has loaded, ajax is run, then on success of that ajax, it loops through an array and runs ajax for each item in the array.

When I do it as i normally would (without using 'async: false', the website UI works as expected, but the backend PHP processing is a jumble and fails. However when I set asynch to false for AJAX, the UI freezes but the backend processing runs perfectly.

How can I get ajax to run by iterating through an array, but making sure it has completed before continuing the loop?

Here is my overly-simplified javascript/ajax structure:

//run once
$.ajax({ url: '/functions/myfile.php',
         data: { blahblahblah },
         type: 'post',
         success: function(data){
             var ajaxIDToConvert = [(array contents)];
             var arrayLength = ajaxIDToConvert.length;
             //loops
                 for (var i = 0; i < arrayLength; i++) {
                     var meh = ajaxIDToConvert[i];

                     $.ajax({ url : '/functions/myfile.php',
                              type : 'post',
                              async: false,
                              data : { blahblahblah},
                              success : function(convertdata) {
                                  var convertResponse = JSON.parse(convertdata);
                              },
                              error: function (err) {
                              }
                            });
                 }
         },
         error: function (err) {

                         }
});

Heres a sample of my PHP log output when not using 'async false', as you can see the php code fails:

File to convert: 527
Converting started for 527: Sat 06:30:06pm

File to convert: 523
Converting started for 523: Sat 06:30:06pm

File to convert: 522
Converting started for 522: Sat 06:30:06pm

File to convert: 524
Converting started for 524: Sat 06:30:06pm

File to convert: 526
Converting started for 526: Sat 06:30:06pm

File to convert: 525
Converting started for 525: Sat 06:30:06pm

Converting ended for 522: Sat 06:30:38pm
522 Not Created
Converting
  ended for 524: Sat 06:30:39pm
524 Not Created

File to convert: 528
 Converting started for 528: Sat 06:30:39pm

File to convert: 529
 Converting started for 529: Sat 06:30:39pm
  Converting ended for 525: Sat 06:30:40pm
525 Not Created
 Converting
  ended for 523: Sat 06:30:42pm
523 Not Created

and here is a sample of the PHP output when using 'asynch: false':

(It produces the desired result...but the web page freezes while this is running)

File to convert: 522
Converting started for 522: Sat 06:33:03pm

  Converting ended for 522: Sat 06:33:12pm
522 Created Successfully

File to convert: 523
 Converting started for 523: Sat 06:33:13pm

  Converting ended for 523: Sat 06:33:22pm
 523 Created Successfully

File to convert: 524
 Converting started for 524: Sat 06:33:22pm

  Converting ended for 524: Sat 06:33:32pm
 524 Created Successfully

File to convert: 525
 Converting started for 525: Sat 06:33:32pm

  Converting ended for 525: Sat 06:33:42pm
525 Created Successfully

File to convert: 526
 Converting started for 526: Sat 06:33:42pm

  Converting ended for 526: Sat 06:33:52pm
 526 Created Successfully

I've also tried doing the following within the success brackets of the first ajax, but it results in the same php execution problems as the first php output above:

var promises = [];
for (var i = 0; i < $total_files; i++){
   /* $.ajax returns a promise*/
   var request = $.ajax({
        /* your ajax config*/
   })

   promises.push( request);
}

$.when.apply(null, promises).done(function(){
   alert('All done')
})

Body:
Try something like this:

var ajaxIDsToConvert = [1, 2, 3];
var deferred = $.Deferred();
var promise = deferred.promise();

$.each(ajaxIDsToConvert, function(index, id) {
    promise = promise.pipe(function () {
      return $.ajax({
        // do required actions with `id` variable
      });
    });
});

deferred.resolve();


问:
Swift 3 - Having issue mutating value of Array in Function
I am attempting to take the last character from the string of each of the words in this array:

```<code>var nonsenseArray = ["bungalow", "buffalo", "indigo", "although", "Ontario", "albino", "%$&#!"]
</code>```

and create a string with each of the characters using a for-loop within a function. I feel like I have a good answer but am getting the following error:

```<code>cannnot use mutating member on immutable value: "every" is a "let" constant
</code>```

Below is my code:

```<code>func combineLastCharacters(array: [String]) -> String {
    var myString = ""
    var array = array
    for every in array {
        myString = "\(every.remove(at: every.index(before:
        every.endIndex)))" + myString
}
return myString
</code>```

I have found from other answers that by using:

```<code>var array = array
</code>```

array should become mutable, so I can use the remove method on it. Any help is greatly appreciated.

The string I am looking to create is "woohoo!"

答:
array may be mutable, but everyis not and remove(at:) is trying to mutate it. Also, you're appending the characters at the start of the string. Try this:

```<code>func combineLastCharacters(array: [String]) -> String {
    var myString = ""
    for var every in array {
        myString += "\(every.remove(at: every.index(before:
        every.endIndex)))"
    }
    return myString
}
</code>```

or just:

```<code>func combineLastCharacters(array: [String]) -> String {
    return array.reduce("", { $0 + String($1.characters.last!) } )
}
</code>```

Body:
I am attempting to take the last character from the string of each of the words in this array:

var nonsenseArray = ["bungalow", "buffalo", "indigo", "although", "Ontario", "albino", "%$&#!"]

and create a string with each of the characters using a for-loop within a function. I feel like I have a good answer but am getting the following error:

cannnot use mutating member on immutable value: "every" is a "let" constant

Below is my code:

func combineLastCharacters(array: [String]) -> String {
    var myString = ""
    var array = array
    for every in array {
        myString = "\(every.remove(at: every.index(before:
        every.endIndex)))" + myString
}
return myString

I have found from other answers that by using:

var array = array

array should become mutable, so I can use the remove method on it. Any help is greatly appreciated.

The string I am looking to create is "woohoo!"

Body:
array may be mutable, but everyis not and remove(at:) is trying to mutate it. Also, you're appending the characters at the start of the string. Try this:

func combineLastCharacters(array: [String]) -> String {
    var myString = ""
    for var every in array {
        myString += "\(every.remove(at: every.index(before:
        every.endIndex)))"
    }
    return myString
}

or just:

func combineLastCharacters(array: [String]) -> String {
    return array.reduce("", { $0 + String($1.characters.last!) } )
}


问:
Values with "." are not imported from excel file
I have an excel file which looks like this:

Each time my file includes a line like this: 2   1.258   4.587   6.325, my code does not read numbers with . or , and for the given line, only 2 is imported.

Here is my code (which works well but not when my file includes decimal values):

```<code>Xtrain1 = xlsread('mma_kag\train1.xlsx','B:F');
</code>```

The error is:

dimension of datapoints must be larger than 0

This means that it does not read the file and I have checked it. It was [].
How to fix this problem?

Here is the link of the excel file.

答:
The numbers in your cells are considered as text and hence the error. It has nothing to do with numbers being not integers. There are two approaches to solve this error.

Excel Approach:

Select all the cells (by pressing Ctrl+A).

Then click on . This will open a dropdown menu.

Now select Convert to Number.

Save the excel file (Ctrl+S).  (Keep a copy of the previous one if you need that)

For details on this, read this topic:

                  Fix text-formatted numbers by applying a number format

MATLAB Approach:

Use the third output of xlsread and convert the text into double like this:

```<code>[~, ~, Xtrain1] = xlsread('mma_kag\train1.xlsx','B:F');
Xtrain1 = str2double(Xtrain1); %Converting the strings in the cell to double
</code>```

Edit:
If your file has numbers as texts scattered arbitrarily (as in the new file that you uploaded), you would need first and third outputs of xlsread. Something like the following would do:

```<code>[tmp,~, Xtrain1] = xlsread('train1.xlsx'); %Select the range as per your need if necessary
Xtrain1 = str2double(Xtrain1);
%Above line will convert the text into numbers and the numbers will be converted to NaNs
Xtrain1(isnan(Xtrain1))=tmp(~isnan(tmp));
%Above line retrieves the numbers from `tmp` & stores them in `Xtrain1`
</code>```

Body:
I have an excel file which looks like this:

Each time my file includes a line like this: 2   1.258   4.587   6.325, my code does not read numbers with . or , and for the given line, only 2 is imported.

Here is my code (which works well but not when my file includes decimal values):

Xtrain1 = xlsread('mma_kag\train1.xlsx','B:F');

The error is:

dimension of datapoints must be larger than 0

This means that it does not read the file and I have checked it. It was [].
How to fix this problem?

Here is the link of the excel file.

Body:
The numbers in your cells are considered as text and hence the error. It has nothing to do with numbers being not integers. There are two approaches to solve this error.

Excel Approach:

Select all the cells (by pressing Ctrl+A).

Then click on . This will open a dropdown menu.

Now select Convert to Number.

Save the excel file (Ctrl+S).  (Keep a copy of the previous one if you need that)

For details on this, read this topic:

                  Fix text-formatted numbers by applying a number format

MATLAB Approach:

Use the third output of xlsread and convert the text into double like this:

[~, ~, Xtrain1] = xlsread('mma_kag\train1.xlsx','B:F');
Xtrain1 = str2double(Xtrain1); %Converting the strings in the cell to double

Edit:
If your file has numbers as texts scattered arbitrarily (as in the new file that you uploaded), you would need first and third outputs of xlsread. Something like the following would do:

[tmp,~, Xtrain1] = xlsread('train1.xlsx'); %Select the range as per your need if necessary
Xtrain1 = str2double(Xtrain1);
%Above line will convert the text into numbers and the numbers will be converted to NaNs
Xtrain1(isnan(Xtrain1))=tmp(~isnan(tmp));
%Above line retrieves the numbers from `tmp` & stores them in `Xtrain1`


问:
Check When User is Roaming
I need to check in my application when the user is in International roaming and stop sending data to server.Is there any way to check that user is roaming.</p>

答: I don't believe so. You should probably leave this up to the user - the iPhone already has a system-wide setting to disable international data usage if the user so chooses.</p>

Title: Check When User is Roaming


问:
Missing implementation for top level functions
I am trying to make a trait usable on top-level functions in Rust.

```<code>trait FnTrait {
    fn call(self);
}

impl FnTrait for fn() {
    fn call(self) {
        self()
    }
}

fn foo() {
    println!("Hello, World!")
}

fn main() {
    FnTrait::call(foo)
}
</code>```

However the code below fails to compile with (Playground Link)

error[E0277]: the trait bound `fn() {foo}: FnTrait` is not satisfied
  --> <anon>:16:5
   |
16 |     FnTrait::call(foo)
   |     ^^^^^^^^^^^^^ the trait `FnTrait` is not implemented for `fn() {foo}`
   |
   = help: the following implementations were found:
             <fn() as FnTrait>
   = note: required by `FnTrait::call`
```

<p>I found I can trick it into compiling by casting <code>foo</code> like so</p>

```FnTrait::call(foo as fn())
```

But it is annoying and some of the functions in my program are more complicated than foo. Any way to avoid the cast? Is my trait wrong somehow?

答:
Every function in Rust has its own type.  As you can see, foo isn't a fn(), it's a fn() {foo}; sadly, this is not an actual type you can write in source, that's just a compiler message thing.  The distinction exists to make it easier for the compiler to let you pass around functions as values whilst still being able to inline the calls.

The consequence is that named functions pointers cannot be turned into general function pointers without either a cast or a type hint.  For example, this works:

```<code>fn foo() {
    println!("Hello, World!")
}

fn bar(f: fn()) {
    f()
}

fn main() {
    bar(foo)
}
</code>```

However, I'm not aware of any way to leverage this to get the trait to work.

The only way forward is to stop trying to implement the trait for function pointers, and instead implement it for everything callable:

```<code>trait FnTrait {
    fn call(self);
}

impl<F> FnTrait for F where F: FnOnce() {
    fn call(self) {
        self()
    }
}

fn foo() {
    println!("Hello, World!")
}

fn main() {
    foo.call();
}
</code>```

(Semi-relevant answer about the difference between Fn, FnMut and FnOnce.)

This will work for anything that's callable with that signature, including both functions and closures.  The downside is that you can only have one such implementation.  You can't implement this trait for any other signature.

One generic implementation, or many specific implementations and lots of manual casting.  Pick your poison.

As an aside: there's no such thing as a "top level function" in Rust, at least not as a thing distinct from other kinds of functions.  Functions are functions, no matter where they appear.  Instance functions a.k.a. methods are still regular functions, it's just that their first argument is called "self".

Body:
I am trying to make a trait usable on top-level functions in Rust.

trait FnTrait {
    fn call(self);
}

impl FnTrait for fn() {
    fn call(self) {
        self()
    }
}

fn foo() {
    println!("Hello, World!")
}

fn main() {
    FnTrait::call(foo)
}

However the code below fails to compile with (Playground Link)

error[E0277]: the trait bound `fn() {foo}: FnTrait` is not satisfied
  --> <anon>:16:5
   |
16 |     FnTrait::call(foo)
   |     ^^^^^^^^^^^^^ the trait `FnTrait` is not implemented for `fn() {foo}`
   |
   = help: the following implementations were found:
             <fn() as FnTrait>
   = note: required by `FnTrait::call`

I found I can trick it into compiling by casting foo like so

FnTrait::call(foo as fn())

But it is annoying and some of the functions in my program are more complicated than foo. Any way to avoid the cast? Is my trait wrong somehow?

Body:
Every function in Rust has its own type.  As you can see, foo isn't a fn(), it's a fn() {foo}; sadly, this is not an actual type you can write in source, that's just a compiler message thing.  The distinction exists to make it easier for the compiler to let you pass around functions as values whilst still being able to inline the calls.

The consequence is that named functions pointers cannot be turned into general function pointers without either a cast or a type hint.  For example, this works:

fn foo() {
    println!("Hello, World!")
}

fn bar(f: fn()) {
    f()
}

fn main() {
    bar(foo)
}

However, I'm not aware of any way to leverage this to get the trait to work.

The only way forward is to stop trying to implement the trait for function pointers, and instead implement it for everything callable:

trait FnTrait {
    fn call(self);
}

impl<F> FnTrait for F where F: FnOnce() {
    fn call(self) {
        self()
    }
}

fn foo() {
    println!("Hello, World!")
}

fn main() {
    foo.call();
}

(Semi-relevant answer about the difference between Fn, FnMut and FnOnce.)

This will work for anything that's callable with that signature, including both functions and closures.  The downside is that you can only have one such implementation.  You can't implement this trait for any other signature.

One generic implementation, or many specific implementations and lots of manual casting.  Pick your poison.

As an aside: there's no such thing as a "top level function" in Rust, at least not as a thing distinct from other kinds of functions.  Functions are functions, no matter where they appear.  Instance functions a.k.a. methods are still regular functions, it's just that their first argument is called "self".


问:
Why doesn't my Deep Q Network master a simple Gridworld (Tensorflow)? (How to evaluate a Deep-Q-Net)
I try to familiarize myself with Q-learning and Deep Neural Networks, currently try to implement Playing Atari with Deep Reinforcement Learning.

To test my implementation and play around with it, I tought I try a simple gridworld. Where i have a N x N Grid and start in the top left corner and finishes at the bottom right. The possible actions are: left, up, right, down.

Even though my implementation has become very similar to this(hope its a good one) it dosn't seem to learn anything. Looking at the total steps it needs to finish(I guess the average would be aroung 500 with a gridsize of 10x10, but there also very low and high values), it seams more random than anything else to me.

I tried it with and without convolutional layers and played around with all the parameters but to be honest, I've no idea if something with my implementation is wrong or it needs to train longer(I let it train for quite a time) or what ever. But at least it seams to converge, here the plot of the loss value one training session:

So what is the problem in this case?

But also and maybe more importantly how can I "debug" this Deep-Q-Nets, in supervised training there are training, test and validation sets and for example with precision and recall it is possible to evaluate them. What options do I have for unsupervised learning with Deep-Q-Nets, so that the next time maybe I can fix it myself?

Finally here is the code:

This is the network:

```<code>ACTIONS = 5

# Inputs
x = tf.placeholder('float', shape=[None, 10, 10, 4])
y = tf.placeholder('float', shape=[None])
a = tf.placeholder('float', shape=[None, ACTIONS])

# Layer 1 Conv1 - input
with tf.name_scope('Layer1'):
    W_conv1 = weight_variable([8,8,4,8])
    b_conv1 = bias_variable([8])
    h_conv1 = tf.nn.relu(conv2d(x, W_conv1, 5)+b_conv1)

# Layer 2 Conv2 - hidden1
with tf.name_scope('Layer2'):
    W_conv2 = weight_variable([2,2,8,8])
    b_conv2 = bias_variable([8])
    h_conv2 = tf.nn.relu(conv2d(h_conv1, W_conv2, 1)+b_conv2)
    h_conv2_max_pool = max_pool_2x2(h_conv2)

# Layer 3 fc1 - hidden 2
with tf.name_scope('Layer3'):
    W_fc1 = weight_variable([8, 32])
    b_fc1 = bias_variable([32])
    h_conv2_flat = tf.reshape(h_conv2_max_pool, [-1, 8])
    h_fc1 = tf.nn.relu(tf.matmul(h_conv2_flat, W_fc1)+b_fc1)

# Layer 4 fc2 - readout
with tf.name_scope('Layer4'):
    W_fc2 = weight_variable([32, ACTIONS])
    b_fc2 = bias_variable([ACTIONS])
    readout = tf.matmul(h_fc1, W_fc2)+ b_fc2

# Training
with tf.name_scope('training'):
    readout_action = tf.reduce_sum(tf.mul(readout, a), reduction_indices=1)
    loss = tf.reduce_mean(tf.square(y - readout_action))
    train = tf.train.AdamOptimizer(1e-6).minimize(loss)

    loss_summ = tf.scalar_summary('loss', loss)
</code>```

And here the training:

```<code># 0 => left
# 1 => up
# 2 => right
# 3 => down
# 4 = noop

ACTIONS = 5
GAMMA = 0.95
BATCH = 50
TRANSITIONS = 2000
OBSERVATIONS = 1000
MAXSTEPS = 1000

D = deque()
epsilon = 1

average = 0
for episode in xrange(1000):
    step_count = 0
    game_ended = False

    state = np.array([0.0]*100, float).reshape(100)
    state[0] = 1

    rsh_state = state.reshape(10,10)
    s = np.stack((rsh_state, rsh_state, rsh_state, rsh_state), axis=2)

    while step_count < MAXSTEPS and not game_ended:
        reward = 0
        step_count += 1

        read = readout.eval(feed_dict={x: [s]})[0]

        act = np.zeros(ACTIONS)
        action = random.randint(0,4)
        if len(D) > OBSERVATIONS and random.random() > epsilon:
            action = np.argmax(read)
        act[action] = 1

        # play the game
        pos_idx = state.argmax(axis=0)
        pos = pos_idx + 1

        state[pos_idx] = 0
        if action == 0 and pos%10 != 1: #left
            state[pos_idx-1] = 1
        elif action == 1 and pos > 10: #up
            state[pos_idx-10] = 1
        elif action == 2 and pos%10 != 0: #right
            state[pos_idx+1] = 1
        elif action == 3 and pos < 91: #down
            state[pos_idx+10] = 1
        else: #noop
            state[pos_idx] = 1
            pass

        if state.argmax(axis=0) == pos_idx and reward > 0:
            reward -= 0.0001

        if step_count == MAXSTEPS:
            reward -= 100
        elif state[99] == 1: # reward & finished
            reward += 100
            game_ended = True
        else:
            reward -= 1

        s_old = np.copy(s)
        s = np.append(s[:,:,1:], state.reshape(10,10,1), axis=2)

        D.append((s_old, act, reward, s))
        if len(D) > TRANSITIONS:
            D.popleft()

        if len(D) > OBSERVATIONS:
            minibatch = random.sample(D, BATCH)

            s_j_batch = [d[0] for d in minibatch]
            a_batch = [d[1] for d in minibatch]
            r_batch = [d[2] for d in minibatch]
            s_j1_batch = [d[3] for d in minibatch]

            readout_j1_batch = readout.eval(feed_dict={x:s_j1_batch})
            y_batch = []

            for i in xrange(0, len(minibatch)):
                y_batch.append(r_batch[i] + GAMMA * np.max(readout_j1_batch[i]))

            train.run(feed_dict={x: s_j_batch, y: y_batch, a: a_batch})

        if epsilon > 0.05:
            epsilon -= 0.01
</code>```

I appreciate every help and ideas you may have!

答:
So it's quite a time ago that i wrote this question but it seams that there is still quite some interest and request for the running code i finally decided to create a github repository

Since it's quite a time ago i wrote it and so on it won't run out of the box, but it shouldn't be that hard to get it running. So here is the deep q network and example i wrote at the time which back then worked, hope you enjoy: Link to deep q repository

Would be nice to see some contribution and if you fix it and get it running make a pull request!

Body:
I try to familiarize myself with Q-learning and Deep Neural Networks, currently try to implement Playing Atari with Deep Reinforcement Learning.

To test my implementation and play around with it, I tought I try a simple gridworld. Where i have a N x N Grid and start in the top left corner and finishes at the bottom right. The possible actions are: left, up, right, down.

Even though my implementation has become very similar to this(hope its a good one) it dosn't seem to learn anything. Looking at the total steps it needs to finish(I guess the average would be aroung 500 with a gridsize of 10x10, but there also very low and high values), it seams more random than anything else to me.

I tried it with and without convolutional layers and played around with all the parameters but to be honest, I've no idea if something with my implementation is wrong or it needs to train longer(I let it train for quite a time) or what ever. But at least it seams to converge, here the plot of the loss value one training session:

So what is the problem in this case?

But also and maybe more importantly how can I "debug" this Deep-Q-Nets, in supervised training there are training, test and validation sets and for example with precision and recall it is possible to evaluate them. What options do I have for unsupervised learning with Deep-Q-Nets, so that the next time maybe I can fix it myself?

Finally here is the code:

This is the network:

ACTIONS = 5

# Inputs
x = tf.placeholder('float', shape=[None, 10, 10, 4])
y = tf.placeholder('float', shape=[None])
a = tf.placeholder('float', shape=[None, ACTIONS])

# Layer 1 Conv1 - input
with tf.name_scope('Layer1'):
    W_conv1 = weight_variable([8,8,4,8])
    b_conv1 = bias_variable([8])
    h_conv1 = tf.nn.relu(conv2d(x, W_conv1, 5)+b_conv1)

# Layer 2 Conv2 - hidden1
with tf.name_scope('Layer2'):
    W_conv2 = weight_variable([2,2,8,8])
    b_conv2 = bias_variable([8])
    h_conv2 = tf.nn.relu(conv2d(h_conv1, W_conv2, 1)+b_conv2)
    h_conv2_max_pool = max_pool_2x2(h_conv2)

# Layer 3 fc1 - hidden 2
with tf.name_scope('Layer3'):
    W_fc1 = weight_variable([8, 32])
    b_fc1 = bias_variable([32])
    h_conv2_flat = tf.reshape(h_conv2_max_pool, [-1, 8])
    h_fc1 = tf.nn.relu(tf.matmul(h_conv2_flat, W_fc1)+b_fc1)

# Layer 4 fc2 - readout
with tf.name_scope('Layer4'):
    W_fc2 = weight_variable([32, ACTIONS])
    b_fc2 = bias_variable([ACTIONS])
    readout = tf.matmul(h_fc1, W_fc2)+ b_fc2

# Training
with tf.name_scope('training'):
    readout_action = tf.reduce_sum(tf.mul(readout, a), reduction_indices=1)
    loss = tf.reduce_mean(tf.square(y - readout_action))
    train = tf.train.AdamOptimizer(1e-6).minimize(loss)

    loss_summ = tf.scalar_summary('loss', loss)

And here the training:

# 0 => left
# 1 => up
# 2 => right
# 3 => down
# 4 = noop

ACTIONS = 5
GAMMA = 0.95
BATCH = 50
TRANSITIONS = 2000
OBSERVATIONS = 1000
MAXSTEPS = 1000

D = deque()
epsilon = 1

average = 0
for episode in xrange(1000):
    step_count = 0
    game_ended = False

    state = np.array([0.0]*100, float).reshape(100)
    state[0] = 1

    rsh_state = state.reshape(10,10)
    s = np.stack((rsh_state, rsh_state, rsh_state, rsh_state), axis=2)

    while step_count < MAXSTEPS and not game_ended:
        reward = 0
        step_count += 1

        read = readout.eval(feed_dict={x: [s]})[0]

        act = np.zeros(ACTIONS)
        action = random.randint(0,4)
        if len(D) > OBSERVATIONS and random.random() > epsilon:
            action = np.argmax(read)
        act[action] = 1

        # play the game
        pos_idx = state.argmax(axis=0)
        pos = pos_idx + 1

        state[pos_idx] = 0
        if action == 0 and pos%10 != 1: #left
            state[pos_idx-1] = 1
        elif action == 1 and pos > 10: #up
            state[pos_idx-10] = 1
        elif action == 2 and pos%10 != 0: #right
            state[pos_idx+1] = 1
        elif action == 3 and pos < 91: #down
            state[pos_idx+10] = 1
        else: #noop
            state[pos_idx] = 1
            pass

        if state.argmax(axis=0) == pos_idx and reward > 0:
            reward -= 0.0001

        if step_count == MAXSTEPS:
            reward -= 100
        elif state[99] == 1: # reward & finished
            reward += 100
            game_ended = True
        else:
            reward -= 1

        s_old = np.copy(s)
        s = np.append(s[:,:,1:], state.reshape(10,10,1), axis=2)

        D.append((s_old, act, reward, s))
        if len(D) > TRANSITIONS:
            D.popleft()

        if len(D) > OBSERVATIONS:
            minibatch = random.sample(D, BATCH)

            s_j_batch = [d[0] for d in minibatch]
            a_batch = [d[1] for d in minibatch]
            r_batch = [d[2] for d in minibatch]
            s_j1_batch = [d[3] for d in minibatch]

            readout_j1_batch = readout.eval(feed_dict={x:s_j1_batch})
            y_batch = []

            for i in xrange(0, len(minibatch)):
                y_batch.append(r_batch[i] + GAMMA * np.max(readout_j1_batch[i]))

            train.run(feed_dict={x: s_j_batch, y: y_batch, a: a_batch})

        if epsilon > 0.05:
            epsilon -= 0.01

I appreciate every help and ideas you may have!


问:
Ionic: How to stop reloading page content once its completely loaded
I am new to ionic1 framework and working on sidemenu ionic app.      For redirection i am using

$state.go('app.home', {},{location: "replace", reload: true});.

when i switch to other tab and return back to previously loaded page it get load all content again.

How to prevent  reloading of page content every time.

Please help me.

答:
```<code>.state('tab.timeline', {
  url: '/timeline',
  cache: true,
  views: {
    'tab-timeline': {
      templateUrl: 'templates/timeline.html',
      controller: 'time'
    }
  }
})
</code>```

This worked for me instantly almost cried tears of joy, just make cache true

Body:
.state('tab.timeline', {
  url: '/timeline',
  cache: true,
  views: {
    'tab-timeline': {
      templateUrl: 'templates/timeline.html',
      controller: 'time'
    }
  }
})

This worked for me instantly almost cried tears of joy, just make cache true