问:
Unable to create oauth keys using wso2 apim 3.1.0 and IS 5.10.0
I am using wso2 APIM 3.1.0 with Wso2 IS 5.10.0 as key manager. This error happens when I create the API in the API publisher portal and publish it. Using API developer portal when I try to subscribe to the API created I am getting the below exception at the generate keys step when I click on the Next button as shown in the below image.
Also on the Identity server side I see the logs. I believe these logs confirm that everything is fine on the IS side

```<code>[2020-05-31 09:29:30,166] [d407196c-7d23-45b4-b5f7-fc6136106c4e]  INFO
{org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration} - An
instance of org.wso2.carbon.apimgt.keymgt.issuers.APIMTokenIssuer is created
for Identity OAuth token generation.
[2020-05-31 09:29:30,221] [d407196c-7d23-45b4-b5f7-fc6136106c4e]  INFO
{org.opensaml.core.config.InitializationService} - Initializing OpenSAML
using the Java Services API
</code>```

I followed this link for configuring wso2 Is as key manager in API manager https://apim.docs.wso2.com/en/latest/install-and-setup/setup/distributed-deployment/configuring-wso2-identity-server-as-a-key-manager/#step-4-configure-the-wso2-is-as-key-manager-with-wso2-api-manager
Is this bug in API manager?

```<code>ERROR {org.wso2.carbon.apimgt.rest.api.store.v1.impl.ApplicationsApiServiceImpl} - Error while generating keys for application dfe28a41-4ff5-48eb-bf91-8d2125a344b9 org.wso2.carbon.apimgt.api.APIManagementException: org.wso2.carbon.apimgt.impl.workflow.WorkflowException: Error occurred while executing SubscriberKeyMgtClient.
    at org.wso2.carbon.apimgt.impl.APIConsumerImpl.requestApprovalForApplicationRegistration_aroundBody144(APIConsumerImpl.java:3907)
    at org.wso2.carbon.apimgt.impl.APIConsumerImpl.requestApprovalForApplicationRegistration(APIConsumerImpl.java:3745)
    at org.wso2.carbon.apimgt.rest.api.store.v1.impl.ApplicationsApiServiceImpl.applicationsApplicationIdGenerateKeysPost(ApplicationsApiServiceImpl.java:505)
    at org.wso2.carbon.apimgt.rest.api.store.v1.ApplicationsApi.applicationsApplicationIdGenerateKeysPost(ApplicationsApi.java:125)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.apache.cxf.service.invoker.AbstractInvoker.performInvocation(AbstractInvoker.java:179)
    at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
    at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:193)
    at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:103)
    at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:59)
    at org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:96)
    at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
    at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
    at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:267)
    at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:234)
    at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:208)
    at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:160)
    at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:216)
    at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:301)
    at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:220)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:276)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.wso2.carbon.identity.context.rewrite.valve.TenantContextRewriteValve.invoke(TenantContextRewriteValve.java:86)
    at org.wso2.carbon.identity.authz.valve.AuthorizationValve.invoke(AuthorizationValve.java:110)
    at org.wso2.carbon.identity.auth.valve.AuthenticationValve.invoke(AuthenticationValve.java:75)
    at org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:99)
    at org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:49)
    at org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:62)
    at org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:145)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:688)
    at org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:57)
    at org.wso2.carbon.tomcat.ext.valves.RequestCorrelationIdValve.invoke(RequestCorrelationIdValve.java:119)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1639)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.wso2.carbon.apimgt.impl.workflow.WorkflowException: Error occurred while executing SubscriberKeyMgtClient.
    at org.wso2.carbon.apimgt.impl.workflow.ApplicationRegistrationSimpleWorkflowExecutor.complete_aroundBody2(ApplicationRegistrationSimpleWorkflowExecutor.java:82)
    at org.wso2.carbon.apimgt.impl.workflow.ApplicationRegistrationSimpleWorkflowExecutor.complete(ApplicationRegistrationSimpleWorkflowExecutor.java:66)
    at org.wso2.carbon.apimgt.impl.workflow.ApplicationRegistrationSimpleWorkflowExecutor.execute_aroundBody0(ApplicationRegistrationSimpleWorkflowExecutor.java:54)
    at org.wso2.carbon.apimgt.impl.workflow.ApplicationRegistrationSimpleWorkflowExecutor.execute(ApplicationRegistrationSimpleWorkflowExecutor.java:47)
    at org.wso2.carbon.apimgt.impl.APIConsumerImpl.requestApprovalForApplicationRegistration_aroundBody144(APIConsumerImpl.java:3876)
    ... 55 more
Caused by: org.wso2.carbon.apimgt.api.APIManagementException: Error occurred while executing SubscriberKeyMgtClient.
    at org.wso2.carbon.apimgt.impl.utils.APIUtil.handleException_aroundBody78(APIUtil.java:1932)
    at org.wso2.carbon.apimgt.impl.utils.APIUtil.handleException(APIUtil.java:1930)
    at org.wso2.carbon.apimgt.impl.workflow.AbstractApplicationRegistrationWorkflowExecutor.dogenerateKeysForApplication_aroundBody8(AbstractApplicationRegistrationWorkflowExecutor.java:170)
    at org.wso2.carbon.apimgt.impl.workflow.AbstractApplicationRegistrationWorkflowExecutor.dogenerateKeysForApplication(AbstractApplicationRegistrationWorkflowExecutor.java:123)
    at org.wso2.carbon.apimgt.impl.workflow.AbstractApplicationRegistrationWorkflowExecutor.generateKeysForApplication_aroundBody6(AbstractApplicationRegistrationWorkflowExecutor.java:119)
    at org.wso2.carbon.apimgt.impl.workflow.AbstractApplicationRegistrationWorkflowExecutor.generateKeysForApplication(AbstractApplicationRegistrationWorkflowExecutor.java:116)
    at org.wso2.carbon.apimgt.impl.workflow.ApplicationRegistrationSimpleWorkflowExecutor.complete_aroundBody2(ApplicationRegistrationSimpleWorkflowExecutor.java:78)
    ... 59 more
Caused by: org.wso2.carbon.apimgt.api.APIManagementException: Error occurred while calling token endpoint: HTTP error code : 400
    at org.wso2.carbon.apimgt.impl.AMDefaultKeyManagerImpl.getNewApplicationAccessToken_aroundBody10(AMDefaultKeyManagerImpl.java:389)
    at org.wso2.carbon.apimgt.impl.AMDefaultKeyManagerImpl.getNewApplicationAccessToken(AMDefaultKeyManagerImpl.java:304)
    at org.wso2.carbon.apimgt.impl.workflow.AbstractApplicationRegistrationWorkflowExecutor.dogenerateKeysForApplication_aroundBody8(AbstractApplicationRegistrationWorkflowExecutor.java:159)
    ... 63 more
</code>```

答:
I assume you have 1 APIM node and 1 keymanager node.

When you click generate keys 2 things happen. 1. Creating an OAuth app. 2. Generate an access token. In this case, what has failed is the step 2. The token gen call has received 400 (Bad request) response. There must be another error log related to this, in one of the nodes (most probably in the KM node).

Do you have the following configured by any chance?

```<code>[apim.oauth_config]
revoke_endpoint = ??
</code>```

Body:
I am using wso2 APIM 3.1.0 with Wso2 IS 5.10.0 as key manager. This error happens when I create the API in the API publisher portal and publish it. Using API developer portal when I try to subscribe to the API created I am getting the below exception at the generate keys step when I click on the Next button as shown in the below image.
Also on the Identity server side I see the logs. I believe these logs confirm that everything is fine on the IS side

[2020-05-31 09:29:30,166] [d407196c-7d23-45b4-b5f7-fc6136106c4e]  INFO
{org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration} - An
instance of org.wso2.carbon.apimgt.keymgt.issuers.APIMTokenIssuer is created
for Identity OAuth token generation.
[2020-05-31 09:29:30,221] [d407196c-7d23-45b4-b5f7-fc6136106c4e]  INFO
{org.opensaml.core.config.InitializationService} - Initializing OpenSAML
using the Java Services API

I followed this link for configuring wso2 Is as key manager in API manager https://apim.docs.wso2.com/en/latest/install-and-setup/setup/distributed-deployment/configuring-wso2-identity-server-as-a-key-manager/#step-4-configure-the-wso2-is-as-key-manager-with-wso2-api-manager
Is this bug in API manager?

ERROR {org.wso2.carbon.apimgt.rest.api.store.v1.impl.ApplicationsApiServiceImpl} - Error while generating keys for application dfe28a41-4ff5-48eb-bf91-8d2125a344b9 org.wso2.carbon.apimgt.api.APIManagementException: org.wso2.carbon.apimgt.impl.workflow.WorkflowException: Error occurred while executing SubscriberKeyMgtClient.
    at org.wso2.carbon.apimgt.impl.APIConsumerImpl.requestApprovalForApplicationRegistration_aroundBody144(APIConsumerImpl.java:3907)
    at org.wso2.carbon.apimgt.impl.APIConsumerImpl.requestApprovalForApplicationRegistration(APIConsumerImpl.java:3745)
    at org.wso2.carbon.apimgt.rest.api.store.v1.impl.ApplicationsApiServiceImpl.applicationsApplicationIdGenerateKeysPost(ApplicationsApiServiceImpl.java:505)
    at org.wso2.carbon.apimgt.rest.api.store.v1.ApplicationsApi.applicationsApplicationIdGenerateKeysPost(ApplicationsApi.java:125)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.apache.cxf.service.invoker.AbstractInvoker.performInvocation(AbstractInvoker.java:179)
    at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
    at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:193)
    at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:103)
    at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:59)
    at org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:96)
    at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
    at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
    at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:267)
    at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:234)
    at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:208)
    at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:160)
    at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:216)
    at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:301)
    at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:220)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:276)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.wso2.carbon.identity.context.rewrite.valve.TenantContextRewriteValve.invoke(TenantContextRewriteValve.java:86)
    at org.wso2.carbon.identity.authz.valve.AuthorizationValve.invoke(AuthorizationValve.java:110)
    at org.wso2.carbon.identity.auth.valve.AuthenticationValve.invoke(AuthenticationValve.java:75)
    at org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:99)
    at org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:49)
    at org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:62)
    at org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:145)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:688)
    at org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:57)
    at org.wso2.carbon.tomcat.ext.valves.RequestCorrelationIdValve.invoke(RequestCorrelationIdValve.java:119)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1639)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.wso2.carbon.apimgt.impl.workflow.WorkflowException: Error occurred while executing SubscriberKeyMgtClient.
    at org.wso2.carbon.apimgt.impl.workflow.ApplicationRegistrationSimpleWorkflowExecutor.complete_aroundBody2(ApplicationRegistrationSimpleWorkflowExecutor.java:82)
    at org.wso2.carbon.apimgt.impl.workflow.ApplicationRegistrationSimpleWorkflowExecutor.complete(ApplicationRegistrationSimpleWorkflowExecutor.java:66)
    at org.wso2.carbon.apimgt.impl.workflow.ApplicationRegistrationSimpleWorkflowExecutor.execute_aroundBody0(ApplicationRegistrationSimpleWorkflowExecutor.java:54)
    at org.wso2.carbon.apimgt.impl.workflow.ApplicationRegistrationSimpleWorkflowExecutor.execute(ApplicationRegistrationSimpleWorkflowExecutor.java:47)
    at org.wso2.carbon.apimgt.impl.APIConsumerImpl.requestApprovalForApplicationRegistration_aroundBody144(APIConsumerImpl.java:3876)
    ... 55 more
Caused by: org.wso2.carbon.apimgt.api.APIManagementException: Error occurred while executing SubscriberKeyMgtClient.
    at org.wso2.carbon.apimgt.impl.utils.APIUtil.handleException_aroundBody78(APIUtil.java:1932)
    at org.wso2.carbon.apimgt.impl.utils.APIUtil.handleException(APIUtil.java:1930)
    at org.wso2.carbon.apimgt.impl.workflow.AbstractApplicationRegistrationWorkflowExecutor.dogenerateKeysForApplication_aroundBody8(AbstractApplicationRegistrationWorkflowExecutor.java:170)
    at org.wso2.carbon.apimgt.impl.workflow.AbstractApplicationRegistrationWorkflowExecutor.dogenerateKeysForApplication(AbstractApplicationRegistrationWorkflowExecutor.java:123)
    at org.wso2.carbon.apimgt.impl.workflow.AbstractApplicationRegistrationWorkflowExecutor.generateKeysForApplication_aroundBody6(AbstractApplicationRegistrationWorkflowExecutor.java:119)
    at org.wso2.carbon.apimgt.impl.workflow.AbstractApplicationRegistrationWorkflowExecutor.generateKeysForApplication(AbstractApplicationRegistrationWorkflowExecutor.java:116)
    at org.wso2.carbon.apimgt.impl.workflow.ApplicationRegistrationSimpleWorkflowExecutor.complete_aroundBody2(ApplicationRegistrationSimpleWorkflowExecutor.java:78)
    ... 59 more
Caused by: org.wso2.carbon.apimgt.api.APIManagementException: Error occurred while calling token endpoint: HTTP error code : 400
    at org.wso2.carbon.apimgt.impl.AMDefaultKeyManagerImpl.getNewApplicationAccessToken_aroundBody10(AMDefaultKeyManagerImpl.java:389)
    at org.wso2.carbon.apimgt.impl.AMDefaultKeyManagerImpl.getNewApplicationAccessToken(AMDefaultKeyManagerImpl.java:304)
    at org.wso2.carbon.apimgt.impl.workflow.AbstractApplicationRegistrationWorkflowExecutor.dogenerateKeysForApplication_aroundBody8(AbstractApplicationRegistrationWorkflowExecutor.java:159)
    ... 63 more

Body:
I assume you have 1 APIM node and 1 keymanager node.

When you click generate keys 2 things happen. 1. Creating an OAuth app. 2. Generate an access token. In this case, what has failed is the step 2. The token gen call has received 400 (Bad request) response. There must be another error log related to this, in one of the nodes (most probably in the KM node).

Do you have the following configured by any chance?

[apim.oauth_config]
revoke_endpoint = ??


来源: stackexchange

问:
Curve geom_line() with ggplot
I used ggplot() and geom-line() as follows

```<code>ggplot(tabla3) + geom_line(aes(tabla3$MC, tabla3$Normal), lwd = 1)
</code>```

Result:

But I want it to look like this:

答:
If you know the mean and standard deviation of your data, why not just plot a normal distribution? </p>

```<code>x <- seq(50, 90, length=101)
hx <- dnorm(x, mean(x), sd(x))

plot(x, hx, type = 'l')

</code>```

<p>ggplot version </p>

```<code>ggplot(data = tibble(x), aes(x)) +
  stat_function(fun = dnorm, n = 101, args = list(mean = mean(x), sd = sd(x))) + ylab("") +
  scale_y_continuous(breaks = NULL)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Curve geom_line() with ggplot

Body:
I used ggplot() and geom-line() as follows

ggplot(tabla3) + geom_line(aes(tabla3$MC, tabla3$Normal), lwd = 1)

Result:

But I want it to look like this:

Body:
If you know the mean and standard deviation of your data, why not just plot a normal distribution?

x <- seq(50, 90, length=101)
hx <- dnorm(x, mean(x), sd(x))

plot(x, hx, type = 'l')

ggplot version

ggplot(data = tibble(x), aes(x)) +
  stat_function(fun = dnorm, n = 101, args = list(mean = mean(x), sd = sd(x))) + ylab("") +
  scale_y_continuous(breaks = NULL)


问:
spring boot data cassandra reactive JmxReporter problem
I updated my project to spring-boot Version 2.1.0.RELEASE.

Now i get the following error:

```<code>Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.cassandra.ReactiveSession]: Factory method 'reactiveSession' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'session' defined in class path resource [ch/sbb/kat/fc/config/CassandraConfig.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: com/codahale/metrics/JmxReporter
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.lambda$instantiate$2(ConstructorResolver.java:615)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:614)
    ... 120 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'session' defined in class path resource [ch/sbb/kat/fc/config/CassandraConfig.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: com/codahale/metrics/JmxReporter
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1745)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:339)
    at ch.sbb.kat.fc.config.CassandraConfig$$EnhancerBySpringCGLIB$$a22674d7.session(<generated>)
    at org.springframework.data.cassandra.config.AbstractCassandraConfiguration.getRequiredSession(AbstractCassandraConfiguration.java:66)
    at org.springframework.data.cassandra.config.AbstractReactiveCassandraConfiguration.reactiveSession(AbstractReactiveCassandraConfiguration.java:47)
    at ch.sbb.kat.fc.config.CassandraConfig$$EnhancerBySpringCGLIB$$a22674d7.CGLIB$reactiveSession$7(<generated>)
    at ch.sbb.kat.fc.config.CassandraConfig$$EnhancerBySpringCGLIB$$a22674d7$$FastClassBySpringCGLIB$$7973a63.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
    at ch.sbb.kat.fc.config.CassandraConfig$$EnhancerBySpringCGLIB$$a22674d7.reactiveSession(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 123 more
Caused by: java.lang.NoClassDefFoundError: com/codahale/metrics/JmxReporter
    at com.datastax.driver.core.Metrics.<init>(Metrics.java:146)
    at com.datastax.driver.core.Cluster$Manager.init(Cluster.java:1501)
    at com.datastax.driver.core.Cluster.init(Cluster.java:208)
    at com.datastax.driver.core.Cluster.connectAsync(Cluster.java:376)
    at com.datastax.driver.core.Cluster.connect(Cluster.java:332)
    at org.springframework.data.cassandra.config.CassandraCqlSessionFactoryBean.connect(CassandraCqlSessionFactoryBean.java:89)
    at org.springframework.data.cassandra.config.CassandraCqlSessionFactoryBean.afterPropertiesSet(CassandraCqlSessionFactoryBean.java:82)
    at org.springframework.data.cassandra.config.CassandraSessionFactoryBean.afterPropertiesSet(CassandraSessionFactoryBean.java:59)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.lambda$invokeInitMethods$5(AbstractAutowireCapableBeanFactory.java:1795)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1794)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1741)
    ... 143 more
Caused by: java.lang.ClassNotFoundException: com.codahale.metrics.JmxReporter
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 155 more
</code>```

Using the property introduced in this issue https://github.com/spring-projects/spring-boot/issues/14778 seems to have no effect to solve my issue.

How can i disable jmx for cassandra?

My current cassandra config looks like this:

```<code>@Configuration
@EnableReactiveCassandraRepositories({"repository"})
public class CassandraConfig extends AbstractReactiveCassandraConfiguration {

    @Value("${cassandra.host}")
    private String host;

    @Override
    protected String getKeyspaceName() {
        return "keyspace";
    }

    @Override
    public String[] getEntityBasePackages() {
        return new String[]{"model"};
    }

    @Override
    public SchemaAction getSchemaAction() {
        return SchemaAction.CREATE_IF_NOT_EXISTS;
    }

    @Override
    public String getContactPoints() {
        return host;
    }
}
</code>```

答:
@Bean
    public CassandraClusterFactoryBean cluster() {
        CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
        cluster.setContactPoints(environment.getProperty("spring.data.cassandra.contact-points"));
        cluster.setPort(Integer.parseInt(environment.getProperty("spring.data.cassandra.port")));
        cluster.setJmxReportingEnabled(false);
        return cluster;
    }

cluster.setJmxReportingEnabled(false) is the answer seems.

Body:
I updated my project to spring-boot Version 2.1.0.RELEASE.

Now i get the following error:

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.cassandra.ReactiveSession]: Factory method 'reactiveSession' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'session' defined in class path resource [ch/sbb/kat/fc/config/CassandraConfig.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: com/codahale/metrics/JmxReporter
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.lambda$instantiate$2(ConstructorResolver.java:615)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:614)
    ... 120 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'session' defined in class path resource [ch/sbb/kat/fc/config/CassandraConfig.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: com/codahale/metrics/JmxReporter
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1745)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:339)
    at ch.sbb.kat.fc.config.CassandraConfig$$EnhancerBySpringCGLIB$$a22674d7.session(<generated>)
    at org.springframework.data.cassandra.config.AbstractCassandraConfiguration.getRequiredSession(AbstractCassandraConfiguration.java:66)
    at org.springframework.data.cassandra.config.AbstractReactiveCassandraConfiguration.reactiveSession(AbstractReactiveCassandraConfiguration.java:47)
    at ch.sbb.kat.fc.config.CassandraConfig$$EnhancerBySpringCGLIB$$a22674d7.CGLIB$reactiveSession$7(<generated>)
    at ch.sbb.kat.fc.config.CassandraConfig$$EnhancerBySpringCGLIB$$a22674d7$$FastClassBySpringCGLIB$$7973a63.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
    at ch.sbb.kat.fc.config.CassandraConfig$$EnhancerBySpringCGLIB$$a22674d7.reactiveSession(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 123 more
Caused by: java.lang.NoClassDefFoundError: com/codahale/metrics/JmxReporter
    at com.datastax.driver.core.Metrics.<init>(Metrics.java:146)
    at com.datastax.driver.core.Cluster$Manager.init(Cluster.java:1501)
    at com.datastax.driver.core.Cluster.init(Cluster.java:208)
    at com.datastax.driver.core.Cluster.connectAsync(Cluster.java:376)
    at com.datastax.driver.core.Cluster.connect(Cluster.java:332)
    at org.springframework.data.cassandra.config.CassandraCqlSessionFactoryBean.connect(CassandraCqlSessionFactoryBean.java:89)
    at org.springframework.data.cassandra.config.CassandraCqlSessionFactoryBean.afterPropertiesSet(CassandraCqlSessionFactoryBean.java:82)
    at org.springframework.data.cassandra.config.CassandraSessionFactoryBean.afterPropertiesSet(CassandraSessionFactoryBean.java:59)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.lambda$invokeInitMethods$5(AbstractAutowireCapableBeanFactory.java:1795)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1794)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1741)
    ... 143 more
Caused by: java.lang.ClassNotFoundException: com.codahale.metrics.JmxReporter
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 155 more

Using the property introduced in this issue https://github.com/spring-projects/spring-boot/issues/14778 seems to have no effect to solve my issue.

How can i disable jmx for cassandra?

My current cassandra config looks like this:

@Configuration
@EnableReactiveCassandraRepositories({"repository"})
public class CassandraConfig extends AbstractReactiveCassandraConfiguration {

    @Value("${cassandra.host}")
    private String host;

    @Override
    protected String getKeyspaceName() {
        return "keyspace";
    }

    @Override
    public String[] getEntityBasePackages() {
        return new String[]{"model"};
    }

    @Override
    public SchemaAction getSchemaAction() {
        return SchemaAction.CREATE_IF_NOT_EXISTS;
    }

    @Override
    public String getContactPoints() {
        return host;
    }
}


问:
Access-Control-Allow-Origin error on axios request even after enabling express CORS middleware
I am recently deployed my API on Heroku, and I'm having some CORS related issues. I've seen many other posts that  talk about enabling CORS (and I've done that in my code), but whenever I make the axios POST request, I still get the same error: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. I've also tried messing around with the configuration object for cors(), but nothing seems to work.

The actual post request from the frontend looks like this:

```<code>const axiosConfig = {
        headers: {
          "Content-Type": "multipart/form-data",
          Accept: "application/json",
        },
      };
  await axios
    .post("https://myapp-backend.herokuapp.com/register", data, axiosConfig)
    .then((_) => Message.success("Successfully registered! "))
    .catch((error) => Message.error(error.message));
</code>```

and my app.js on the backend looks like this.

```<code>const createError = require("http-errors");
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const logger = require("morgan");
const multer = require("multer");
const cors = require("cors");

const app = express();
app.use(
  cors({
    allowedHeaders: ["authorization", "Content-Type"], // you can change the headers
    exposedHeaders: ["authorization"], // you can change the headers
    origin: "*",
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    preflightContinue: false,
  })
);

// set up different routers
const indexRouter = require("./routes/index");
const usersRouter = require("./routes/users");
const registrationRouter = require("./registration/routes");
const retailRouter = require("./retail-info/routes");
const bookingRouter = require("./booking/routes");

const port = process.env.PORT || 8080;

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    if (file.originalname.startsWith("CODE_COVER_QLYag759")) {
      cb(null, "temp-storage/cover/");
    } else {
      cb(null, "temp-storage/");
    }
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname)); //Appending extension
  },
});

const upload = multer({
  // dest: "temp-storage/",
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024, // no larger than 5mb, change as needed.
  },
});

// view engine setup

app.use(logger("dev"));
app.use(express.json());
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public")));

app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/register", upload.any(), registrationRouter);
app.use("/retail", retailRouter);
app.use("/booking", bookingRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.json({ error: err.message });
});

app.get("*", (req, res) => {
  res.sendFile(path.resolve(__dirname, "build", "index.html"));
});

app.listen(port, console.log(`MyApp backend started on port ${port}!`));

module.exports = app;
</code>```

I'd really appreciate it if someone could help me out!

答:
You can try setting headers to allow as one of the answers suggest

```<code> Access-Control-Allow-Origin: *
</code>```

Or, you can use a middleware cors package in node to do this. CORS npm

app.use(cors());

https://auth0.com/blog/cors-tutorial-a-guide-to-cross-origin-resource-sharing/

Or, you can use a proxy from where you're requesting in the client-side like this:

```<code>var proxy = https://cors-anywhere.herokuapp.com/;
      await axios
        .post(proxy+"https://myapp-backend.herokuapp.com/register", data, axiosConfig)
        .then((_) => Message.success("Successfully registered! "))
        .catch((error) => Message.error(error.message));
</code>```

Body:
I am recently deployed my API on Heroku, and I'm having some CORS related issues. I've seen many other posts that  talk about enabling CORS (and I've done that in my code), but whenever I make the axios POST request, I still get the same error: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. I've also tried messing around with the configuration object for cors(), but nothing seems to work.

The actual post request from the frontend looks like this:

const axiosConfig = {
        headers: {
          "Content-Type": "multipart/form-data",
          Accept: "application/json",
        },
      };
  await axios
    .post("https://myapp-backend.herokuapp.com/register", data, axiosConfig)
    .then((_) => Message.success("Successfully registered! "))
    .catch((error) => Message.error(error.message));

and my app.js on the backend looks like this.

const createError = require("http-errors");
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const logger = require("morgan");
const multer = require("multer");
const cors = require("cors");

const app = express();
app.use(
  cors({
    allowedHeaders: ["authorization", "Content-Type"], // you can change the headers
    exposedHeaders: ["authorization"], // you can change the headers
    origin: "*",
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    preflightContinue: false,
  })
);

// set up different routers
const indexRouter = require("./routes/index");
const usersRouter = require("./routes/users");
const registrationRouter = require("./registration/routes");
const retailRouter = require("./retail-info/routes");
const bookingRouter = require("./booking/routes");

const port = process.env.PORT || 8080;

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    if (file.originalname.startsWith("CODE_COVER_QLYag759")) {
      cb(null, "temp-storage/cover/");
    } else {
      cb(null, "temp-storage/");
    }
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname)); //Appending extension
  },
});

const upload = multer({
  // dest: "temp-storage/",
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024, // no larger than 5mb, change as needed.
  },
});

// view engine setup

app.use(logger("dev"));
app.use(express.json());
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public")));

app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/register", upload.any(), registrationRouter);
app.use("/retail", retailRouter);
app.use("/booking", bookingRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.json({ error: err.message });
});

app.get("*", (req, res) => {
  res.sendFile(path.resolve(__dirname, "build", "index.html"));
});

app.listen(port, console.log(`MyApp backend started on port ${port}!`));

module.exports = app;

I'd really appreciate it if someone could help me out!

Body:
You can try setting headers to allow as one of the answers suggest

 Access-Control-Allow-Origin: *

Or, you can use a middleware cors package in node to do this. CORS npm

app.use(cors());

https://auth0.com/blog/cors-tutorial-a-guide-to-cross-origin-resource-sharing/

Or, you can use a proxy from where you're requesting in the client-side like this:

var proxy = https://cors-anywhere.herokuapp.com/;
      await axios
        .post(proxy+"https://myapp-backend.herokuapp.com/register", data, axiosConfig)
        .then((_) => Message.success("Successfully registered! "))
        .catch((error) => Message.error(error.message));


问:
configuration of a maven project with sub project to access all java facilities
I have a mavent parent project with maven child project using microservices within Eclipse. But I don't have access to all java facilities and information. For example the type of compiler and java libraries or JRE information are not available. Other example, I cannot right click on a method and go to its implementation. When I right click on the project and go to properties, I have the following image.

EDIT

.project file

```<code><?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
    <name>immobilier</name>
    <comment></comment>
    <projects>
    </projects>
    <buildSpec>
        <buildCommand>
            <name>org.eclipse.m2e.core.maven2Builder</name>
            <arguments>
            </arguments>
        </buildCommand>
    </buildSpec>
    <natures>
        <nature>org.eclipse.m2e.core.maven2Nature</nature>
    </natures>
</projectDescription>
</code>```

答:
I did it in a new workspace

It is OK for all sub-modules and I haven't any more the parent module (is it normal ?). Furthermore I haven't the module user-service, a module that I have added during development and not yet saved on git

Body:
I have a mavent parent project with maven child project using microservices within Eclipse. But I don't have access to all java facilities and information. For example the type of compiler and java libraries or JRE information are not available. Other example, I cannot right click on a method and go to its implementation. When I right click on the project and go to properties, I have the following image.

EDIT

.project file

<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
    <name>immobilier</name>
    <comment></comment>
    <projects>
    </projects>
    <buildSpec>
        <buildCommand>
            <name>org.eclipse.m2e.core.maven2Builder</name>
            <arguments>
            </arguments>
        </buildCommand>
    </buildSpec>
    <natures>
        <nature>org.eclipse.m2e.core.maven2Nature</nature>
    </natures>
</projectDescription>


问:
spring-boot Error: Exceeded maxRedirects. Probably stuck in a redirect loop
I am trying to perform JWT auth in spring boot and the request are getting stuck in redirect loop.

JWTAuthenticationProvider

```<code>@Component
public class JwtAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean supports(Class<?> authentication) {
        return (JwtAuthenticationToken.class.isAssignableFrom(authentication));
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails,
            UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    }

    @Override
    protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
            throws AuthenticationException {
        JwtAuthenticationToken jwtAuthenticationToken = (JwtAuthenticationToken) authentication;
        String token = jwtAuthenticationToken.getToken();

        JwtParsedUser parsedUser = jwtUtil.parseToken(token);

        if (parsedUser == null) {
            throw new JwtException("JWT token is not valid");
        }
        UserDetails user = User.withUsername(parsedUser.getUserName()).password("temp_password").authorities(parsedUser.getRole()).build();
        return user;
    }
</code>```

JwtAuthenticationFilter

```<code>public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super("/**");
        this.setAuthenticationManager(authenticationManager);
    }

    @Override
    protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
        return true;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {

        String header = request.getHeader("Authorization");

        if (header == null || !header.startsWith("Bearer ")) {
            throw new JwtException("No JWT token found in request headers");
        }

        String authToken = header.substring(7);

        JwtAuthenticationToken authRequest = new JwtAuthenticationToken(authToken);

        return getAuthenticationManager().authenticate(authRequest);
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request,

            HttpServletResponse response, FilterChain chain, Authentication authResult)
            throws IOException, ServletException {
        super.successfulAuthentication(request, response, chain, authResult);

        chain.doFilter(request, response);
    }

}
</code>```

SecurityConfiguration

```<code>@Configuration
@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationProvider jwtAuthenticationProvider;

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(jwtAuthenticationProvider);

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable().authorizeRequests().antMatchers("/secured-resource-1/**", "/secured-resource-2/**")
                .hasRole("ADMIN").antMatchers("/secured-resource-2/**").hasRole("ADMIN").and().formLogin()
                .successHandler(new AuthenticationSuccessHandler()).and().httpBasic().and().exceptionHandling()
                .accessDeniedHandler(new CustomAccessDeniedHandler()).authenticationEntryPoint(getBasicAuthEntryPoint())
                .and()
                .addFilterBefore(new JwtAuthenticationFilter(authenticationManager()),
                        FilterSecurityInterceptor.class)
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Bean
    public CustomBasicAuthenticationEntryPoint getBasicAuthEntryPoint() {
        return new CustomBasicAuthenticationEntryPoint();
    }
}
</code>```

MainController

```<code>@RestController
public class MainController {
    @Autowired
    private JwtUtil jwtUtil;

    @GetMapping("/secured-resource-1")
    public String securedResource1() {
        return "Secured resource1";
    }
}
</code>```

When I hit the endpoint with the valid JWT token, the code goes in a loop from Filter to provider class and ends in Error:

```<code>Exceeded maxRedirects. Probably stuck in a redirect loop http://localhost:8000/ error.
</code>```

Debug logs shows the following error:

```<code>Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Cannot call sendError() after the response has been committed] with root cause

java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
</code>```

Any suggestions what am I missing here.
Thanks in advance.

答:
I solved this problem with another approach.
In the JwtAuthenticationFilter class we need to set authentication object in context and call chain.doFilter. Calling super.successfulAuthentication can be skipped as we have overridden the implementation.</p>

```<code> @Override
   protected void successfulAuthentication(HttpServletRequest request,

   HttpServletResponse response, FilterChain chain, Authentication authResult)
                throws IOException, ServletException {
            //super.successfulAuthentication(request, response, chain, authResult);
            SecurityContextHolder.getContext().setAuthentication(authResult);
            chain.doFilter(request, response);
        }

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super("/**");
        this.setAuthenticationManager(authenticationManager);
        //this.setAuthenticationSuccessHandler(new JwtAuthenticationSuccessHandler());
    }
</code>```

Body:
I am trying to perform JWT auth in spring boot and the request are getting stuck in redirect loop.

JWTAuthenticationProvider

@Component
public class JwtAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean supports(Class<?> authentication) {
        return (JwtAuthenticationToken.class.isAssignableFrom(authentication));
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails,
            UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    }

    @Override
    protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
            throws AuthenticationException {
        JwtAuthenticationToken jwtAuthenticationToken = (JwtAuthenticationToken) authentication;
        String token = jwtAuthenticationToken.getToken();

        JwtParsedUser parsedUser = jwtUtil.parseToken(token);

        if (parsedUser == null) {
            throw new JwtException("JWT token is not valid");
        }
        UserDetails user = User.withUsername(parsedUser.getUserName()).password("temp_password").authorities(parsedUser.getRole()).build();
        return user;
    }

JwtAuthenticationFilter

public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super("/**");
        this.setAuthenticationManager(authenticationManager);
    }

    @Override
    protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
        return true;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {

        String header = request.getHeader("Authorization");

        if (header == null || !header.startsWith("Bearer ")) {
            throw new JwtException("No JWT token found in request headers");
        }

        String authToken = header.substring(7);

        JwtAuthenticationToken authRequest = new JwtAuthenticationToken(authToken);

        return getAuthenticationManager().authenticate(authRequest);
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request,

            HttpServletResponse response, FilterChain chain, Authentication authResult)
            throws IOException, ServletException {
        super.successfulAuthentication(request, response, chain, authResult);

        chain.doFilter(request, response);
    }

}

SecurityConfiguration

@Configuration
@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationProvider jwtAuthenticationProvider;

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(jwtAuthenticationProvider);

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable().authorizeRequests().antMatchers("/secured-resource-1/**", "/secured-resource-2/**")
                .hasRole("ADMIN").antMatchers("/secured-resource-2/**").hasRole("ADMIN").and().formLogin()
                .successHandler(new AuthenticationSuccessHandler()).and().httpBasic().and().exceptionHandling()
                .accessDeniedHandler(new CustomAccessDeniedHandler()).authenticationEntryPoint(getBasicAuthEntryPoint())
                .and()
                .addFilterBefore(new JwtAuthenticationFilter(authenticationManager()),
                        FilterSecurityInterceptor.class)
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Bean
    public CustomBasicAuthenticationEntryPoint getBasicAuthEntryPoint() {
        return new CustomBasicAuthenticationEntryPoint();
    }
}

MainController

@RestController
public class MainController {
    @Autowired
    private JwtUtil jwtUtil;

    @GetMapping("/secured-resource-1")
    public String securedResource1() {
        return "Secured resource1";
    }
}

When I hit the endpoint with the valid JWT token, the code goes in a loop from Filter to provider class and ends in Error:

Exceeded maxRedirects. Probably stuck in a redirect loop http://localhost:8000/ error.

Debug logs shows the following error:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Cannot call sendError() after the response has been committed] with root cause

java.lang.IllegalStateException: Cannot call sendError() after the response has been committed

Any suggestions what am I missing here.
Thanks in advance.

Body:
I solved this problem with another approach.
In the JwtAuthenticationFilter class we need to set authentication object in context and call chain.doFilter. Calling super.successfulAuthentication can be skipped as we have overridden the implementation.

 @Override
   protected void successfulAuthentication(HttpServletRequest request,

   HttpServletResponse response, FilterChain chain, Authentication authResult)
                throws IOException, ServletException {
            //super.successfulAuthentication(request, response, chain, authResult);
            SecurityContextHolder.getContext().setAuthentication(authResult);
            chain.doFilter(request, response);
        }

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super("/**");
        this.setAuthenticationManager(authenticationManager);
        //this.setAuthenticationSuccessHandler(new JwtAuthenticationSuccessHandler());
    }


问:
Testing whether a value is odd or even
I decided to create simple isEven and isOdd function with a very simple algorithm:

```<code>function isEven(n) {
  n = Number(n);
  return n === 0 || !!(n && !(n%2));
}

function isOdd(n) {
  return isEven(Number(n) + 1);
}
</code>```

That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.

```<code>// Returns true if:
//
//    n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string

(function (global) {

  function basicTests(n) {

    // Deal with empty string
    if (n === '')
      return false;

    // Convert n to Number (may set to NaN)
    n = Number(n);

    // Deal with NaN
    if (isNaN(n))
      return false;

    // Deal with infinity -
    if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
      return false;

    // Return n as a number
    return n;
  }

  function isEven(n) {

    // Do basic tests
    if (basicTests(n) === false)
      return false;

    // Convert to Number and proceed
    n = Number(n);

    // Return true/false
    return n === 0 || !!(n && !(n%2));
  }
  global.isEven = isEven;

  // Returns true if n is an integer and (n+1) is even
  // Returns false if n is not an integer or (n+1) is not even
  // Empty string evaluates to zero so returns false (zero is even)
  function isOdd(n) {

    // Do basic tests
    if (basicTests(n) === false)
      return false;

    // Return true/false
    return n === 0 || !!(n && (n%2));
  }
  global.isOdd = isOdd;

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

Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?

There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript.

答:
Use modulus:

```<code>function isEven(n) {
   return n % 2 == 0;
}

function isOdd(n) {
   return Math.abs(n % 2) == 1;
}
</code>```

You can check that any value in Javascript can be coerced to a number with:

```<code>Number.isFinite(parseFloat(n))
</code>```

This check should preferably be done outside the isEven and isOdd functions, so you don't have to duplicate error handling in both functions.

ContentLicense: CC BY-SA 3.0

Title: Testing whether a value is odd or even

Body:
I decided to create simple isEven and isOdd function with a very simple algorithm:

function isEven(n) {
  n = Number(n);
  return n === 0 || !!(n && !(n%2));
}

function isOdd(n) {
  return isEven(Number(n) + 1);
}

That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.

// Returns true if:
//
//    n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string

(function (global) {

  function basicTests(n) {

    // Deal with empty string
    if (n === '')
      return false;

    // Convert n to Number (may set to NaN)
    n = Number(n);

    // Deal with NaN
    if (isNaN(n))
      return false;

    // Deal with infinity -
    if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
      return false;

    // Return n as a number
    return n;
  }

  function isEven(n) {

    // Do basic tests
    if (basicTests(n) === false)
      return false;

    // Convert to Number and proceed
    n = Number(n);

    // Return true/false
    return n === 0 || !!(n && !(n%2));
  }
  global.isEven = isEven;

  // Returns true if n is an integer and (n+1) is even
  // Returns false if n is not an integer or (n+1) is not even
  // Empty string evaluates to zero so returns false (zero is even)
  function isOdd(n) {

    // Do basic tests
    if (basicTests(n) === false)
      return false;

    // Return true/false
    return n === 0 || !!(n && (n%2));
  }
  global.isOdd = isOdd;

}(this));

Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?

There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript.

Body:
Use modulus:

function isEven(n) {
   return n % 2 == 0;
}

function isOdd(n) {
   return Math.abs(n % 2) == 1;
}

You can check that any value in Javascript can be coerced to a number with:

Number.isFinite(parseFloat(n))

This check should preferably be done outside the isEven and isOdd functions, so you don't have to duplicate error handling in both functions.


问:
How to adjust TextField width?
I'm re-writing a simple app which calculates averages. However, I have a hard time with a TextField. I would like it to be exactly as on a first screenshot.

The TextField's width is stretched, I don't want that. I want it to be exactly as it is on the screenshot.

Desired look:

What I have:

Code:

import 'package:flutter/material.dart';
import 'package:easy_localization/easy_localization.dart';

class ArithmeticAverageScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('arithmetic_average_title').tr(),
      ),
      body: Container(
        padding: EdgeInsets.all(16.0),
        child: Column(
          children: <Widget>[
            Card(
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 20.0),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    ListTile(
                      leading: Icon(Icons.help),
                      title: Text('arithmetic_average_help').tr(),
                      subtitle: Text('arithmetic_average_help_content').tr(),
                    )
                  ],
                ),
              )
            ),
            SizedBox(height: 16.0),
            Card(
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 20.0),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: <Widget>[
                    Text('arithmetic_average_your_grades', style: Theme.of(context).textTheme.headline5).tr(),
                    SizedBox(height: 16.0),
                    Text('arithmetic_average_grades_one_at_a_time', style: Theme.of(context).textTheme.headline6,).tr(),
                    SizedBox(height: 16.0),
                    Text('arithmetic_average_grade', style: Theme.of(context).textTheme.subtitle2).tr(),
                    TextField()
                  ],
                ),
              ),
            )
          ],
        ),
      )
    );
  }
}
```

答:
When ever you want to play with height and width you can use the widget Container.If you want to play with a property which cannot found in the widget you are using wrap it with a widget with that property will help you.</p>

```<code>Container(
  margin: const EdgeInsets.only(right: 150),
  child: new TextField(
  decoration: new InputDecoration(
    hintText: 'Grade',
   )
  )
 )
</code>```

Title: How to adjust TextField width?

Body:
When ever you want to play with height and width you can use the widget Container.If you want to play with a property which cannot found in the widget you are using wrap it with a widget with that property will help you.

Container(
  margin: const EdgeInsets.only(right: 150),
  child: new TextField(
  decoration: new InputDecoration(
    hintText: 'Grade',
   )
  )
 )


问:
Combined form input values in component state
Need help for combining two inputs values at one state key.
When make change at Arrival date input can read the new value at data.arrivalDate and respectively when make change to Arrival time input can read it's value from data.arrivalTime.

What I want to do is, when click on the Submit button - before send the data - to combine results from both inputs in a single state field arrivesAt so to recieve string like 2020-01-01/09:05, so I don't need the old state keys data.fromDate & data.fromTime in my data object at all.

Here goes my code:
https://codesandbox.io/s/blue-tdd-xesmm?file=/src/App.js

答:
Tried this way but every time when hit the submit button gettin' previous state, not the current one. What am I missing? My code was a liitle bit messy at the begining so fixed it.

  const handleChange = event => {
    let target = event.target;
    let value = target.type === "checkbox" ? target.checked : target.value;
    let name = target.name;
    setData(previousData => ({
      ...previousData,
      [name]: value
    }));
    if (target.type == "date" || target.type == "time") {
      setData(previousData => ({
        ...previousData,
        arrivesAt: `${data.arrivalDate} & ${data.arrivalTime}`
      }));
    }
  };```


问:
regex - How to match email:password regex combination only in the first 10 lines by ignoring the rest of the long text
I'm quite new to using regex and I'm trying to match email:password combinations in a long text using regex and below is the working regex I use for my requirement and I currently have a set of long text files to look for a possible match.

```<code>[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+[*:]+(\b\w{5,}\b)
</code>```

However I wanted to know how could I match only the first 10 lines of my text. I want my regex to return a match only if there are email:password combinations in the first 10 lines and ignore the rest of the text. Any help would be appreciated.

```<code> Email : test@hotmail.com
 Password : password94
 Combo : test@hotmail.com:password94
 Plan : Premium
 Screens : 4
 HD : true
 UHD : true
 Expires in : 11-06-2019
 Country : en-PH
 NetFlix Checker | by xRisky
 Combo : test2@hotmail.com:password96
 Combo : test1@hotmail.com:password95
</code>```

For example I only want to match the first email:pass combo in the 3rd line and not the ones in line 11 and 12

答:
Assuming the text in question is being stored as a single string, you can reduce that to just the first 10 lines through a combination of splitting, splicing and joining:

```<code>my_text_reduced = "\n".join(my_text.split("\n")[:10])
</code>```

That said, you might want to fix up your regex pattern a bit; for example I can't help but notice that you haven't escaped the periods in it. The period is actually a special regex character that matches all possible characters, so your pattern would match email addresses with invalid characters in its current state. You could also replace a-zA-Z0-9_ with just \w to clean it up a little.

Body:
I'm quite new to using regex and I'm trying to match email:password combinations in a long text using regex and below is the working regex I use for my requirement and I currently have a set of long text files to look for a possible match.

[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+[*:]+(\b\w{5,}\b)

However I wanted to know how could I match only the first 10 lines of my text. I want my regex to return a match only if there are email:password combinations in the first 10 lines and ignore the rest of the text. Any help would be appreciated.

 Email : test@hotmail.com
 Password : password94
 Combo : test@hotmail.com:password94
 Plan : Premium
 Screens : 4
 HD : true
 UHD : true
 Expires in : 11-06-2019
 Country : en-PH
 NetFlix Checker | by xRisky
 Combo : test2@hotmail.com:password96
 Combo : test1@hotmail.com:password95

For example I only want to match the first email:pass combo in the 3rd line and not the ones in line 11 and 12

Body:
Assuming the text in question is being stored as a single string, you can reduce that to just the first 10 lines through a combination of splitting, splicing and joining:

my_text_reduced = "\n".join(my_text.split("\n")[:10])

That said, you might want to fix up your regex pattern a bit; for example I can't help but notice that you haven't escaped the periods in it. The period is actually a special regex character that matches all possible characters, so your pattern would match email addresses with invalid characters in its current state. You could also replace a-zA-Z0-9_ with just \w to clean it up a little.


问:
Saving object in React.useState
I have a form in my react project, and I want the value of each field to be stored in the state.
instead of having multiple states for each field, how can I store the form value as an object in the state? and more importantly how can I access it? (with react hooks)</p>

```<code>import React from 'react';

export const UserData = () => {
  return(
     <form>
        <input type="text" placeholder="Name" />
        <input type="email" placeholder="Email" />
        <button>Confirm</button>
     </form>
  )
}
</code>```

答:
React Hooks allows you to define a JavaScript Object using useState. See
https://daveceddia.com/usestate-hook-examples/

```<code>function LoginForm() {
   const [form, setState] = useState({
   username: '',
   password: ''
});
</code>```

Update the form using the function :

```<code>const updateField = e => {
    setState({
        ...form,
        [e.target.name]: e.target.value
    });
};
</code>```

Call the function onSubmit of the button

```<code><form onSubmit={updateField}>
    <input type="text" placeholder="Name" />
    <input type="email" placeholder="Email" />
    <Button >Confirm</button>
</form>
</code>```

Title: Saving object in React.useState

Body:
I have a form in my react project, and I want the value of each field to be stored in the state.
instead of having multiple states for each field, how can I store the form value as an object in the state? and more importantly how can I access it? (with react hooks)

import React from 'react';

export const UserData = () => {
  return(
     <form>
        <input type="text" placeholder="Name" />
        <input type="email" placeholder="Email" />
        <button>Confirm</button>
     </form>
  )
}

Body:
React Hooks allows you to define a JavaScript Object using useState. See
https://daveceddia.com/usestate-hook-examples/

function LoginForm() {
   const [form, setState] = useState({
   username: '',
   password: ''
});

Update the form using the function :

const updateField = e => {
    setState({
        ...form,
        [e.target.name]: e.target.value
    });
};

Call the function onSubmit of the button

<form onSubmit={updateField}>
    <input type="text" placeholder="Name" />
    <input type="email" placeholder="Email" />
    <Button >Confirm</button>
</form>


问:
Why the means are different when appending items to np.array and a list in Python
I have a code which looks like this:

```<code>list_a = []
arr = np.array([])
for _ in range(1,101):
    list_a.append(np.random.randint(1,1001,100).mean())
    arr = np.append(arr, np.random.randint(1,1001,100).mean())

print(f'casted list to np.array mean - {np.array(list_a).mean()}')
print(f'old school average - {sum(list_a)/len(list_a)}')
print(f'just arr.mean - {arr.mean()}')
print(f'first array element - {arr[0]}')
print(f'first list element - {list_a[0]}')
print(f'last arr element - {arr[99]}')
print(f'last list element - {list_a[99]}')
</code>```

This prints:

```<code>casted list to np.array mean - 498.9785
old school average - 498.97850000000005
just arr.mean - 499.5889000000001
first array element - 510.76
first list element - 518.8
last arr element - 527.54
last list element - 521.58
</code>```

Why do I get means that are not equal and why does the first and the last elements ( I am assuming the rest too ) are not equal when they are inside the same loop? Is there a difference when casting list to np.array and getting the mean vs just appending items to a np.array and getting the mean?

答:
np.random.randint() generates a new number every time you call it so it makes sense the numbers in both lists are different. If you want to add the same number to both lists, store it in a variable first and then append it to both lists:

```<code>list_a = []
arr = np.array([])
for _ in range(1,101):
    value = np.random.randint(1,1001,100).mean()
    list_a.append(value)
    arr = np.append(arr, value)

print(f'casted list to np.array mean - {np.array(list_a).mean()}')
print(f'old school average - {sum(list_a)/len(list_a)}')
print(f'just arr.mean - {arr.mean()}')
print(f'first array element - {arr[0]}')
print(f'first list element - {list_a[0]}')
print(f'last arr element - {arr[99]}')
print(f'last list element - {list_a[99]}')
</code>```

The difference between the first two averages is a difference in representation by the print() function, the values themselves only differ by 0.000000000000005.

Body:
I have a code which looks like this:

list_a = []
arr = np.array([])
for _ in range(1,101):
    list_a.append(np.random.randint(1,1001,100).mean())
    arr = np.append(arr, np.random.randint(1,1001,100).mean())

print(f'casted list to np.array mean - {np.array(list_a).mean()}')
print(f'old school average - {sum(list_a)/len(list_a)}')
print(f'just arr.mean - {arr.mean()}')
print(f'first array element - {arr[0]}')
print(f'first list element - {list_a[0]}')
print(f'last arr element - {arr[99]}')
print(f'last list element - {list_a[99]}')

This prints:

casted list to np.array mean - 498.9785
old school average - 498.97850000000005
just arr.mean - 499.5889000000001
first array element - 510.76
first list element - 518.8
last arr element - 527.54
last list element - 521.58

Why do I get means that are not equal and why does the first and the last elements ( I am assuming the rest too ) are not equal when they are inside the same loop? Is there a difference when casting list to np.array and getting the mean vs just appending items to a np.array and getting the mean?

Body:
np.random.randint() generates a new number every time you call it so it makes sense the numbers in both lists are different. If you want to add the same number to both lists, store it in a variable first and then append it to both lists:

list_a = []
arr = np.array([])
for _ in range(1,101):
    value = np.random.randint(1,1001,100).mean()
    list_a.append(value)
    arr = np.append(arr, value)

print(f'casted list to np.array mean - {np.array(list_a).mean()}')
print(f'old school average - {sum(list_a)/len(list_a)}')
print(f'just arr.mean - {arr.mean()}')
print(f'first array element - {arr[0]}')
print(f'first list element - {list_a[0]}')
print(f'last arr element - {arr[99]}')
print(f'last list element - {list_a[99]}')

The difference between the first two averages is a difference in representation by the print() function, the values themselves only differ by 0.000000000000005.


问:
Ansible copy files with wildcard?
In my files directory I have various files, with a similar name structure:

```<code>data-example.zip
data-precise.zip
data-arbitrary.zip
data-collected.zip
</code>```

I would like to transfer all of these files in the /tmp directory of my remote machine using Ansible without specifying each file name explicitly.
In other words I would like to transfer every file that stars with "data-".

What is the correct way to do that? In a similar thread, someone suggested the with_fileglob keyword, - but I couldn't get that to work.
Can someone provide me an example on how to accomplish said task?

答:
Shortly after posting the question I actually figured it out myself. The with_fileglob keyword is the way to do it.

```<code>- name: "Transferring all data files"
  copy:
    src: "{{ item }}"
    dest: /tmp/
  with_fileglob: "data-*"
</code>```

Title: Ansible copy files with wildcard?

Body:
In my files directory I have various files, with a similar name structure:

data-example.zip
data-precise.zip
data-arbitrary.zip
data-collected.zip

I would like to transfer all of these files in the /tmp directory of my remote machine using Ansible without specifying each file name explicitly.
In other words I would like to transfer every file that stars with "data-".

What is the correct way to do that? In a similar thread, someone suggested the with_fileglob keyword, - but I couldn't get that to work.
Can someone provide me an example on how to accomplish said task?

Body:
Shortly after posting the question I actually figured it out myself. The with_fileglob keyword is the way to do it.

- name: "Transferring all data files"
  copy:
    src: "{{ item }}"
    dest: /tmp/
  with_fileglob: "data-*"


问:
seaborn plot a numpy matrix with color
I want to plot a 3D matrix using the first column as the x coordinate, second as the y coordinate and the third column as the color.

So I tried it simply like this:

```<code>scat=np.matrix([[0,1,2],[10,11,12],[20,21,22]])

ax = sns.scatterplot(data=scat)
</code>```

Buf for some strange reason instead of scatterplotting it, it plots it like a line plot on the x axis from left to right (from 0 to 2) for each row of data.

So how can I plot matrices how I described using seaborn

答:
does this works?

```<code>scat  =np.array([[0,1,2],[10,11,12],[20,21,22]])
a  =scat.T
a  =pd.DataFrame({'x':a[0], 'y':a[1] , 'z':a[2]})
ax =sns.scatterplot(data=a, x='x', y='y', hue='z',palette="deep")
</code>```

edit: you can use palette , you can refer https://seaborn.pydata.org/tutorial/color_palettes.html or https://chrisalbon.com/python/data_visualization/seaborn_color_palettes/

Title: seaborn plot a numpy matrix with color

Body:
I want to plot a 3D matrix using the first column as the x coordinate, second as the y coordinate and the third column as the color.

So I tried it simply like this:

scat=np.matrix([[0,1,2],[10,11,12],[20,21,22]])

ax = sns.scatterplot(data=scat)

Buf for some strange reason instead of scatterplotting it, it plots it like a line plot on the x axis from left to right (from 0 to 2) for each row of data.

So how can I plot matrices how I described using seaborn

Body:
does this works?

scat  =np.array([[0,1,2],[10,11,12],[20,21,22]])
a  =scat.T
a  =pd.DataFrame({'x':a[0], 'y':a[1] , 'z':a[2]})
ax =sns.scatterplot(data=a, x='x', y='y', hue='z',palette="deep")

edit: you can use palette , you can refer https://seaborn.pydata.org/tutorial/color_palettes.html or https://chrisalbon.com/python/data_visualization/seaborn_color_palettes/


问:
Having hard time understanding SQL Query
I ran across this query and having hard time understanding what it does

```<code>SELECT DISTINCT
    EMPLOYEE.EMPLOYEE_ID,
    EMPLOYEE.LAST_NAME,
    EMPLOYEE.FIRST_NAME,
    COUNT(*)
FROM EMPLOYEE
JOIN ENTRY ON EMPLOYEE.EMPLOYEE_ID = ENTRY.EMPLOYEE_ID
JOIN TICKET ON ENTRY.TICKET_ID = TICKET.TICKET_ID
WHERE ENTRY.ACTIVITY_ID = 'ADVTS' AND EMPLOYEE.DEPARTMENT_ID ='SLS'
GROUP BY EMPLOYEE.EMPLOYEE_ID,  EMPLOYEE.LAST_NAME,
    EMPLOYEE.FIRST_NAME,ENTRY.ENTRY_ID
HAVING COUNT(ENTRY.ENTRY_ID) >=
(SELECT CAST(1.25 * COUNT(ENTRY.ACTIVITY_ID)/COUNT(DISTINCT EMPLOYEE.EMPLOYEE_ID) AS float)
FROM
  EMPLOYEE
JOIN
  ENTRY ON EMPLOYEE.EMPLOYEE_ID = ENTRY.EMPLOYEE_ID
WHERE
  ENTRY.ACTIVITY_ID = 'ADVTS' AND EMPLOYEE.DEPARTMENT_ID = 'SLS')
</code>```

As far as I understand it gives a list of EMPLOYEEs who done ADVTS ACTIVITY and from DEPARTMENT SLS which made ENTRYs at least as much as Average entries made in the DEPARTMENT SLS for ADVTS purposes

Thanks to anyone who take their time to help

Edit succesful result after comments:

```<code>SELECT
    EMPLOYEE.EMPLOYEE_ID,
    EMPLOYEE.LAST_NAME,
    EMPLOYEE.FIRST_NAME
    FROM EMPLOYEE
JOIN
  ENTRY ON ENTRY.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID
GROUP
   BY EMPLOYEE.EMPLOYEE_ID, EMPLOYEE.LAST_NAME,
    EMPLOYEE.FIRST_NAME
HAVING
  COUNT(ENTRY.ENTRY_ID) >=
(SELECT
  CAST(1.25 *
  COUNT(ENTRY.ACTIVITY_ID)/COUNT(DISTINCT EMPLOYEE.EMPLOYEE_ID)AS float)
FROM
  EMPLOYEE JOIN ENTRY ON EMPLOYEE.EMPLOYEE_ID = ENTRY.EMPLOYEE_ID
WHERE
  ENTRY.ACTIVITY_ID = 'ADVTS' AND EMPLOYEE.DEPARTMENT_ID = 'SLS')
</code>```

OUTPUT:

```<code>EMPLOYEE_ID| LAST_NAME| FIRST_NAME
7          | Salesman | Efficient
</code>```

答:
Assuming that TICKET_ID is unique in Ticket and is never NULL in ENTRY, then you can get rid of that JOIN.

Then I assume the purpose of the query is to return employees whose count is more than 1.25 the overall average.  That requires a few more (reasonable) assumptions, but this is more simply written as:

```<code>SELECT e.*
FROM (SELECT EM.EMPLOYEE_ID, EM.LAST_NAME, EM.FIRST_NAME, COUNT(*) AS CNT,
             SUM(COUNT(*)) OVER () * 1.0 / COUNT(*) OVER () as AVG_CNT
      FROM EMPLOYEE EM JOIN
           ENTRY EM
           ON EM.EMPLOYEE_ID = EN.EMPLOYEE_ID
      WHERE EN.ACTIVITY_ID = 'ADVTS' AND EM.DEPARTMENT_ID = 'SLS'
      GROUP BY EM.EMPLOYEE_ID, EM.LAST_NAME, EM.FIRST_NAME
     ) e
WHERE cnt >= 1.25 * avg_cnt
</code>```

Body:
I ran across this query and having hard time understanding what it does

SELECT DISTINCT
    EMPLOYEE.EMPLOYEE_ID,
    EMPLOYEE.LAST_NAME,
    EMPLOYEE.FIRST_NAME,
    COUNT(*)
FROM EMPLOYEE
JOIN ENTRY ON EMPLOYEE.EMPLOYEE_ID = ENTRY.EMPLOYEE_ID
JOIN TICKET ON ENTRY.TICKET_ID = TICKET.TICKET_ID
WHERE ENTRY.ACTIVITY_ID = 'ADVTS' AND EMPLOYEE.DEPARTMENT_ID ='SLS'
GROUP BY EMPLOYEE.EMPLOYEE_ID,  EMPLOYEE.LAST_NAME,
    EMPLOYEE.FIRST_NAME,ENTRY.ENTRY_ID
HAVING COUNT(ENTRY.ENTRY_ID) >=
(SELECT CAST(1.25 * COUNT(ENTRY.ACTIVITY_ID)/COUNT(DISTINCT EMPLOYEE.EMPLOYEE_ID) AS float)
FROM
  EMPLOYEE
JOIN
  ENTRY ON EMPLOYEE.EMPLOYEE_ID = ENTRY.EMPLOYEE_ID
WHERE
  ENTRY.ACTIVITY_ID = 'ADVTS' AND EMPLOYEE.DEPARTMENT_ID = 'SLS')

As far as I understand it gives a list of EMPLOYEEs who done ADVTS ACTIVITY and from DEPARTMENT SLS which made ENTRYs at least as much as Average entries made in the DEPARTMENT SLS for ADVTS purposes

Thanks to anyone who take their time to help

Edit succesful result after comments:

SELECT
    EMPLOYEE.EMPLOYEE_ID,
    EMPLOYEE.LAST_NAME,
    EMPLOYEE.FIRST_NAME
    FROM EMPLOYEE
JOIN
  ENTRY ON ENTRY.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID
GROUP
   BY EMPLOYEE.EMPLOYEE_ID, EMPLOYEE.LAST_NAME,
    EMPLOYEE.FIRST_NAME
HAVING
  COUNT(ENTRY.ENTRY_ID) >=
(SELECT
  CAST(1.25 *
  COUNT(ENTRY.ACTIVITY_ID)/COUNT(DISTINCT EMPLOYEE.EMPLOYEE_ID)AS float)
FROM
  EMPLOYEE JOIN ENTRY ON EMPLOYEE.EMPLOYEE_ID = ENTRY.EMPLOYEE_ID
WHERE
  ENTRY.ACTIVITY_ID = 'ADVTS' AND EMPLOYEE.DEPARTMENT_ID = 'SLS')

OUTPUT:

EMPLOYEE_ID| LAST_NAME| FIRST_NAME
7          | Salesman | Efficient

Body:
Assuming that TICKET_ID is unique in Ticket and is never NULL in ENTRY, then you can get rid of that JOIN.

Then I assume the purpose of the query is to return employees whose count is more than 1.25 the overall average.  That requires a few more (reasonable) assumptions, but this is more simply written as:

SELECT e.*
FROM (SELECT EM.EMPLOYEE_ID, EM.LAST_NAME, EM.FIRST_NAME, COUNT(*) AS CNT,
             SUM(COUNT(*)) OVER () * 1.0 / COUNT(*) OVER () as AVG_CNT
      FROM EMPLOYEE EM JOIN
           ENTRY EM
           ON EM.EMPLOYEE_ID = EN.EMPLOYEE_ID
      WHERE EN.ACTIVITY_ID = 'ADVTS' AND EM.DEPARTMENT_ID = 'SLS'
      GROUP BY EM.EMPLOYEE_ID, EM.LAST_NAME, EM.FIRST_NAME
     ) e
WHERE cnt >= 1.25 * avg_cnt


问:
mysql query: how to get the number of yes/no votes per day
I have to create a mysql query to get a voting distribution of each day exceeding a particular date, something like this...

```<code>    date          yes_votes    no_votes
------------------------------------------
    2010-01-07    21           22
    2010-01-07    2            0
</code>```

My table is like this..

```<code>    post_votes
--------------------------
    id(longint)
    date(timestamp)
    flag(tinyint) // this stores the yes/no votes 1-yes, 2-no
</code>```

I am stuck at this....

```<code>SELECT COUNT(*) AS count, DATE(date) FROM post_votes WHERE date > '2010-07-01' GROUP BY DATE(date)
</code>```

this gives the total number of votes per day, but not the distribution that I want.

答:
```<code>SELECT DATE(date) as dt,
sum(if(flag=1,1,0)) as yes,
sum(if(flag=2,1,0)) as no
FROM post_votes WHERE date > '2010-07-01'
GROUP BY dt
</code>```

Body:
I have to create a mysql query to get a voting distribution of each day exceeding a particular date, something like this...

    date          yes_votes    no_votes
------------------------------------------
    2010-01-07    21           22
    2010-01-07    2            0

My table is like this..

    post_votes
--------------------------
    id(longint)
    date(timestamp)
    flag(tinyint) // this stores the yes/no votes 1-yes, 2-no

I am stuck at this....

SELECT COUNT(*) AS count, DATE(date) FROM post_votes WHERE date > '2010-07-01' GROUP BY DATE(date)

this gives the total number of votes per day, but not the distribution that I want.


问:
how to download/create pdf through webview in flutter
I have created a webviewscaffold but can't download anything from it while browsing from the webview, I made but when I click the button it does nothing. I don't know where to start, like in other browsers that can download and preview, I'm trying to achieve the same thing in here.

```<code>class AppState extends State<App> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          Align(
            alignment: Alignment(1, 1),
            child: Container(
              child: Web(), // it is a statefulwidget that have WebviewScaffold, i have created it on a new page and imported/used here
            ),
          ),
          Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              Padding(
                padding: EdgeInsets.only(top: 20.0),
              )
            ],
          ),
          Align(
            alignment: Alignment(0.7, -0.93),
            child: FloatingActionButton(
                tooltip: "Share",
                child: Icon(
                  Icons.share,
                  color: Colors.amberAccent,
                ),
                onPressed: () {
                  _onShareTap();
                }),
          ),
        ],
      ),
    );
  }
</code>```

I expect, when I click the print or download button within the webview it should work like any other browser.

答:
You can use my plugin flutter_inappwebview, which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews.

To be able to recognize downloadable files, you need to set the useOnDownloadStart: true option, and then you can listen the onDownloadStart event!

Also, for example, on Android you need to add write permission inside your AndroidManifest.xml file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
```

<p>Then, you need to ask permission using the permission_handler plugin. Instead, to effectively download your file, you can use the flutter_downloader plugin.</p>

<p>Here is a complete example using http://ovh.net/files/ (in particular, the http://ovh.net/files/1Mio.dat as URL) to test the download:</p>

<pre class="lang-dart prettyprint-override"><code>import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await FlutterDownloader.initialize(
      debug: true // optional: set false to disable printing logs to console
  );
  await Permission.storage.request();
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
          Expanded(
              child: InAppWebView(
            initialUrl: "http://ovh.net/files/1Mio.dat",
            initialHeaders: {},
            initialOptions: InAppWebViewGroupOptions(
              crossPlatform: InAppWebViewOptions(
                debuggingEnabled: true,
                useOnDownloadStart: true
              ),
            ),
            onWebViewCreated: (InAppWebViewController controller) {
              webView = controller;
            },
            onLoadStart: (InAppWebViewController controller, String url) {

            },
            onLoadStop: (InAppWebViewController controller, String url) {

            },
            onDownloadStart: (controller, url) async {
              print("onDownloadStart $url");
              final taskId = await FlutterDownloader.enqueue(
                url: url,
                savedDir: (await getExternalStorageDirectory()).path,
                showNotification: true, // show download progress in status bar (for Android)
                openFileFromNotification: true, // click on notification to open downloaded file (for Android)
              );
            },
          ))
        ])),
      ),
    );
  }
}
</code>```

Here, as you can see, I'm using also the path_provider plugin to get the folder where I want to save the file.

Body:
I have created a webviewscaffold but can't download anything from it while browsing from the webview, I made but when I click the button it does nothing. I don't know where to start, like in other browsers that can download and preview, I'm trying to achieve the same thing in here.

class AppState extends State<App> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          Align(
            alignment: Alignment(1, 1),
            child: Container(
              child: Web(), // it is a statefulwidget that have WebviewScaffold, i have created it on a new page and imported/used here
            ),
          ),
          Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              Padding(
                padding: EdgeInsets.only(top: 20.0),
              )
            ],
          ),
          Align(
            alignment: Alignment(0.7, -0.93),
            child: FloatingActionButton(
                tooltip: "Share",
                child: Icon(
                  Icons.share,
                  color: Colors.amberAccent,
                ),
                onPressed: () {
                  _onShareTap();
                }),
          ),
        ],
      ),
    );
  }

I expect, when I click the print or download button within the webview it should work like any other browser.

Body:
You can use my plugin flutter_inappwebview, which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews.

To be able to recognize downloadable files, you need to set the useOnDownloadStart: true option, and then you can listen the onDownloadStart event!

Also, for example, on Android you need to add write permission inside your AndroidManifest.xml file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Then, you need to ask permission using the permission_handler plugin. Instead, to effectively download your file, you can use the flutter_downloader plugin.

Here is a complete example using http://ovh.net/files/ (in particular, the http://ovh.net/files/1Mio.dat as URL) to test the download:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await FlutterDownloader.initialize(
      debug: true // optional: set false to disable printing logs to console
  );
  await Permission.storage.request();
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
          Expanded(
              child: InAppWebView(
            initialUrl: "http://ovh.net/files/1Mio.dat",
            initialHeaders: {},
            initialOptions: InAppWebViewGroupOptions(
              crossPlatform: InAppWebViewOptions(
                debuggingEnabled: true,
                useOnDownloadStart: true
              ),
            ),
            onWebViewCreated: (InAppWebViewController controller) {
              webView = controller;
            },
            onLoadStart: (InAppWebViewController controller, String url) {

            },
            onLoadStop: (InAppWebViewController controller, String url) {

            },
            onDownloadStart: (controller, url) async {
              print("onDownloadStart $url");
              final taskId = await FlutterDownloader.enqueue(
                url: url,
                savedDir: (await getExternalStorageDirectory()).path,
                showNotification: true, // show download progress in status bar (for Android)
                openFileFromNotification: true, // click on notification to open downloaded file (for Android)
              );
            },
          ))
        ])),
      ),
    );
  }
}

Here, as you can see, I'm using also the path_provider plugin to get the folder where I want to save the file.


问:
Oracle-Trigger for testing the number of students in a class
I am trying to create a before insert trigger which restricts the number of students in a group, I mean, if the number of students in a group is greater than 5, the user can't introduce any other record in this same group but he can in others where there are less than 5 students.

In the table I have this information:

So the trigger should let adding records in all of the rows except into the second one because there are already 5 students there.

I tried the following code:

```<code>create or replace trigger groups_capacity
 before insert on s183410_group
  for each row

  declare
   counter INTEGER;

 BEGIN
    select count(*)into counter from s183410_group group by class_id;

        if counter>5 and :old.class_id=:new.class_id then
            raise_application_error(-20002,'This class is full.There cannot be more than 5 students in the same group.');
        end if;

END;
</code>```

I think that the counter does not change it value for each row. I am new in oracle and don't know really how to use it.

Thank you very much in advance!!

答:
You need to use a Statement Trigger,  in which to check whether any of the groups by class_id violates the rule, but not a Row Level Trigger in order not to get mutating trigger error :

```<code>CREATE OR REPLACE TRIGGER groups_capacity
  AFTER INSERT ON s183410_group

DECLARE
  counter INT;
BEGIN
  SELECT MAX(COUNT(*)) INTO counter FROM s183410_group GROUP BY class_id;

  IF counter > 5 THEN
    raise_application_error(-20002,
                            'This class is full.
                             There cannot be more than 5 students in the same group.');
  END IF;
END;
</code>```

Body:
I am trying to create a before insert trigger which restricts the number of students in a group, I mean, if the number of students in a group is greater than 5, the user can't introduce any other record in this same group but he can in others where there are less than 5 students.

In the table I have this information:

So the trigger should let adding records in all of the rows except into the second one because there are already 5 students there.

I tried the following code:

create or replace trigger groups_capacity
 before insert on s183410_group
  for each row

  declare
   counter INTEGER;

 BEGIN
    select count(*)into counter from s183410_group group by class_id;

        if counter>5 and :old.class_id=:new.class_id then
            raise_application_error(-20002,'This class is full.There cannot be more than 5 students in the same group.');
        end if;

END;

I think that the counter does not change it value for each row. I am new in oracle and don't know really how to use it.

Thank you very much in advance!!

Body:
You need to use a Statement Trigger,  in which to check whether any of the groups by class_id violates the rule, but not a Row Level Trigger in order not to get mutating trigger error :

CREATE OR REPLACE TRIGGER groups_capacity
  AFTER INSERT ON s183410_group

DECLARE
  counter INT;
BEGIN
  SELECT MAX(COUNT(*)) INTO counter FROM s183410_group GROUP BY class_id;

  IF counter > 5 THEN
    raise_application_error(-20002,
                            'This class is full.
                             There cannot be more than 5 students in the same group.');
  END IF;
END;