问:
Trigger function on number input
I have a text input where users are able to write addresses, I want to trigger a javascript function when a number is typed in the text input, how can I achieve it?

EDIT: What I need is to know when a number has been typed, onkeyup via jquery works like a charm, this is what I did:

```<code>$("#q").keyup((e) => {

        var value = $("#q").val();

        var regex = new RegExp("[a-zA-Z0-9_ ]\\d+");

        var succeded = regex.test(value);

        ...
</code>```

答:
you just need to use build in KeyEvents, like (keyDown, keyUp, keyPress , etc.).
You can find a lot of information about it.
KeyboardEvent mozilla

Create html input, and give unique ID.

Form JS code take this element.

Then just bind event handler to target element.

["YOUR_ELEMENT"].addEventListener("keypress", function(e) {
console.log(e.value);}, false);

Title: Trigger function on number input

Body:
I have a text input where users are able to write addresses, I want to trigger a javascript function when a number is typed in the text input, how can I achieve it?

EDIT: What I need is to know when a number has been typed, onkeyup via jquery works like a charm, this is what I did:

$("#q").keyup((e) => {

        var value = $("#q").val();

        var regex = new RegExp("[a-zA-Z0-9_ ]\\d+");

        var succeded = regex.test(value);

        ...


来源: stackexchange

问:
How to separate upper and lower case with counter?
I am thinking of something with collections

```<code>s = 'Hello Mr. Rogers, how are you this fine Tuesday?'
import collections
c = collections.Counter(s)
</code>```

As a result I have

```<code>Counter({' ': 8,
         ',': 1,
         '.': 1,
         '?': 1,
         'H': 1,
         'M': 1,
         'R': 1,
         'T': 1,
         'a': 2,
         'd': 1,
         'e': 5,
         'f': 1,
         'g': 1,
         'h': 2,
         'i': 2,
         'l': 2,
         'n': 1,
         'o': 4,
         'r': 3,
         's': 3,
         't': 1,
         'u': 2,
         'w': 1,
         'y': 2})
</code>```

If I try sum I got syntax problem

```<code>print sum(1 for i in c if i.isupper())

File "<ipython-input-21-66a7538534ee>", line 4
    print sum(1 for i in c if i.isupper())
            ^
SyntaxError: invalid syntax
</code>```

How should I count only upper or lower from the counter?

答:
You can try something like this:</p>

```<code>import collections

s = 'Hello Mr. Rogers, how are you this fine Tuesday?'
c = collections.Counter([ch for ch in s if ch.isupper()])
# Change to ch.islower() if you need lower case
# c = collections.Counter([ch for ch in s if ch.islower()])
print(c)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am thinking of something with collections

s = 'Hello Mr. Rogers, how are you this fine Tuesday?'
import collections
c = collections.Counter(s)

As a result I have

Counter({' ': 8,
         ',': 1,
         '.': 1,
         '?': 1,
         'H': 1,
         'M': 1,
         'R': 1,
         'T': 1,
         'a': 2,
         'd': 1,
         'e': 5,
         'f': 1,
         'g': 1,
         'h': 2,
         'i': 2,
         'l': 2,
         'n': 1,
         'o': 4,
         'r': 3,
         's': 3,
         't': 1,
         'u': 2,
         'w': 1,
         'y': 2})

If I try sum I got syntax problem

print sum(1 for i in c if i.isupper())

File "<ipython-input-21-66a7538534ee>", line 4
    print sum(1 for i in c if i.isupper())
            ^
SyntaxError: invalid syntax

How should I count only upper or lower from the counter?

Body:
You can try something like this:

import collections

s = 'Hello Mr. Rogers, how are you this fine Tuesday?'
c = collections.Counter([ch for ch in s if ch.isupper()])
# Change to ch.islower() if you need lower case
# c = collections.Counter([ch for ch in s if ch.islower()])
print(c)


问:
PHP won't echo the correct date
```<code>/* yeardate = 2000 monthdate = 02 daydate = 02 */
$date = new DateTime($yeardate.'-'.$monthdate.'-'.$daydate);
echo date('Y/m/d', strtotime($date));
</code>```

Keeps echoing 1970/01/01 or something on the lines of that.

答:
Here you can use php date function,</p>

```<code>echo date('Y-m-d');
</code>```

Title: PHP won't echo the correct date

Body:
/* yeardate = 2000 monthdate = 02 daydate = 02 */
$date = new DateTime($yeardate.'-'.$monthdate.'-'.$daydate);
echo date('Y/m/d', strtotime($date));

Keeps echoing 1970/01/01 or something on the lines of that.

Body:
Here you can use php date function,

echo date('Y-m-d');


问:
OAuth2 Authentication fails when using grant type "client_credentials"
I have created an authorization server using OAuth2, currently, I am able to get a bearer token when calling:

```<code>POST /oauth/token?grant_type=client_credentials&client_id=user-service&client_secret=userServicePassword&scope=server HTTP/1.1
Host: localhost:1002
Content-Type: application/json
Authorization: Basic dXNlci1zZXJ2aWNlOnVzZXJTZXJ2aWNlUGFzc3dvcmQ=
</code>```

I use the returned token and make a request to the resource server like this:

```<code>POST /users/create HTTP/1.1
Host: localhost:1002
Content-Type: application/json
Authorization: Bearer 7ba026a4-2ae2-46be-8bd6-65d4aeb09dac
{
    "username":"nicolasmanic",
    "password":"12345",
    "authorities":["ADMIN", "USER"]
}
</code>```

But I get

```<code>{
  "timestamp": 1496657103659,
  "status": 403,
  "error": "Forbidden",
  "exception": "org.springframework.security.access.AccessDeniedException",
  "message": "Access Denied",
  "path": "/users/create"
}
</code>```

My OAuth2AuthorizationConfig

```<code>@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {

    private static final String STORY_SERVICE_PASSWORD = "storyServicePassword";
    private static final String USER_SERVICE_PASSWORD = "userServicePassword";

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .tokenStore(new InMemoryTokenStore())
                .authenticationManager(authenticationManager) //Enable password grant type.
                .userDetailsService(userService);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        clients.inMemory()
                .withClient("browser")
                .authorizedGrantTypes("refresh_token", "password")
                .scopes("ui")
                .and()
                .withClient("story-service")
                .secret(STORY_SERVICE_PASSWORD)
                .authorizedGrantTypes("client_credentials", "refresh_token")
                .scopes("server")
                .and()
                .withClient("user-service")
                .secret(USER_SERVICE_PASSWORD)
                .authorizedGrantTypes("client_credentials", "refresh_token")
                .scopes("server");
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }
}
</code>```

My WebSecurityConfig

```<code>@Configuration
@Order(101)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

        @Autowired
        private UserService userDetailsService;

        /*
        * Authenticate all urls except from home {/} and /login/* etc.
        * */
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable()
                    .authorizeRequests()
                    .antMatchers("/","/login").permitAll();
        }

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService)
                    .passwordEncoder(new BCryptPasswordEncoder());
        }

        @Override
        @Bean
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }
</code>```

and finally my Controller

```<code>@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/current", method = RequestMethod.GET)
    public Principal getUser(Principal principal) {
        return principal;
    }

    @PreAuthorize("#oauth2.hasScope('server')")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public void createUser(@Valid @RequestBody User user) {
        userService.create(user);
    }
}
</code>```

Do you have any idea what I am configuring wrong?

EDIT

Also here is the stacktrace:

```<code>2017-06-05 14:17:45 - DispatcherServlet with name 'dispatcherServlet' processing POST request for [/users/create]
2017-06-05 14:17:45 - Looking up handler method for path /users/create
2017-06-05 14:17:45 - Returning handler method [public void gr.personal.auth.controller.UserController.createUser(gr.personal.auth.domain.User)]
2017-06-05 14:17:45 - Read [class gr.personal.auth.domain.User] as "application/json;charset=UTF-8" with [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@3dc82e6a]
2017-06-05 14:17:45 - Resolving exception from handler [public void gr.personal.auth.controller.UserController.createUser(gr.personal.auth.domain.User)]: org.springframework.security.access.AccessDeniedException: Access is denied
2017-06-05 14:17:45 - Resolving exception from handler [public void gr.personal.auth.controller.UserController.createUser(gr.personal.auth.domain.User)]: org.springframework.security.access.AccessDeniedException: Access is denied
2017-06-05 14:17:45 - Resolving exception from handler [public void gr.personal.auth.controller.UserController.createUser(gr.personal.auth.domain.User)]: org.springframework.security.access.AccessDeniedException: Access is denied
2017-06-05 14:17:45 - Could not complete request
org.springframework.security.access.AccessDeniedException: Access is denied
    at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) ~[spring-security-core-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) ~[spring-security-core-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:65) ~[spring-security-core-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at gr.personal.auth.controller.UserController$$EnhancerBySpringCGLIB$$b0fa6c15.createUser(<generated>) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_25]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_25]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_25]
    at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_25]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) [spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:110) [spring-boot-actuator-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:106) [spring-boot-actuator-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_25]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_25]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_25]
2017-06-05 14:17:45 - DispatcherServlet with name 'dispatcherServlet' processing POST request for [/error]
</code>```

答: you have to add @EnableGlobalMethodSecurity to your OAuth2AuthorizationConfig class.

Body:
I have created an authorization server using OAuth2, currently, I am able to get a bearer token when calling:

POST /oauth/token?grant_type=client_credentials&client_id=user-service&client_secret=userServicePassword&scope=server HTTP/1.1
Host: localhost:1002
Content-Type: application/json
Authorization: Basic dXNlci1zZXJ2aWNlOnVzZXJTZXJ2aWNlUGFzc3dvcmQ=

I use the returned token and make a request to the resource server like this:

POST /users/create HTTP/1.1
Host: localhost:1002
Content-Type: application/json
Authorization: Bearer 7ba026a4-2ae2-46be-8bd6-65d4aeb09dac
{
    "username":"nicolasmanic",
    "password":"12345",
    "authorities":["ADMIN", "USER"]
}

But I get

{
  "timestamp": 1496657103659,
  "status": 403,
  "error": "Forbidden",
  "exception": "org.springframework.security.access.AccessDeniedException",
  "message": "Access Denied",
  "path": "/users/create"
}

My OAuth2AuthorizationConfig

@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {

    private static final String STORY_SERVICE_PASSWORD = "storyServicePassword";
    private static final String USER_SERVICE_PASSWORD = "userServicePassword";

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .tokenStore(new InMemoryTokenStore())
                .authenticationManager(authenticationManager) //Enable password grant type.
                .userDetailsService(userService);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        clients.inMemory()
                .withClient("browser")
                .authorizedGrantTypes("refresh_token", "password")
                .scopes("ui")
                .and()
                .withClient("story-service")
                .secret(STORY_SERVICE_PASSWORD)
                .authorizedGrantTypes("client_credentials", "refresh_token")
                .scopes("server")
                .and()
                .withClient("user-service")
                .secret(USER_SERVICE_PASSWORD)
                .authorizedGrantTypes("client_credentials", "refresh_token")
                .scopes("server");
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }
}

My WebSecurityConfig

@Configuration
@Order(101)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

        @Autowired
        private UserService userDetailsService;

        /*
        * Authenticate all urls except from home {/} and /login/* etc.
        * */
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable()
                    .authorizeRequests()
                    .antMatchers("/","/login").permitAll();
        }

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService)
                    .passwordEncoder(new BCryptPasswordEncoder());
        }

        @Override
        @Bean
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }

and finally my Controller

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/current", method = RequestMethod.GET)
    public Principal getUser(Principal principal) {
        return principal;
    }

    @PreAuthorize("#oauth2.hasScope('server')")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public void createUser(@Valid @RequestBody User user) {
        userService.create(user);
    }
}

Do you have any idea what I am configuring wrong?

EDIT

Also here is the stacktrace:

2017-06-05 14:17:45 - DispatcherServlet with name 'dispatcherServlet' processing POST request for [/users/create]
2017-06-05 14:17:45 - Looking up handler method for path /users/create
2017-06-05 14:17:45 - Returning handler method [public void gr.personal.auth.controller.UserController.createUser(gr.personal.auth.domain.User)]
2017-06-05 14:17:45 - Read [class gr.personal.auth.domain.User] as "application/json;charset=UTF-8" with [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@3dc82e6a]
2017-06-05 14:17:45 - Resolving exception from handler [public void gr.personal.auth.controller.UserController.createUser(gr.personal.auth.domain.User)]: org.springframework.security.access.AccessDeniedException: Access is denied
2017-06-05 14:17:45 - Resolving exception from handler [public void gr.personal.auth.controller.UserController.createUser(gr.personal.auth.domain.User)]: org.springframework.security.access.AccessDeniedException: Access is denied
2017-06-05 14:17:45 - Resolving exception from handler [public void gr.personal.auth.controller.UserController.createUser(gr.personal.auth.domain.User)]: org.springframework.security.access.AccessDeniedException: Access is denied
2017-06-05 14:17:45 - Could not complete request
org.springframework.security.access.AccessDeniedException: Access is denied
    at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) ~[spring-security-core-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) ~[spring-security-core-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:65) ~[spring-security-core-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at gr.personal.auth.controller.UserController$$EnhancerBySpringCGLIB$$b0fa6c15.createUser(<generated>) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_25]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_25]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_25]
    at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_25]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) [spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:110) [spring-boot-actuator-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) [spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:106) [spring-boot-actuator-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_25]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_25]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_25]
2017-06-05 14:17:45 - DispatcherServlet with name 'dispatcherServlet' processing POST request for [/error]


问:
How does Java makes use of multiple cores?
A JVM runs in a single process and threads in a JVM share the heap belonging to that process. Then how does JVM make use of multiple cores which provide multiple OS threads for high concurrency?</p>

答:
Java will benefit from multiple cores, if the OS distribute threads over the available processors. JVM itself do not do anything special to get its threads scheduled evenly across multiple cores. A few things to keep in mind:

While implementing parallel algorithms, it might be better to spawn as many threads as there are cores. (Runtime.getRuntime().availableProcessors()). Not more, not less.

Make use of the facilities provided by the java.util.concurrent package.

Make sure that you have Java Concurrency in Practice in your personal library.


问:
Debugging batching in Tensorflow Serving (no effect observed)
I have a small web server that gets input in terms of sentences and needs to return a model prediction using Tensorflow Serving. It's working all fine and well using our single GPU, but now I'd like to enable batching such that Tensorflow Serving waits a bit to group incoming sentences before processing them together in one batch on the GPU.

I'm using the predesigned server framework with the predesigned batching framework using the initial release of Tensorflow Serving. I'm enabling batching using the --batching flag and have set batch_timeout_micros = 10000 and max_batch_size = 1000. The logging does confirm that batching is enabled and that the GPU is being used.

However, when sending requests to the serving server the batching has minimal effect. Sending 50 requests at the same time almost linearly scales in terms of time usage with sending 5 requests. Interestingly, the predict() function of the server is run once for each request (see here), which suggests to me that the batching is not being handled properly.

Am I missing something? How do I check what's wrong with the batching?

Note that this is different from How to do batching in Tensorflow Serving? as that question only examines how to send multiple requests from a single client, but not how to enable Tensorflow Serving's behind-the-scenes batching for multiple separate requests.

答:
(I am not familiar with the server framework, but I'm quite familiar with HPC and with cuBLAS and cuDNN, the libraries TF uses to do its dot products and convolutions on GPU)

There are several issues that could cause disappointing performance scaling with the batch size.

I/O overhead, by which I mean network transfers, disk access (for large data), serialization, deserialization and similar cruft. These things tend to be linear in the size of the data.

To look into this overhead, I suggest you deploy 2 models: one that you actually need, and one that's trivial, but uses the same I/O, then subtract the time needed by one from another.

This time difference should be similar to the time running the complex model takes, when you use it directly, without the I/O overhead.

If the bottleneck is in the I/O, speeding up the GPU work is inconsequential.

Note that even if increasing the batch size makes the GPU faster, it might make the whole thing slower, because the GPU now has to wait for the I/O of the whole batch to finish to even start working.

cuDNN scaling: Things like matmul need large batch sizes to achieve their optimal throughput, but convolutions using cuDNN might not (At least it hasn't been my experience, but this might depend on the version and the GPU arch)

RAM, GPU RAM, or PCIe bandwidth-limited models: If your model's bottleneck is in any of these, it probably won't benefit from bigger batch sizes.

The way to check this is to run your model directly (perhaps with mock input), compare the timing to the aforementioned time difference and plot it as a function of the batch size.

By the way, as per the performance guide, one thing you could try is using the NCHW layout, if you are not already. There are other tips there.


问:
Django, haystack, elastic search and one to many relation
I have problem with haystack - I do not know how to search for models A whose all foreign keys meet given condition.

My simplified models look like:

```<code>Group:
    id
Meeting:
    group = models.ForeignKey(Group)
    day_of_week = models.IntegerField()
    hour = models.IntegerField()
    length = models.IntegerField()
</code>```

So basically, a group can have many meetings and users should be able to search for those groups whose all meetings are in given time range. eg:

```<code>Group(1)
    Meeting(day_of_week=Monday, hour=9, length=2)
Group(2)
    Meeting(day_of_week=Monday, hour=10, length=1)
    Meeting(day_of_week=Tuesday, hour=8, length=2)
Group(3)
    Meeting(day_of_week=Monday, hour=10, length=1)
    Meeting(day_of_week=Wednesday, hour=12, length=1)
</code>```

and search: "Monday from 8 to 11", "Tuesday, from 12 to 14 (2p.m.)", "Wednesday, from 6 to 17 (5p.m.)" should return group 1 and 3, because all meetings from those groups contains in user specified ranges and group 2 is not returned, because second meeting is not in given range (tho the first one is).

If I was to write a SQL, I would probably go for something like "select count of matching meetings and count of all meetings if those numbers are equal -> then all meetings meet:

```<code>SELECT g.id,
       count(m2.id)
FROM groups g
JOIN meetings m2 ON m2.group_id = g.id
AND ((m2.day_of_week = 0  -- monday
      AND m2.hour >= 8
      AND m2.length<=3)
     OR (m2.day_of_week=1  -- tuesday
         AND m2.hour >= 12
         AND m2.length<=2)
     OR (m2.day_of_week=2 -- wednesday
         AND m2.hour >= 6
         AND m2.length<=11))
GROUP BY g.id
HAVING count(m2.id) =
  (SELECT count(*)
   FROM meetings
   WHERE meetings.group_id=g.id);
</code>```

But we are using haystack + elastic search for indexing and I have completely no idea how to flatten the model to index and write a query. Can anyone help me with it?

答:
ElasticSearch solution

The key to the solution is ElasticSearch feature named nested objects. Luckily this feature is present in all ES versions. Nested object is key here, because data in meeting are strictly associated.

```<code>PUT /myindex
{
  "mappings": {
    "groups": {
      "properties": {
        "meetings": {
          "type": "nested",
          "properties": {
             "dayOfWeek": { "type": "integer"},
             "start": {"type": "integer"},
             "end": {"type": "integer"}
          }
        },
        "groupId": {"type":"integer"}
      }
    }
  }
}

POST /myindex/groups/_bulk
{"index": {}}
{"groupId": 1, "meetings": [{"dayOfWeek": 0, "start": 9,  "end": 11}]}
{"index": {}}
{"groupId": 2, "meetings": [{"dayOfWeek": 0, "start": 10, "end": 11}, { "dayOfWeek": 1, "start": 8,  "end": 10}]}
{"index": {}}
{"groupId": 3, "meetings": [{"dayOfWeek": 0, "start": 10, "end": 11}, {"dayOfWeek": 2, "start": 12, "end": 13}]}
</code>```

At this point it is clearly visible that meetings belong to groups and we will search in groups.

It is not possible to directly write query to get all groups whose all nested objects meet condition, but... it can be inversed easily to: get all groups where none of the meeting contains wrong time.

```<code>GET /myindex/_search
{
  "query": {
    "bool": {
      "must_not" : {
       "nested": {
          "path": "meetings",
          "filter": {
              "bool": {
                "must_not": {
                  "bool": {
                    "should": [
                        {
                          "bool": {
                            "must": [
                              {"term" : { "dayOfWeek" : 0 }},
                              {"range": {"start": {"from":8, "to":11}}},
                              {"range": {"end": {"from":8, "to":11}}}
                            ]
                          }
                        },
                        {
                          "bool": {
                            "must": [
                              {"term" : { "dayOfWeek" : 1 }},
                              {"range": {"start": {"from":12, "to":14}}},
                              {"range": {"end": {"from":12, "to":14}}}
                            ]
                          }
                        },
                        {
                          "bool": {
                            "must": [
                              {"term" : { "dayOfWeek" : 2 }},
                              {"range": {"start": {"from":6, "to":17}}},
                              {"range": {"end": {"from":6, "to":17}}}
                            ]
                          }
                        }
                      ]
                    }
                }
              }
            }
          }
       }
      }
    }
  }
</code>```

This will return groups 1 and 3. Group 2 will not be returned because one of this meetings overlaps with wrong datetime.

Haystack integration

The second problem was integration with Django Haystack, because by default it doesn't support engine-specific features like nested fields in ES. Luckily I am not the only one who needs it in django app and someone has already resolved it.

Body:
I have problem with haystack - I do not know how to search for models A whose all foreign keys meet given condition.

My simplified models look like:

Group:
    id
Meeting:
    group = models.ForeignKey(Group)
    day_of_week = models.IntegerField()
    hour = models.IntegerField()
    length = models.IntegerField()

So basically, a group can have many meetings and users should be able to search for those groups whose all meetings are in given time range. eg:

Group(1)
    Meeting(day_of_week=Monday, hour=9, length=2)
Group(2)
    Meeting(day_of_week=Monday, hour=10, length=1)
    Meeting(day_of_week=Tuesday, hour=8, length=2)
Group(3)
    Meeting(day_of_week=Monday, hour=10, length=1)
    Meeting(day_of_week=Wednesday, hour=12, length=1)

and search: "Monday from 8 to 11", "Tuesday, from 12 to 14 (2p.m.)", "Wednesday, from 6 to 17 (5p.m.)" should return group 1 and 3, because all meetings from those groups contains in user specified ranges and group 2 is not returned, because second meeting is not in given range (tho the first one is).

If I was to write a SQL, I would probably go for something like "select count of matching meetings and count of all meetings if those numbers are equal -> then all meetings meet:

SELECT g.id,
       count(m2.id)
FROM groups g
JOIN meetings m2 ON m2.group_id = g.id
AND ((m2.day_of_week = 0  -- monday
      AND m2.hour >= 8
      AND m2.length<=3)
     OR (m2.day_of_week=1  -- tuesday
         AND m2.hour >= 12
         AND m2.length<=2)
     OR (m2.day_of_week=2 -- wednesday
         AND m2.hour >= 6
         AND m2.length<=11))
GROUP BY g.id
HAVING count(m2.id) =
  (SELECT count(*)
   FROM meetings
   WHERE meetings.group_id=g.id);

But we are using haystack + elastic search for indexing and I have completely no idea how to flatten the model to index and write a query. Can anyone help me with it?

Body:
ElasticSearch solution

The key to the solution is ElasticSearch feature named nested objects. Luckily this feature is present in all ES versions. Nested object is key here, because data in meeting are strictly associated.

PUT /myindex
{
  "mappings": {
    "groups": {
      "properties": {
        "meetings": {
          "type": "nested",
          "properties": {
             "dayOfWeek": { "type": "integer"},
             "start": {"type": "integer"},
             "end": {"type": "integer"}
          }
        },
        "groupId": {"type":"integer"}
      }
    }
  }
}

POST /myindex/groups/_bulk
{"index": {}}
{"groupId": 1, "meetings": [{"dayOfWeek": 0, "start": 9,  "end": 11}]}
{"index": {}}
{"groupId": 2, "meetings": [{"dayOfWeek": 0, "start": 10, "end": 11}, { "dayOfWeek": 1, "start": 8,  "end": 10}]}
{"index": {}}
{"groupId": 3, "meetings": [{"dayOfWeek": 0, "start": 10, "end": 11}, {"dayOfWeek": 2, "start": 12, "end": 13}]}

At this point it is clearly visible that meetings belong to groups and we will search in groups.

It is not possible to directly write query to get all groups whose all nested objects meet condition, but... it can be inversed easily to: get all groups where none of the meeting contains wrong time.

GET /myindex/_search
{
  "query": {
    "bool": {
      "must_not" : {
       "nested": {
          "path": "meetings",
          "filter": {
              "bool": {
                "must_not": {
                  "bool": {
                    "should": [
                        {
                          "bool": {
                            "must": [
                              {"term" : { "dayOfWeek" : 0 }},
                              {"range": {"start": {"from":8, "to":11}}},
                              {"range": {"end": {"from":8, "to":11}}}
                            ]
                          }
                        },
                        {
                          "bool": {
                            "must": [
                              {"term" : { "dayOfWeek" : 1 }},
                              {"range": {"start": {"from":12, "to":14}}},
                              {"range": {"end": {"from":12, "to":14}}}
                            ]
                          }
                        },
                        {
                          "bool": {
                            "must": [
                              {"term" : { "dayOfWeek" : 2 }},
                              {"range": {"start": {"from":6, "to":17}}},
                              {"range": {"end": {"from":6, "to":17}}}
                            ]
                          }
                        }
                      ]
                    }
                }
              }
            }
          }
       }
      }
    }
  }

This will return groups 1 and 3. Group 2 will not be returned because one of this meetings overlaps with wrong datetime.

Haystack integration

The second problem was integration with Django Haystack, because by default it doesn't support engine-specific features like nested fields in ES. Luckily I am not the only one who needs it in django app and someone has already resolved it.


问:
Distributing a java app as exe, with dependency on xml files
I need to distribute a java application as exe, but my jar depends on xml files that are read/written in by the program.

I have tried jar to exe tools (NSIS, jar2exe) but non of them seem to have an option to include files on which the program depends.

My actual question would be : how do I include both the jar and xml files in an exe ?

Thank you for your help !

答: Your jar files should not depend on xml which are read or write by your application. Jar should contain only application code. and Your xml's should be put on some location to read/write. Jar should be your application code package. if it genrates, write or update some xmls those should be put on a separate location from jar files.</p>


问:
GMap.NET.GMapControl with custom map provider?
I want to use another map provider in my GMapControl.

For example, I can use GoogleMap:

```<code>GMapControl myMapControl = new GMapControl();
myMapControl.MapProvider = GMapProviders.GoogleMap;
</code>```

All build-in map providers are stored in GMapProviders.

How can I add my custom GMapProvider?

I need to add 2Gis map provider.

答:
There is a WMSProvider class in:

WMSProvider

It works fine, by changing szWmsLayer and CustomWMSURL vars.

ContentLicense: CC BY-SA 4.0

Body:
I want to use another map provider in my GMapControl.

For example, I can use GoogleMap:

GMapControl myMapControl = new GMapControl();
myMapControl.MapProvider = GMapProviders.GoogleMap;

All build-in map providers are stored in GMapProviders.

How can I add my custom GMapProvider?

I need to add 2Gis map provider.


问:
Writing a QRegularExpression to only return the greedy last match
I have a input file that looks like this:

```<code>.SUBCKT (stuff including newline characters)
.ENDS (stuff)

.SUBCKT (stuff including newline characters)
.ENDS (stuff)

.SUBCKT (stuff including newline characters)
.ENDS (stuff)

.SUBCKT (stuff including newline characters)
.ENDS (stuff I don't want)

(What I want to get, includes a newline characters)

.END
</code>```

So what I want to do is write a regular expression (using Qt so QRegularExpression) that will get me all the stuff that "I want to get" (between the last .ENDS and the .END without getting the "stuff I don't want". The stuff I don't want is after the last .ENDS and the first newline character after it.

My most successfull attempt at getting this has been this code:

```<code>QStringList toplevel;
QRegularExpression regexp_toplevel("\\.ENDS(.*?)\n(.*?)\\.END",QRegularExpression::DotMatchesEverythingOption);
QRegularExpressionMatchIterator toplevel_i = regexp_toplevel.globalMatch(contents);
while (toplevel_i.hasNext()){
    QRegularExpressionMatch match = toplevel_i.next();
    toplevel << match.captured(2);
}
</code>```

The code above returns a list of strings and the last one is what I want. But since the iteration is done java-stlye I'm not 100% percent sure that what I want will ALWAYS be the last one. Is there any way I can write the expression getting ONLY what is between the last .ENDS after the the first newline and the .END?

答:
You may use

```<code>(?ms).*^\.ENDS(?-s:.*)\n(.*)\.END
</code>```

See the regex demo

Details:

(?ms) - m will make ^ match a line start and s will make the . match line breaks

.* - will match any 0+ chars, as many as possible (greedily), up to the last occurrence of...

^\.ENDS - an .ENDS substring at the start of a line

(?-s:.*) - the rest of the line (if any chars are still there)

\n - a newline (may be replaced with \\R to match any style line break)

(.*) - Group 1: any 0+ chars up, as many as possible, up to the last  (if you need to match up to the first .END, add ? after *)

\.END - .END literal substring.

Declare as

```<code>QRegularExpression regexp_toplevel("(?ms).*^\\.ENDS(?-s:.*)\n(.*)\\.END");
</code>```

The value you need will be inside match.captured(1).

Body:
I have a input file that looks like this:

.SUBCKT (stuff including newline characters)
.ENDS (stuff)

.SUBCKT (stuff including newline characters)
.ENDS (stuff)

.SUBCKT (stuff including newline characters)
.ENDS (stuff)

.SUBCKT (stuff including newline characters)
.ENDS (stuff I don't want)

(What I want to get, includes a newline characters)

.END

So what I want to do is write a regular expression (using Qt so QRegularExpression) that will get me all the stuff that "I want to get" (between the last .ENDS and the .END without getting the "stuff I don't want". The stuff I don't want is after the last .ENDS and the first newline character after it.

My most successfull attempt at getting this has been this code:

QStringList toplevel;
QRegularExpression regexp_toplevel("\\.ENDS(.*?)\n(.*?)\\.END",QRegularExpression::DotMatchesEverythingOption);
QRegularExpressionMatchIterator toplevel_i = regexp_toplevel.globalMatch(contents);
while (toplevel_i.hasNext()){
    QRegularExpressionMatch match = toplevel_i.next();
    toplevel << match.captured(2);
}

The code above returns a list of strings and the last one is what I want. But since the iteration is done java-stlye I'm not 100% percent sure that what I want will ALWAYS be the last one. Is there any way I can write the expression getting ONLY what is between the last .ENDS after the the first newline and the .END?

Body:
You may use

(?ms).*^\.ENDS(?-s:.*)\n(.*)\.END

See the regex demo

Details:

(?ms) - m will make ^ match a line start and s will make the . match line breaks

.* - will match any 0+ chars, as many as possible (greedily), up to the last occurrence of...

^\.ENDS - an .ENDS substring at the start of a line

(?-s:.*) - the rest of the line (if any chars are still there)

\n - a newline (may be replaced with \\R to match any style line break)

(.*) - Group 1: any 0+ chars up, as many as possible, up to the last  (if you need to match up to the first .END, add ? after *)

\.END - .END literal substring.

Declare as

QRegularExpression regexp_toplevel("(?ms).*^\\.ENDS(?-s:.*)\n(.*)\\.END");

The value you need will be inside match.captured(1).


问:
How to retrieve specifics a firebase database entry?
I've been trying to retrieve data fields from the data that I have stored in a firebase realtime database, and I'm stuck.

This is what my database looks like:

This is a method that I've called in my AuthStateListener object and is defined as follows:

```<code>private void alterTextView(final String id) {
    if(id!=null) {
        mDatabase.child("Users").child(id).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    if (ds.exists()) {
                        UserInformation userInformation = ds.child(id).getValue(UserInformation.class);
                        String name = userInformation.getName();
                        mWelcomeUserMessage.setText(name);
                        //logging name
                        Log.d("My activity", "name of user with userID - " + id + " is : " + userInformation.getName());
                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
}
</code>```

The call to this function is as such:

```<code> mAuthStatelistener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            //if user is logged in, the sign_in and sign_up buttons should not be displayed
            if (firebaseAuth.getCurrentUser() != null) {
                userId = firebaseAuth.getCurrentUser().getUid();
                Log.d("Main Activity", "Current userId : " + userId);
                alterTextView(userId);
                mLogInButton.setVisibility(View.INVISIBLE);
                mSignUpButton.setVisibility(View.INVISIBLE);
                //getUserName(firebaseAuth.getCurrentUser().getUid());
                mLogOutButton.setVisibility(View.VISIBLE);
            } else {
                mLogInButton.setVisibility(View.VISIBLE);
                mSignUpButton.setVisibility(View.VISIBLE);
                mWelcomeUserMessage.setVisibility(View.GONE);
                mLogOutButton.setVisibility(View.GONE);
            }
        }
    };
</code>```

For some reason, I keep getting a null pointer exception in the first excerpt of code in the line where I store the name from the userInformation object -

```<code>String name = userInformation.getName();
</code>```

I just can't understand why this is happening.

My main goal is to print out the name of the logged in user once he/she has logged in.

Does anyone know a way to do this?

Update 1 This is what my UserInformation class looks like:

```<code>public class UserInformation {

private String name;
private String student_number;
private String faculty;
private boolean isAdmin;

public String getName() {
    return name;
}

public String getStudent_number() {
    return student_number;
}

public String getFaculty() {
    return faculty;
}

public void setName(String name) {
    this.name = name;
}

public boolean isAdmin() {
    return isAdmin;
}

public void setAdmin(boolean admin) {
    isAdmin = admin;
}

public void setStudent_number(String student_number) {
    this.student_number = student_number;
}

public void setFaculty(String faculty) {
    this.faculty = faculty;
}
}
</code>```

答:
The loop in your onDataChange() method isn't needed:

```<code>public void onDataChange(DataSnapshot dataSnapshot) {
    if (ds.exists()) {
        UserInformation userInformation = ds.child(id).getValue(UserInformation.class);
        String name = userInformation.getName();
        mWelcomeUserMessage.setText(name);
        //logging name
        Log.d("My activity", "name of user with userID - " + id + " is : " + userInformation.getName());
    }
}
</code>```

A loop is only needed when you use a query with a value listener, since a query can have multiple results. But in your case you directly access the correct child node, so a loop is not needed.

Body:
I've been trying to retrieve data fields from the data that I have stored in a firebase realtime database, and I'm stuck.

This is what my database looks like:

This is a method that I've called in my AuthStateListener object and is defined as follows:

private void alterTextView(final String id) {
    if(id!=null) {
        mDatabase.child("Users").child(id).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    if (ds.exists()) {
                        UserInformation userInformation = ds.child(id).getValue(UserInformation.class);
                        String name = userInformation.getName();
                        mWelcomeUserMessage.setText(name);
                        //logging name
                        Log.d("My activity", "name of user with userID - " + id + " is : " + userInformation.getName());
                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
}

The call to this function is as such:

 mAuthStatelistener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            //if user is logged in, the sign_in and sign_up buttons should not be displayed
            if (firebaseAuth.getCurrentUser() != null) {
                userId = firebaseAuth.getCurrentUser().getUid();
                Log.d("Main Activity", "Current userId : " + userId);
                alterTextView(userId);
                mLogInButton.setVisibility(View.INVISIBLE);
                mSignUpButton.setVisibility(View.INVISIBLE);
                //getUserName(firebaseAuth.getCurrentUser().getUid());
                mLogOutButton.setVisibility(View.VISIBLE);
            } else {
                mLogInButton.setVisibility(View.VISIBLE);
                mSignUpButton.setVisibility(View.VISIBLE);
                mWelcomeUserMessage.setVisibility(View.GONE);
                mLogOutButton.setVisibility(View.GONE);
            }
        }
    };

For some reason, I keep getting a null pointer exception in the first excerpt of code in the line where I store the name from the userInformation object -

String name = userInformation.getName();

I just can't understand why this is happening.

My main goal is to print out the name of the logged in user once he/she has logged in.

Does anyone know a way to do this?

Update 1 This is what my UserInformation class looks like:

public class UserInformation {

private String name;
private String student_number;
private String faculty;
private boolean isAdmin;

public String getName() {
    return name;
}

public String getStudent_number() {
    return student_number;
}

public String getFaculty() {
    return faculty;
}

public void setName(String name) {
    this.name = name;
}

public boolean isAdmin() {
    return isAdmin;
}

public void setAdmin(boolean admin) {
    isAdmin = admin;
}

public void setStudent_number(String student_number) {
    this.student_number = student_number;
}

public void setFaculty(String faculty) {
    this.faculty = faculty;
}
}

Body:
The loop in your onDataChange() method isn't needed:

public void onDataChange(DataSnapshot dataSnapshot) {
    if (ds.exists()) {
        UserInformation userInformation = ds.child(id).getValue(UserInformation.class);
        String name = userInformation.getName();
        mWelcomeUserMessage.setText(name);
        //logging name
        Log.d("My activity", "name of user with userID - " + id + " is : " + userInformation.getName());
    }
}

A loop is only needed when you use a query with a value listener, since a query can have multiple results. But in your case you directly access the correct child node, so a loop is not needed.


问:
Easy way to store and retrieve objects in Java without using a relational DB?
Do you know of an "easy" way to store and retrieve objects in Java without using a relational DB / ORM like Hibernate?

[Note that I am not considering serialization as-is for this purpose, as it won't allow to retrieve arbitrary objects in the middle of an object graph. Neither am I considering DB4O because of its restrictive license. Thanks.]

"Easy" meaning: not having to handle low-level details such as key/value pairs to rebuild an object graph (as with BerkeleyDB or traditional caches). The same applies for rebuilding objects from a document- or column-oriented DB (CouchDB, HBase, ..., even Lucene).

Perhaps there are interesting projects out there that provide a layer of integration between the mentioned storage systems and the object model (like ORM would be for RDBMSs) that I am not aware of.

Anyone successfully using those in production, or experimenting with persistence strategies other than relational DBs? How about RDF stores?

Update: I came across a very interesting article: A list of distributed key-value stores

答:
NeoDatis looks interesting.  It is licensed under the LGPL, so not quite as restrictive as the GLP proper.

Check out their 1 minute tutorial to see if it will work for your needs.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Steve K


问:
Query Fine Tuning
I am fairly new to sql and would like to ask for your assistance regarding this query. Is there another way to rewrite this?

```<code> Select *
 From emp
 Where emp_no IN (
     Select emp_no
     From dept_emp
     Where dept_no = 'd002'
     );
</code>```

Any assistance is greatly appreciated.

Thanks.

答:
```
 - If have the relation between two tables best-way you can used join. other wise you can used inner query (sub select)
 - When you used join in RDBMS it will faster that inner query.
 - join must be indexed based like: primary key and foreign key. Other wise executing cost will be high. non-index query time consumed maximum.
```

Title: Query Fine Tuning

Body:
I am fairly new to sql and would like to ask for your assistance regarding this query. Is there another way to rewrite this?

 Select *
 From emp
 Where emp_no IN (
     Select emp_no
     From dept_emp
     Where dept_no = 'd002'
     );

Any assistance is greatly appreciated.

Thanks.


问:
Why DOM didn't update by setAttribute when using Aframe v0.5.0?
I'm going to set the aframe-v0.5.0  position and color, and it renders correct in the browser, but when I use box.getAtrribute("position"), it returns "undefined", then I found  positon attribute is empty string showing in the DOM(same situation for scale/rotation):

```<code><a-box width="1" geometry="" height="1" depth="1" color="#0cf" material="" position="" rotation="" scale="" visible=""></a-box>
</code>```

So I switch back to aframe-v0.2.0, and everything works fine!
Can't get any answer from google, is it something changed in aframe-v0.5.0?
Here's my code below, and aframe.js is put in the , my script is put in the .

```<code>var body = document.body;
var scene = document.createElement("a-scene");
var camera = document.createElement("a-entity");
    camera.setAttribute("camera", "userHeight: 1.6");
    camera.setAttribute("look-controls", "");
    camera.setAttribute("wasd-controls", "");
var box = document.createElement("a-box");
    box.setAttribute("width", 1);
    box.setAttribute("height", 1);
    box.setAttribute("depth", 1);
    box.setAttribute("color", "#0cf");
    box.setAttribute("position", "0 0 -5");
scene.appendChild(camera);
scene.appendChild(box);
body.appendChild(scene);

console.log( box.getAttribute("position") ) //"undefined"
</code>```

example here:
http://minicg.com/demo/aframe050_test/

答:
im not sure if I'm correct, but in my opinion You try to read the attribute before it's properly placed on the scene. When i added a 2s setTimeout() before the getAttribute() call, it works fine:

https://codepen.io/gftruj/pen/JJoENb

But waiting 2 seconds before reading attributes is outrageous !!!

Yep, that's why i'd recommend putting your code inside a registered component. You can add any js code in the init() function, and You should be sure everything is properly loaded.
 For example create manually a  element, and put your code in

```<code>    AFRAME.registerComponent('myCode', {
      init: function () {
        //whatever you want, remember that the scope here is not the window,
        //but the element using this component ( now it'd be the a-scene)
      }
    });
</code>```

Body:
I'm going to set the aframe-v0.5.0  position and color, and it renders correct in the browser, but when I use box.getAtrribute("position"), it returns "undefined", then I found  positon attribute is empty string showing in the DOM(same situation for scale/rotation):

So I switch back to aframe-v0.2.0, and everything works fine!
Can't get any answer from google, is it something changed in aframe-v0.5.0?
Here's my code below, and aframe.js is put in the , my script is put in the .

var body = document.body;
var scene = document.createElement("a-scene");
var camera = document.createElement("a-entity");
    camera.setAttribute("camera", "userHeight: 1.6");
    camera.setAttribute("look-controls", "");
    camera.setAttribute("wasd-controls", "");
var box = document.createElement("a-box");
    box.setAttribute("width", 1);
    box.setAttribute("height", 1);
    box.setAttribute("depth", 1);
    box.setAttribute("color", "#0cf");
    box.setAttribute("position", "0 0 -5");
scene.appendChild(camera);
scene.appendChild(box);
body.appendChild(scene);

console.log( box.getAttribute("position") ) //"undefined"

example here:
http://minicg.com/demo/aframe050_test/

Body:
im not sure if I'm correct, but in my opinion You try to read the attribute before it's properly placed on the scene. When i added a 2s setTimeout() before the getAttribute() call, it works fine:

https://codepen.io/gftruj/pen/JJoENb

But waiting 2 seconds before reading attributes is outrageous !!!

Yep, that's why i'd recommend putting your code inside a registered component. You can add any js code in the init() function, and You should be sure everything is properly loaded.
 For example create manually a <a-scene myCode> element, and put your code in

    AFRAME.registerComponent('myCode', {
      init: function () {
        //whatever you want, remember that the scope here is not the window,
        //but the element using this component ( now it'd be the a-scene)
      }
    });


答:
You lack the () in your generator expresion:

```<code>sum((1 for x in c if x.isupper()))
4
</code>```

EDIT: As @Błotosmętek sugest, you lack the () in your print, i guess you are using python3, you should use print()

Title: How to separate upper and lower case with counter?

Body:
You lack the () in your generator expresion:

sum((1 for x in c if x.isupper()))
4

EDIT: As @Błotosmętek sugest, you lack the () in your print, i guess you are using python3, you should use print()


问:
jQuery Shimmer Button Effect
Is there a way to create a shimmer effect on an HTML element, using jQuery, simulating a moving lightsource? I see this on Flash components, but haven't seen one with jQuery yet. Want to avoid having to make shimmering GIFs if I can.

EDIT1: I imagine I'll have to capture the hover event and then use animate to stack a white fuzzy diagonal image on top of an IMG or DIV tag's boundaries, moving it from left to right once.

答:
Here is a tutorial with a jQuery shimmer effect (demo link at the bottom of the post):

http://www.eu-live.com/?p=164

Title: jQuery Shimmer Button Effect


问:
Max number of parametrs to private methods
So there is some kind of a rule for clean code "No more then 3/4 parametrs to method".

Am curious about should I follow this rule for private methods, method which are disigned to use by other function and not called by user. Or I can pass more then 3/4 parametrs to private methods?

答:
Having clean and easy to use classes is not only necessary for the public API.

Having internal code hard to read and use is not acceptable.

It results to an unbalanced quality design : clean public API design but lower quality in implementation.

While the implementation is as much important to get a good software.

Or I can pass more then 3/4 parametrs to private methods?

You should rather provide a custom class as parameter that holds information you want to pass as individual parameters.


问:
Handle a signal as error
Hi I'm programming a threaded socket program, The program may receive a SIGPIPE signal and will exit, If I catch the signal and ignore it the program will have undefined behavior because I don't know how to handle this as error, How can I catch a signal and notify the current position of the code that it needs to return from a function with error code so the program flow will continue as normal, I want to threat the SIGPIPE as it is error in read/write syscalls, cause i know how to handle read/write errors when I receive them.

```<code>{
    signal(SIGPIPE,sig_handler);
}

void sig_handler(int signo)
{
  if (signo == SIGPIPE){
    printf("hi\n");

  }
}
</code>```

答:
if you want to ignore the SIGPIPE and handle the error directly in your code.
but signal handlers in C have many restrictions .
The most easy way is to set the SIGPIPE handler to SIG_IGN. This will prevent any socket write from causing a SIGPIPE signal.
To ignore the SIGPIPE signal, use the following code:

```<code>signal(SIGPIPE, SIG_IGN);
</code>```

OR
to handle this try this:

```<code>#include <signal.h>
/* Catch Signal Handler functio */
void signal_handler(int signum)
{
 printf("Caught signal SIGPIPE %d\n",signum);
}
</code>```

and In program:

```<code>/* Catch Signal Handler SIGPIPE */
signal(SIGPIPE, signal_callback_handler);
</code>```

Another methode is that set the socket options while creating the socket: change the socket so it never generates SIGPIPE on write().

```<code>int num = 1;
setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&num, sizeof(int));
</code>```

Title: Handle a signal as error

Body:
Hi I'm programming a threaded socket program, The program may receive a SIGPIPE signal and will exit, If I catch the signal and ignore it the program will have undefined behavior because I don't know how to handle this as error, How can I catch a signal and notify the current position of the code that it needs to return from a function with error code so the program flow will continue as normal, I want to threat the SIGPIPE as it is error in read/write syscalls, cause i know how to handle read/write errors when I receive them.

{
    signal(SIGPIPE,sig_handler);
}

void sig_handler(int signo)
{
  if (signo == SIGPIPE){
    printf("hi\n");

  }
}

Body:
if you want to ignore the SIGPIPE and handle the error directly in your code.
but signal handlers in C have many restrictions .
The most easy way is to set the SIGPIPE handler to SIG_IGN. This will prevent any socket write from causing a SIGPIPE signal.
To ignore the SIGPIPE signal, use the following code:

signal(SIGPIPE, SIG_IGN);

OR
to handle this try this:

#include <signal.h>
/* Catch Signal Handler functio */
void signal_handler(int signum)
{
 printf("Caught signal SIGPIPE %d\n",signum);
}

and In program:

/* Catch Signal Handler SIGPIPE */
signal(SIGPIPE, signal_callback_handler);

Another methode is that set the socket options while creating the socket: change the socket so it never generates SIGPIPE on write().

int num = 1;
setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&num, sizeof(int));


问:
Ionic v1 - $ionicModal - 'fromTemplateUrl' is undefined
I'm following the documentation on how to implement the $ionicModel

http://ionicframework.com/docs/v1/api/service/$ionicModal/

However, I'm getting the error:

TypeError: Cannot read property 'fromTemplateUrl' of undefined

My Controller:

```<code>.controller('barCtrl', ['$scope', '$stateParams', '$ionicHistory', '$rootScope', '$ionicModal',
function ($scope, $stateParams, $ionicHistory, $rootScope, $cordovaInAppBrowser, $ionicModal) {
    /* Modal */
    $ionicModal.fromTemplateUrl('/templates/bar.html', {
        scope: $scope,
        animation: 'slide-in-up'
    }).then(function (modal) {
        $scope.modal = modal;
    });
    $scope.openModal = function () {
        $scope.modal.show();
    };
    $scope.closeModal = function () {
        $scope.modal.hide();
    };
    // Cleanup the modal when we're done with it!
    $scope.$on('$destroy', function () {
        $scope.modal.remove();
    });
    // Execute action on hide modal
    $scope.$on('modal.hidden', function () {
        // Execute action
    });
    // Execute action on remove modal
    $scope.$on('modal.removed', function () {
        // Execute action
    });

}])
</code>```

Template:

```<code>    <script id="bar.html" type="text/ng-template">
        <ion-modal-view>
            <ion-header-bar>
                <h1 class="title">My Modal title</h1>
            </ion-header-bar>
            <ion-content>
                Hello!
            </ion-content>
        </ion-modal-view>
    </script>
</code>```

答:
Your order is wrong for dependencies.

Change this

```<code>.controller('barCtrl', ['$scope', '$stateParams', '$ionicHistory', '$rootScope', '$ionicModal',
function ($scope, $stateParams, $ionicHistory, $rootScope, $cordovaInAppBrowser, $ionicModal)
</code>```

to

```<code>.controller('barCtrl', ['$scope', '$stateParams', '$ionicHistory', '$rootScope', '$ionicModal',
    function ($scope, $stateParams, $ionicHistory, $rootScope, $ionicModal)
</code>```

Body:
I'm following the documentation on how to implement the $ionicModel

http://ionicframework.com/docs/v1/api/service/$ionicModal/

However, I'm getting the error:

TypeError: Cannot read property 'fromTemplateUrl' of undefined

My Controller:

.controller('barCtrl', ['$scope', '$stateParams', '$ionicHistory', '$rootScope', '$ionicModal',
function ($scope, $stateParams, $ionicHistory, $rootScope, $cordovaInAppBrowser, $ionicModal) {
    /* Modal */
    $ionicModal.fromTemplateUrl('/templates/bar.html', {
        scope: $scope,
        animation: 'slide-in-up'
    }).then(function (modal) {
        $scope.modal = modal;
    });
    $scope.openModal = function () {
        $scope.modal.show();
    };
    $scope.closeModal = function () {
        $scope.modal.hide();
    };
    // Cleanup the modal when we're done with it!
    $scope.$on('$destroy', function () {
        $scope.modal.remove();
    });
    // Execute action on hide modal
    $scope.$on('modal.hidden', function () {
        // Execute action
    });
    // Execute action on remove modal
    $scope.$on('modal.removed', function () {
        // Execute action
    });

}])

Template:

Body:
Your order is wrong for dependencies.

Change this

.controller('barCtrl', ['$scope', '$stateParams', '$ionicHistory', '$rootScope', '$ionicModal',
function ($scope, $stateParams, $ionicHistory, $rootScope, $cordovaInAppBrowser, $ionicModal)

to

.controller('barCtrl', ['$scope', '$stateParams', '$ionicHistory', '$rootScope', '$ionicModal',
    function ($scope, $stateParams, $ionicHistory, $rootScope, $ionicModal)


问:
asp.net core in vs 2017 minify each js file for each view
I have a mvc core project ,and i have a js file for each view on views folder.
How to globally minify each js file of each view into wwwroot/views/.. folder with use bundleconfig.json like this :

```<code> {
   "outputFileName": "wwwroot/views/*.min.js",
   "inputFiles": [
     "Views/**/jquery/*.js"
   ],
   "minify": {
     "enabled": true,
     "renameLocals": true
   }
 }
</code>```

I don't want bundle all js file in one file.

答:
Use following extension it may help you to resolve this issue.

https://github.com/ravikumar77/BundlerMinifier

Body:
I have a mvc core project ,and i have a js file for each view on views folder.
How to globally minify each js file of each view into wwwroot/views/.. folder with use bundleconfig.json like this :

 {
   "outputFileName": "wwwroot/views/*.min.js",
   "inputFiles": [
     "Views/**/jquery/*.js"
   ],
   "minify": {
     "enabled": true,
     "renameLocals": true
   }
 }

I don't want bundle all js file in one file.


问:
Update array roles of Meteor.users
I am using Meteor roles of alanning, https://github.com/alanning/meteor-roles

I am doing the part where the user will be added to a team and have an access.
The problem is in this code,

```<code>Meteor.users.update('profile.team':team.name,{$pull:{'roles["default-group"]':access}});

 Meteor.users.update('profile.team':team.name,{$push:{"roles['default-group']":access}});
</code>```

In the default-group role of a user, I need to add/remove the access.

These lines are not working. how to fix it?

答:
Are you not supposed to use below given code to perform add or remove operation?

```<code>Roles.addUsersToRoles(joesUserId, ['manage-team','schedule-game'], 'manchester-united.com')
</code>```

For deleting:

Roles.setUserRoles(targetUserId, [], group)

Title: Update array roles of Meteor.users

Body:
I am using Meteor roles of alanning, https://github.com/alanning/meteor-roles

I am doing the part where the user will be added to a team and have an access.
The problem is in this code,

Meteor.users.update('profile.team':team.name,{$pull:{'roles["default-group"]':access}});

 Meteor.users.update('profile.team':team.name,{$push:{"roles['default-group']":access}});

In the default-group role of a user, I need to add/remove the access.

These lines are not working. how to fix it?

Body:
Are you not supposed to use below given code to perform add or remove operation?

Roles.addUsersToRoles(joesUserId, ['manage-team','schedule-game'], 'manchester-united.com')

For deleting:

Roles.setUserRoles(targetUserId, [], group)


问:
Ajax get method returns empty model
I have a cancel button on a form that is suppose to (re)AJAX the original page... The problem is that it sends back the page empty without any data. I can't figure out what I'm doing wrong.
This is my code:

```<code> $("#cancel-price-button").click(function() {
        $("#client-pricing-container").html("<h1 style='color:grey'>Loading...</h1>");
        $.ajax({
            type: "GET",
            url: '@Url.Action("GetProjectPricing","Project",Model?.Project?.ProjectPricings)',
            success: function(data) {$("#client-pricing-container").html(data); },
            error: function(data) {
            $("#client-pricing-container").html("<h1 style='color:red'>Ajax Error!</h1>");
            console.log('An ajax error occurred.');
            console.log(data);
                   }
               });
               });
</code>```

This is my controller:

```<code> [HttpGet]
        public ActionResult GetProjectPricing(string returnMessage,string returnClass,int?id=null)
        {
            if (id == null)
            {
                var pricingDetail = ProjectDataAccess.GetProjectDetails(null);
                pricingDetail.Project = new Project();
                pricingDetail.ReturnMessage = returnMessage;
                pricingDetail.ReturnClass = returnClass;
                return PartialView("Partial/ClientPricing", pricingDetail);
            }
            var pricingDetails = ProjectDataAccess.GetProjectDetails(id.Value);
            if (pricingDetails == null) return PartialView("Error");
            pricingDetails.ReturnMessage = returnMessage;
            pricingDetails.ReturnClass = returnClass;
            return PartialView("Partial/ClientPricing", pricingDetails);

        }
</code>```

答:
Issues like this are usually due to discrepancies between the shape or naming of the parameters your API method is expecting and what is getting passed from your view.

In your case, your API expects:

GetProjectPricing(string returnMessage, string returnClass, int? id=null)

You're passing the following object:

Model?.Project?.ProjectPricings

So, assuming that you have already ensured that the object (or its parents) arent null, you need to make sure that the structure of ProjectPricings matches the expected shape and has the expected properties. If not (or if you aren't positive it does), try this:

@Url.Action("GetProjectPricing","Project", new { returnMessage = "some text2", returnClass = "someClass", id = 9})

'id' can be left out, since you have a default value in your method signature

Title: Ajax get method returns empty model

Body:
I have a cancel button on a form that is suppose to (re)AJAX the original page... The problem is that it sends back the page empty without any data. I can't figure out what I'm doing wrong.
This is my code:

 $("#cancel-price-button").click(function() {
        $("#client-pricing-container").html("
Loading...
");
        $.ajax({
            type: "GET",
            url: '@Url.Action("GetProjectPricing","Project",Model?.Project?.ProjectPricings)',
            success: function(data) {$("#client-pricing-container").html(data); },
            error: function(data) {
            $("#client-pricing-container").html("
Ajax Error!
");
            console.log('An ajax error occurred.');
            console.log(data);
                   }
               });
               });

This is my controller:

 [HttpGet]
        public ActionResult GetProjectPricing(string returnMessage,string returnClass,int?id=null)
        {
            if (id == null)
            {
                var pricingDetail = ProjectDataAccess.GetProjectDetails(null);
                pricingDetail.Project = new Project();
                pricingDetail.ReturnMessage = returnMessage;
                pricingDetail.ReturnClass = returnClass;
                return PartialView("Partial/ClientPricing", pricingDetail);
            }
            var pricingDetails = ProjectDataAccess.GetProjectDetails(id.Value);
            if (pricingDetails == null) return PartialView("Error");
            pricingDetails.ReturnMessage = returnMessage;
            pricingDetails.ReturnClass = returnClass;
            return PartialView("Partial/ClientPricing", pricingDetails);

        }