问:
AngularJs Directive Link function can't access attr attribute
I have the following return of an directive in angularJS

```<code>return {
            restrict: _restrict,
            link: function (scope, element, attrs) {
                $timeout(LinkPre, 0);  //Calling a scoped method
            },
            templateUrl: ConstrutorapiTemplatesChart,
            scope: "@",
            controller: Controller
        }
</code>```

My LinkPre function is the function below

```<code>var LinkPre = function (scope, elem, attrs) {
            attrs.$observe(_attrUrl, function (relatorio) {
                if (relatorio != "") AoMudarUrl(scope, elem, relatorio);
            });
        }
</code>```

I got an error on the LinkPre function, that the attrs is undefined

Cannot read property '$observe' of undefined

Anyone has any ideia why?

Obs: I need that the Link function be executed after the directive is rendered

答:
Firstly you need to pass correctly your parameters to the function.
Then if your function is defined inside the associated controller, you need to add the controller in the link function and call the function through the controller reference.

Try with:

```<code>link: function (scope, element, attrs, myController) {
    $timeout(myController.LinkPre.bind(this, scope, element, attrs));
}
</code>```

Body:
I have the following return of an directive in angularJS

return {
            restrict: _restrict,
            link: function (scope, element, attrs) {
                $timeout(LinkPre, 0);  //Calling a scoped method
            },
            templateUrl: ConstrutorapiTemplatesChart,
            scope: "@",
            controller: Controller
        }

My LinkPre function is the function below

var LinkPre = function (scope, elem, attrs) {
            attrs.$observe(_attrUrl, function (relatorio) {
                if (relatorio != "") AoMudarUrl(scope, elem, relatorio);
            });
        }

I got an error on the LinkPre function, that the attrs is undefined

Cannot read property '$observe' of undefined

Anyone has any ideia why?

Obs: I need that the Link function be executed after the directive is rendered

Body:
Firstly you need to pass correctly your parameters to the function.
Then if your function is defined inside the associated controller, you need to add the controller in the link function and call the function through the controller reference.

Try with:

link: function (scope, element, attrs, myController) {
    $timeout(myController.LinkPre.bind(this, scope, element, attrs));
}


来源: stackexchange

问:
Hover over an image in one column to make text appear in a different column
Apologies as I know this question has been asked in various different forms, but I can't find an answer to my exact problem - at least not one that I understand!

I'm very new to programming, and am currently building myself a webpage for my wedding cake business to try and familiarise myself with HTML, CSS and a bit of JavaScript and JQuery. I have a list of thumbnail images in one column, which I added "onmouseover" to so that when hovered over (in addition to a css transition) they display a large version of themselves in a central column. I want to also display information about each cake in a third column to the right hand side of the main image but I have no idea how to go about doing this!

```<code><div class="col-md-3">
<ul class="cake-thumbs">
    <li>
        <figure class="cake-img">
            <img onmouseover="getElementById('preview').src=this.src" id="img10" src="Resources/img/10.jpg" alt="Pastel Pink Placard and Pearls">
        </figure>
    </li>
    <li>
        <figure class="cake-img">
            <img onmouseover="getElementById('preview').src=this.src" id="img11" src="Resources/img/11.jpg" alt="Naked Wedding Cake with fresh fruit">
        </figure>
    </li>
    <li>
        <figure class="cake-img">
            <img onmouseover="getElementById('preview').src=this.src" id="img12" src="Resources/img/12.jpg" alt="Gold Damask and Pearls">
        </figure>
    </li>
</ul>
</div>
<div class="col-md-6">
        <img id="preview" src="Resources/img/1.jpg" alt="">
</div>
<div class="col-md-3">
    <p id="info">Price and servings here</p>
</div>
</code>```

答:
Here is a simple jquery expression that would get this done.

NOTE: this is a broad question, but this will definitly get you pointed in the right direction

```<code>$(document).on('hover', '.cake-img', function(event) {
    $('.col-md-3').text('sample text here');
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Apologies as I know this question has been asked in various different forms, but I can't find an answer to my exact problem - at least not one that I understand!

I'm very new to programming, and am currently building myself a webpage for my wedding cake business to try and familiarise myself with HTML, CSS and a bit of JavaScript and JQuery. I have a list of thumbnail images in one column, which I added "onmouseover" to so that when hovered over (in addition to a css transition) they display a large version of themselves in a central column. I want to also display information about each cake in a third column to the right hand side of the main image but I have no idea how to go about doing this!

Price and servings here

Body:
Here is a simple jquery expression that would get this done.

NOTE: this is a broad question, but this will definitly get you pointed in the right direction

$(document).on('hover', '.cake-img', function(event) {
    $('.col-md-3').text('sample text here');
});


问:
Cannot call sendError() after the response has been committed
I have the following filter:

```<code>public class IPFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if ("/api/v1/auth/user".equals(((HttpServletRequest) request).getRequestURI())) {
             //skip
            chain.doFilter(request, response);
        }
        ...
    }
    ...
}
</code>```

After I've added if I see

```<code>2017-06-08 20:09:54,150 INFO com.finvale.controllers.AuthController.me:93 - Get me [org.springframework.security.oauth2.provider.OAuth2Authentication@474166d5: Principal: ADMIN_1; Credentials: [PROTECTED]; Authenticated: true; Details: remoteAddress=127.0.0.1, tokenType=BearertokenValue=<TOKEN>; Granted Authorities: ROLE_CONSUMER, ROLE_ADMINISTRATOR, ROLE_PROVIDER]
2017-06-08 20:09:54,154 ERROR org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet].log:181 - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
    at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:456)
    at javax.servlet.http.HttpServletResponseWrapper.sendError(HttpServletResponseWrapper.java:120)
    at org.springframework.session.web.http.OnCommittedResponseWrapper.sendError(OnCommittedResponseWrapper.java:116)
    at javax.servlet.http.HttpServletResponseWrapper.sendError(HttpServletResponseWrapper.java:120)
    at javax.servlet.http.HttpServletResponseWrapper.sendError(HttpServletResponseWrapper.java:120)
    at javax.servlet.http.HttpServletResponseWrapper.sendError(HttpServletResponseWrapper.java:120)
    at org.springframework.security.web.util.OnCommittedResponseWrapper.sendError(OnCommittedResponseWrapper.java:119)
    at com.finvale.auth.IPFilter.doFilter(IPFilter.java:70)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:108)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter.doFilter(OAuth2AuthenticationProcessingFilter.java:176)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter.doFilter(OAuth2ClientContextFilter.java:60)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:167)
    at org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:80)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:106)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    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.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:783)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
    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)
2017-06-08 20:09:54,158 DEBUG com.finvale.config.ApiRequestMappingHandlerMapping.getHandlerInternal:310 - Looking up handler method for path /error
2017-06-08 20:09:54,159 DEBUG com.finvale.config.ApiRequestMappingHandlerMapping.getHandlerInternal:317 - Returning handler method [public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)]
2017-06-08 20:09:54,164 ERROR org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet].log:181 - Servlet.service() for servlet dispatcherServlet threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
    at org.apache.catalina.connector.Response.getWriter(Response.java:609)
    at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:211)
    at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:109)
    at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:109)
    at org.springframework.session.web.http.OnCommittedResponseWrapper.getWriter(OnCommittedResponseWrapper.java:149)
    at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:109)
    at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:109)
    at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:109)
    at org.springframework.security.web.util.OnCommittedResponseWrapper.getWriter(OnCommittedResponseWrapper.java:149)
    at org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$SpelView.render(ErrorMvcAutoConfiguration.java:227)
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1282)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1037)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:980)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at com.finvale.auth.IPFilter.doFilter(IPFilter.java:56)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:116)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter.doFilter(OAuth2AuthenticationProcessingFilter.java:176)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter.doFilter(OAuth2ClientContextFilter.java:60)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:167)
    at org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:80)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:726)
    at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:592)
    at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:526)
    at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:389)
    at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:254)
    at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:349)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:175)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    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:783)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
    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)
</code>```

What did I wrong ?

答:
It should look like this:</p>

```<code>public class IPFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if ("/api/v1/auth/user".equals(((HttpServletRequest) request).getRequestURI())) {
             //skip
            chain.doFilter(request, response);
            return; //   <--- important line
        }
        ...
    }
    ...
}
</code>```

Body:
I have the following filter:

public class IPFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if ("/api/v1/auth/user".equals(((HttpServletRequest) request).getRequestURI())) {
             //skip
            chain.doFilter(request, response);
        }
        ...
    }
    ...
}

After I've added if I see

2017-06-08 20:09:54,150 INFO com.finvale.controllers.AuthController.me:93 - Get me [org.springframework.security.oauth2.provider.OAuth2Authentication@474166d5: Principal: ADMIN_1; Credentials: [PROTECTED]; Authenticated: true; Details: remoteAddress=127.0.0.1, tokenType=BearertokenValue=<TOKEN>; Granted Authorities: ROLE_CONSUMER, ROLE_ADMINISTRATOR, ROLE_PROVIDER]
2017-06-08 20:09:54,154 ERROR org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet].log:181 - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
    at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:456)
    at javax.servlet.http.HttpServletResponseWrapper.sendError(HttpServletResponseWrapper.java:120)
    at org.springframework.session.web.http.OnCommittedResponseWrapper.sendError(OnCommittedResponseWrapper.java:116)
    at javax.servlet.http.HttpServletResponseWrapper.sendError(HttpServletResponseWrapper.java:120)
    at javax.servlet.http.HttpServletResponseWrapper.sendError(HttpServletResponseWrapper.java:120)
    at javax.servlet.http.HttpServletResponseWrapper.sendError(HttpServletResponseWrapper.java:120)
    at org.springframework.security.web.util.OnCommittedResponseWrapper.sendError(OnCommittedResponseWrapper.java:119)
    at com.finvale.auth.IPFilter.doFilter(IPFilter.java:70)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:108)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter.doFilter(OAuth2AuthenticationProcessingFilter.java:176)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter.doFilter(OAuth2ClientContextFilter.java:60)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:167)
    at org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:80)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:106)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    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.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:783)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
    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)
2017-06-08 20:09:54,158 DEBUG com.finvale.config.ApiRequestMappingHandlerMapping.getHandlerInternal:310 - Looking up handler method for path /error
2017-06-08 20:09:54,159 DEBUG com.finvale.config.ApiRequestMappingHandlerMapping.getHandlerInternal:317 - Returning handler method [public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)]
2017-06-08 20:09:54,164 ERROR org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet].log:181 - Servlet.service() for servlet dispatcherServlet threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
    at org.apache.catalina.connector.Response.getWriter(Response.java:609)
    at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:211)
    at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:109)
    at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:109)
    at org.springframework.session.web.http.OnCommittedResponseWrapper.getWriter(OnCommittedResponseWrapper.java:149)
    at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:109)
    at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:109)
    at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:109)
    at org.springframework.security.web.util.OnCommittedResponseWrapper.getWriter(OnCommittedResponseWrapper.java:149)
    at org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$SpelView.render(ErrorMvcAutoConfiguration.java:227)
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1282)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1037)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:980)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at com.finvale.auth.IPFilter.doFilter(IPFilter.java:56)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:116)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter.doFilter(OAuth2AuthenticationProcessingFilter.java:176)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter.doFilter(OAuth2ClientContextFilter.java:60)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:167)
    at org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:80)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:726)
    at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:592)
    at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:526)
    at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:389)
    at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:254)
    at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:349)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:175)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    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:783)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
    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)

What did I wrong ?

Body:
It should look like this:

public class IPFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if ("/api/v1/auth/user".equals(((HttpServletRequest) request).getRequestURI())) {
             //skip
            chain.doFilter(request, response);
            return; //   <--- important line
        }
        ...
    }
    ...
}

ContentLicense: CC BY-SA 4.0


问:
How can I make a TimerTask run in a certain period and to
I have a method that has to take a picture of the screen every 0.5 seconds and saves the image in a place on the HD. But I need him to run between 11:55 a.m. and 4:55 p.m. to 5:00 p.m.

I just got to start the Task and I could not stop it.

My doubt is:

How could I schedule, for the thread to run only within a certain period of time.

```<code>public class Main {

private Toolkit a = Toolkit.getDefaultToolkit();
private Dimension screenSize = a.getScreenSize();
private Rectangle screenLimit = new Rectangle(screenSize);
private Robot robot;

private File file;

BufferedImage img;

private final static int TWO_AM = 11;
private final static int ZERO_MINUTES = 28;

private static Date getTomorrowMorning1145AM(){

    Date date2am = new java.util.Date();
       date2am.setHours(TWO_AM);
       date2am.setMinutes(ZERO_MINUTES);

       return date2am;
  }

public Main() {

    String path = "c:\\print\\"+System.getProperty("user.name")+"\\";

    try {
        robot = new Robot();
        file = new File(path);
    } catch (AWTException e1) {
        e1.printStackTrace();
    }

    if(!file.exists()){
        file.mkdirs();
    }

    TimerTask tt = new TimerTask() {

        @Override
        public void run() {

            try {
                tirarPrint(path+"print_" + new Date().getTime() + ".jpg");
            } catch (IOException | AWTException e) {
                e.printStackTrace();
            }

        }
    };

    Timer t = new Timer();

    t.schedule(tt, 0, 500);

}

private void tirarPrint(String caminho) throws AWTException, IOException {

    img = robot.createScreenCapture(screenLimit);
    ImageIO.write(img, "jpg", new File(caminho));

 }

public static void main(String[] args) {
    new Main();
  }
}
</code>```

答:
For this task I would use two ExecutorServices.

One checks every minute if it is the right time frame and the second executes your program code every 0.5s.

http://tutorials.jenkov.com/java-util-concurrent/executorservice.html

```<code>public static ScheduledExecutorService timerFrameExecutor = Executors.newSingleThreadScheduledExecutor();
public static ScheduledExecutorService shortTimeExecutor = Executors.newSingleThreadScheduledExecutor();

public static void main(String[] args) {
    Runnable timerFrameRunnable = new Runnable() {

        @Override
        public void run() {
            if (inTimePeriond() == false) {
                shortTimeExecutor.shutdown();
            } else {
                if (shortTimeExecutor.isShutdown()) {
                    Runnable shortTimeRunnable = new Runnable() {

                        @Override
                        public void run() {
                            // do your stuff
                        }
                    };
                    shortTimeExecutor.scheduleAtFixedRate(shortTimeRunnable, 0, 500, TimeUnit.MILLISECONDS);
                }
            }
        }
    };
    timerFrameExecutor.scheduleAtFixedRate(timerFrameRunnable, 0, 1, TimeUnit.MINUTES);
}
</code>```

To implement the inTimePeriod() function see this question:
Check if a given time lies between two times regardless of date

Body:
I have a method that has to take a picture of the screen every 0.5 seconds and saves the image in a place on the HD. But I need him to run between 11:55 a.m. and 4:55 p.m. to 5:00 p.m.

I just got to start the Task and I could not stop it.

My doubt is:

How could I schedule, for the thread to run only within a certain period of time.

public class Main {

private Toolkit a = Toolkit.getDefaultToolkit();
private Dimension screenSize = a.getScreenSize();
private Rectangle screenLimit = new Rectangle(screenSize);
private Robot robot;

private File file;

BufferedImage img;

private final static int TWO_AM = 11;
private final static int ZERO_MINUTES = 28;

private static Date getTomorrowMorning1145AM(){

    Date date2am = new java.util.Date();
       date2am.setHours(TWO_AM);
       date2am.setMinutes(ZERO_MINUTES);

       return date2am;
  }

public Main() {

    String path = "c:\\print\\"+System.getProperty("user.name")+"\\";

    try {
        robot = new Robot();
        file = new File(path);
    } catch (AWTException e1) {
        e1.printStackTrace();
    }

    if(!file.exists()){
        file.mkdirs();
    }

    TimerTask tt = new TimerTask() {

        @Override
        public void run() {

            try {
                tirarPrint(path+"print_" + new Date().getTime() + ".jpg");
            } catch (IOException | AWTException e) {
                e.printStackTrace();
            }

        }
    };

    Timer t = new Timer();

    t.schedule(tt, 0, 500);

}

private void tirarPrint(String caminho) throws AWTException, IOException {

    img = robot.createScreenCapture(screenLimit);
    ImageIO.write(img, "jpg", new File(caminho));

 }

public static void main(String[] args) {
    new Main();
  }
}

Body:
For this task I would use two ExecutorServices.

One checks every minute if it is the right time frame and the second executes your program code every 0.5s.

http://tutorials.jenkov.com/java-util-concurrent/executorservice.html

public static ScheduledExecutorService timerFrameExecutor = Executors.newSingleThreadScheduledExecutor();
public static ScheduledExecutorService shortTimeExecutor = Executors.newSingleThreadScheduledExecutor();

public static void main(String[] args) {
    Runnable timerFrameRunnable = new Runnable() {

        @Override
        public void run() {
            if (inTimePeriond() == false) {
                shortTimeExecutor.shutdown();
            } else {
                if (shortTimeExecutor.isShutdown()) {
                    Runnable shortTimeRunnable = new Runnable() {

                        @Override
                        public void run() {
                            // do your stuff
                        }
                    };
                    shortTimeExecutor.scheduleAtFixedRate(shortTimeRunnable, 0, 500, TimeUnit.MILLISECONDS);
                }
            }
        }
    };
    timerFrameExecutor.scheduleAtFixedRate(timerFrameRunnable, 0, 1, TimeUnit.MINUTES);
}

To implement the inTimePeriod() function see this question:
Check if a given time lies between two times regardless of date


问:
Angular 2. How to apply orderBy?
I have a piece of code.

            #
            Name
            Score

            {{i+1}}
            {{participant.username}}
            {{participant.score}}

```

In Angular 1 i have orderBy filter to order rows by my filter. But how can i do orderBy in Angular 2 the same way ? Thank you.

答:
If you are using lodash your pipe can be like this:

```<code>import { Pipe, PipeTransform } from '@angular/core';
import { orderBy } from 'lodash';

@Pipe({
  name: 'orderBy'
})
export class OrderByPipe implements PipeTransform {
  transform = orderBy;
}
</code>```

And then you can use all the power of the method:

```<code><li *ngFor="let product of products | orderBy: 'price': 'desc'">
  {{product.name}}
</li>
</code>```

Title: Angular 2. How to apply orderBy?

Body:
I have a piece of code.

            #
            Name
            Score

            {{i+1}}
            {{participant.username}}
            {{participant.score}}

In Angular 1 i have orderBy filter to order rows by my filter. But how can i do orderBy in Angular 2 the same way ? Thank you.

Body:
If you are using lodash your pipe can be like this:

import { Pipe, PipeTransform } from '@angular/core';
import { orderBy } from 'lodash';

@Pipe({
  name: 'orderBy'
})
export class OrderByPipe implements PipeTransform {
  transform = orderBy;
}

And then you can use all the power of the method:

<li *ngFor="let product of products | orderBy: 'price': 'desc'">
  {{product.name}}
</li>


问:
Adding a textfile with a name to each directory
I'm having some trouble with trying to add a text file to each directory in this directory having a certain name. I have a directory called Daily Notes where I save my notes for the day and I have this further organized by week. So I have a bunch of directories in here such as 6.5.17-6.10.17 and in each of these I need a text file with the name format such as 6.7.17DailyNotes.txt. I know I can easily do this by hand each day, but I have some free time and am trying to learn how to program with cmd. I tried to just make a test text file with a for loop but it saved it to the directory containing the batch file. Here is my code right now:

```<code>@echo off
setlocal disabledelayedexpansion

set "folder=%~1"
if not defined folder set "folder=%cd%"

for /D %%a in ("%folder%\*") do (
    echo test > test.txt
)

endlocal
</code>```

So, I want to go into each directory and make 5 text files, one for each day with the format month.day.yearDailyNotes.txt. I was thinking I could just make a variable from reading the directory name and count up in days from that for the text files. Any advice?

答:
Your comment

I know it would be very difficult to handle month changes in the
  middle of the week, I was thinking it will be acceptable to just
  handle that part manually, so have a file named something like
  10.32.17DailyNotes.txt which I manually will change after

makes it much easier (Date/Time Math in Batch is possible, but ugly and involves a lot of code)

```<code>@echo off
setlocal enabledelayedexpansion
REM next two lines for simulating your environment:
set "folder=%~dp0"
md 6.5.17-6.10.17 6.11.17-6.16.17 2>nul

REM for every folder
for /d %%f in ("%folder%*.*.*-*.*.*") do (
  REM extract day, month and year [from first part of foldername]
  for /f "tokens=1-3 delims=.-" %%a in ("%%~nxf")do (
    REM calculate "end day" [may be greater than days in that month]
    set /a end=%%b+5
    REM for [start] to [end]
    for /l %%i in (%%b,1,!end!) do (
      REM create blank file
      break > "%%f\%%a.%%i.%%cDailyNotes.txt"
    )
  )
)
</code>```

Body:
I'm having some trouble with trying to add a text file to each directory in this directory having a certain name. I have a directory called Daily Notes where I save my notes for the day and I have this further organized by week. So I have a bunch of directories in here such as 6.5.17-6.10.17 and in each of these I need a text file with the name format such as 6.7.17DailyNotes.txt. I know I can easily do this by hand each day, but I have some free time and am trying to learn how to program with cmd. I tried to just make a test text file with a for loop but it saved it to the directory containing the batch file. Here is my code right now:

@echo off
setlocal disabledelayedexpansion

set "folder=%~1"
if not defined folder set "folder=%cd%"

for /D %%a in ("%folder%\*") do (
    echo test > test.txt
)

endlocal

So, I want to go into each directory and make 5 text files, one for each day with the format month.day.yearDailyNotes.txt. I was thinking I could just make a variable from reading the directory name and count up in days from that for the text files. Any advice?

Body:
Your comment

I know it would be very difficult to handle month changes in the
  middle of the week, I was thinking it will be acceptable to just
  handle that part manually, so have a file named something like
  10.32.17DailyNotes.txt which I manually will change after

makes it much easier (Date/Time Math in Batch is possible, but ugly and involves a lot of code)

@echo off
setlocal enabledelayedexpansion
REM next two lines for simulating your environment:
set "folder=%~dp0"
md 6.5.17-6.10.17 6.11.17-6.16.17 2>nul

REM for every folder
for /d %%f in ("%folder%*.*.*-*.*.*") do (
  REM extract day, month and year [from first part of foldername]
  for /f "tokens=1-3 delims=.-" %%a in ("%%~nxf")do (
    REM calculate "end day" [may be greater than days in that month]
    set /a end=%%b+5
    REM for [start] to [end]
    for /l %%i in (%%b,1,!end!) do (
      REM create blank file
      break > "%%f\%%a.%%i.%%cDailyNotes.txt"
    )
  )
)


问:
C# DataGridView.DataSource difference between using BindingSource and not
I found that I can just set the DataGridView.DataSource directly to the DataTable without using the BindingSource in between, which is what all of the tutorials I've seen so far are using. So what is the difference between these two?</p>

答:
Some information here on how the use of a BindingSource is an improvement to the old way of binding directly to a DataTable.

http://msdn.microsoft.com/en-us/library/aa480734.aspx

In summary:

The BindingSource component simplifies
  the developer's job by providing
  currency management, change
  notification and the ability to easily
  access the members in a bound list.
  There are, however, some other
  lesser-known improvements to the data
  binding story worth discussing, and in
  fact, are important additions that
  complement the functionality offered
  by the BindingSource component.

The Binding object has several new
  members in the .NET Framework 2.0 that
  enable greater control over the
  binding operation. For example, you
  can control how data is formatted in a
  bound control, when the data source is
  updated, and how null and DBNull
  values in the data source are handled.
  These new members are also supported
  with corresponding Add methods in the
  ControlBindingsCollection. You can
  take advantage of these additions by
  using the Formatting and Advanced
  Binding dialog box in Visual Studio or
  through code. In addition, the Binding
  object has better support for handling
  exceptions and errors that can occur
  in the binding process with the
  addition of the BindingComplete event.

ContentLicense: CC BY-SA 2.5


问:
Reduce and assign using Stream api for multiple variables
I need to do following in lambda but unable to think of way where single stream and reducing(s) can help :(

I have Employee ArrayList where name member variable can be duplicate across object in list. I need to create map where key is employee name and value is object where we have sum of cost1 and cost2 for that employee.

Employee class has -> String name, Integer cost1, Integer cost2

Output class has -> Integer cost1, Integer cost2

```<code>List <Employee> employeeList = new ArrayList<>();
// data population in inputMap
Map<String, Output> outputMap = new HashMap<>();
for (Employee emp : employeeList)
{
    Output op = outputMap.get(emp.getName());
    if(op == null){
      Output newOp = new Output ();
      newOp.setCost1(emp.getCost1())
      newOp.setCost2(emp.getCost2())
      newOp.put(emp.getName(), newOp);
    }else{
       int cost1 = op.getCost1() + emp.getCost1();
       int cost2 = op.getCost2() + emp.getCost2();
       op.setCost1(cost1);
       op.setCost2(cost2);
       newOp.put(emp.getName(), op);
    }
}
</code>```

答:
Whenever you need to get a reduced map out of the elements of your stream, you can use the three-argument version of Collectors.toMap:

```<code>Map<String, Output> result = employeeList.stream()
    .collect(Collectors.toMap(
        Employee::getName,
        employee -> new Output(employee.getCost1(), employee.getCost2()),
        (left, right) -> {
            left.setCost1(left.getCost1() + right.getCost1());
            left.setCost2(left.getCost2() + right.getCost2());
            return left;
        }));
</code>```

Collectors.toMap, as its name suggests, collects the elements of the stream to a map. Its first argument is a function that converts elements of the stream to keys, the second argument is another function that converts elements of the stream to values, and the third argument is a merge function that is applied to values when there's a collision on the keys.

In this case, I'm using a mutable reduction on the left operand of the merge function. This is to avoid creating too many instances of the Output class. It is safe to reduce this way because in the value function (the second argument of Collectors.toMap) I'm creating a new instance of the Output class.

This solution could be greatly improved if you could add the following constructor and method to the Output class:

```<code>// creates an Output instance out of an Employee instance
public Output(Employee employee) {
    this.cost1 = employee.getCost1();
    this.cost2 = employee.getCost2();
}

// merges another Output instance into this Output instance
public Output merge(Output another) {
    this.cost1 += another.cost1;
    this.cost2 += another.cost2;
    return this;
}
</code>```

Now, collecting to the map would be much simpler:

```<code>Map<String, Output> result = employeeList.stream()
    .collect(Collectors.toMap(Employee::getName, Output::new, Output::merge));
</code>```

Body:
I need to do following in lambda but unable to think of way where single stream and reducing(s) can help :(

I have Employee ArrayList where name member variable can be duplicate across object in list. I need to create map where key is employee name and value is object where we have sum of cost1 and cost2 for that employee.

Employee class has -> String name, Integer cost1, Integer cost2

Output class has -> Integer cost1, Integer cost2

List <Employee> employeeList = new ArrayList<>();
// data population in inputMap
Map<String, Output> outputMap = new HashMap<>();
for (Employee emp : employeeList)
{
    Output op = outputMap.get(emp.getName());
    if(op == null){
      Output newOp = new Output ();
      newOp.setCost1(emp.getCost1())
      newOp.setCost2(emp.getCost2())
      newOp.put(emp.getName(), newOp);
    }else{
       int cost1 = op.getCost1() + emp.getCost1();
       int cost2 = op.getCost2() + emp.getCost2();
       op.setCost1(cost1);
       op.setCost2(cost2);
       newOp.put(emp.getName(), op);
    }
}

Body:
Whenever you need to get a reduced map out of the elements of your stream, you can use the three-argument version of Collectors.toMap:

Map<String, Output> result = employeeList.stream()
    .collect(Collectors.toMap(
        Employee::getName,
        employee -> new Output(employee.getCost1(), employee.getCost2()),
        (left, right) -> {
            left.setCost1(left.getCost1() + right.getCost1());
            left.setCost2(left.getCost2() + right.getCost2());
            return left;
        }));

Collectors.toMap, as its name suggests, collects the elements of the stream to a map. Its first argument is a function that converts elements of the stream to keys, the second argument is another function that converts elements of the stream to values, and the third argument is a merge function that is applied to values when there's a collision on the keys.

In this case, I'm using a mutable reduction on the left operand of the merge function. This is to avoid creating too many instances of the Output class. It is safe to reduce this way because in the value function (the second argument of Collectors.toMap) I'm creating a new instance of the Output class.

This solution could be greatly improved if you could add the following constructor and method to the Output class:

// creates an Output instance out of an Employee instance
public Output(Employee employee) {
    this.cost1 = employee.getCost1();
    this.cost2 = employee.getCost2();
}

// merges another Output instance into this Output instance
public Output merge(Output another) {
    this.cost1 += another.cost1;
    this.cost2 += another.cost2;
    return this;
}

Now, collecting to the map would be much simpler:

Map<String, Output> result = employeeList.stream()
    .collect(Collectors.toMap(Employee::getName, Output::new, Output::merge));


问:
Powershell convertto-json without labels
how to correctly convert a Powershell array of object properties to a json array of values, that is without the objects property lables in the array.

for example:
I want to make 2 json arrays for chart.js
I will group some process objects:

```<code>$processgroup = get-process | group -property name

$processgroup.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

$chartlabels = $processgroup.name | convertto-json

$chartlabels

$chartlabels
[
    "ApMsgFwd",
    "ApntEx",
    "Apoint",
    "ApplicationFrameHost",
    "armsvc",
    "BtwRSupportService",
    "chrome",
    "com.docker.proxy",
    "com.docker.service",
    "concentr",
    "conhost",
    "csrss",
    "dllhost",
    "Docker for Windows",
    "dockerd",
    "dwm",
    "Everything",
    "EXCEL",
    "explorer",
    "fontdrvhost",
    "GROOVE",
    "hidfind",
    "HidMonitorSvc",
    "Idle",
    "iexplore",
    "IpOverUsbSvc",
    "jucheck",
    "jusched",
    "LicensingUI",
    "lsass",
    "mDNSResponder",
    "Memory Compression",
    "mqsvc",
    "MSASCuiL",
    "MsMpEng",
    "MSOIDSVC",
    "MSOIDSVCM",
    "MySQLNotifier",
    "NisSrv",
    "notepad",
    "notepad++",
    "nvSCPAPISvr",
    "nvvsvc",
    "nvwmi64",
    "nvxdsync",
    "OfficeClickToRun",
    "OneDrive",
    "OUTLOOK",
    "powershell",
    "powershell_ise",
    "prevhost",
    "Receiver",
    "redirector",
    "rundll32",
    "RuntimeBroker",
    "SearchIndexer",
    "SearchUI",
    "Secure System",
    "SecurityHealthService",
    "SelfServicePlugin",
    "services",
    "SettingSyncHost",
    "ShellExperienceHost",
    "sihost",
    "SkypeHost",
    "smss",
    "SMSvcHost",
    "spiceworks",
    "spiceworks-httpd",
    "spoolsv",
    "SppExtComObj",
    "sppsvc",
    "sqlwriter",
    "svchost",
    "System",
    "SystemSettings",
    "taskhostw",
    "TSVNCache",
    "vmcompute",
    "vmms",
    "vmnat",
    "vmnetdhcp",
    "vmware-authd",
    "vmware-tray",
    "vmware-usbarbitrator64",
    "wfcrun32",
    "wininit",
    "winlogon",
    "WINWORD",
    "WmiPrvSE",
    "WUDFHost"
]

#this is the array I want for charts labels, now for the chart value array

$chartvalues = $processgroup | select count | convertto-json

$chartvalues
[
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  30
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  5
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  4
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  30
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  75
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    }
]
</code>```

how do I omit the "Count" label so PowerShell creates a single json array of the values only, as in the process name array.

I have tried

```<code>$chartvalues = $processgroup.count
</code>```

results in the count of the number of groups

and I have tried

```<code>$chartvalues = $ processgroup | select count -expandproperty count | convertto-json
</code>```

with the same result as above example

答:
All you have to do use the -ExpandProperty property of Select-Object to achieve your stated desire.  Is there any reason not to preserve the property->value notation which association inside of a single JSON array?  e.g.:

```<code>$processgroup = get-process | group -property name,count | select name,count | convertto-json
</code>```

yields:

```<code>$processgroup
[
    {
        "Name":  "acevents",
        "Count":  1
    },
    {
        "Name":  "acrotray",
        "Count":  1
    },
    {
        "Name":  "AGSService",
        "Count":  1
    },
    {
        "Name":  "aiCOMMAPI",
        "Count":  1
    },
    {
        "Name":  "armsvc",
        "Count":  1
    },
    {
        "Name":  "audiodg",
        "Count":  1
    },
    {
        "Name":  "AuditManagerService",
        "Count":  1
    },
    {
        "Name":  "CcmExec",
        "Count":  1
    },
    {
        "Name":  "chrome",
        "Count":  9
    },
    {
        "Name":  "conhost",
        "Count":  2
    },
    {
        "Name":  "csrss",
        "Count":  2
    },
    {
        "Name":  "dllhost",
        "Count":  2
    },
    {
        "Name":  "dwm",
        "Count":  1
    },
    {
        "Name":  "explorer",
        "Count":  1
    },
    {
        "Name":  "Idle",
        "Count":  1
    },
    {
        "Name":  "lsass",
        "Count":  1
    },
    {
        "Name":  "lync",
        "Count":  1
    },
    {
        "Name":  "msdtc",
        "Count":  1
    }
]
</code>```

Body:
how to correctly convert a Powershell array of object properties to a json array of values, that is without the objects property lables in the array.

for example:
I want to make 2 json arrays for chart.js
I will group some process objects:

$processgroup = get-process | group -property name

$processgroup.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

$chartlabels = $processgroup.name | convertto-json

$chartlabels

$chartlabels
[
    "ApMsgFwd",
    "ApntEx",
    "Apoint",
    "ApplicationFrameHost",
    "armsvc",
    "BtwRSupportService",
    "chrome",
    "com.docker.proxy",
    "com.docker.service",
    "concentr",
    "conhost",
    "csrss",
    "dllhost",
    "Docker for Windows",
    "dockerd",
    "dwm",
    "Everything",
    "EXCEL",
    "explorer",
    "fontdrvhost",
    "GROOVE",
    "hidfind",
    "HidMonitorSvc",
    "Idle",
    "iexplore",
    "IpOverUsbSvc",
    "jucheck",
    "jusched",
    "LicensingUI",
    "lsass",
    "mDNSResponder",
    "Memory Compression",
    "mqsvc",
    "MSASCuiL",
    "MsMpEng",
    "MSOIDSVC",
    "MSOIDSVCM",
    "MySQLNotifier",
    "NisSrv",
    "notepad",
    "notepad++",
    "nvSCPAPISvr",
    "nvvsvc",
    "nvwmi64",
    "nvxdsync",
    "OfficeClickToRun",
    "OneDrive",
    "OUTLOOK",
    "powershell",
    "powershell_ise",
    "prevhost",
    "Receiver",
    "redirector",
    "rundll32",
    "RuntimeBroker",
    "SearchIndexer",
    "SearchUI",
    "Secure System",
    "SecurityHealthService",
    "SelfServicePlugin",
    "services",
    "SettingSyncHost",
    "ShellExperienceHost",
    "sihost",
    "SkypeHost",
    "smss",
    "SMSvcHost",
    "spiceworks",
    "spiceworks-httpd",
    "spoolsv",
    "SppExtComObj",
    "sppsvc",
    "sqlwriter",
    "svchost",
    "System",
    "SystemSettings",
    "taskhostw",
    "TSVNCache",
    "vmcompute",
    "vmms",
    "vmnat",
    "vmnetdhcp",
    "vmware-authd",
    "vmware-tray",
    "vmware-usbarbitrator64",
    "wfcrun32",
    "wininit",
    "winlogon",
    "WINWORD",
    "WmiPrvSE",
    "WUDFHost"
]

#this is the array I want for charts labels, now for the chart value array

$chartvalues = $processgroup | select count | convertto-json

$chartvalues
[
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  30
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  5
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  4
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  30
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  75
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    },
    {
        "Count":  2
    },
    {
        "Count":  1
    },
    {
        "Count":  1
    }
]

how do I omit the "Count" label so PowerShell creates a single json array of the values only, as in the process name array.

I have tried

$chartvalues = $processgroup.count

results in the count of the number of groups

and I have tried

$chartvalues = $ processgroup | select count -expandproperty count | convertto-json

with the same result as above example

Body:
All you have to do use the -ExpandProperty property of Select-Object to achieve your stated desire.  Is there any reason not to preserve the property->value notation which association inside of a single JSON array?  e.g.:

$processgroup = get-process | group -property name,count | select name,count | convertto-json

yields:

$processgroup
[
    {
        "Name":  "acevents",
        "Count":  1
    },
    {
        "Name":  "acrotray",
        "Count":  1
    },
    {
        "Name":  "AGSService",
        "Count":  1
    },
    {
        "Name":  "aiCOMMAPI",
        "Count":  1
    },
    {
        "Name":  "armsvc",
        "Count":  1
    },
    {
        "Name":  "audiodg",
        "Count":  1
    },
    {
        "Name":  "AuditManagerService",
        "Count":  1
    },
    {
        "Name":  "CcmExec",
        "Count":  1
    },
    {
        "Name":  "chrome",
        "Count":  9
    },
    {
        "Name":  "conhost",
        "Count":  2
    },
    {
        "Name":  "csrss",
        "Count":  2
    },
    {
        "Name":  "dllhost",
        "Count":  2
    },
    {
        "Name":  "dwm",
        "Count":  1
    },
    {
        "Name":  "explorer",
        "Count":  1
    },
    {
        "Name":  "Idle",
        "Count":  1
    },
    {
        "Name":  "lsass",
        "Count":  1
    },
    {
        "Name":  "lync",
        "Count":  1
    },
    {
        "Name":  "msdtc",
        "Count":  1
    }
]


问:
Convert a scala Set of Strings to a Set of Long
how can I convert a Scala set of strings

```<code>val s = Set("1","2","3")
</code>```

to a set of long?

```<code>Set(1, 2, 3)
</code>```

Thanks!

答:
Adding long value check:

```<code>import scala.util.{Try, Success, Failure}

val s = Set("1", "2", "3", "x")

s.map( x => Try(x.toLong) match {
  case Success(e) => e
  case Failure(_) => -999L
} )
res1: scala.collection.immutable.Set[Long] = Set(1, 2, 3, -999)
</code>```

Body:
how can I convert a Scala set of strings

val s = Set("1","2","3")

to a set of long?

Set(1, 2, 3)

Thanks!

Body:
Adding long value check:

import scala.util.{Try, Success, Failure}

val s = Set("1", "2", "3", "x")

s.map( x => Try(x.toLong) match {
  case Success(e) => e
  case Failure(_) => -999L
} )
res1: scala.collection.immutable.Set[Long] = Set(1, 2, 3, -999)


问:
API call using data from Redux reducer?
I want to do API request to the server using data from Reducer (Updated state) after I dispatch it. I would have done it in the Dispatcher if I have enough data, but I only send necessary data to dispatcher.

How should I do it ?

/* Book list container*/
const mapStateToProps = (state) => {
    return {
      books: state.bookApp.books
    }
}

const mapDispatchToProps = (dispatch) => {
    // Calling change book title from component
    return {
      // Dispatch new title to the book list by it's id
      onChangeBookTitle: (id, newTitle) => {
        dispatch(updateBookTitle(id, newTitle))
      }
    }
}

// Connect redux to bookList component
export default connect(
    mapStateToProps,
    mapDispatchToProps
)(BookList);

/* Book list action creator */
export const updateBookTitle = (id, newTitle) => {
  return {
    type: 'EDIT_BOOK_TITLE',
    title: newTitle
  }
};

/* Book list reducer */
// Assume there's already a book to update
const defaultState = {
  bookList: []
}

const bookApp = (state = defaultState, action) => {
  switch(action.type) {
    case 'EDIT_BOOK_TITLE' : {
        let newBookList;
        // Create new copy of booklist
        // Do some transformation
        // And voilaa... i got new book list
        return {...state, bookList: newBookList}

        // This is the place where I want to do my API call, using the new BookList data
    }
    default:
        return state;
}```

答:
This is a good use case for a thunk action creator:

```<code>export const updateBookTitle = (id, newTitle) => {
    return (dispatch, getState) => {
        dispatch({type : 'EDIT_BOOK_TITLE', title : newTitle});

        const updatedState = getState();
        // read values from updated state and make an API call here
    }
}
</code>```

However, note that you should not do any API calls from a reducer!  That is absolutely against how Redux is supposed to be used.

Title: API call using data from Redux reducer?

Body:
This is a good use case for a thunk action creator:

export const updateBookTitle = (id, newTitle) => {
    return (dispatch, getState) => {
        dispatch({type : 'EDIT_BOOK_TITLE', title : newTitle});

        const updatedState = getState();
        // read values from updated state and make an API call here
    }
}

However, note that you should not do any API calls from a reducer!  That is absolutely against how Redux is supposed to be used.


答:
jQuery will make this (wait for it...) a piece of cake ;)

```<code>$('.cake-img img').mouseover(function(){
    $('#preview').attr('src', this.src)
})
</code>```

You can place this at the end of your page, or in the head, wrapped in a  document.ready call, removing the inline JavaScript you have.

Title: Hover over an image in one column to make text appear in a different column

Body:
Apologies as I know this question has been asked in various different forms, but I can't find an answer to my exact problem - at least not one that I understand!

I'm very new to programming, and am currently building myself a webpage for my wedding cake business to try and familiarise myself with HTML, CSS and a bit of JavaScript and JQuery. I have a list of thumbnail images in one column, which I added "onmouseover" to so that when hovered over (in addition to a css transition) they display a large version of themselves in a central column. I want to also display information about each cake in a third column to the right hand side of the main image but I have no idea how to go about doing this!

Price and servings here

Body:
jQuery will make this (wait for it...) a piece of cake ;)

$('.cake-img img').mouseover(function(){
    $('#preview').attr('src', this.src)
})

You can place this at the end of your page, or in the head, wrapped in a  document.ready call, removing the inline JavaScript you have.


问:
How will I know when to create an interface?
I'm at a point in my development learning where I feel like I must learn more about interfaces.

I frequently read about them but it just seems like I cannot grasp them.

I've read examples like: Animal base class, with IAnimal interface for things like 'Walk', 'Run', 'GetLegs', etc - but I've never been working on something and felt like "Hey I should use an interface here!"

What am I missing? Why is it such a hard concept for me to grasp! I am just intimidated by the fact that I might not ever realize a concrete need for one - mostly due to some missing aspect of understanding them! It makes me feel like I'm missing something up top in terms of being a developer! If anyone has had an experience like this and had a breakthrough I would appreciate some tips on how to understand this concept. Thank you.

答:
I've used interfaces now and then and here's my latest usage (names have been generalized):

I have a bunch of custom controls on a WinForm that need to save data to my business object.  One approach is to call each control separately:

```<code>myBusinessObject.Save(controlA.Data);
myBusinessObject.Save(controlB.Data);
myBusinessObject.Save(controlC.Data);
</code>```

The problem with this implementation is that any time I add a control I have to go into my "Save Data" method and add the new control.

I changed my controls to implement an ISaveable interface that has a method SaveToBusinessObject(...) so now my "Save Data" method just iterates through the controls and if it finds one that is ISaveable, it calls SaveToBusinessObject.  So now when a new control is needed, all someone has to do is implement ISaveable in that object (and never touch another class).

```<code>foreach(Control c in Controls)
{
  ISaveable s = c as ISaveable;

  if( s != null )
      s.SaveToBusinessObject(myBusinessObject);
}
</code>```

The oftentimes unrealized benefit to interfaces is that you localize modifications.  Once defined, you'll rarely change the overall flow of an application but you will often make changes on the detail-level.  When you keep the details in specific objects, a change in ProcessA will not affect a change in ProcessB.  (Base classes also give you this benefit.)

EDIT:  Another benefit is specificity in actions.  Like in my example, all I want to do is save the data; I don't care what type of control it is or if it can do anything else -- I just want to know if I can save the data in the control.  It makes my save code pretty clear -- there are no checks to see if it's text, numeric, boolean or whatever because the  custom control handles all of that.

LastEditorDisplayName: ALassek

Body:
I've used interfaces now and then and here's my latest usage (names have been generalized):

I have a bunch of custom controls on a WinForm that need to save data to my business object.  One approach is to call each control separately:

myBusinessObject.Save(controlA.Data);
myBusinessObject.Save(controlB.Data);
myBusinessObject.Save(controlC.Data);

The problem with this implementation is that any time I add a control I have to go into my "Save Data" method and add the new control.

I changed my controls to implement an ISaveable interface that has a method SaveToBusinessObject(...) so now my "Save Data" method just iterates through the controls and if it finds one that is ISaveable, it calls SaveToBusinessObject.  So now when a new control is needed, all someone has to do is implement ISaveable in that object (and never touch another class).

foreach(Control c in Controls)
{
  ISaveable s = c as ISaveable;

  if( s != null )
      s.SaveToBusinessObject(myBusinessObject);
}

The oftentimes unrealized benefit to interfaces is that you localize modifications.  Once defined, you'll rarely change the overall flow of an application but you will often make changes on the detail-level.  When you keep the details in specific objects, a change in ProcessA will not affect a change in ProcessB.  (Base classes also give you this benefit.)

EDIT:  Another benefit is specificity in actions.  Like in my example, all I want to do is save the data; I don't care what type of control it is or if it can do anything else -- I just want to know if I can save the data in the control.  It makes my save code pretty clear -- there are no checks to see if it's text, numeric, boolean or whatever because the  custom control handles all of that.

OwnerDisplayName: Austin Salonen

LastEditorDisplayName: Austin Salonen


问:
How to make two microservices listen on same port in azure service fabric
I have created a project with two microservices and want both of them to listen to same port.
I have two separate ServiceManifest File in which i have defined same endpoint for both of them but when i deploy it locally or remotely it doesn't work.

When I deploy it locally it shows following Exception:
Exception thrown: 'System.Reflection.TargetInvocationException' in mscorlib.dll

答:
Depending on the communication stack you are using you have a few options.

If HTTP based web API - you can use the reverse proxy and dynamic port assignment for the services: https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-reverseproxy

If using Service Remoting - just use dynamic ports.

For external communication to the cluster - taka look here: https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-reverseproxy#special-handling-for-port-sharing-services


问:
node js store returned API key as variable
I am new to node and am trying to using A node.js library for the Pardot API

This I pass my userKey, email and password to pardot, this returns my api_key.

I am using the following code to authenticate, then when I run my node server I can see the api_key being passed back.

how do I then store that api_key as a variable to then use to post data to the API?

my node code

```<code>var nodePardot = require('node-pardot');

// Create client using email, password and user_key
nodePardot.PardotAPI({
    userKey: 'kyujk',
    email: 'uu.uuy@uu.co.uk',
    password: 'uit.09',
    DEBUG: true
}, function(err, client) {
    // Authentication completed
    console.log('Authentication completed');

    // gets api key
    var api_key = api_key;
    console.log('key',api_key);
});
</code>```

my console output

```<code>[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
Server started! At http://localhost:8080
Initializing node-pardot in DEBUG mode
params {"email":"bhyuyten.jj@jyj.co.uk","password":"tyjt.09","user_key":"yjty76","format":"json"}
uri https://pi.pardot.com/api/login/version/3?email=ss.jyj%s.co.uk&password=tyjt.09&user_key=yjty76&api_key=&format=json
parsedResponse {"@attributes":{"stat":"ok","version":1},"api_key":"878074492492dhjjk67u","version":4}
Authentication completed
key undefined
parsedResponse {"@attributes":{"stat":"ok","version":1},"api_key":"878074492492dhjjk67u","version":4}

var nodePardot = require('node-pardot');

    // Create client using email, password and user_key
    nodePardot.PardotAPI({
        userKey: 'fdgr',
        email: 'rg.gg@gg.co.uk',
        password: 'dfherg',
        DEBUG: true
    }, function(err, client) {
        // Authentication completed
        console.log('Authentication completed');

        // gets api key
        var api_key = api_key;
        console.log('key',api_key);
    });
</code>```

答:
Looking at the source of node-pardot here and here, it looks like the API Key is at client.apiKey

Also, you should always check for the error condition in nodejs-style callback functions!

```<code>nodePardot.PardotAPI({
    userKey: '...',
    email: '...',
    password: '...',
    DEBUG: true
}, function(err, client) {
    if(err){
        // Authentication failed
        // handle error
        console.error("Authentication Failed", err)
    } else {
        // Authentication successful
        // gets api key
        var api_key = client.apiKey;
        console.log("Authentication successful", api_key);
    }
});
</code>```

P.S. You should never post API keys and credentials on public forums and QA sites

Body:
I am new to node and am trying to using A node.js library for the Pardot API

This I pass my userKey, email and password to pardot, this returns my api_key.

I am using the following code to authenticate, then when I run my node server I can see the api_key being passed back.

how do I then store that api_key as a variable to then use to post data to the API?

my node code

var nodePardot = require('node-pardot');

// Create client using email, password and user_key
nodePardot.PardotAPI({
    userKey: 'kyujk',
    email: 'uu.uuy@uu.co.uk',
    password: 'uit.09',
    DEBUG: true
}, function(err, client) {
    // Authentication completed
    console.log('Authentication completed');

    // gets api key
    var api_key = api_key;
    console.log('key',api_key);
});

my console output

[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
Server started! At http://localhost:8080
Initializing node-pardot in DEBUG mode
params {"email":"bhyuyten.jj@jyj.co.uk","password":"tyjt.09","user_key":"yjty76","format":"json"}
uri https://pi.pardot.com/api/login/version/3?email=ss.jyj%s.co.uk&password=tyjt.09&user_key=yjty76&api_key=&format=json
parsedResponse {"@attributes":{"stat":"ok","version":1},"api_key":"878074492492dhjjk67u","version":4}
Authentication completed
key undefined
parsedResponse {"@attributes":{"stat":"ok","version":1},"api_key":"878074492492dhjjk67u","version":4}

var nodePardot = require('node-pardot');

    // Create client using email, password and user_key
    nodePardot.PardotAPI({
        userKey: 'fdgr',
        email: 'rg.gg@gg.co.uk',
        password: 'dfherg',
        DEBUG: true
    }, function(err, client) {
        // Authentication completed
        console.log('Authentication completed');

        // gets api key
        var api_key = api_key;
        console.log('key',api_key);
    });

Body:
Looking at the source of node-pardot here and here, it looks like the API Key is at client.apiKey

Also, you should always check for the error condition in nodejs-style callback functions!

nodePardot.PardotAPI({
    userKey: '...',
    email: '...',
    password: '...',
    DEBUG: true
}, function(err, client) {
    if(err){
        // Authentication failed
        // handle error
        console.error("Authentication Failed", err)
    } else {
        // Authentication successful
        // gets api key
        var api_key = client.apiKey;
        console.log("Authentication successful", api_key);
    }
});

P.S. You should never post API keys and credentials on public forums and QA sites