问:
Bean service not created on second call
I am having some unexpected behaviour when trying to inject my service bean to my controller. What I mean getting is when I initial call my controller with the end point localhost:8082/content/asset ; the first instance the service is created and I get back the result I expect. However when I then make a second call to for example localhost:8082/content/asset/all my service is null for some reason and I am not sure what is going on as both calls are part of the same controller.

Here is my controller

```<code>@Log4j2
@Controller
public class ContentCreationController {

    @Autowired
    private ContentCategoryService contentCategoryService;

    //the service is not null
    @Secured({"ROLE_PROJECTADMIN", "ROLE_ADMIN"})
    @GetMapping("content/asset")
    @ResponseBody
    public ModelAndView homeContent(HttpServletRequest request) {
        contentCategoryService.getContentCategoriesByUser(request.getUserPrincipal().getName());
        return new ModelAndView("content_creation");
    }

    //this call the service is null
    @Secured({"ROLE_PROJECTADMIN", "ROLE_API", "ROLE_STUDENT", "ROLE_TEACHER", "ROLE_ADMIN"})
    @GetMapping("content/asset/all")
    @ResponseBody
    private List<ContentCategory> getAllContentCategory(HttpServletRequest request) {
        log.info("Request: " + request.getUserPrincipal().getName());

        return contentCategoryService.getContentCategoriesByUser(request.getUserPrincipal().getName());
    }

}
</code>```

Here is my service

```<code>@Service
@Log4j2
public class ContentCategoryService {
    @Secured({"ROLE_STUDENT", "ROLE_TEACHER", "ROLE_ADMIN"})
    public List<ContentCategory> getContentCategoriesByUser(String username){
        //get user
        User u = userService.loadUserByUsername(username);

        List<ContentCategory> list = contentCategoryRepository.findByEnabled(true);
        return list.stream().filter(i -> {
            for(String r : i.getAuthorisedRoles()){
                if(i.getContentProvider() != null && i.getMultiMediaContentList() != null){
                    log.info(i.getName() + " has " + i.getMultiMediaContentList().size() + " content items");
                }else{
                    log.info(i.getName() + " has 0 content items and thus, no content provider!");
                }
                if(UserUtilities.userHasRole(u, r)){
                    return true;
                }
            }
            return false;
        }).collect(Collectors.toList());
    }
}
</code>```

Here is the full stack trace

```<code>java.lang.NullPointerException
    at com.avantiplc.controllers.ContentCreationController.getAllContentCategory(ContentCreationController.java:38)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    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.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.servlet.resource.ResourceUrlEncodingFilter.doFilterInternal(ResourceUrlEncodingFilter.java:53)
    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:115)
    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:169)
    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.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:121)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:100)
    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.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
    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.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87)
    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.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    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.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.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:522)
    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:1110)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:785)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1425)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
</code>```

any help would be much appreciated.

答:
My issue was that for some reason in Spring the methods within the controller must be public.

for example my following method was private

```<code>    @Secured({"ROLE_PROJECTADMIN", "ROLE_API", "ROLE_STUDENT", "ROLE_TEACHER", "ROLE_ADMIN"})
    @GetMapping("content/asset/all")
    @ResponseBody
    private List<ContentCategory> getAllContentCategory(HttpServletRequest request) {
        log.info("Request: " + request.getUserPrincipal().getName());

        return contentCategoryService.getContentCategoriesByUser(request.getUserPrincipal().getName());
    }
</code>```

But when I set the access modifier to public the service was being created  correctly.

Title: Bean service not created on second call

Body:
I am having some unexpected behaviour when trying to inject my service bean to my controller. What I mean getting is when I initial call my controller with the end point localhost:8082/content/asset ; the first instance the service is created and I get back the result I expect. However when I then make a second call to for example localhost:8082/content/asset/all my service is null for some reason and I am not sure what is going on as both calls are part of the same controller.

Here is my controller

@Log4j2
@Controller
public class ContentCreationController {

    @Autowired
    private ContentCategoryService contentCategoryService;

    //the service is not null
    @Secured({"ROLE_PROJECTADMIN", "ROLE_ADMIN"})
    @GetMapping("content/asset")
    @ResponseBody
    public ModelAndView homeContent(HttpServletRequest request) {
        contentCategoryService.getContentCategoriesByUser(request.getUserPrincipal().getName());
        return new ModelAndView("content_creation");
    }

    //this call the service is null
    @Secured({"ROLE_PROJECTADMIN", "ROLE_API", "ROLE_STUDENT", "ROLE_TEACHER", "ROLE_ADMIN"})
    @GetMapping("content/asset/all")
    @ResponseBody
    private List<ContentCategory> getAllContentCategory(HttpServletRequest request) {
        log.info("Request: " + request.getUserPrincipal().getName());

        return contentCategoryService.getContentCategoriesByUser(request.getUserPrincipal().getName());
    }

}

Here is my service

@Service
@Log4j2
public class ContentCategoryService {
    @Secured({"ROLE_STUDENT", "ROLE_TEACHER", "ROLE_ADMIN"})
    public List<ContentCategory> getContentCategoriesByUser(String username){
        //get user
        User u = userService.loadUserByUsername(username);

        List<ContentCategory> list = contentCategoryRepository.findByEnabled(true);
        return list.stream().filter(i -> {
            for(String r : i.getAuthorisedRoles()){
                if(i.getContentProvider() != null && i.getMultiMediaContentList() != null){
                    log.info(i.getName() + " has " + i.getMultiMediaContentList().size() + " content items");
                }else{
                    log.info(i.getName() + " has 0 content items and thus, no content provider!");
                }
                if(UserUtilities.userHasRole(u, r)){
                    return true;
                }
            }
            return false;
        }).collect(Collectors.toList());
    }
}

Here is the full stack trace

java.lang.NullPointerException
    at com.avantiplc.controllers.ContentCreationController.getAllContentCategory(ContentCreationController.java:38)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    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.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.servlet.resource.ResourceUrlEncodingFilter.doFilterInternal(ResourceUrlEncodingFilter.java:53)
    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:115)
    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:169)
    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.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:121)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:100)
    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.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
    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.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87)
    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.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    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.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.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:522)
    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:1110)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:785)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1425)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

any help would be much appreciated.

Body:
My issue was that for some reason in Spring the methods within the controller must be public.

for example my following method was private

    @Secured({"ROLE_PROJECTADMIN", "ROLE_API", "ROLE_STUDENT", "ROLE_TEACHER", "ROLE_ADMIN"})
    @GetMapping("content/asset/all")
    @ResponseBody
    private List<ContentCategory> getAllContentCategory(HttpServletRequest request) {
        log.info("Request: " + request.getUserPrincipal().getName());

        return contentCategoryService.getContentCategoriesByUser(request.getUserPrincipal().getName());
    }

But when I set the access modifier to public the service was being created  correctly.


来源: stackexchange

问:
Passing argument 4 of 'obj_setProperty' from incompatible pointer type
I am getting the above compiler error in XCode, and I cannot work out what's going on.

```<code>#import <UIKit/UIKit.h>

// #import "HeaderPanelViewController.h"
#import "HTTPClientCommunicator.h"
#import "WebSocket.h"

@class HeaderPanelViewController;

@protocol ServerDateTimeUpdating
-(void)serverDateTimeHasBeenUpdatedWithDate:(NSString *) dateString andTime:(NSString *) timeString;
@end

@interface SmartWardPTAppDelegate : NSObject <UIApplicationDelegate, WebSocketDelegate> {

}

@property (nonatomic, retain) id<ServerDateTimeUpdating> *serverDateTimeDelegate;
....
@end
</code>```

Then in this line

```<code>@synthesize serverDateTimeDelegate;
</code>```

in ApplicationDelegate.m I am getting the error "Passing argument 4 of 'obj_setProperty' from incompatible pointer type". I did a bit of research and found that 'retain' only works on class types, which is fair enough. If I actually remove the 'retain' from the line

```<code>@property (nonatomic, retain) id<ServerDateTimeUpdating> *serverDateTimeDelegate;
</code>```

it does compile without complaints. However, I think, that's the wrong thing to do. Surely my 'id' is a class type and surely it should be retained in the setter. BTW, here is the declaration of my HeaderPanelViewController which implements the aforementioned protocol:

```<code> @interface HeaderPanelViewController : UIViewController<ServerDateTimeUpdating> {

 }

...
@end
</code>```

Also, if I actually do remove the retain I get a problem later down the track when I actually call the setter to register my HeaderPanelViewController as the delegate:

```<code>// Register this instance as the delegate for ServerDateTimeUpdating
// Retrieve the ApplicationDelegate...
ApplicationDelegate *applicationDelegate = (ApplicationDelegate *) [UIApplication sharedApplication].delegate;
// ...and register this instance
applicationDelegate.serverDateTimeDelegate = self;
</code>```

The last line causes the XCode error message "Passing argument 1 of 'setServerDateTimeDelegate' from incompatible pointer type".

答:
Your problem is here:

```<code>@property (nonatomic, retain) id<ServerDateTimeUpdating> *serverDateTimeDelegate;
</code>```

id is already a pointer type, so you declaring serverDateTimeDelegate as a pointer  (*) effectively makes the property a pointer to a pointer.

Get rid of the * and everything should work fine.

ContentLicense: CC BY-SA 2.5

Body:
I am getting the above compiler error in XCode, and I cannot work out what's going on.

#import <UIKit/UIKit.h>

// #import "HeaderPanelViewController.h"
#import "HTTPClientCommunicator.h"
#import "WebSocket.h"

@class HeaderPanelViewController;

@protocol ServerDateTimeUpdating
-(void)serverDateTimeHasBeenUpdatedWithDate:(NSString *) dateString andTime:(NSString *) timeString;
@end

@interface SmartWardPTAppDelegate : NSObject <UIApplicationDelegate, WebSocketDelegate> {

}

@property (nonatomic, retain) id<ServerDateTimeUpdating> *serverDateTimeDelegate;
....
@end

Then in this line

@synthesize serverDateTimeDelegate;

in ApplicationDelegate.m I am getting the error "Passing argument 4 of 'obj_setProperty' from incompatible pointer type". I did a bit of research and found that 'retain' only works on class types, which is fair enough. If I actually remove the 'retain' from the line

@property (nonatomic, retain) id<ServerDateTimeUpdating> *serverDateTimeDelegate;

it does compile without complaints. However, I think, that's the wrong thing to do. Surely my 'id' is a class type and surely it should be retained in the setter. BTW, here is the declaration of my HeaderPanelViewController which implements the aforementioned protocol:

 @interface HeaderPanelViewController : UIViewController<ServerDateTimeUpdating> {

 }

...
@end

Also, if I actually do remove the retain I get a problem later down the track when I actually call the setter to register my HeaderPanelViewController as the delegate:

// Register this instance as the delegate for ServerDateTimeUpdating
// Retrieve the ApplicationDelegate...
ApplicationDelegate *applicationDelegate = (ApplicationDelegate *) [UIApplication sharedApplication].delegate;
// ...and register this instance
applicationDelegate.serverDateTimeDelegate = self;

The last line causes the XCode error message "Passing argument 1 of 'setServerDateTimeDelegate' from incompatible pointer type".

Body:
Your problem is here:

@property (nonatomic, retain) id<ServerDateTimeUpdating> *serverDateTimeDelegate;

id is already a pointer type, so you declaring serverDateTimeDelegate as a pointer  (*) effectively makes the property a pointer to a pointer.

Get rid of the * and everything should work fine.


问:
Java generics method <T extends Integer> +1
Im new to generics. Maybe my question is dumb and silly but why the following doesnt work?

```<code>public <T extends Integer> Integer methodA(T t){
   return t = t + 1;
}
</code>```

It says that Operator cannot be applied to 'T', 'int'. What should I do to make this code work?

答:
You could do:

```<code>return t + 1;
</code>```

But generally your declaration T extends Integer makes little sense, because Integer is marked final, so one cannot extend it.

ContentLicense: CC BY-SA 3.0

Body:
Im new to generics. Maybe my question is dumb and silly but why the following doesnt work?

public <T extends Integer> Integer methodA(T t){
   return t = t + 1;
}

It says that Operator cannot be applied to 'T', 'int'. What should I do to make this code work?

Body:
You could do:

return t + 1;

But generally your declaration T extends Integer makes little sense, because Integer is marked final, so one cannot extend it.


问:
Get user products with using user_id in codeigniter
Hey guys I'm making a website in codeigniter and I'm trying to make the page for another user profile. On the profile of another user I want to show all the products that that user uploaded. I tried to do it like the same as you're own user profile but with that I'm using the session user_id.

This is what I have right now:

Controller function:

```<code>public function userdetails($user_id)
 {
  //load the model
  $this->load->model('User_model');

  $data['userdetail_list'] = $this->User_model->getdata($user_id);
  $data['products'] = $this->User_model->userproducts();
  $this->load->view('profiel_user',$data);

 }
</code>```

function in model:

```<code>public function userproducts($user_id)
{
    $this->db->where('user_id',$user_id);
    $query = $this->db->get('products');
    if($query->num_rows()>0)
    {
       return $query->result_array();
    }
    return array();
}
</code>```

So when I'm on a user profile page, I want to show all the products that belong to the profile user_id I clicked on.

I also have this function already to get the user_id of that profile page I'm on:

```<code>function getdata($user_id){
  $this->db->select("*");
  $this->db->from('users');
  $this->db->where('user_id', $user_id);
  $query = $this->db->get();
  return $query->result();
 }
</code>```

Anyone got model code of how I can do it?
thanks

database information:

Table 1 : products:

```<code>product_id
product_naam
product_beschrijving
user_id
ophaal_plaats
product_foto
product_foto_thumb
date_created
date_updated
category_id

table 2 : users:

user_id
email
voornaam
achternaam
beschrijving
profiel_foto
</code>```

答:
Create a similar function like this

```<code>public function product_other_user_id($user_id)
      {
          $this->db->where('user_id', $user_id);
          return $this->db->get('products')->result();
      }
</code>```

then in your controller call that function after you have user_id for example

```<code>$userProducts = product_other_user_id($user_id);
</code>```

When you return combine both user and their products in an array or an associate array whatever you feel comfortable with.

Body:
Hey guys I'm making a website in codeigniter and I'm trying to make the page for another user profile. On the profile of another user I want to show all the products that that user uploaded. I tried to do it like the same as you're own user profile but with that I'm using the session user_id.

This is what I have right now:

Controller function:

public function userdetails($user_id)
 {
  //load the model
  $this->load->model('User_model');

  $data['userdetail_list'] = $this->User_model->getdata($user_id);
  $data['products'] = $this->User_model->userproducts();
  $this->load->view('profiel_user',$data);

 }

function in model:

public function userproducts($user_id)
{
    $this->db->where('user_id',$user_id);
    $query = $this->db->get('products');
    if($query->num_rows()>0)
    {
       return $query->result_array();
    }
    return array();
}

So when I'm on a user profile page, I want to show all the products that belong to the profile user_id I clicked on.

I also have this function already to get the user_id of that profile page I'm on:

function getdata($user_id){
  $this->db->select("*");
  $this->db->from('users');
  $this->db->where('user_id', $user_id);
  $query = $this->db->get();
  return $query->result();
 }

Anyone got model code of how I can do it?
thanks

database information:

Table 1 : products:

product_id
product_naam
product_beschrijving
user_id
ophaal_plaats
product_foto
product_foto_thumb
date_created
date_updated
category_id

table 2 : users:

user_id
email
voornaam
achternaam
beschrijving
profiel_foto

Body:
Create a similar function like this

public function product_other_user_id($user_id)
      {
          $this->db->where('user_id', $user_id);
          return $this->db->get('products')->result();
      }

then in your controller call that function after you have user_id for example

$userProducts = product_other_user_id($user_id);

When you return combine both user and their products in an array or an associate array whatever you feel comfortable with.


问:
Xcode 8 recompiling complete code every time
With any change in code (though file is not in .pch), complete project recompiles every time.</p>

答:
Try to:
 1. Navigate to Project
 2. Click Build Settings
 3. Check that OptimizationLevel is set to None for debugging.
 4. Click Add User-Defined Setting
 5. Set SWIFT_WHOLE_MODULE_OPTIMIZATION to YES.


问:
gpg: skipped "XXBDXX4E": secret key not available. gpg: signing failed: secret key not available
I follow this tutorial: https://help.github.com/articles/signing-commits-using-gpg/

I try to sign when commit like this:
https://github.com/spring-guides/tut-spring-boot-oauth2/commit/824f418ab9d04114b14a90f7c19b4b8d6dda67b7

but error:

```<code>C:\Users\Administrator\Desktop\foo\test_gpg>git commit -m "test"
gpg: skipped "DABDD34E": secret key not available
gpg: signing failed: secret key not available
error: gpg failed to sign the data
fatal: failed to write commit object
</code>```

My config:

```<code>C:\Users\Administrator\Desktop\foo\test_gpg>git config --list --show-origin
file:"C:\\ProgramData/Git/config"       core.symlinks=false
file:"C:\\ProgramData/Git/config"       core.autocrlf=true
file:"C:\\ProgramData/Git/config"       core.fscache=true
file:"C:\\ProgramData/Git/config"       color.diff=auto
file:"C:\\ProgramData/Git/config"       color.status=auto
file:"C:\\ProgramData/Git/config"       color.branch=auto
file:"C:\\ProgramData/Git/config"       color.interactive=true
file:"C:\\ProgramData/Git/config"       help.format=html
file:"C:\\ProgramData/Git/config"       http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
file:"C:\\ProgramData/Git/config"       diff.astextplain.textconv=astextplain
file:"C:\\ProgramData/Git/config"       rebase.autosquash=true
file:"C:\\Program Files\\Git\\mingw64/etc/gitconfig"    credential.helper=manager
file:C:/Users/Administrator/.gitconfig  user.name=donhuvy
file:C:/Users/Administrator/.gitconfig  user.email=donhuvy@hotmail.com
file:C:/Users/Administrator/.gitconfig  user.signingkey=DABDD34E
file:C:/Users/Administrator/.gitconfig  commit.gpgsign=true
file:C:/Users/Administrator/.gitconfig  use.signingkey=DABDD34E
file:.git/config        core.repositoryformatversion=0
file:.git/config        core.filemode=false
file:.git/config        core.bare=false
file:.git/config        core.logallrefupdates=true
file:.git/config        core.symlinks=false
file:.git/config        core.ignorecase=true
file:.git/config        core.hidedotfiles=dotGitOnly
file:.git/config        remote.origin.url=https://github.com/donhuvy/test_gpg.git
file:.git/config        remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
file:.git/config        branch.master.remote=origin
file:.git/config        branch.master.merge=refs/heads/master
file:.git/config        commit.gpgsign=true
</code>```

and

```<code>C:\Users\Administrator\Desktop\foo\test_gpg>gpg --list-key
C:/Users/Administrator/AppData/Roaming/gnupg/pubring.gpg
--------------------------------------------------------
pub   2048R/DABDD34E 2016-06-10
uid       [ultimate] donhuvy (Do Nhu Vy) <v@vyhn.net>
uid       [ultimate] Do Nhu Vy (Do Nhu Vy) <v@vyhn.net>
sub   2048R/C6B535A2 2016-06-10
</code>```

(I register 3 emails with GitHub: v@vyhn.net, donhuvy@hotmail.com and xxxxx@gmail.com)
What I have been wrong? How I sign my commit?

答:
I am using TortoiseGIT on Windows 10, and I was having the same problem right now.

For me this solved the problem:

```<code>git config --global gpg.program "c:\Program Files (x86)\GnuPG\bin\gpg.exe"
</code>```

Body:
I follow this tutorial: https://help.github.com/articles/signing-commits-using-gpg/

I try to sign when commit like this:
https://github.com/spring-guides/tut-spring-boot-oauth2/commit/824f418ab9d04114b14a90f7c19b4b8d6dda67b7

but error:

C:\Users\Administrator\Desktop\foo\test_gpg>git commit -m "test"
gpg: skipped "DABDD34E": secret key not available
gpg: signing failed: secret key not available
error: gpg failed to sign the data
fatal: failed to write commit object

My config:

C:\Users\Administrator\Desktop\foo\test_gpg>git config --list --show-origin
file:"C:\\ProgramData/Git/config"       core.symlinks=false
file:"C:\\ProgramData/Git/config"       core.autocrlf=true
file:"C:\\ProgramData/Git/config"       core.fscache=true
file:"C:\\ProgramData/Git/config"       color.diff=auto
file:"C:\\ProgramData/Git/config"       color.status=auto
file:"C:\\ProgramData/Git/config"       color.branch=auto
file:"C:\\ProgramData/Git/config"       color.interactive=true
file:"C:\\ProgramData/Git/config"       help.format=html
file:"C:\\ProgramData/Git/config"       http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
file:"C:\\ProgramData/Git/config"       diff.astextplain.textconv=astextplain
file:"C:\\ProgramData/Git/config"       rebase.autosquash=true
file:"C:\\Program Files\\Git\\mingw64/etc/gitconfig"    credential.helper=manager
file:C:/Users/Administrator/.gitconfig  user.name=donhuvy
file:C:/Users/Administrator/.gitconfig  user.email=donhuvy@hotmail.com
file:C:/Users/Administrator/.gitconfig  user.signingkey=DABDD34E
file:C:/Users/Administrator/.gitconfig  commit.gpgsign=true
file:C:/Users/Administrator/.gitconfig  use.signingkey=DABDD34E
file:.git/config        core.repositoryformatversion=0
file:.git/config        core.filemode=false
file:.git/config        core.bare=false
file:.git/config        core.logallrefupdates=true
file:.git/config        core.symlinks=false
file:.git/config        core.ignorecase=true
file:.git/config        core.hidedotfiles=dotGitOnly
file:.git/config        remote.origin.url=https://github.com/donhuvy/test_gpg.git
file:.git/config        remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
file:.git/config        branch.master.remote=origin
file:.git/config        branch.master.merge=refs/heads/master
file:.git/config        commit.gpgsign=true

and

C:\Users\Administrator\Desktop\foo\test_gpg>gpg --list-key
C:/Users/Administrator/AppData/Roaming/gnupg/pubring.gpg
--------------------------------------------------------
pub   2048R/DABDD34E 2016-06-10
uid       [ultimate] donhuvy (Do Nhu Vy) <v@vyhn.net>
uid       [ultimate] Do Nhu Vy (Do Nhu Vy) <v@vyhn.net>
sub   2048R/C6B535A2 2016-06-10

(I register 3 emails with GitHub: v@vyhn.net, donhuvy@hotmail.com and xxxxx@gmail.com)
What I have been wrong? How I sign my commit?

Body:
I am using TortoiseGIT on Windows 10, and I was having the same problem right now.

For me this solved the problem:

git config --global gpg.program "c:\Program Files (x86)\GnuPG\bin\gpg.exe"


问:
Contract verification failure in corda Hello World pt 2
I'm following the tutorial in corda tutorial pt 2 using kotlin.  Everytime I try to start a new flow via the CRaSH shell in PartyA using the next command:

```<code>start IOUFlow iouValue: 30, otherParty: "C=US, L=New York, O=PartyB"
</code>```

I get a Contract Verification Failure:

```<code>Done
Contract verification failed: List has more than one element., contract: com.template.IOUContract@7c109db7, transaction: D08920023D788F80F289527BD9C27BCD54B7DAC6C53866BFA7B90B23E0E4749B
</code>```

IOUFlow class:

```<code>@InitiatingFlow
@StartableByRPC
class IOUFlow(val iouValue: Int,
              val otherParty: Party) : FlowLogic<Unit>() {

    override val progressTracker = ProgressTracker()

    @Suspendable
    override fun call() {
        val notary = serviceHub.networkMapCache.notaryIdentities[0]
        val outputState = IOUState(iouValue, ourIdentity, otherParty)
        val outputContract = IOUContract::class.jvmName
        val outputContractAndState = StateAndContract(outputState, outputContract)
        val cmd = Command(IOUContract.Create(), listOf(ourIdentity.owningKey, otherParty.owningKey))

        val txBuilder = TransactionBuilder(notary = notary)
                .addOutputState(outputState, TEMPLATE_CONTRACT_ID)
                .addCommand(cmd)

        txBuilder.withItems(outputContractAndState, cmd)
        txBuilder.verify(serviceHub)
        val signedTx = serviceHub.signInitialTransaction(txBuilder)
        val otherpartySession = initiateFlow(otherParty)
        val fullySignedTx = subFlow(CollectSignaturesFlow(signedTx, listOf(otherpartySession), CollectSignaturesFlow.tracker()))
        subFlow(FinalityFlow(fullySignedTx))
    }
}
</code>```

I've tried modifying App.kt to deal with this problem without luck.  Does anyone know what the problem is?

Thanks in advance for your help.

答:
The issue is that you're adding the command and output to the transaction twice:

```<code>val txBuilder = TransactionBuilder(notary = notary)
    .addOutputState(outputState, TEMPLATE_CONTRACT_ID)
    .addCommand(cmd)

txBuilder.withItems(outputContractAndState, cmd)
</code>```

This causes the contract verification to fail, as you have two outputs instead of one.

Body:
I'm following the tutorial in corda tutorial pt 2 using kotlin.  Everytime I try to start a new flow via the CRaSH shell in PartyA using the next command:

start IOUFlow iouValue: 30, otherParty: "C=US, L=New York, O=PartyB"

I get a Contract Verification Failure:

Done
Contract verification failed: List has more than one element., contract: com.template.IOUContract@7c109db7, transaction: D08920023D788F80F289527BD9C27BCD54B7DAC6C53866BFA7B90B23E0E4749B

IOUFlow class:

@InitiatingFlow
@StartableByRPC
class IOUFlow(val iouValue: Int,
              val otherParty: Party) : FlowLogic<Unit>() {

    override val progressTracker = ProgressTracker()

    @Suspendable
    override fun call() {
        val notary = serviceHub.networkMapCache.notaryIdentities[0]
        val outputState = IOUState(iouValue, ourIdentity, otherParty)
        val outputContract = IOUContract::class.jvmName
        val outputContractAndState = StateAndContract(outputState, outputContract)
        val cmd = Command(IOUContract.Create(), listOf(ourIdentity.owningKey, otherParty.owningKey))

        val txBuilder = TransactionBuilder(notary = notary)
                .addOutputState(outputState, TEMPLATE_CONTRACT_ID)
                .addCommand(cmd)

        txBuilder.withItems(outputContractAndState, cmd)
        txBuilder.verify(serviceHub)
        val signedTx = serviceHub.signInitialTransaction(txBuilder)
        val otherpartySession = initiateFlow(otherParty)
        val fullySignedTx = subFlow(CollectSignaturesFlow(signedTx, listOf(otherpartySession), CollectSignaturesFlow.tracker()))
        subFlow(FinalityFlow(fullySignedTx))
    }
}

I've tried modifying App.kt to deal with this problem without luck.  Does anyone know what the problem is?

Thanks in advance for your help.

Body:
The issue is that you're adding the command and output to the transaction twice:

val txBuilder = TransactionBuilder(notary = notary)
    .addOutputState(outputState, TEMPLATE_CONTRACT_ID)
    .addCommand(cmd)

txBuilder.withItems(outputContractAndState, cmd)

This causes the contract verification to fail, as you have two outputs instead of one.


问:
Java: duplicate method signature in nested class
Hopefully this question hasn't already been asked. I've had a look around but haven't found a similar post.

Experimenting in Java I've noticed that there is no restriction on having duplicate method signatures in a nested class, which seems counter-intuitive.

For example, if I create class A containing a method with the signature int x() and later add a nested class B containing an identical method, the compiler seems to have no problem with it. My initial assumption was that it would complain that x is already defined. Perhaps I'm missing something obvious that explains why this is allowed?

```<code>class A {
    int x() {
        return 1;
    }

    class B {
        int x() {
            return 2;
        }
    }
}
</code>```

Subsequently, is there any way to access class A's method x from within the scope of class B, or is it permanently hidden by the method x of the local scope?

Edit: I appreciate that the core of the question is the same as this post, however, I was more interested in understanding why this behaviour is allowed as it wasn't immediately clear to me.

答:
If you are using non-static nested class (inner class) then it wouldn't be able to access to x method of B class from other classes. But if you are using static nested class you will be able to access that method from other classes. Example:

```<code>public class A {

    int x() {
        new A.B().x();
        return 1;
    }

    static class B {
        int x() {
            new A().x();
            return 2;
        }
    }
}

public static void main(String[] args) {
        A a = new A();
        a.x();
        B b = new A.B();
        b.x();
}
</code>```

I hope this example answering your question... ☺

Body:
Hopefully this question hasn't already been asked. I've had a look around but haven't found a similar post.

Experimenting in Java I've noticed that there is no restriction on having duplicate method signatures in a nested class, which seems counter-intuitive.

For example, if I create class A containing a method with the signature int x() and later add a nested class B containing an identical method, the compiler seems to have no problem with it. My initial assumption was that it would complain that x is already defined. Perhaps I'm missing something obvious that explains why this is allowed?

class A {
    int x() {
        return 1;
    }

    class B {
        int x() {
            return 2;
        }
    }
}

Subsequently, is there any way to access class A's method x from within the scope of class B, or is it permanently hidden by the method x of the local scope?

Edit: I appreciate that the core of the question is the same as this post, however, I was more interested in understanding why this behaviour is allowed as it wasn't immediately clear to me.

Body:
If you are using non-static nested class (inner class) then it wouldn't be able to access to x method of B class from other classes. But if you are using static nested class you will be able to access that method from other classes. Example:

public class A {

    int x() {
        new A.B().x();
        return 1;
    }

    static class B {
        int x() {
            new A().x();
            return 2;
        }
    }
}

public static void main(String[] args) {
        A a = new A();
        a.x();
        B b = new A.B();
        b.x();
}

I hope this example answering your question... ☺


问:
jScrollPane inside jQuery Accordion, works but is invisible!
I'm using the following plugins.

jQuery accordion:
http://jquery.bassistance.de/accordion/demo/

jScrollPane:
// Can't post a second hyperlink

Both work correct, but I can't get jScrollPane to work inside the accordion.

```<code>            <div class="basic" style="float:left;"  id="list1a"> <!-- Accordion -->
            <a><p class="text" style="font-size:18px; color:#848484;">&#187NEWS</p></a>
            <div class="content">
                <div class="scroll-pane"> <!-- jScrollPane -->
                    <p style="font-size: 11px;">
                        Lorem ipsum dolor sit amet etc...
                    </p>
                </div>
            </div> <!-- And a few other elements -->
</code>```

When I place div.content outside of the accordion it works correctly. But inside the accordion the scrollbar is invisible. It's still there, I can scroll it, I can grab onto it, but I can't see it. I maybe thought I had to reinitialise the scrollpane when the accordion opens again after it has been closed, but it still works correctly so I'm now guessing it's a CSS problem? I'm not highly experienced with Javascript but I can image they clash somehow.

Thanks for your help in advance!

答: Got it! It was a CSS problem indeed. The background color of the accordion was set to white, and somehow it overlapped the scrollpane. Set it to transparant now, everything works fine!</p>

Body:
I'm using the following plugins.

jQuery accordion:
http://jquery.bassistance.de/accordion/demo/

jScrollPane:
// Can't post a second hyperlink

Both work correct, but I can't get jScrollPane to work inside the accordion.

&#187NEWS

                        Lorem ipsum dolor sit amet etc...

When I place div.content outside of the accordion it works correctly. But inside the accordion the scrollbar is invisible. It's still there, I can scroll it, I can grab onto it, but I can't see it. I maybe thought I had to reinitialise the scrollpane when the accordion opens again after it has been closed, but it still works correctly so I'm now guessing it's a CSS problem? I'm not highly experienced with Javascript but I can image they clash somehow.

Thanks for your help in advance!


问:
how to make first column in a row sticky when scrolling horizontal using flex layout?
how to make first column in a row sticky when scrolling horizontal using flex layout ?

.wrapper {
  display: flex;
  height: 100vh;
  overflow-x: auto
}

.first-column {
  flex: 1 0 300px;
  background: gray;
}

.second-column {
  flex: 0 0 auto;
  padding: 20px;
  overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="first-column">
    <blockquote><i>Please, make me fixed!</i></blockquote>
  </div>
  <div class="second-column">
    hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are
    u?hello How are u?
  </div>
</div></code>```

This is a row inside a *ngFor(loop). So there can be multiple such rows like a table structure.I want the second div appear scroll beneath first column when scrolling horizontal and usual vertical scroll

答:
Its very simple bro as u mentioned in the question use position:sticky Css to left div

 See the snippet below

.wrapper {
  display: flex;
  height: 100vh;
  overflow-x: auto
}

.first-column {
  flex: 1 0 300px;
  background: gray;
  position: sticky;
  left: 0;
}

.second-column {
  flex: 0 0 auto;
  padding: 20px;
  overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="first-column">
    <blockquote><i>Please, make me fixed!</i></blockquote>
  </div>
  <div class="second-column">
    hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are
    u?hello How are u?
  </div>
</div></code>```

Body:
how to make first column in a row sticky when scrolling horizontal using flex layout ?

.wrapper {
  display: flex;
  height: 100vh;
  overflow-x: auto
}

.first-column {
  flex: 1 0 300px;
  background: gray;
}

.second-column {
  flex: 0 0 auto;
  padding: 20px;
  overflow: auto;
}

Please, make me fixed!

    hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are
    u?hello How are u?

This is a row inside a *ngFor(loop). So there can be multiple such rows like a table structure.I want the second div appear scroll beneath first column when scrolling horizontal and usual vertical scroll

Body:
Its very simple bro as u mentioned in the question use position:sticky Css to left div

 See the snippet below

.wrapper {
  display: flex;
  height: 100vh;
  overflow-x: auto
}

.first-column {
  flex: 1 0 300px;
  background: gray;
  position: sticky;
  left: 0;
}

.second-column {
  flex: 0 0 auto;
  padding: 20px;
  overflow: auto;
}

<div class="wrapper">
  <div class="first-column">
    <blockquote><i>Please, make me fixed!</i></blockquote>
  </div>
  <div class="second-column">
    hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are u?hello How are
    u?hello How are u?
  </div>
</div>


问:
HTMLService or Google Apps script
I've use Google Apps Script before, but haven't bene programming for oabout a year now.

For a new project I would like to know if I should continue using Google Apps script or switch to HTMLService.

So first question is if Google Apps Script still is and well be supported by Google.

Second question is what are the main differences between HTMLService and Google Apps Script that make it worth switching.

答:
For first Question:  Yes, The Google app script used to make google products as custom like google spread sheet , google docs and we can insert the script into google sites so that we can share output through website.

For second Question:  In Google app script the ClassUIApp is deprecated in that place we can using HTML services
https://developers.google.com/apps-script/reference/ui/ui-app

Title: HTMLService or Google Apps script


问:
How does the Maven Transitive dependencies flow work?
I am new to Maven so still trying to understand how it works. I have a library B which is dependent on A. So A is added in dependency of B.
I have project C which is dependent on  B and also on A.
So if I add B library as in C's POM then the transitive dependency should work and C should see A. C -> B -> A

I see my colleague has written something like following in C's POM :

```<code><dependency>
        <groupId>B</groupId>
        <artifactId>B</artifactId>
        <version>1.0</version>
        <exclusions>
            <exclusion>
                <groupId>C</groupId>
                <artifactId>C</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>C</groupId>
        <artifactId>C</artifactId>
        <version>1.0</version>
    </dependency>
</dependencies>
</code>```

When I look into B's pom , I find that there is no packaging information. So it is neither a jar nor a war. It is being just used a library.

My question is , does the library's(B) dependent modules are passed as transitive dependencies to the Project(C) which is using library(B) in its dependency.

答:
Yes : Maven resolves the whole dependency tree then configures your project accordingly. You can see this resolution with the goal dependency:tree

When you include B in your project C, Maven reads B's pom.xml which includes A transitively. Maven then flattens this tree, solves the conflicts if any, and configures two dependencies for your project.

Your project C can now access A and B as if they were integrated.

Note that the Maven plugin in Eclipse (if you use it) is pretty smart and can decide to use a JAR or the project files directly if it's available in your workspace. This can lead to some confusion, but in-fine; it works.

Body:
I am new to Maven so still trying to understand how it works. I have a library B which is dependent on A. So A is added in dependency of B.
I have project C which is dependent on  B and also on A.
So if I add B library as in C's POM then the transitive dependency should work and C should see A. C -> B -> A

I see my colleague has written something like following in C's POM :

<dependency>
        <groupId>B</groupId>
        <artifactId>B</artifactId>
        <version>1.0</version>
        <exclusions>
            <exclusion>
                <groupId>C</groupId>
                <artifactId>C</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>C</groupId>
        <artifactId>C</artifactId>
        <version>1.0</version>
    </dependency>
</dependencies>

When I look into B's pom , I find that there is no packaging information. So it is neither a jar nor a war. It is being just used a library.

My question is , does the library's(B) dependent modules are passed as transitive dependencies to the Project(C) which is using library(B) in its dependency.


问:
getting 0>=0 while running program
I run this code

```<code>public void loadtwo()
{
    try{
        String query="SELECT Grade.GradeName, [Group].GroupName, AcademicInfo.EntranceYear, Semester.SemesterName, AcademicRank.AcademicRankName, Others.OthersName, AcademicInfo.AcademicInfoID,AcademicInfo.Major, AcademicInfo.Department\n "+
                "FROM AcademicInfo INNER JOIN\n" +
                "AcademicRank ON AcademicInfo.AcademicRankID = AcademicRank.AcademicRankID INNER JOIN\n" +
                "Grade ON AcademicInfo.GradeID = Grade.GradeID INNER JOIN\n" +
                "[Group] ON AcademicInfo.GroupID = [Group].GroupID INNER JOIN\n" +
                "Others ON AcademicInfo.OthersID = Others.OthersID INNER JOIN\n" +
                "Semester ON AcademicInfo.SemesterID = Semester.SemesterID";
        DBlabprj.rs=DBlabprj.stmt.executeQuery(query);
        int i=0;
        while(DBlabprj.rs.next())
        {
            edutbl.setValueAt(DBlabprj.rs.getString("GradeName"),i,0);
            edutbl.setValueAt(DBlabprj.rs.getString("GroupName"),i,1);
            edutbl.setValueAt(DBlabprj.rs.getInt("EntranceYear"),i,2);
            edutbl.setValueAt(DBlabprj.rs.getString("SemesterName"),i,3);
            edutbl.setValueAt(DBlabprj.rs.getString("AcademicRankName"),i,4);
            edutbl.setValueAt(DBlabprj.rs.getString("OthersName"),i,5);
            edutbl.setValueAt(DBlabprj.rs.getInt("AcademicInfoID"),i,6);
            edutbl.setValueAt(DBlabprj.rs.getString("Major"),i,7);
            edutbl.setValueAt(DBlabprj.rs.getString("Department"),i,8);

            i++;
        }
    }
    catch(Exception e)
    {
        JOptionPane.showMessageDialog(rootPane,e.getMessage());
    }
}
</code>```

and I get this error:

0>=0

I can't understand what's wrong, when I remove the [] from Group I get this error:

Incorrect Syntax near the word 'Group'

答:
I have remove /n from your query and replace spaces use this one. Group is a reserved keyword but it will not create an error if it is inside the brackets. Better try a different name.

```<code>String query="SELECT Grade.GradeName, [Group].GroupName, AcademicInfo.EntranceYear, Semester.SemesterName, AcademicRank.AcademicRankName, Others.OthersName, AcademicInfo.AcademicInfoID,AcademicInfo.Major, AcademicInfo.Department  "+
                       "FROM AcademicInfo INNER JOIN " +
                       "AcademicRank ON AcademicInfo.AcademicRankID = AcademicRank.AcademicRankID INNER JOIN " +
                       "Grade ON AcademicInfo.GradeID = Grade.GradeID INNER JOIN " +
                       "[Group] ON AcademicInfo.GroupID = [Group].GroupID INNER JOIN " +
                       "Others ON AcademicInfo.OthersID = Others.OthersID INNER JOIN " +
                       "Semester ON AcademicInfo.SemesterID = Semester.SemesterID";
</code>```

JTable columns start with 1 not with 0 so make int i=1;

```<code>edutbl.setValueAt(DBlabprj.rs.getString("GradeName"),i,0);
</code>```

Title: getting 0>=0 while running program

Body:
I run this code

public void loadtwo()
{
    try{
        String query="SELECT Grade.GradeName, [Group].GroupName, AcademicInfo.EntranceYear, Semester.SemesterName, AcademicRank.AcademicRankName, Others.OthersName, AcademicInfo.AcademicInfoID,AcademicInfo.Major, AcademicInfo.Department\n "+
                "FROM AcademicInfo INNER JOIN\n" +
                "AcademicRank ON AcademicInfo.AcademicRankID = AcademicRank.AcademicRankID INNER JOIN\n" +
                "Grade ON AcademicInfo.GradeID = Grade.GradeID INNER JOIN\n" +
                "[Group] ON AcademicInfo.GroupID = [Group].GroupID INNER JOIN\n" +
                "Others ON AcademicInfo.OthersID = Others.OthersID INNER JOIN\n" +
                "Semester ON AcademicInfo.SemesterID = Semester.SemesterID";
        DBlabprj.rs=DBlabprj.stmt.executeQuery(query);
        int i=0;
        while(DBlabprj.rs.next())
        {
            edutbl.setValueAt(DBlabprj.rs.getString("GradeName"),i,0);
            edutbl.setValueAt(DBlabprj.rs.getString("GroupName"),i,1);
            edutbl.setValueAt(DBlabprj.rs.getInt("EntranceYear"),i,2);
            edutbl.setValueAt(DBlabprj.rs.getString("SemesterName"),i,3);
            edutbl.setValueAt(DBlabprj.rs.getString("AcademicRankName"),i,4);
            edutbl.setValueAt(DBlabprj.rs.getString("OthersName"),i,5);
            edutbl.setValueAt(DBlabprj.rs.getInt("AcademicInfoID"),i,6);
            edutbl.setValueAt(DBlabprj.rs.getString("Major"),i,7);
            edutbl.setValueAt(DBlabprj.rs.getString("Department"),i,8);

            i++;
        }
    }
    catch(Exception e)
    {
        JOptionPane.showMessageDialog(rootPane,e.getMessage());
    }
}

and I get this error:

0>=0

I can't understand what's wrong, when I remove the [] from Group I get this error:

Incorrect Syntax near the word 'Group'

Body:
I have remove /n from your query and replace spaces use this one. Group is a reserved keyword but it will not create an error if it is inside the brackets. Better try a different name.

String query="SELECT Grade.GradeName, [Group].GroupName, AcademicInfo.EntranceYear, Semester.SemesterName, AcademicRank.AcademicRankName, Others.OthersName, AcademicInfo.AcademicInfoID,AcademicInfo.Major, AcademicInfo.Department  "+
                       "FROM AcademicInfo INNER JOIN " +
                       "AcademicRank ON AcademicInfo.AcademicRankID = AcademicRank.AcademicRankID INNER JOIN " +
                       "Grade ON AcademicInfo.GradeID = Grade.GradeID INNER JOIN " +
                       "[Group] ON AcademicInfo.GroupID = [Group].GroupID INNER JOIN " +
                       "Others ON AcademicInfo.OthersID = Others.OthersID INNER JOIN " +
                       "Semester ON AcademicInfo.SemesterID = Semester.SemesterID";

JTable columns start with 1 not with 0 so make int i=1;

edutbl.setValueAt(DBlabprj.rs.getString("GradeName"),i,0);


问:
select single item from a collection : Python
I created a utility function to return the expected single item from an generator expression

```<code>print one(name for name in ('bob','fred') if name=='bob')
</code>```

Is this a good way to go about it?

```<code>def one(g):
    try:
        val = g.next()
        try:
            g.next()
        except StopIteration:
            return val
        else:
            raise Exception('Too many values')
    except StopIteration:
        raise Exception('No values')
</code>```

答:
First, (to answer the actual question!) your solution will work fine as will the other variants proposed.

I would add that in this case, IMO, generators are overly complicated. If you expect to have one value, you'll probably never have enough for memory usage to be a concern, so I would have just used the obvious and much clearer:

```<code>children = [name for name in ('bob','fred') if name=='bob']
if len(children) == 0:
    raise Exception('No values')
elif len(children) > 1:
    raise Exception('Too many values')
else:
    child = children[0]
</code>```

OwnerDisplayName: GHZ

Body:
I created a utility function to return the expected single item from an generator expression

print one(name for name in ('bob','fred') if name=='bob')

Is this a good way to go about it?

def one(g):
    try:
        val = g.next()
        try:
            g.next()
        except StopIteration:
            return val
        else:
            raise Exception('Too many values')
    except StopIteration:
        raise Exception('No values')

LastEditorDisplayName: nosklo

Body:
First, (to answer the actual question!) your solution will work fine as will the other variants proposed.

I would add that in this case, IMO, generators are overly complicated. If you expect to have one value, you'll probably never have enough for memory usage to be a concern, so I would have just used the obvious and much clearer:

children = [name for name in ('bob','fred') if name=='bob']
if len(children) == 0:
    raise Exception('No values')
elif len(children) > 1:
    raise Exception('Too many values')
else:
    child = children[0]

OwnerDisplayName: dF


问:
How to make a "very" custom validation using Ruby and 'paperclip'?
In my RoR3 application I require custom validations for the 'paperclip' gem.
I have to call those in a precise time during the execution of the code and only to validate part of the form fields (not all fields in the form).

So I made something in the way explained belowe. However it doesn't work, probably because I not (and I don't know how to) "fill" the uploading file ('paperclip' parameters) to make my custom validation on it.

What i made is:

In the view:

```<code><%= form_for(@account, :html => { :multipart => true }) do |f| %>
  ...
    <%= f.label :avatar %>
  ...
<% end %>
</code>```

In the controller:

```<code>...

update
  ...
  @account.validates_account_avatar(params[:account])
  ...
end

...
</code>```

In the model:

```<code>  has_attached_file :avatar,
    :styles => {
      :thumb=> "100x100#",
      :small  => "150x150>" }

  def validates_account_avatar(account)
    allowed_mime_types = %w{"image/bmp", "image/gif", "image/jpeg", "image/png"}
    max_size = 2048

    self.errors.add( :avatar, "must be a file" ) if account[:avatar].blank?
    self.errors.add( :avatar, "isn't a valid image format") if allowed_mime_types.one? {|allowed_content_type| allowed_content_type.match(account[:avatar].content_type.to_s)}
    self.errors.add( :avatar, "is to big") if account[:avatar].size > max_size

    self.validate

    return true if self.errors.empty?
    return false
  end
</code>```

Debugging parameters I get this:

```<code>... account"=>{"avatar"=>#<File:/tmp/RackMultipart20110119-94706-mxpg37>}, "commit"=>" ...
</code>```

Of course, if you have a better way to resolve this issue, don't hesitate to recommend to me.

答:
You can do each of those validations with already existing paperclip validations

validates_attachment_size

validates_attachment_content_type

validates_attachment_presence

these are pre-existing validations with Paperclip, read:https://github.com/thoughtbot/paperclip.

Body:
In my RoR3 application I require custom validations for the 'paperclip' gem.
I have to call those in a precise time during the execution of the code and only to validate part of the form fields (not all fields in the form).

So I made something in the way explained belowe. However it doesn't work, probably because I not (and I don't know how to) "fill" the uploading file ('paperclip' parameters) to make my custom validation on it.

What i made is:

In the view:

<%= form_for(@account, :html => { :multipart => true }) do |f| %>
  ...
    <%= f.label :avatar %>
  ...
<% end %>

In the controller:

...

update
  ...
  @account.validates_account_avatar(params[:account])
  ...
end

...

In the model:

  has_attached_file :avatar,
    :styles => {
      :thumb=> "100x100#",
      :small  => "150x150>" }

  def validates_account_avatar(account)
    allowed_mime_types = %w{"image/bmp", "image/gif", "image/jpeg", "image/png"}
    max_size = 2048

    self.errors.add( :avatar, "must be a file" ) if account[:avatar].blank?
    self.errors.add( :avatar, "isn't a valid image format") if allowed_mime_types.one? {|allowed_content_type| allowed_content_type.match(account[:avatar].content_type.to_s)}
    self.errors.add( :avatar, "is to big") if account[:avatar].size > max_size

    self.validate

    return true if self.errors.empty?
    return false
  end

Debugging parameters I get this:

... account"=>{"avatar"=>#<File:/tmp/RackMultipart20110119-94706-mxpg37>}, "commit"=>" ...

Of course, if you have a better way to resolve this issue, don't hesitate to recommend to me.


问:
Error dropping database (can't rmdir './someDB/', errno: 17)
It's insane. I have tried all the methods but it still throws the same error.

I have a database, want it to run on MySQL-Server. At the beginning of the Database:

```<code>DROP SCHEMA IF EXISTS someDB;
CREATE SCHEMA someDB;
USE someDB;
</code>```

When I tried SHOW DATABASES LIKE 'someDB'; it confirms the existence of it.

I tried:

chmod for the full path to it /var/lib/mysql/someDB/someDB.sql

Stopping MySQL-Server, Deleting the the someDB folder and starting the Server again.

I removed the entire MySQL-Server and reinstalled it again.

After hours of trying, I really need you help.

EDIT:
Answering Y. Collin Comment, when I run sudo ls -la ./someDB, it returns:

```<code>total 20
drwxrwxr-x 2 ubuntu ubuntu  4096 Nov 14 16:53 .
drwxrwxrwx 5 mysql  mysql   4096 Nov 14 16:53 ..
-rwxrwxrwx 1 ubuntu ubuntu 12243 Nov 14 16:53 someDB.sql
</code>```

答:
It turned out that I have a logical mistake.

Inside the someDB.sql file, I am using the USE statement. However, I am trying to run the database by using this command:

```<code>mysql -u root -p someDB < someDB.sql
</code>```

Which is absolutely wrong because the above statement prompt the USE which conflicts with the first line in the sql file (i.e DROP SCHEMA...).

The correct way to do it is:

```<code>mysql -u root -p < someDB.sql
</code>```

because the USE statement is placed in the file already!

Body:
It's insane. I have tried all the methods but it still throws the same error.

I have a database, want it to run on MySQL-Server. At the beginning of the Database:

DROP SCHEMA IF EXISTS someDB;
CREATE SCHEMA someDB;
USE someDB;

When I tried SHOW DATABASES LIKE 'someDB'; it confirms the existence of it.

I tried:

chmod for the full path to it /var/lib/mysql/someDB/someDB.sql

Stopping MySQL-Server, Deleting the the someDB folder and starting the Server again.

I removed the entire MySQL-Server and reinstalled it again.

After hours of trying, I really need you help.

EDIT:
Answering Y. Collin Comment, when I run sudo ls -la ./someDB, it returns:

total 20
drwxrwxr-x 2 ubuntu ubuntu  4096 Nov 14 16:53 .
drwxrwxrwx 5 mysql  mysql   4096 Nov 14 16:53 ..
-rwxrwxrwx 1 ubuntu ubuntu 12243 Nov 14 16:53 someDB.sql

Body:
It turned out that I have a logical mistake.

Inside the someDB.sql file, I am using the USE statement. However, I am trying to run the database by using this command:

mysql -u root -p someDB < someDB.sql

Which is absolutely wrong because the above statement prompt the USE which conflicts with the first line in the sql file (i.e DROP SCHEMA...).

The correct way to do it is:

mysql -u root -p < someDB.sql

because the USE statement is placed in the file already!


问:
WARN 18:20:25 ClusterName mismatch from /123.123.123.12 XYZ Cluster!=ABC Cluster
I've a Cassandra cluster on 456.456.456.23, I named it XYZ Cluster in yml file. While seed server coming up I get warning that the cluster name mismatch with another cluster ABC on 123.123.123.12 which is on completely different VM and should not be linked. How does it even know that there's another cluster exist! How do I solve this issue? I get this issue on Cassandra 2.x as well as 3.7
Appreciate your help...</p>

答:
This is related to unsafe removal of the node from existing Cassandra cluster. You haven't safely decommissioned and removed the 456.456.456.23 from your ABC cluster. Actually you are investigating it into wrong direction, its not 456.456.456.23 which is approaching or aware of ABC cluster. Its 123.123.123.12 which is aware and have information of node 456.456.456.23.
So simply you have to check node details in your ABC cluster and remove its entry as node from ABC cluster. How?- Using below commands.

Check node tool details using below command on ABC cluster.

```<code>bin/nodetool status
</code>```

It will give you output as below

```<code>Datacenter: DC1
===============
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address      Load       Tokens       Owns    Host ID                               Rack
DN  456.456.456.23  ?          256          ?       08feba11-f04a-4226-8d08-c72c9e49ae25  r1

Datacenter: dc1
===============
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address      Load       Tokens       Owns    Host ID                               Rack
UN  123.123.123.12  261.35 MB  256          ?       3b95008a-0a67-4c3e-87f1-394fabfc0230  rack1
</code>```

You can simply remove node by using below command use UUID to specify node. URL for help.

```<code>bin/nodetool removenode 08feba11-f04a-4226-8d08-c72c9e49ae25
</code>```

Note-In production it was supposed to be decommissioned properly which should have avoided this issue to happen. you can use this URL to decommission node.

Body:
This is related to unsafe removal of the node from existing Cassandra cluster. You haven't safely decommissioned and removed the 456.456.456.23 from your ABC cluster. Actually you are investigating it into wrong direction, its not 456.456.456.23 which is approaching or aware of ABC cluster. Its 123.123.123.12 which is aware and have information of node 456.456.456.23.
So simply you have to check node details in your ABC cluster and remove its entry as node from ABC cluster. How?- Using below commands.

Check node tool details using below command on ABC cluster.

bin/nodetool status

It will give you output as below

Datacenter: DC1
===============
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address      Load       Tokens       Owns    Host ID                               Rack
DN  456.456.456.23  ?          256          ?       08feba11-f04a-4226-8d08-c72c9e49ae25  r1

Datacenter: dc1
===============
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address      Load       Tokens       Owns    Host ID                               Rack
UN  123.123.123.12  261.35 MB  256          ?       3b95008a-0a67-4c3e-87f1-394fabfc0230  rack1

You can simply remove node by using below command use UUID to specify node. URL for help.

bin/nodetool removenode 08feba11-f04a-4226-8d08-c72c9e49ae25

Note-In production it was supposed to be decommissioned properly which should have avoided this issue to happen. you can use this URL to decommission node.


答:
This will work

```<code>public <T extends Integer> Integer methodA(T t){
    return t + 1;
}
</code>```

The reason return t = t + 1; doesn't work is that t+1 returns an int that can only be auto-boxed to an Integer. As far as the compiler knows, T may be a sub-class of Integer (even though there is no such thing, as Integer is a final class), so it doesn't allow an assignment of any Integer to a variable of type T.

Title: Java generics method <T extends Integer> +1

Body:
Im new to generics. Maybe my question is dumb and silly but why the following doesnt work?

public <T extends Integer> Integer methodA(T t){
   return t = t + 1;
}

It says that Operator cannot be applied to 'T', 'int'. What should I do to make this code work?

Body:
This will work

public <T extends Integer> Integer methodA(T t){
    return t + 1;
}

The reason return t = t + 1; doesn't work is that t+1 returns an int that can only be auto-boxed to an Integer. As far as the compiler knows, T may be a sub-class of Integer (even though there is no such thing, as Integer is a final class), so it doesn't allow an assignment of any Integer to a variable of type T.


问:
Log4Net Layout.XmlLayout does not create logs in .NET Core platform
I have implemented logger for my application and I wanted to log the activity in XML format (XmlLayout) on .NET Core Console Application.
The Log4Net configuration includes FileAppender and XmlFileAppender as follows.

```<code><log4net>
  <appender name="FileAppender" type="log4net.Appender.FileAppender">
  <file value="C:\Log4NetLogs\UaGatewayText.log.txt"/>
  <layout type="log4net.Layout.PatternLayout">
  <conversionPattern value="[%date{dd.MM.yyyy}] [%date{ABSOLUTE}] [%thread]
     %level %property{TEST - Ua.Gateway} %message%newline" />

     </layout>
        </appender>
           <appender name="ConsolAppender"
                            type="log4net.Appender.ConsoleAppender">
        <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="[%dae{DATE}] [%date{ABSOLUTE}] [%thread]
                  [%level] %message%newline" />
      </layout>
   </appender>

    <appender name="XmlFileAppender"
               type="log4net.Appender.RollingFileAppender">
           <file type="log4net.Util.PatternString"
                value="C:\Log4NetLogs\UaGatewayXml.log.xml" />
        <appendToFile value= "true" />
        <rollingStyle value="size"/>
        <maximumFileSize value ="50MB"/>
        <maxSizeRollBackups value ="10"/>
       <layout type="log4net.Layout.XmlLayout" />
    </appender>

   <root>
     <level value="ALL" />
    <appender-ref ref="FileAppender" />
    <appender-ref ref="XmlFileAppender" />

   </root>

 </log4net>
</code>```

In .NET Core Console App, XmlAppender creates  UaGatewayXml.log.xml file in the directory and does not write any log. However, it works great with FileAppender.

The above configuration works as expected for .NET Framework (4.5.*) for both XmlFileAppender and FileAppender.

Do I have to make any change in the Config file?
Thanks

答:
I had the same problem with an ASP.Net Core 2.0 web application.

I enabled internal debugging and saw the following:

log4net:ERROR [RollingFileAppender] ErrorCode: GenericFailure. Failed in DoAppend
System.ArgumentException: Invalid name character in 'log4j:event'. The ':' character, hexadecimal value 0x3A, cannot be included in a name.
   at System.Xml.XmlWellFormedWriter.CheckNCName(String ncname)
   at System.Xml.XmlWellFormedWriter.WriteStartElement(String prefix, String localName, String ns)
   at log4net.Layout.XmlLayoutSchemaLog4j.FormatXml(XmlWriter writer, LoggingEvent loggingEvent)
   at log4net.Layout.XmlLayoutBase.Format(TextWriter writer, LoggingEvent loggingEvent)
   at log4net.Appender.FileAppender.Append(LoggingEvent loggingEvent)
   at log4net.Appender.AppenderSkeleton.DoAppend(LoggingEvent loggingEvent)

I replaced

```<code><layout type="log4net.Layout.XmlLayoutSchemaLog4j">
</code>```

with

```<code><layout type="log4net.Layout.PatternLayout">
  <conversionPattern value="%date{yyyyMMddHHmmss.fff} [%thread] %-5level %logger %appdomain - %class - %exception - %method - %property{GlobalLog4NetProperty} - %property{ThreadProperty} - %property{log4net:HostName} - %message%newline"/>
</layout>
</code>```

Body:
I have implemented logger for my application and I wanted to log the activity in XML format (XmlLayout) on .NET Core Console Application.
The Log4Net configuration includes FileAppender and XmlFileAppender as follows.

<log4net>
  <appender name="FileAppender" type="log4net.Appender.FileAppender">
  <file value="C:\Log4NetLogs\UaGatewayText.log.txt"/>
  <layout type="log4net.Layout.PatternLayout">
  <conversionPattern value="[%date{dd.MM.yyyy}] [%date{ABSOLUTE}] [%thread]
     %level %property{TEST - Ua.Gateway} %message%newline" />

     </layout>
        </appender>
           <appender name="ConsolAppender"
                            type="log4net.Appender.ConsoleAppender">
        <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="[%dae{DATE}] [%date{ABSOLUTE}] [%thread]
                  [%level] %message%newline" />
      </layout>
   </appender>

    <appender name="XmlFileAppender"
               type="log4net.Appender.RollingFileAppender">
           <file type="log4net.Util.PatternString"
                value="C:\Log4NetLogs\UaGatewayXml.log.xml" />
        <appendToFile value= "true" />
        <rollingStyle value="size"/>
        <maximumFileSize value ="50MB"/>
        <maxSizeRollBackups value ="10"/>
       <layout type="log4net.Layout.XmlLayout" />
    </appender>

   <root>
     <level value="ALL" />
    <appender-ref ref="FileAppender" />
    <appender-ref ref="XmlFileAppender" />

   </root>

 </log4net>

In .NET Core Console App, XmlAppender creates  UaGatewayXml.log.xml file in the directory and does not write any log. However, it works great with FileAppender.

The above configuration works as expected for .NET Framework (4.5.*) for both XmlFileAppender and FileAppender.

Do I have to make any change in the Config file?
Thanks

Body:
I had the same problem with an ASP.Net Core 2.0 web application.

I enabled internal debugging and saw the following:

log4net:ERROR [RollingFileAppender] ErrorCode: GenericFailure. Failed in DoAppend
System.ArgumentException: Invalid name character in 'log4j:event'. The ':' character, hexadecimal value 0x3A, cannot be included in a name.
   at System.Xml.XmlWellFormedWriter.CheckNCName(String ncname)
   at System.Xml.XmlWellFormedWriter.WriteStartElement(String prefix, String localName, String ns)
   at log4net.Layout.XmlLayoutSchemaLog4j.FormatXml(XmlWriter writer, LoggingEvent loggingEvent)
   at log4net.Layout.XmlLayoutBase.Format(TextWriter writer, LoggingEvent loggingEvent)
   at log4net.Appender.FileAppender.Append(LoggingEvent loggingEvent)
   at log4net.Appender.AppenderSkeleton.DoAppend(LoggingEvent loggingEvent)

I replaced

<layout type="log4net.Layout.XmlLayoutSchemaLog4j">

with

<layout type="log4net.Layout.PatternLayout">
  <conversionPattern value="%date{yyyyMMddHHmmss.fff} [%thread] %-5level %logger %appdomain - %class - %exception - %method - %property{GlobalLog4NetProperty} - %property{ThreadProperty} - %property{log4net:HostName} - %message%newline"/>
</layout>


问:
JasperReport creation with image fails to create temporary file on Windows Vista, 7 or Server 2008
We are getting the following error while generating a Jasper report when running our app on some machines with Windows Vista, Windows 7 or Windows 2008:

java.lang.RuntimeException: net.sf.jasperreports.engine.JRException: javax.imageio.IIOException: Can't create output stream!
  at br.com.oobj.relatorio.RRelatorioJasper.gerarJasperPrint(RRelatorioJasper.java:61)
  at br.com.oobj.relatorio.RRelatorioJasper.gerarJasperPrint(RRelatorioJasper.java:44)
  at br.com.oobj.cte.dacte.RGerarDacte.gerarJasperPrint(RGerarDacte.java:153)
  at br.com.oobj.cte.dacte.RGerarDacte.gerarJasperPrint(RGerarDacte.java:66)
  at br.com.oobj.me.impressao.GeradorDacte.gerarDAME(GeradorDacte.java:55)
  at br.com.oobj.me.impressao.GeradorDameDelegator.gerarDAME(GeradorDameDelegator.java:23)
  at br.com.oobj.me.impressao.ServicoImpressao.processar(ServicoImpressao.java:117)
  at br.com.oobj.me.impressao.ConsumidorImpressao.novaMensagem(ConsumidorImpressao.java:71)
  at br.com.oobj.util.fila.ConsumidorNotificante.run(ConsumidorNotificante.java:229)
  at br.com.oobj.me.impressao.ConsumidorImpressao.run(ConsumidorImpressao.java:47)
  Caused by: net.sf.jasperreports.engine.JRException: javax.imageio.IIOException: Can't create output stream!
  at net.sf.jasperreports.engine.util.JRJdk14ImageEncoder.encode(JRJdk14ImageEncoder.java:90)
  at net.sf.jasperreports.engine.util.JRAbstractImageEncoder.encode(JRAbstractImageEncoder.java:74)
  at net.sf.jasperreports.engine.util.JRImageLoader.loadImageDataFromAWTImage(JRImageLoader.java:166)
  at net.sf.jasperreports.engine.JRImageRenderer.getInstance(JRImageRenderer.java:207)
  at net.sf.jasperreports.engine.JRImageRenderer.getInstance(JRImageRenderer.java:190)
  at net.sf.jasperreports.engine.fill.JRFillImage.evaluateImage(JRFillImage.java:901)
  at net.sf.jasperreports.engine.fill.JRFillImage.evaluate(JRFillImage.java:870)
  at net.sf.jasperreports.engine.fill.JRFillElementContainer.evaluate(JRFillElementContainer.java:275)
  at net.sf.jasperreports.engine.fill.JRFillBand.evaluate(JRFillBand.java:426)
  at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillBandNoOverflow(JRVerticalFiller.java:424)
  at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillPageHeader(JRVerticalFiller.java:388)
  at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReportStart(JRVerticalFiller.java:249)
  at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:113)
  at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:891)
  at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:814)
  at net.sf.jasperreports.engine.fill.JRFiller.fillReport(JRFiller.java:89)
  at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:601)
  at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:517)
  at br.com.oobj.relatorio.RRelatorioJasper.gerarJasperPrint(RRelatorioJasper.java:58)
  ... 9 more
  Caused by: javax.imageio.IIOException: Can't create output stream!
  at javax.imageio.ImageIO.write(Unknown Source)
  at net.sf.jasperreports.engine.util.JRJdk14ImageEncoder.encode(JRJdk14ImageEncoder.java:86)
  ... 27 more
  Caused by: javax.imageio.IIOException: Can't create cache file!
  at javax.imageio.ImageIO.createImageOutputStream(Unknown Source)
  ... 29 more
  Caused by: java.io.IOException: The system cannot find the path specified
  at java.io.WinNTFileSystem.createFileExclusively(Native Method)
  at java.io.File.checkAndCreate(Unknown Source)
  at java.io.File.createTempFile(Unknown Source)
  at javax.imageio.stream.FileCacheImageOutputStream.(Unknown Source)
  at com.sun.imageio.spi.OutputStreamImageOutputStreamSpi.createOutputStreamInstance(Unknown Source)
  ... 30 more

The report references an external JPG image. The application runs as a windows service. I already tried to start the service with an administrator user, with no success.

In some machines, we solved the issue by relocating the image to a different drive other than C:

Will be very grateful with any help you can bring.

Thanks,
Jonathas

答:
It seems that Windows 2008 has different defaults for some system directives concerning services.

While running the application in user mode (i.e. running from within a windows user session), the problem does not verify.

Also, if we moved the file to a drive other than the drive on which windows is installed, the problem does not occur.

It's not exactly a solution (I didn't figure out exactly what system directive to change), but I belive this information could eventually help.


问:
How to change border color and close / delete button for Material Chip View?
I'm using Material Chip View. Is there anyway for me to change the chip border colour and the remove / delete chip button?

Material Chip View https://github.com/robertlevonyan/materialChipView

答:
I referred your given lib.

You can easily change remove/delete button by replacing its image from library (named 'ic_close.png').

and for adding a border you need to change code of Chip.java like,

```<code>private void initTypedArray(AttributeSet attrs) {
        TypedArray ta = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.Chip, 0, 0);

        chipText = ta.getString(R.styleable.Chip_mcv_chipText);
        hasIcon = ta.getBoolean(R.styleable.Chip_mcv_hasIcon, false);
        chipIcon = ta.getDrawable(R.styleable.Chip_mcv_chipIcon);
        closable = ta.getBoolean(R.styleable.Chip_mcv_closable, false);
        selectable = ta.getBoolean(R.styleable.Chip_mcv_selectable, false);
        backgroundColor = ta.getColor(R.styleable.Chip_mcv_backgroundColor, ContextCompat.getColor(getContext(), R.color.colorChipBackground));
        selectedBackgroundColor = ta.getColor(R.styleable.Chip_mcv_selectedBackgroundColor, ContextCompat.getColor(getContext(), R.color.colorChipBackgroundClicked));
        textColor = ta.getColor(R.styleable.Chip_mcv_textColor, ContextCompat.getColor(getContext(), R.color.colorChipText));
        selectedTextColor = ta.getColor(R.styleable.Chip_mcv_selectedTextColor, ContextCompat.getColor(getContext(), R.color.colorChipTextClicked));
        closeColor = ta.getColor(R.styleable.Chip_mcv_closeColor, ContextCompat.getColor(getContext(), R.color.colorChipCloseInactive));
        selectedCloseColor = ta.getColor(R.styleable.Chip_mcv_selectedCloseColor, ContextCompat.getColor(getContext(), R.color.colorChipCloseClicked));
        cornerRadius = (int) ta.getDimension(R.styleable.Chip_mcv_cornerRadius, getResources().getDimension(R.dimen.chip_height) / 2);
        strokeSize = (int) ta.getDimension(R.styleable.Chip_mcv_strokeSize, 2);
        strokeColor = ta.getColor(R.styleable.Chip_mcv_strokeColor, ContextCompat.getColor(getContext(), R.color.colorChipCloseClicked));
        iconText = ta.getString(R.styleable.Chip_mcv_iconText);
        iconTextColor = ta.getColor(R.styleable.Chip_mcv_iconTextColor, ContextCompat.getColor(getContext(), R.color.colorChipBackgroundClicked));
        iconTextBackgroundColor = ta.getColor(R.styleable.Chip_mcv_iconTextColor, ContextCompat.getColor(getContext(), R.color.colorChipCloseClicked));

        ta.recycle();
    }
</code>```

And you need to change color from, <color name="colorChipCloseClicked">#F5F5F5</color>

to <color name="colorChipCloseClicked">#D32F2F</color>

it will be look like this,

Hope this helps you!!

Body:
I referred your given lib.

You can easily change remove/delete button by replacing its image from library (named 'ic_close.png').

and for adding a border you need to change code of Chip.java like,

private void initTypedArray(AttributeSet attrs) {
        TypedArray ta = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.Chip, 0, 0);

        chipText = ta.getString(R.styleable.Chip_mcv_chipText);
        hasIcon = ta.getBoolean(R.styleable.Chip_mcv_hasIcon, false);
        chipIcon = ta.getDrawable(R.styleable.Chip_mcv_chipIcon);
        closable = ta.getBoolean(R.styleable.Chip_mcv_closable, false);
        selectable = ta.getBoolean(R.styleable.Chip_mcv_selectable, false);
        backgroundColor = ta.getColor(R.styleable.Chip_mcv_backgroundColor, ContextCompat.getColor(getContext(), R.color.colorChipBackground));
        selectedBackgroundColor = ta.getColor(R.styleable.Chip_mcv_selectedBackgroundColor, ContextCompat.getColor(getContext(), R.color.colorChipBackgroundClicked));
        textColor = ta.getColor(R.styleable.Chip_mcv_textColor, ContextCompat.getColor(getContext(), R.color.colorChipText));
        selectedTextColor = ta.getColor(R.styleable.Chip_mcv_selectedTextColor, ContextCompat.getColor(getContext(), R.color.colorChipTextClicked));
        closeColor = ta.getColor(R.styleable.Chip_mcv_closeColor, ContextCompat.getColor(getContext(), R.color.colorChipCloseInactive));
        selectedCloseColor = ta.getColor(R.styleable.Chip_mcv_selectedCloseColor, ContextCompat.getColor(getContext(), R.color.colorChipCloseClicked));
        cornerRadius = (int) ta.getDimension(R.styleable.Chip_mcv_cornerRadius, getResources().getDimension(R.dimen.chip_height) / 2);
        strokeSize = (int) ta.getDimension(R.styleable.Chip_mcv_strokeSize, 2);
        strokeColor = ta.getColor(R.styleable.Chip_mcv_strokeColor, ContextCompat.getColor(getContext(), R.color.colorChipCloseClicked));
        iconText = ta.getString(R.styleable.Chip_mcv_iconText);
        iconTextColor = ta.getColor(R.styleable.Chip_mcv_iconTextColor, ContextCompat.getColor(getContext(), R.color.colorChipBackgroundClicked));
        iconTextBackgroundColor = ta.getColor(R.styleable.Chip_mcv_iconTextColor, ContextCompat.getColor(getContext(), R.color.colorChipCloseClicked));

        ta.recycle();
    }

And you need to change color from, <color name="colorChipCloseClicked">#F5F5F5</color>

to <color name="colorChipCloseClicked">#D32F2F</color>

it will be look like this,

Hope this helps you!!


问:
Saving dictionary key values to a variable
I am passing keyword as the parameter to function and want to save the value of that keyword to a variable.

The is in the form of a dictionary:

This is the code so far:

```<code>def foo(**var2):
    print (var2)

foo(source_id=3, limit = 200)
foo(research_id = 1)
</code>```

I want to save values of source_id, limit and research_id to a variable.

答:
If you want to store the keyword arguments into variables, you should try:

```<code>def foo(**var2):
    s_id = var2.get('source_id')
    limit = var2.get('limit')
    research_id = var2.get('research_id')
    print('source_id = ', s_id)
    print('limit = ', limit)
    print('research_id = ', research_id)

foo(source_id=3, limit=200)
</code>```

prints

```<code>source_id =  3
limit =  200
research_id = None
</code>```

and

```<code>foo(research_id=1)
</code>```

prints

```<code>source_id =  None
limit =  None
research_id = 1
</code>```

Body:
I am passing keyword as the parameter to function and want to save the value of that keyword to a variable.

The is in the form of a dictionary:

This is the code so far:

def foo(**var2):
    print (var2)

foo(source_id=3, limit = 200)
foo(research_id = 1)

I want to save values of source_id, limit and research_id to a variable.

Body:
If you want to store the keyword arguments into variables, you should try:

def foo(**var2):
    s_id = var2.get('source_id')
    limit = var2.get('limit')
    research_id = var2.get('research_id')
    print('source_id = ', s_id)
    print('limit = ', limit)
    print('research_id = ', research_id)

foo(source_id=3, limit=200)

prints

source_id =  3
limit =  200
research_id = None

and

foo(research_id=1)

prints

source_id =  None
limit =  None
research_id = 1