问:
WSO2 IoT 3.1.0 failed to retreive oauth token using jwt error
I am installing WSO2 IOT Server 3.1.0 on a server. I just want to run it with default basic configurations. After Uploading to my server, I configured it to run with the IP using the script as mentioned in this link.

After running the script, I ran the broker and the iotserver profiles. I am able to log in the API store and publisher but when I tries to log in the devicemgt web console. I am getting the following error.

Error Snapshot:

Exception In Logs:

```<code>An exception thrown when executing the script '/app/modules/login.js'. {auth-module}
TID: [-1234] [] [2017-12-04 00:32:43,944] ERROR {auth-module} -  org.wso2.carbon.apimgt.integration.client.exception.APIMClientOAuthException: failed to retrieve oauth token using jwt {auth-module}
org.mozilla.javascript.WrappedException: Wrapped org.wso2.carbon.apimgt.integration.client.exception.APIMClientOAuthException: failed to retrieve oauth token using jwt (/devicemgt/app/modules/login.js#31)
    at org.mozilla.javascript.Context.throwAsScriptRuntimeEx(Context.java:1754)
    at org.mozilla.javascript.MemberBox.invoke(MemberBox.java:148)
    at org.mozilla.javascript.NativeJavaMethod.call(NativeJavaMethod.java:225)
    at org.mozilla.javascript.optimizer.OptRuntime.callProp0(OptRuntime.java:85)
    at org.jaggeryjs.rhino.devicemgt.app.modules.c3._c_anonymous_2(/devicemgt/app/modules/login.js:31)
    at org.jaggeryjs.rhino.devicemgt.app.modules.c3.call(/devicemgt/app/modules/login.js)
    at org.mozilla.javascript.optimizer.OptRuntime.call1(OptRuntime.java:32)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c0._c_executeScript_10(/devicemgt/lib/modules/auth/auth.js:234)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c0.call(/devicemgt/lib/modules/auth/auth.js)
    at org.mozilla.javascript.optimizer.OptRuntime.callName(OptRuntime.java:63)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c0._c_handleEvent_11(/devicemgt/lib/modules/auth/auth.js:259)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c0.call(/devicemgt/lib/modules/auth/auth.js)
    at org.mozilla.javascript.optimizer.OptRuntime.callName(OptRuntime.java:63)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c0._c_anonymous_20(/devicemgt/lib/modules/auth/auth.js:547)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c0.call(/devicemgt/lib/modules/auth/auth.js)
    at org.mozilla.javascript.optimizer.OptRuntime.call2(OptRuntime.java:42)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c2._c_anonymous_1(/devicemgt/lib/modules/auth/acs.jag:34)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c2.call(/devicemgt/lib/modules/auth/acs.jag)
    at org.mozilla.javascript.optimizer.OptRuntime.call0(OptRuntime.java:23)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c2._c_script_0(/devicemgt/lib/modules/auth/acs.jag:22)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c2.call(/devicemgt/lib/modules/auth/acs.jag)
    at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:394)
    at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3091)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c2.call(/devicemgt/lib/modules/auth/acs.jag)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c2.exec(/devicemgt/lib/modules/auth/acs.jag)
    at org.jaggeryjs.scriptengine.engine.RhinoEngine.execScript(RhinoEngine.java:567)
    at org.jaggeryjs.scriptengine.engine.RhinoEngine.exec(RhinoEngine.java:273)
    at org.jaggeryjs.jaggery.core.manager.WebAppManager.exec(WebAppManager.java:588)
    at org.jaggeryjs.jaggery.core.manager.WebAppManager.execute(WebAppManager.java:508)
    at org.jaggeryjs.jaggery.core.JaggeryServlet.doPost(JaggeryServlet.java:29)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:747)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:485)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:377)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:337)
    at org.jaggeryjs.jaggery.core.JaggeryFilter.doFilter(JaggeryFilter.java:21)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter.doFilter(ContentTypeBasedCachePreventionFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.owasp.csrfguard.CsrfGuardFilter.doFilter(CsrfGuardFilter.java:88)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.filters.HttpHeaderSecurityFilter.doFilter(HttpHeaderSecurityFilter.java:120)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:99)
    at org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
    at org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:57)
    at org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticationValve.invoke(WebappAuthenticationValve.java:45)
    at org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
    at org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:62)
    at org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:159)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
    at org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:57)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1087)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1760)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1719)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.wso2.carbon.apimgt.integration.client.exception.APIMClientOAuthException: failed to retrieve oauth token using jwt
    at org.wso2.carbon.apimgt.integration.client.OAuthRequestInterceptor.apply(OAuthRequestInterceptor.java:118)
    at feign.SynchronousMethodHandler.targetRequest(SynchronousMethodHandler.java:158)
    at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:88)
    at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:76)
    at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:103)
    at com.sun.proxy.$Proxy38.tiersTierLevelTierNameGet(Unknown Source)
    at org.wso2.carbon.apimgt.application.extension.APIManagementProviderServiceImpl.isTierLoaded(APIManagementProviderServiceImpl.java:56)
    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.mozilla.javascript.MemberBox.invoke(MemberBox.java:126)
    ... 75 more
Caused by: org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException: Error when parsing the response <am:fault xmlns:am="http://wso2.org/apimanager"><am:code>101500</am:code><am:type>Status report</am:type><am:message>Runtime Error</am:message><am:description>Error in Sender</am:description></am:fault>
    at org.wso2.carbon.identity.jwt.client.extension.JWTClient.getTokenInfo(JWTClient.java:169)
    at org.wso2.carbon.identity.jwt.client.extension.JWTClient.getAccessToken(JWTClient.java:79)
    at org.wso2.carbon.apimgt.integration.client.OAuthRequestInterceptor.apply(OAuthRequestInterceptor.java:99)
    ... 86 more
Caused by: Unexpected character (<) at position 0.
    at org.json.simple.parser.Yylex.yylex(Unknown Source)
    at org.json.simple.parser.JSONParser.nextToken(Unknown Source)
    at org.json.simple.parser.JSONParser.parse(Unknown Source)
    at org.json.simple.parser.JSONParser.parse(Unknown Source)
    at org.json.simple.parser.JSONParser.parse(Unknown Source)
    at org.wso2.carbon.identity.jwt.client.extension.JWTClient.getTokenInfo(JWTClient.java:153)
    ... 88 more
</code>```

Can anybody help pointing out what is going wrong and what is happening?

答:
Are you using the same IP as the one you entered when asked for the common name when running the change IP script, to access the server?

Appreciate if you could add here the entire log for server startup. That way we would be able to figure out what exactly is causing the problem.

Body:
I am installing WSO2 IOT Server 3.1.0 on a server. I just want to run it with default basic configurations. After Uploading to my server, I configured it to run with the IP using the script as mentioned in this link.

After running the script, I ran the broker and the iotserver profiles. I am able to log in the API store and publisher but when I tries to log in the devicemgt web console. I am getting the following error.

Error Snapshot:

Exception In Logs:

An exception thrown when executing the script '/app/modules/login.js'. {auth-module}
TID: [-1234] [] [2017-12-04 00:32:43,944] ERROR {auth-module} -  org.wso2.carbon.apimgt.integration.client.exception.APIMClientOAuthException: failed to retrieve oauth token using jwt {auth-module}
org.mozilla.javascript.WrappedException: Wrapped org.wso2.carbon.apimgt.integration.client.exception.APIMClientOAuthException: failed to retrieve oauth token using jwt (/devicemgt/app/modules/login.js#31)
    at org.mozilla.javascript.Context.throwAsScriptRuntimeEx(Context.java:1754)
    at org.mozilla.javascript.MemberBox.invoke(MemberBox.java:148)
    at org.mozilla.javascript.NativeJavaMethod.call(NativeJavaMethod.java:225)
    at org.mozilla.javascript.optimizer.OptRuntime.callProp0(OptRuntime.java:85)
    at org.jaggeryjs.rhino.devicemgt.app.modules.c3._c_anonymous_2(/devicemgt/app/modules/login.js:31)
    at org.jaggeryjs.rhino.devicemgt.app.modules.c3.call(/devicemgt/app/modules/login.js)
    at org.mozilla.javascript.optimizer.OptRuntime.call1(OptRuntime.java:32)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c0._c_executeScript_10(/devicemgt/lib/modules/auth/auth.js:234)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c0.call(/devicemgt/lib/modules/auth/auth.js)
    at org.mozilla.javascript.optimizer.OptRuntime.callName(OptRuntime.java:63)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c0._c_handleEvent_11(/devicemgt/lib/modules/auth/auth.js:259)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c0.call(/devicemgt/lib/modules/auth/auth.js)
    at org.mozilla.javascript.optimizer.OptRuntime.callName(OptRuntime.java:63)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c0._c_anonymous_20(/devicemgt/lib/modules/auth/auth.js:547)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c0.call(/devicemgt/lib/modules/auth/auth.js)
    at org.mozilla.javascript.optimizer.OptRuntime.call2(OptRuntime.java:42)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c2._c_anonymous_1(/devicemgt/lib/modules/auth/acs.jag:34)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c2.call(/devicemgt/lib/modules/auth/acs.jag)
    at org.mozilla.javascript.optimizer.OptRuntime.call0(OptRuntime.java:23)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c2._c_script_0(/devicemgt/lib/modules/auth/acs.jag:22)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c2.call(/devicemgt/lib/modules/auth/acs.jag)
    at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:394)
    at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3091)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c2.call(/devicemgt/lib/modules/auth/acs.jag)
    at org.jaggeryjs.rhino.devicemgt.lib.modules.auth.c2.exec(/devicemgt/lib/modules/auth/acs.jag)
    at org.jaggeryjs.scriptengine.engine.RhinoEngine.execScript(RhinoEngine.java:567)
    at org.jaggeryjs.scriptengine.engine.RhinoEngine.exec(RhinoEngine.java:273)
    at org.jaggeryjs.jaggery.core.manager.WebAppManager.exec(WebAppManager.java:588)
    at org.jaggeryjs.jaggery.core.manager.WebAppManager.execute(WebAppManager.java:508)
    at org.jaggeryjs.jaggery.core.JaggeryServlet.doPost(JaggeryServlet.java:29)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:747)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:485)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:377)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:337)
    at org.jaggeryjs.jaggery.core.JaggeryFilter.doFilter(JaggeryFilter.java:21)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter.doFilter(ContentTypeBasedCachePreventionFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.owasp.csrfguard.CsrfGuardFilter.doFilter(CsrfGuardFilter.java:88)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.filters.HttpHeaderSecurityFilter.doFilter(HttpHeaderSecurityFilter.java:120)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:99)
    at org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
    at org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:57)
    at org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticationValve.invoke(WebappAuthenticationValve.java:45)
    at org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
    at org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:62)
    at org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:159)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
    at org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:57)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1087)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1760)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1719)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.wso2.carbon.apimgt.integration.client.exception.APIMClientOAuthException: failed to retrieve oauth token using jwt
    at org.wso2.carbon.apimgt.integration.client.OAuthRequestInterceptor.apply(OAuthRequestInterceptor.java:118)
    at feign.SynchronousMethodHandler.targetRequest(SynchronousMethodHandler.java:158)
    at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:88)
    at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:76)
    at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:103)
    at com.sun.proxy.$Proxy38.tiersTierLevelTierNameGet(Unknown Source)
    at org.wso2.carbon.apimgt.application.extension.APIManagementProviderServiceImpl.isTierLoaded(APIManagementProviderServiceImpl.java:56)
    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.mozilla.javascript.MemberBox.invoke(MemberBox.java:126)
    ... 75 more
Caused by: org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException: Error when parsing the response <am:fault xmlns:am="http://wso2.org/apimanager"><am:code>101500</am:code><am:type>Status report</am:type><am:message>Runtime Error</am:message><am:description>Error in Sender</am:description></am:fault>
    at org.wso2.carbon.identity.jwt.client.extension.JWTClient.getTokenInfo(JWTClient.java:169)
    at org.wso2.carbon.identity.jwt.client.extension.JWTClient.getAccessToken(JWTClient.java:79)
    at org.wso2.carbon.apimgt.integration.client.OAuthRequestInterceptor.apply(OAuthRequestInterceptor.java:99)
    ... 86 more
Caused by: Unexpected character (<) at position 0.
    at org.json.simple.parser.Yylex.yylex(Unknown Source)
    at org.json.simple.parser.JSONParser.nextToken(Unknown Source)
    at org.json.simple.parser.JSONParser.parse(Unknown Source)
    at org.json.simple.parser.JSONParser.parse(Unknown Source)
    at org.json.simple.parser.JSONParser.parse(Unknown Source)
    at org.wso2.carbon.identity.jwt.client.extension.JWTClient.getTokenInfo(JWTClient.java:153)
    ... 88 more

Can anybody help pointing out what is going wrong and what is happening?


来源: stackexchange

问:
PHP-invoked python script cannot write
I've set up a small web app that passes user data to a python script. Python is supposed to go to work, create a file on the webserver, and allow the user to download it. However, the script execution seems to stop where the Python write() command is issued.

Python:

```<code>print("Writing to '" + filename + "'")
f = open('backups/' + filename, 'w')
f.write(self.output())
f.close()
print("Done!")
</code>```

PHP:

```<code>$user = escapeshellarg($_POST['user']);
$password = escapeshellarg($_POST['password']);
$command = './backup.py '.$user.' '.$password;
print(exec($command));
</code>```

Actual result:

Python does create a file in the desired directory but it remains empty. 2. Python never outputs "Done!" (Because permissions are denied)

Expected result:

Python creates a file with data

Python proceeds to print "Done!" which is output to the calling PHP script

I've done the following:

www-data has group write permissions (drwxrwsr-x) for the directory ./backup

The #!/usr/bin/env python3 shebang is present in the python file

The python file is executable

When I change to user www-data with sudo su www-data and then start the php commandline, and enter the above command invoking my Python script, the file is created correctly!

If I start a builtin php server, it also works fine, only if the php script is handled through apache, it doesn't work

答:
I have officially wasted an entire day of my life on this.

The permissions were all right.
What was happening is that the python script failed ONLY if it was being invoked through my php script and ONLY if that was being served by Apache.

Looking through the Apache error log revealed that the python script failed because it could not write bytes to the file and ascii conversion failed because there was unicode data in the output.

So doing f = open(filename, 'wb') solved the issue.

This behaviour was not observed on my development machine or through the built-in PHP server. Still wonder why there's a difference in file handling. Would appreciate an answer if anyone has one.

ContentLicense: CC BY-SA 3.0

Title: PHP-invoked python script cannot write

Body:
I've set up a small web app that passes user data to a python script. Python is supposed to go to work, create a file on the webserver, and allow the user to download it. However, the script execution seems to stop where the Python write() command is issued.

Python:

print("Writing to '" + filename + "'")
f = open('backups/' + filename, 'w')
f.write(self.output())
f.close()
print("Done!")

PHP:

$user = escapeshellarg($_POST['user']);
$password = escapeshellarg($_POST['password']);
$command = './backup.py '.$user.' '.$password;
print(exec($command));

Actual result:

Python does create a file in the desired directory but it remains empty. 2. Python never outputs "Done!" (Because permissions are denied)

Expected result:

Python creates a file with data

Python proceeds to print "Done!" which is output to the calling PHP script

I've done the following:

www-data has group write permissions (drwxrwsr-x) for the directory ./backup

The #!/usr/bin/env python3 shebang is present in the python file

The python file is executable

When I change to user www-data with sudo su www-data and then start the php commandline, and enter the above command invoking my Python script, the file is created correctly!

If I start a builtin php server, it also works fine, only if the php script is handled through apache, it doesn't work


问:
How to share entity between REST service between two microservices?
I have created two micro-services using java. I need to make a REST api call from service A to service B. The data sent will be in JSON format. Using jax-rs I need to create entity class in both the service.

Since both the entity class be same in both the projects. Do i

Create an common jar and use is for all my entity/domain objects? Does this make my microservice more tightly coupled?

Do i create the same class in both the microservice projects? This will just mean repeating the work in both the projects?

Is there a better way to communicate between the sevices?

答:
This is common situation where we as developer gets confused. I would suggest to have a common jar(shared) which can be used in both micro services (A and B). It is nothing but sharing a third resource as we use third-party libraries.
In my current project we were in the same situation and we found the best approach to have separate shared libraries(api-shared as name) and consuming it as jar in different micro-services.

In your second approach you ended up with redundant code and also difficult to maintain. Lets say if you have any changes in entity then you have to change in both the entities which is not quite a good way to synchronize the thing.

All in all I would suggest you to use shared jar for both micro services.

Regards

Techno


问:
MongoDB: Find array element which having some value?
```<code>{
"_id" : ObjectId("55caf0298c1c44740469306c"),
"data" : {
    "field" : {
        "fields" : [
            {
                "name" : "demo",
                "type" : "data",
                "value" : "A"
            }
        ]
    }
}
</code>```

}

I want Only those Array element should come where value=A, rest is blank so it should not show.

Desire Output:

```<code>{
    "_id" : ObjectId("55caef098c1c447404693064"),
    "data" : {
        "field" : {
            "fields" : [
                {
                    "value" : "A"
                }
            ]
        }
    }
}
</code>```

And also after finding all values in document I want to modify those values.

Note: value=A is not always first element ,it can be 2nd 3rd element.And in each document "value" : "A" is not not fixed it can be different like "value" : "B", only i want those document where value key is having value and where its blank it should not show.

Query:

```<code>db.getCollection('collection').aggregate([
    {$match: {'data.field.fields.name': 'demo'}},
    { "$project": {
        "_id": 0,
        "value": { "$arrayElemAt": ["$data.field.fields.value", 0] }

    }}
])
</code>```

Now i want to update the value .How can I update?

答:
```<code>db.collection.find({
    'data.field.fields': {
        $elemMatch: {
            value: 'A'
        }
    }
}, {
    'data.field.fields.$': 1
})
</code>```

Body:
{
"_id" : ObjectId("55caf0298c1c44740469306c"),
"data" : {
    "field" : {
        "fields" : [
            {
                "name" : "demo",
                "type" : "data",
                "value" : "A"
            }
        ]
    }
}

}

I want Only those Array element should come where value=A, rest is blank so it should not show.

Desire Output:

{
    "_id" : ObjectId("55caef098c1c447404693064"),
    "data" : {
        "field" : {
            "fields" : [
                {
                    "value" : "A"
                }
            ]
        }
    }
}

And also after finding all values in document I want to modify those values.

Note: value=A is not always first element ,it can be 2nd 3rd element.And in each document "value" : "A" is not not fixed it can be different like "value" : "B", only i want those document where value key is having value and where its blank it should not show.

Query:

db.getCollection('collection').aggregate([
    {$match: {'data.field.fields.name': 'demo'}},
    { "$project": {
        "_id": 0,
        "value": { "$arrayElemAt": ["$data.field.fields.value", 0] }

    }}
])

Now i want to update the value .How can I update?


问:
String changing in function unexpectedly
I was playing around with stacks to understand the concept and implementation better and I stumbled upon a weird bug. I'm passing a string into a function, breaking down the string into individual char's and adding them to a stack, but when I printed the stack it was not the data I entered.

I fixed the bug (I commented it out to recreate the error) but i'm curious as to why this was happening, the miss matched output was constant and never changed.

```<code>#include "stack.h"
#include <string>
#include <iostream>

using namespace std;

void bracketCheck(const std::string& s){
    Stack<char> stack;

    // this works as expected:

    /*for (auto i = s.begin(); i != s.end(); i++){
        stack.push(*i);
        cout << stack.top() << endl;
    }*/

    //this gives a jumbled outout:

    for (auto i = s.front(); i != s.back(); i++){
        stack.push(i);
        cout << stack.top() << endl;
    }
}

void main(){
    string a = "stanley";
    bracketCheck(a);
    system("pause");
}
</code>```

stack.h:

```<code>#include <list>

using namespace std;
template<class T>

class Stack{
private:
    list<T> data_;
public:
    Stack(){}
    void push(const T& data){
        //v1
        data_.push_front(data);
    }
    T top() const{
        list<T>::const_iterator it = data_.begin();
        return *it;
    }
};
</code>```

the output i'm getting:

```<code>s
t
u
v
w
x
</code>```

答:
The string::front() function returns a reference to the actual character at the front of the string. By looping with for (auto i = s.front(); i != s.back(); i++), you're actually incrementing the contents of the string itself, not looping over indices of the string.

Pretty hilarious, actually. You're very lucky that incrementing s 6 times ends up at y, which just so happens to be the last character of the string you actually use. So the break-condition of the for-loop (i != s.back()) just so happens to be met. Lucky break. If the string had been pretty much anything else, you'd get a much more nasty crash.

Body:
I was playing around with stacks to understand the concept and implementation better and I stumbled upon a weird bug. I'm passing a string into a function, breaking down the string into individual char's and adding them to a stack, but when I printed the stack it was not the data I entered.

I fixed the bug (I commented it out to recreate the error) but i'm curious as to why this was happening, the miss matched output was constant and never changed.

#include "stack.h"
#include <string>
#include <iostream>

using namespace std;

void bracketCheck(const std::string& s){
    Stack<char> stack;

    // this works as expected:

    /*for (auto i = s.begin(); i != s.end(); i++){
        stack.push(*i);
        cout << stack.top() << endl;
    }*/

    //this gives a jumbled outout:

    for (auto i = s.front(); i != s.back(); i++){
        stack.push(i);
        cout << stack.top() << endl;
    }
}

void main(){
    string a = "stanley";
    bracketCheck(a);
    system("pause");
}

stack.h:

#include <list>

using namespace std;
template<class T>

class Stack{
private:
    list<T> data_;
public:
    Stack(){}
    void push(const T& data){
        //v1
        data_.push_front(data);
    }
    T top() const{
        list<T>::const_iterator it = data_.begin();
        return *it;
    }
};

the output i'm getting:

s
t
u
v
w
x


问:
ScrollView unable to display image which passed from another VC
I need to display the image pass in from the another ViewController

first,I have tested using only ImageView to display the image and it works as below:

Thanks. Your help is greatly appreciated.

```<code>class ViewController: UIViewController, UIScrollViewDelegate {

    @IBOutlet weak var TempImgView: UIImgeView!
    var passInImg: UIImage?

    override func viewDidLoad() {

        super.viewDidLoad()

       TempImgView.image = passInImg!

   }
</code>```

When I use UIScrollView ( for scrolling the large passInImg) , below code not working

Probelm:

error : fatal error: unexpectedly found nil while unwrapping an
  optional value

But I have tested the pass in image  in the above code.

what need to be done with the scrollView?

Should be used in viewDidLoad?

class ViewController: UIViewController, UIScrollViewDelegate {

```<code>@IBOutlet weak var myUIScrollView: UIScrollView!

var myImgView: UIImageView!
var passInImg: UIImage?

override func viewDidLoad() {
    super.viewDidLoad()

    self.myUIScrollView.maximumZoomScale = 10.0

    self.myUIScrollView.minimumZoomScale = 1.0

    self.myUIScrollView.delegate = self

    myImgView.image = passInImg!

    self.myUIScrollView.addSubview(myImgView)

}

func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {

    return myImgView
}
</code>```

答:
Please initialize the myImgView with frame before set the image.

It return nil because the myImgView not initalize

```<code>myImgView  = UIImageView(frame:CGRectMake(10, 50, 100, 300));
</code>```

It works for me. Hope it will helps you.Thanks alot

Body:
I need to display the image pass in from the another ViewController

first,I have tested using only ImageView to display the image and it works as below:

Thanks. Your help is greatly appreciated.

class ViewController: UIViewController, UIScrollViewDelegate {

    @IBOutlet weak var TempImgView: UIImgeView!
    var passInImg: UIImage?

    override func viewDidLoad() {

        super.viewDidLoad()

       TempImgView.image = passInImg!

   }

When I use UIScrollView ( for scrolling the large passInImg) , below code not working

Probelm:

error : fatal error: unexpectedly found nil while unwrapping an
  optional value

But I have tested the pass in image  in the above code.

what need to be done with the scrollView?

Should be used in viewDidLoad?

class ViewController: UIViewController, UIScrollViewDelegate {

@IBOutlet weak var myUIScrollView: UIScrollView!

var myImgView: UIImageView!
var passInImg: UIImage?

override func viewDidLoad() {
    super.viewDidLoad()

    self.myUIScrollView.maximumZoomScale = 10.0

    self.myUIScrollView.minimumZoomScale = 1.0

    self.myUIScrollView.delegate = self

    myImgView.image = passInImg!

    self.myUIScrollView.addSubview(myImgView)

}

func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {

    return myImgView
}

Body:
Please initialize the myImgView with frame before set the image.

It return nil because the myImgView not initalize

myImgView  = UIImageView(frame:CGRectMake(10, 50, 100, 300));

It works for me. Hope it will helps you.Thanks alot


问:
calculate total time
I have some json data which contain different time on each day. I have to calculate sum of time according to day.Here is my JSON

```<code>   [
    {
        "id":"1",
        "monday_NT":"3:45",
        "monday_TH":"2:45",
        "monday_DT":"4:45",
        "monday_DTH":"2:45",
    },
    {
        "id":"2",
        "monday_NT":"2:45",
        "monday_TH":"5:45",
        "monday_DT":"3:45",
        "monday_DTH":"1:49",
    }
]
</code>```

I have done this calculation but I used too many variables for this calculation.Here is my code for monday:

```<code>var monday_NT_hr=0;
var monday_TH_hr=0;
var monday_DT_hr=0;
var monday_DTH_hr=0;
var monday_NT_min=0;
var monday_TH_min=0;
var monday_DT_min=0;
var monday_DTH_min=0;
for(var i=0;i<data.length;i++)
{
    for(var index in data[i])
    {
        if(index=="monday_NT")
        {
            monday_NT_hr +=data[i][index].split(":")[0];
            monday_NT_min +=data[i][index].split(":")[1];
        }
        if(index=="monday_TH")
        {
            monday_TH_hr +=data[i][index].split(":")[0];
            monday_TH_min +=data[i][index].split(":")[1];
        }
        if(index=="monday_DT")
        {
            monday_DT_hr +=data[i][index].split(":")[0];
            monday_DT_min +=data[i][index].split(":")[1];
        }
        if(index=="monday_DTH")
        {
            monday_DTH_hr +=data[i][index].split(":")[0];
            monday_DTH_min +=data[i][index].split(":")[1];
        }
    }
}
</code>```

Is there anyway so less variable is used for this calculation?
Please help.

答:
if you want to calculate time difference of two times in 24hr formate

```<code>var time1 = "22:00"
var time2 = "01:00"
</code>```

Ans: 3:00 Hrs

```<code>var c = a.split(":")
var d = b.split(":")
var aH = parseInt(c[0])
var aM = parseInt(c[1])
var bH = parseInt(d[0])
var bM = parseInt(d[1])

if(aM > bH) {
 bH -= 1
 bM += 60
}
if(aH > bH) {
    bH += 24
}
var hour = bH - aH
var min = bM - aM
console.log( hour + ":" + min)
</code>```

See Demo

Title: calculate total time

Body:
I have some json data which contain different time on each day. I have to calculate sum of time according to day.Here is my JSON

   [
    {
        "id":"1",
        "monday_NT":"3:45",
        "monday_TH":"2:45",
        "monday_DT":"4:45",
        "monday_DTH":"2:45",
    },
    {
        "id":"2",
        "monday_NT":"2:45",
        "monday_TH":"5:45",
        "monday_DT":"3:45",
        "monday_DTH":"1:49",
    }
]

I have done this calculation but I used too many variables for this calculation.Here is my code for monday:

var monday_NT_hr=0;
var monday_TH_hr=0;
var monday_DT_hr=0;
var monday_DTH_hr=0;
var monday_NT_min=0;
var monday_TH_min=0;
var monday_DT_min=0;
var monday_DTH_min=0;
for(var i=0;i<data.length;i++)
{
    for(var index in data[i])
    {
        if(index=="monday_NT")
        {
            monday_NT_hr +=data[i][index].split(":")[0];
            monday_NT_min +=data[i][index].split(":")[1];
        }
        if(index=="monday_TH")
        {
            monday_TH_hr +=data[i][index].split(":")[0];
            monday_TH_min +=data[i][index].split(":")[1];
        }
        if(index=="monday_DT")
        {
            monday_DT_hr +=data[i][index].split(":")[0];
            monday_DT_min +=data[i][index].split(":")[1];
        }
        if(index=="monday_DTH")
        {
            monday_DTH_hr +=data[i][index].split(":")[0];
            monday_DTH_min +=data[i][index].split(":")[1];
        }
    }
}

Is there anyway so less variable is used for this calculation?
Please help.

Body:
if you want to calculate time difference of two times in 24hr formate

var time1 = "22:00"
var time2 = "01:00"

Ans: 3:00 Hrs

var c = a.split(":")
var d = b.split(":")
var aH = parseInt(c[0])
var aM = parseInt(c[1])
var bH = parseInt(d[0])
var bM = parseInt(d[1])

if(aM > bH) {
 bH -= 1
 bM += 60
}
if(aH > bH) {
    bH += 24
}
var hour = bH - aH
var min = bM - aM
console.log( hour + ":" + min)

See Demo


问:
Selectively removing trailing string
I want to remove the last letter "O", except where is is part of the word "HELLO".

I've tried doing this:

Example:

```<code>a <- c("HELLO XO","DO HELLO","TWO XO","HO")
gsub("[^HELLO]O\\>","",a)

[1] "HELLO " " HELLO" "T " "HO"
</code>```

but I want

```<code>"HELLO X" "D HELLO" "TW X" "H"
</code>```

答:
Your regular expression is nit correct.[^HELLO] means any character except H, E, L and O. But you need except only exactly HELL before O. So, you should use following expression:

```<code>a <- c("HELLO XO","DO HELLO","TWO XO","HO")
gsub("(?<!\\bHELL)O\\b", "", a, perl=TRUE)
</code>```

Title: Selectively removing trailing string

Body:
I want to remove the last letter "O", except where is is part of the word "HELLO".

I've tried doing this:

Example:

a <- c("HELLO XO","DO HELLO","TWO XO","HO")
gsub("[^HELLO]O\\>","",a)

[1] "HELLO " " HELLO" "T " "HO"

but I want

"HELLO X" "D HELLO" "TW X" "H"

Body:
Your regular expression is nit correct.[^HELLO] means any character except H, E, L and O. But you need except only exactly HELL before O. So, you should use following expression:

a <- c("HELLO XO","DO HELLO","TWO XO","HO")
gsub("(?<!\\bHELL)O\\b", "", a, perl=TRUE)


问:
Effective versioning of Components in Jira/GreenHopper?
Is there a best practise or recommended method of versioning components of a project? Just I may have an EnvironmentServices project with components SpecificService1, SpecificService2... each of these children have independent versioning.

What is the most effective method of implementing this? As standalone Jira doesn't seem to support component versioning: as raised here.

Would it be to create projects for each 'SpecificService' I wish to have a lifecyle for? Or can I take advantage of GreenHopper and use Component/Version hierarchies?

Any suggestions are appreciated.

答:
We have this as our company, and after trying the Greenhopper stuff, we went back to the obvious answer: naming conventions.

As an example, say we have a single project for some tightly integrated codebases which include REST Service and an administration WebApp.  We then have the components "Service" and "WebApp".  Then we create versions called "Service 1.2.0" and "WebApp 2.1.1".  This allows us to have bugs which apply to both components to be in both versions.

It doesn't enforce anything, but it is really clear to anyone browsing the system what the deal is, and people catch on quickly.

ContentLicense: CC BY-SA 2.5


答: String methods front() and back() returns references to first and last character of string (reference to char), your input string is 'stanley', now look at the ASCII code table, s is 115 in decimal, and y is 121 in decimal, you created for loop which printed all values in range [115,121).

Title: String changing in function unexpectedly


问:
Android Fab icon color is not bright enough
I am using FloatingActionButton icon for sharing a resource my icon look like this

It looks like gray color is overlapped.

My xml for FloatingActionButton icon is

```<code><android.support.design.widget.FloatingActionButton
       android:id="@+id/fab"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_gravity="bottom|end"
       android:layout_marginBottom="15dp"
       android:layout_marginRight="15dp"
       android:tint="@android:color/white"
       app:backgroundTint="@color/colorPrimary"
       app:srcCompat="@android:drawable/ic_menu_share" />
</code>```

However I want the white color to be bright enough as in this icon

答:
Put like this

```<code><android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="16dp"
    android:clickable="true"
    android:src="@drawable/ic_menu_share"
    app:backgroundTint="@android:color/white"/>
</code>```

Notice it is:

```<code>app:backgroundTint="@android:color/white
</code>```

and not

```<code>android:backgroundTint="@android:color/white"
</code>```

Hope it's helps you.

Body:
I am using FloatingActionButton icon for sharing a resource my icon look like this

It looks like gray color is overlapped.

My xml for FloatingActionButton icon is

<android.support.design.widget.FloatingActionButton
       android:id="@+id/fab"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_gravity="bottom|end"
       android:layout_marginBottom="15dp"
       android:layout_marginRight="15dp"
       android:tint="@android:color/white"
       app:backgroundTint="@color/colorPrimary"
       app:srcCompat="@android:drawable/ic_menu_share" />

However I want the white color to be bright enough as in this icon

Body:
Put like this

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="16dp"
    android:clickable="true"
    android:src="@drawable/ic_menu_share"
    app:backgroundTint="@android:color/white"/>

Notice it is:

app:backgroundTint="@android:color/white

and not

android:backgroundTint="@android:color/white"

Hope it's helps you.


问:
How to enable the design mode of iframe?
I have tried to edit div text which I open in an iFrame like this:

```<code>$(function() {
    var iframeBody = $("#texteditor").contents().find("body");
    var styleTag = iframeBody.append($('#content'));
    iframeBody.designMode = "on";
})
</code>```

and the page look llike this:

I am trying to edit the text, but it's not working

答:
Try instead

```<code>var iframe = $("#texteditor <iframe-selector>");
var jqIframeBody = $(iframe[0].contentDocument.body);
</code>```

Basically you cannot write a absolute selector starts from your parent window contents, you need to first get into the context (window/document) of iframe and then perform dom operations, or messaging through 1postMessage` however you want.

Body:
I have tried to edit div text which I open in an iFrame like this:

$(function() {
    var iframeBody = $("#texteditor").contents().find("body");
    var styleTag = iframeBody.append($('#content'));
    iframeBody.designMode = "on";
})

and the page look llike this:

I am trying to edit the text, but it's not working

Body:
Try instead

var iframe = $("#texteditor <iframe-selector>");
var jqIframeBody = $(iframe[0].contentDocument.body);

Basically you cannot write a absolute selector starts from your parent window contents, you need to first get into the context (window/document) of iframe and then perform dom operations, or messaging through 1postMessage` however you want.


问:
Select wav files from a folder whose partial names are in a text file
I have 500 wave files in a folder ABC which are named  like

```<code>F1001
F1002
F1003
...
F1100
F2001
F2002
...
F2100
M3001
M3002
...
M3100
M4001
M4002
...
M4100
</code>```

all with extension .wav.

Also I have a text file which contains 3 digit numbers like

001

003

098

034 .... (200 in total).

I want to select wave files from the folder ABC whose names end with these 3 digits.

Expecting MATLAB or bash script solutions.

I read this:
Copy or move files to another directory based on partial names in a text file. But I don't know how to use it for me.

答:
```<code>find . -name "*.wav" | grep -f <(awk '{print $0 ".wav"}' file)
</code>```

grep -f will use the patterns stored in file, one per line, and look for them in your find result. But you want the three numbers to be at the end, so in the above command the last awk statement will provide a modified file with ".wav" appended at each line. So for the line 001, "0001.wav" will match but any file 0010.wav will not.

see: process substitution syntax and grep --help

Body:
I have 500 wave files in a folder ABC which are named  like

F1001
F1002
F1003
...
F1100
F2001
F2002
...
F2100
M3001
M3002
...
M3100
M4001
M4002
...
M4100

all with extension .wav.

Also I have a text file which contains 3 digit numbers like

001

003

098

034 .... (200 in total).

I want to select wave files from the folder ABC whose names end with these 3 digits.

Expecting MATLAB or bash script solutions.

I read this:
Copy or move files to another directory based on partial names in a text file. But I don't know how to use it for me.

Body:
find . -name "*.wav" | grep -f <(awk '{print $0 ".wav"}' file)

grep -f will use the patterns stored in file, one per line, and look for them in your find result. But you want the three numbers to be at the end, so in the above command the last awk statement will provide a modified file with ".wav" appended at each line. So for the line 001, "0001.wav" will match but any file 0010.wav will not.

see: process substitution syntax and grep --help


问:
PLSQL Procedure needs to return single value at a time, if there are more than one records in table
I am trying to create procedure that should return single value at a time. Actually, I already did but there is one challenge that I am facing.

Suppose, I am passing 3 inputs to the procedure and as per those input procedure will return single output. But the table I am referring consist of more that one result for that particular query and my procedure is returning multiplestate exception to me.

Can anyone please help me in this case. Below is the procedure I am using.

```<code>PROCEDURE p_regidexport(countryid IN varchar2, cropid IN varchar2, productid IN VARCHAR2, pregid out varchar2)
IS
fnc       VARCHAR2(30) := 'P_REGIDEXPORT';
query     VARCHAR2(10000);
regid varchar2(20);

BEGIN
        begin
          select nvl(REG_ID,'0') into regid from Registration
          where
          LOC_ID =(select loc_id from location where Country = countryid ) AND
          CROP_ID = (select crop_id from crop where CROP_NM =  cropid)AND
          REG_NAME = productid ;
          EXCEPTION
            WHEN no_data_found THEN
                  dbms_output.put_line('No record ');  --- or regid  ='0';
        end;
        pregid := regid;
        --sub_log('P_REGIDEXPORT:'||pregid);
        dbms_output.put_line(pregid);
        EXCEPTION
        WHEN others THEN
        dbms_output.put_line('No record present' || ' - ' || sqlerrm);
    END P_REGIDEXPORT;
</code>```

答:
Chahar, For your requirement you can use pipeline function. In this you can call call the function as if you call the table. Please find the sample code below which will help you understanding the concept.

Sample Code as below:

```<code>CREATE OR REPLACE
PACKAGE TEST_PIPELINE AS

type return_varchar is table of varchar2(4000);

  /* TODO enter package declarations (types, exceptions, methods etc) here */

FUNCTION row_generator return return_varchar PIPELINED ;
END TEST_PIPELINE;

CREATE OR REPLACE
PACKAGE BODY TEST_PIPELINE AS

  FUNCTION row_generator return return_varchar PIPELINED  AS
  BEGIN
    -- TODO: Implementation required for FUNCTION TEST_PIPELINE.row_generator
   for i in  (select col1 from(
select 1 as col1 from dual
union all
select 2 from dual
union all
select 3 from dual)) loop
    pipe row(i.col1);
end loop;

  END row_generator;

END TEST_PIPELINE;
</code>```

Calling the pipeline function:

```<code>select * from table(TEST_PIPELINE.row_generator);
</code>```

I have modified your code, please have a look:

```<code> CREATE OR REPLACE
PACKAGE regdexport AS

type return_varchar is table of varchar2(4000);

FUNCTION p_regidexport(countryid IN varchar2, cropid IN varchar2, productid IN VARCHAR2, pregid out varchar2) return return_varchar PIPELINED ;
END regdexport;

CREATE OR REPLACE
PACKAGE BODY regdexport AS
FUNCTION p_regidexport(countryid IN varchar2, cropid IN varchar2, productid IN VARCHAR2, pregid out varchar2) return return_varchar
IS
fnc       VARCHAR2(30) := 'P_REGIDEXPORT';
query     VARCHAR2(10000);
regid varchar2(20);

BEGIN
        begin
          for  i in (select nvl(REG_ID,'0') into regid from Registration
          where
          LOC_ID =(select loc_id from location where Country = countryid ) AND
          CROP_ID = (select crop_id from crop where CROP_NM =  cropid)AND
          REG_NAME = productid)
          loop
                pipe row(i.regid);
          end loop;
          EXCEPTION
            WHEN no_data_found THEN
                  dbms_output.put_line('No record ');  --- or regid  ='0';
        end;
        EXCEPTION
        WHEN others THEN
        dbms_output.put_line('No record present' || ' - ' || sqlerrm);
    END P_REGIDEXPORT;
</code>```

Calling the function:

```<code>select * from table(regdexport.p_regidexport(par1,par2,par3));
</code>```

Hope this helps.

Body:
I am trying to create procedure that should return single value at a time. Actually, I already did but there is one challenge that I am facing.

Suppose, I am passing 3 inputs to the procedure and as per those input procedure will return single output. But the table I am referring consist of more that one result for that particular query and my procedure is returning multiplestate exception to me.

Can anyone please help me in this case. Below is the procedure I am using.

PROCEDURE p_regidexport(countryid IN varchar2, cropid IN varchar2, productid IN VARCHAR2, pregid out varchar2)
IS
fnc       VARCHAR2(30) := 'P_REGIDEXPORT';
query     VARCHAR2(10000);
regid varchar2(20);

BEGIN
        begin
          select nvl(REG_ID,'0') into regid from Registration
          where
          LOC_ID =(select loc_id from location where Country = countryid ) AND
          CROP_ID = (select crop_id from crop where CROP_NM =  cropid)AND
          REG_NAME = productid ;
          EXCEPTION
            WHEN no_data_found THEN
                  dbms_output.put_line('No record ');  --- or regid  ='0';
        end;
        pregid := regid;
        --sub_log('P_REGIDEXPORT:'||pregid);
        dbms_output.put_line(pregid);
        EXCEPTION
        WHEN others THEN
        dbms_output.put_line('No record present' || ' - ' || sqlerrm);
    END P_REGIDEXPORT;

Body:
Chahar, For your requirement you can use pipeline function. In this you can call call the function as if you call the table. Please find the sample code below which will help you understanding the concept.

Sample Code as below:

CREATE OR REPLACE
PACKAGE TEST_PIPELINE AS

type return_varchar is table of varchar2(4000);

  /* TODO enter package declarations (types, exceptions, methods etc) here */

FUNCTION row_generator return return_varchar PIPELINED ;
END TEST_PIPELINE;

CREATE OR REPLACE
PACKAGE BODY TEST_PIPELINE AS

  FUNCTION row_generator return return_varchar PIPELINED  AS
  BEGIN
    -- TODO: Implementation required for FUNCTION TEST_PIPELINE.row_generator
   for i in  (select col1 from(
select 1 as col1 from dual
union all
select 2 from dual
union all
select 3 from dual)) loop
    pipe row(i.col1);
end loop;

  END row_generator;

END TEST_PIPELINE;

Calling the pipeline function:

select * from table(TEST_PIPELINE.row_generator);

I have modified your code, please have a look:

 CREATE OR REPLACE
PACKAGE regdexport AS

type return_varchar is table of varchar2(4000);

FUNCTION p_regidexport(countryid IN varchar2, cropid IN varchar2, productid IN VARCHAR2, pregid out varchar2) return return_varchar PIPELINED ;
END regdexport;

CREATE OR REPLACE
PACKAGE BODY regdexport AS
FUNCTION p_regidexport(countryid IN varchar2, cropid IN varchar2, productid IN VARCHAR2, pregid out varchar2) return return_varchar
IS
fnc       VARCHAR2(30) := 'P_REGIDEXPORT';
query     VARCHAR2(10000);
regid varchar2(20);

BEGIN
        begin
          for  i in (select nvl(REG_ID,'0') into regid from Registration
          where
          LOC_ID =(select loc_id from location where Country = countryid ) AND
          CROP_ID = (select crop_id from crop where CROP_NM =  cropid)AND
          REG_NAME = productid)
          loop
                pipe row(i.regid);
          end loop;
          EXCEPTION
            WHEN no_data_found THEN
                  dbms_output.put_line('No record ');  --- or regid  ='0';
        end;
        EXCEPTION
        WHEN others THEN
        dbms_output.put_line('No record present' || ' - ' || sqlerrm);
    END P_REGIDEXPORT;

Calling the function:

select * from table(regdexport.p_regidexport(par1,par2,par3));

Hope this helps.


问:
DropwizardMetricServices doesn't submit the gauge metric to JMX for second time (after removing the first time)
DropwizardMetricServices#submit() I'm using doesn't submit the gauge metric for second time.

i.e. My use-case is to remove the gauge metric from JMX after reading it. And my application can send the same metric (with different value).

For the first time the gauge metric is submitted successfully (then my application removes it once it reads the metric). But, the same metric is not submitted the second time.

So, I'm a bit confused what would be the reason for DropwizardMetricServices#submit() not to work for the second time?

Below is the code:

Submit metric:

```<code>private void submitNonSparseMetric(final String metricName, final long value) {
    validateMetricName(metricName);
    metricService.submit(metricName, value); // metricService is the DropwizardMetricServices
    log(metricName, value);
    LOGGER.debug("Submitted the metric {} to JMX", metricName);
}
</code>```

Code that reads and removes the metric:

```<code>protected void collectMetrics() {
    // Create the connection
    Long currTime = System.currentTimeMillis()/1000; // Graphite needs
    Socket connection = createConnection();
    if (connection == null){
        return;
    }
    // Get the output stream
    DataOutputStream outputStream = getDataOutputStream(connection);
    if (outputStream == null){
        closeConnection();
        return;
    }
    // Get metrics from JMX
    Map<String, Gauge> g = metricRegistry.getGauges(); // metricRegistry is com.codahale.metrics.MetricRegistry
    for(Entry<String, Gauge> e : g.entrySet()){
        String key = e.getKey();
        if(p2cMetric(key)){
            String metricName = convertToMetricStandard(key);
            String metricValue = String.valueOf(e.getValue().getValue());

            String metricToSend = String.format("%s %s %s\n", metricName, metricValue, currTime);
            try {
                writeToStream(outputStream, metricToSend);
                // Remove the metric from JMX after successfully sending metric to graphite
                removeMetricFromJMX(key);
            } catch (IOException e1) {
                LOGGER.error("Unable to send metric to Graphite - {}", e1.getMessage());
            }
        }

    }

    closeOutputStream();
    closeConnection();
}
</code>```

答:
I think I found the issue.

As per the DropwizardMetricServices doc - https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/actuate/metrics/dropwizard/DropwizardMetricServices.html#submit-java.lang.String-double- ,
submit() method Set the specified gauge value.
So, I think it's recommended to use DropwizardMetricServices#submit() method to only set the values of any existing gauge metric in JMX and not for adding any new metric to JMX.

So, once I replaced DropwizardMetricServices#submit() with MetricRegistry#register() (com.codahale.metrics.MetricRegistry) method to submit all my metrics it worked as expected and my metrics are readded to JMX (once they were removed by my application).

But, I'm just wondering what makes DropwizardMetricServices#submit() to only add new metrics to JMX and not any metric that's already been removed (from JMX). Does DropwizardMetricServices cache (in memory) all the metrics submitted to JMX? that makes DropwizardMetricServices#submit() method not to resubmit the metric?

Body:
DropwizardMetricServices#submit() I'm using doesn't submit the gauge metric for second time.

i.e. My use-case is to remove the gauge metric from JMX after reading it. And my application can send the same metric (with different value).

For the first time the gauge metric is submitted successfully (then my application removes it once it reads the metric). But, the same metric is not submitted the second time.

So, I'm a bit confused what would be the reason for DropwizardMetricServices#submit() not to work for the second time?

Below is the code:

Submit metric:

private void submitNonSparseMetric(final String metricName, final long value) {
    validateMetricName(metricName);
    metricService.submit(metricName, value); // metricService is the DropwizardMetricServices
    log(metricName, value);
    LOGGER.debug("Submitted the metric {} to JMX", metricName);
}

Code that reads and removes the metric:

protected void collectMetrics() {
    // Create the connection
    Long currTime = System.currentTimeMillis()/1000; // Graphite needs
    Socket connection = createConnection();
    if (connection == null){
        return;
    }
    // Get the output stream
    DataOutputStream outputStream = getDataOutputStream(connection);
    if (outputStream == null){
        closeConnection();
        return;
    }
    // Get metrics from JMX
    Map<String, Gauge> g = metricRegistry.getGauges(); // metricRegistry is com.codahale.metrics.MetricRegistry
    for(Entry<String, Gauge> e : g.entrySet()){
        String key = e.getKey();
        if(p2cMetric(key)){
            String metricName = convertToMetricStandard(key);
            String metricValue = String.valueOf(e.getValue().getValue());

            String metricToSend = String.format("%s %s %s\n", metricName, metricValue, currTime);
            try {
                writeToStream(outputStream, metricToSend);
                // Remove the metric from JMX after successfully sending metric to graphite
                removeMetricFromJMX(key);
            } catch (IOException e1) {
                LOGGER.error("Unable to send metric to Graphite - {}", e1.getMessage());
            }
        }

    }

    closeOutputStream();
    closeConnection();
}


问:
Java crontab (Ubuntu)
Having issues in setting up a Java crontab to run every 1 minute. New to this - have tried a few things though, appreciate any pointers

Java class runs on Ubuntu command without any issues
(Have updated CLASSPATH in bashrc for the dependent libraries etc.)

crontab -e
*/1 * * * * root (cd /usr/share/java; java packagename.class)

答:
You can execute this script from anywhere. (That's because of the absolute paths)</p>

```<code>#!/bin/sh
PATH=/usr/share/java;$PATH
java -cp /your/path a.b.c.ClassName &>/your/path/to/output
</code>```

Title: Java crontab (Ubuntu)

Body:
You can execute this script from anywhere. (That's because of the absolute paths)

#!/bin/sh
PATH=/usr/share/java;$PATH
java -cp /your/path a.b.c.ClassName &>/your/path/to/output


问:
KStream incompatible types
I was trying something  with coding part by using strings and came up with the code below , please help with the syntax issues with the code.

```<code>KStreamBuilder builder = new KStreamBuilder();
KStream<String, String> textlines = builder.stream("INTOPIC");
KStream<String, String> mstream = textlines
    .foreach(new ForeachAction<String, String>(){
        public void apply(String key, String value){
            String str=value.replace("[","");
            for(int y=0; y<str.length(); y++){
                //System.out.print(str.charAt(y));
            }
            //System.out.print("\n");
        }
    });
mstream.to("OUTTOPIC");
</code>```

In the second KStream statement it is showing incompatible types.....
I want the replace logic to work with and it should be affected to textlines variable.
Thanks in advance.

答:
The result of foreach is the void, not the next KStream. If you want to transform data, then you need to use map instead...

Code will look following way (especially if you need to change key as well, if not - see next variant):

```<code>KStreamBuilder builder = new KStreamBuilder();
KStream<String, String> textlines = builder.stream("INTOPIC");
KStream<String, String> mstream = textlines
    .map((key, value) -> new KeyValue<>(key, value.replace("[",""))));
mstream.to("OUTTOPIC");
</code>```

or you can replace lines 3-4 with following (it will result in better execution):

```<code>KStream<String, String> mstream = textlines
    .mapValues(value -> value.replace("[",""));
</code>```

Title: KStream incompatible types

Body:
I was trying something  with coding part by using strings and came up with the code below , please help with the syntax issues with the code.

KStreamBuilder builder = new KStreamBuilder();
KStream<String, String> textlines = builder.stream("INTOPIC");
KStream<String, String> mstream = textlines
    .foreach(new ForeachAction<String, String>(){
        public void apply(String key, String value){
            String str=value.replace("[","");
            for(int y=0; y<str.length(); y++){
                //System.out.print(str.charAt(y));
            }
            //System.out.print("\n");
        }
    });
mstream.to("OUTTOPIC");

In the second KStream statement it is showing incompatible types.....
I want the replace logic to work with and it should be affected to textlines variable.
Thanks in advance.

Body:
The result of foreach is the void, not the next KStream. If you want to transform data, then you need to use map instead...

Code will look following way (especially if you need to change key as well, if not - see next variant):

KStreamBuilder builder = new KStreamBuilder();
KStream<String, String> textlines = builder.stream("INTOPIC");
KStream<String, String> mstream = textlines
    .map((key, value) -> new KeyValue<>(key, value.replace("[",""))));
mstream.to("OUTTOPIC");

or you can replace lines 3-4 with following (it will result in better execution):

KStream<String, String> mstream = textlines
    .mapValues(value -> value.replace("[",""));


问:
Is it possible to rewrite strings in unknown json structure?
I have a requirement to parse arbitrary json, encode/rewrite any string key or value longer than 85 characters(think of a kind of short URL service) and marshal it back to raw json.
 e.g. a document like this {"Name": "Ed", "Text": "long characters....85 chars"} should become something like this {"Name": "Ed", "Text": "short://ID=3403"}. This example is simple but I have to deal with complex structures with nested objects and arrays and basically unknown  structures.

My question is: Is it possible to do this using a known library or even the standard encoding/json package?
 What I actually need is the equivalent of an implementation of Marshaler interface on type  string but we know that's not possible so I'm wondering what other options I have (beside forking the standard encoding/json package)

答:
Yes, it is possible using the standard library and a little bit of code.

Unmarshal to interface{}

```<code>var v interface{}
if err := json.Unmarshal(data, &v); err != nil {
  // handle error
}
</code>```

Traverse the unmarshaled value, shortening strings and rewriting as you go:

```<code>func shorten(v interface{}) interface{} {
    switch v := v.(type) {
    case []interface{}:
        for i, e := range v {
            v[i] = shorten(e)
        }
        return v
    case map[string]interface{}:
        m := make(map[string]interface{})
        for k, e := range v {
            m[shortenString(k)] = shorten(e)
        }
        return m
    case string:
        return shortenString(v)
    default:
        return v
    }
}
</code>```

The function shorten calls shortenString(s string) string to convert a long string to short://ID=xxx.

Marshal the value back to JSON:

```<code>p, err := json.Marshal(shorten(v))
if err != nil {
    // handle error
}

// p is a []byte
fmt.Printf("%s\n", p)
</code>```

playground example

Body:
Yes, it is possible using the standard library and a little bit of code.

Unmarshal to interface{}

var v interface{}
if err := json.Unmarshal(data, &v); err != nil {
  // handle error
}

Traverse the unmarshaled value, shortening strings and rewriting as you go:

func shorten(v interface{}) interface{} {
    switch v := v.(type) {
    case []interface{}:
        for i, e := range v {
            v[i] = shorten(e)
        }
        return v
    case map[string]interface{}:
        m := make(map[string]interface{})
        for k, e := range v {
            m[shortenString(k)] = shorten(e)
        }
        return m
    case string:
        return shortenString(v)
    default:
        return v
    }
}

The function shorten calls shortenString(s string) string to convert a long string to short://ID=xxx.

Marshal the value back to JSON:

p, err := json.Marshal(shorten(v))
if err != nil {
    // handle error
}

// p is a []byte
fmt.Printf("%s\n", p)

playground example


问:
React-Native - KeyboardAvoidingView - Error
I use the keyboardAvoidingView, to display inputs and used next focus. But, when i click in first input ( print label 1623 - Acidez ), this is hidden. How make show this?

```<code><ReactNative.View key={this.state.selectedTabIndex}>
                <ReactNative.ScrollView style={{ height: this.props.styles.height - 40 }}>

                    <ReactNative.KeyboardAvoidingView
                        keyboardVerticalOffset={0}

                        behavior="position"
                        contentContainerStyle={{ paddingTop: this.state.size }}
                    >
                        {this.tabs[this.state.selectedTabIndex].render()}
                    </ReactNative.KeyboardAvoidingView>

                </ReactNative.ScrollView>
            </ReactNative.View>
</code>```

答:
if you increase 'keyboardVerticalOffset' to bigger value like '100' of KeyboardAvoidingView to some bigger amount it would scroll up from keyboard thus avoiding it.I also spent much time in finding the right solution on internet but finally figure it out myself for 'react-native' version '0.50.4'.I got it working like this </p>

```<code><View style={…..}>
      <ScrollView>
         <KeyboardAvoidingView style={{ flex: 1 }}
            keyboardVerticalOffset={100} behavior={"position"}>

        </KeyboardAvoidingView>
      </ScrollView>
 </View>
</code>```

Body:
I use the keyboardAvoidingView, to display inputs and used next focus. But, when i click in first input ( print label 1623 - Acidez ), this is hidden. How make show this?

<ReactNative.View key={this.state.selectedTabIndex}>
                <ReactNative.ScrollView style={{ height: this.props.styles.height - 40 }}>

                    <ReactNative.KeyboardAvoidingView
                        keyboardVerticalOffset={0}

                        behavior="position"
                        contentContainerStyle={{ paddingTop: this.state.size }}
                    >
                        {this.tabs[this.state.selectedTabIndex].render()}
                    </ReactNative.KeyboardAvoidingView>

                </ReactNative.ScrollView>
            </ReactNative.View>

Body:
if you increase 'keyboardVerticalOffset' to bigger value like '100' of KeyboardAvoidingView to some bigger amount it would scroll up from keyboard thus avoiding it.I also spent much time in finding the right solution on internet but finally figure it out myself for 'react-native' version '0.50.4'.I got it working like this

<View style={…..}>
      <ScrollView>
         <KeyboardAvoidingView style={{ flex: 1 }}
            keyboardVerticalOffset={100} behavior={"position"}>

        </KeyboardAvoidingView>
      </ScrollView>
 </View>


问:
Orphan rows are being left in the table
I have the following models:

```<code>class Page extends AppModel {
    var $name = 'Page';
    var $order = array('Page.modified' => 'desc');

    var $hasOne = array(
        'Post' => array(
            'className' => 'Post',
            'dependent' => TRUE
        ));

class Post extends AppModel {
    var $name = 'Post';
    var $hasAndBelongsToMany = array(
        'Category' => array(
            'className' => 'Category'
        )
    );
    var $belongsTo = array(
        'Page' => array(
            'className' => 'Page',
            'dependent' => TRUE
        )
    );
</code>```

Here is the controller code:

```<code>function admin_delete($id = NULL) {
    if ($this->Post->delete($id, TRUE)) {
        $this->Session->setFlash('This Post has been deleted', 'flash_good');
        $this->redirect(array('action' => 'index'));
    }
}
</code>```

My tables are as follows:

```<code>Page:
---------------------------
id title uri meta_keywords

Post:
---------------------------
id page_id title uri body
</code>```

Whenever, I try to delete a Post, the Page related to the Post, doesn't get deleted and is left in the table. What should I do for the related Page row to be deleted when I delete the Post?

答:
The sort answer is: Delete the page and this will delete the post too. :)

The long explanation: Dependent works only for hasMany or hasOne, in other words it will delete childs of the parent record as well. In your schema your child id the post, because it contain foreign key of the pages table.

Title: Orphan rows are being left in the table

Body:
I have the following models:

class Page extends AppModel {
    var $name = 'Page';
    var $order = array('Page.modified' => 'desc');

    var $hasOne = array(
        'Post' => array(
            'className' => 'Post',
            'dependent' => TRUE
        ));

class Post extends AppModel {
    var $name = 'Post';
    var $hasAndBelongsToMany = array(
        'Category' => array(
            'className' => 'Category'
        )
    );
    var $belongsTo = array(
        'Page' => array(
            'className' => 'Page',
            'dependent' => TRUE
        )
    );

Here is the controller code:

function admin_delete($id = NULL) {
    if ($this->Post->delete($id, TRUE)) {
        $this->Session->setFlash('This Post has been deleted', 'flash_good');
        $this->redirect(array('action' => 'index'));
    }
}

My tables are as follows:

Page:
---------------------------
id title uri meta_keywords

Post:
---------------------------
id page_id title uri body

Whenever, I try to delete a Post, the Page related to the Post, doesn't get deleted and is left in the table. What should I do for the related Page row to be deleted when I delete the Post?


问:
Windows CE 4.0 with Windows Server 2012
In my company, we have upgraded the Windows Server 2003 to Windows Server 2012 and we have some thin clients with an old version of RDP and they can't connect to the Server 2012 because when I does, I get this message: Because of a security error, the client could not connect to the remote computer. Verify that you are logged on to the network, and then try connecting again.

Our thin clients are: Compaq Evo T30 and a Neoware CA19 and they have Windows CE 4.0 installed by default.

Searching in internet, I've found this tutorial: http://www.hjgode.de/wp/2014/03/12/windows-server-2012-rds-and-windows-mobile-connection-error/ but I can't apply it to our server because we don't want to have less security.

I've searched everything on internet to configure the Windows CE to be able to connect to our server 2012 but I can't find anything helpful :( Seriously, we don't want to apply the steps of the previous tutorial, we prefer buying new Thin Clients instead of doing that, but it will be better if there is a way to be able to connect to the server 2012 without changing anything in the server.

Anyone can help me? Please, it's very important.

Thanks in advance! :)

答: Unless there is a way to update your clients to a newer release of Windows CE that support new RDP versions (you should test that first) probably replacing them is the only option.</p>

Title: Windows CE 4.0 with Windows Server 2012


问:
Intent.action.VIEW does not work on some devices
I need to open my application when clicked the URL Link in E-mail, Message or Browser applications. So, see the my code for this feature:

```<code><activity
    android:name=".ui.main.MainActivity"
    android:configChanges="orientation"
    android:screenOrientation="portrait">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

    <intent-filter>
        <data android:scheme="https" />
        <data android:scheme="https" android:host="www.mysite.org"/>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <category android:name="android.intent.category.APP_EMAIL"/>
        <category android:name="android.intent.category.APP_MESSAGING"/>
        <category android:name="android.intent.category.APP_BROWSER"/>
        <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>
</activity>
</code>```

This code is sufficient and works on some mobile devices, especially devices with android versions 5.0, 6.0 and 7.0 but does not work on versions 7.1 and 8.0. Why does this happen? Is it a permission problem?

答:
Ex: Your url will be something like https://example.com and you have the intent filter in Android Manifest as below:

```<code><activity
    android:name="com.droid.MainActivity"
    android:label="@string/app_name" >

    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data
            android:host="example.com"
            android:scheme="https" />
    </intent-filter>
</activity>
</code>```

Use the URL Mapping editor to easily add URL intent filters to your Activities with Android App Links (Android Studio > Tools > Android App Links).

Body:
I need to open my application when clicked the URL Link in E-mail, Message or Browser applications. So, see the my code for this feature:

<activity
    android:name=".ui.main.MainActivity"
    android:configChanges="orientation"
    android:screenOrientation="portrait">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

    <intent-filter>
        <data android:scheme="https" />
        <data android:scheme="https" android:host="www.mysite.org"/>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <category android:name="android.intent.category.APP_EMAIL"/>
        <category android:name="android.intent.category.APP_MESSAGING"/>
        <category android:name="android.intent.category.APP_BROWSER"/>
        <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>
</activity>

This code is sufficient and works on some mobile devices, especially devices with android versions 5.0, 6.0 and 7.0 but does not work on versions 7.1 and 8.0. Why does this happen? Is it a permission problem?

Body:
Ex: Your url will be something like https://example.com and you have the intent filter in Android Manifest as below:

<activity
    android:name="com.droid.MainActivity"
    android:label="@string/app_name" >

    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data
            android:host="example.com"
            android:scheme="https" />
    </intent-filter>
</activity>

Use the URL Mapping editor to easily add URL intent filters to your Activities with Android App Links (Android Studio > Tools > Android App Links).


问:
Return a Specific Revision of An Object
I want to get my Envers to return the entities with the highest revision that is still below a given revision number.

What I came up with is the following:

```<code>@PersistenceContext
private EntityManager em;

@Test
public void test() throws Exception {
    final Number before = AuditReaderFactory.get(this.em).getRevisionNumberForDate(new Date(Long.MAX_VALUE));

    final UserEntity user = new UserEntity().loginName("one");
    doInTransaction(() -> this.em.persist(user));

    final Number middle = AuditReaderFactory.get(this.em).getRevisionNumberForDate(new Date(Long.MAX_VALUE));

    user.setLoginName("two");
    doInTransaction(() -> this.em.persist(user));

    final Number after = AuditReaderFactory.get(this.em).getRevisionNumberForDate(new Date(Long.MAX_VALUE));

    Assert.assertEquals(new ArrayList<>(), getRevisions(before));
    Assert.assertEquals(Arrays.asList(user), getRevisions(middle));
    Assert.assertEquals(new ArrayList<>(), getRevisions(after));
}

private void doInTransaction(Runnable magic) {
    try {
        this.em.getTransaction().begin();
        magic.run();
        this.em.getTransaction().commit();
    } catch (final Exception e) {
        this.em.getTransaction().rollback();
        throw new RuntimeException(e);
    }
}

private List<UserEntity> getRevisions(Number revisionNumber) {
    final AuditReader auditReader = AuditReaderFactory.get(this.em);
    try {
        return auditReader.createQuery().forRevisionsOfEntity(UserEntity.class, true, false)
                .add(AuditEntity.revisionNumber().maximize().computeAggregationInInstanceContext()) // the highest revision possible
                .add(AuditEntity.revisionNumber().le(revisionNumber)) // as long as the revision is below or equal to revisionNumber
                .getResultList();
    } catch (final NoResultException e) {
        return null;
    }
}
</code>```

The method that does not work is getRevisions(Object, Number). It returns nothing for the before revision (that's correct), it returns still nothing for the middle revision (not correct, now the entity exists!) and then returns something for the after revision (also not correct, the entity was deleted).

The reason for that behavior is clear when we look at the resulting SQL:

```<code>SELECT * from user_aud u
    WHERE u.REV = (
        SELECT MAX (v.REV)
            FROM user_aud v
            WHERE v.id=u.id
        )
    AND u.REV <= ? ORDER BY u.REV asc
</code>```

The u.REV <= ? part should be inside the inner query. The way it's generated now Hibernate decides that the max revision is 3, and then selects nothing because rev should be below 2.

I can't seem to figure out how to fix the query, and there is very little documentation on the subject. I tried removing computeAggregationInInstanceCont(), but there was no change in how the code behaved.

What is the correct query to get the highest revision below a user-defined value?

答:
This problem boiled down to setting the brackets correctly: </p>

```<code>private List<UserEntity> getRevisions(Number revisionNumber) {
    final AuditReader auditReader = AuditReaderFactory.get(this.em);
    try {
        return auditReader.createQuery().forRevisionsOfEntity(UserEntity.class, true, false)
                .add(AuditEntity.revisionNumber().maximize().computeAggregationInInstanceContext().add(AuditEntity.revisionNumber().le(revisionNumber)))
                .getResultList();
    } catch (final NoResultException e) {
        return null;
    }
}
</code>```

Title: Return a Specific Revision of An Object

Body:
I want to get my Envers to return the entities with the highest revision that is still below a given revision number.

What I came up with is the following:

@PersistenceContext
private EntityManager em;

@Test
public void test() throws Exception {
    final Number before = AuditReaderFactory.get(this.em).getRevisionNumberForDate(new Date(Long.MAX_VALUE));

    final UserEntity user = new UserEntity().loginName("one");
    doInTransaction(() -> this.em.persist(user));

    final Number middle = AuditReaderFactory.get(this.em).getRevisionNumberForDate(new Date(Long.MAX_VALUE));

    user.setLoginName("two");
    doInTransaction(() -> this.em.persist(user));

    final Number after = AuditReaderFactory.get(this.em).getRevisionNumberForDate(new Date(Long.MAX_VALUE));

    Assert.assertEquals(new ArrayList<>(), getRevisions(before));
    Assert.assertEquals(Arrays.asList(user), getRevisions(middle));
    Assert.assertEquals(new ArrayList<>(), getRevisions(after));
}

private void doInTransaction(Runnable magic) {
    try {
        this.em.getTransaction().begin();
        magic.run();
        this.em.getTransaction().commit();
    } catch (final Exception e) {
        this.em.getTransaction().rollback();
        throw new RuntimeException(e);
    }
}

private List<UserEntity> getRevisions(Number revisionNumber) {
    final AuditReader auditReader = AuditReaderFactory.get(this.em);
    try {
        return auditReader.createQuery().forRevisionsOfEntity(UserEntity.class, true, false)
                .add(AuditEntity.revisionNumber().maximize().computeAggregationInInstanceContext()) // the highest revision possible
                .add(AuditEntity.revisionNumber().le(revisionNumber)) // as long as the revision is below or equal to revisionNumber
                .getResultList();
    } catch (final NoResultException e) {
        return null;
    }
}

The method that does not work is getRevisions(Object, Number). It returns nothing for the before revision (that's correct), it returns still nothing for the middle revision (not correct, now the entity exists!) and then returns something for the after revision (also not correct, the entity was deleted).

The reason for that behavior is clear when we look at the resulting SQL:

SELECT * from user_aud u
    WHERE u.REV = (
        SELECT MAX (v.REV)
            FROM user_aud v
            WHERE v.id=u.id
        )
    AND u.REV <= ? ORDER BY u.REV asc

The u.REV <= ? part should be inside the inner query. The way it's generated now Hibernate decides that the max revision is 3, and then selects nothing because rev should be below 2.

I can't seem to figure out how to fix the query, and there is very little documentation on the subject. I tried removing computeAggregationInInstanceCont(), but there was no change in how the code behaved.

What is the correct query to get the highest revision below a user-defined value?

Body:
This problem boiled down to setting the brackets correctly:

private List<UserEntity> getRevisions(Number revisionNumber) {
    final AuditReader auditReader = AuditReaderFactory.get(this.em);
    try {
        return auditReader.createQuery().forRevisionsOfEntity(UserEntity.class, true, false)
                .add(AuditEntity.revisionNumber().maximize().computeAggregationInInstanceContext().add(AuditEntity.revisionNumber().le(revisionNumber)))
                .getResultList();
    } catch (final NoResultException e) {
        return null;
    }
}


问:
Invalid Toolchain. Itunes store operation failed
As soon as I updated xcode to 9.2 , I cannot validate my archived builds. I get this error message every time:

Invalid Toolchain. New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds.

Is this something wrong with Apple's new relase of xcode? Otherwise, I didn't change anything that would make this project using "Beta software".

答:
Edit: Seems like Apple resolved the issue! I just uploaded a build with 9.2.

I'm having the same issue. Changing the toolchain setting did not help.
Downloading Xcode 9.1 now but I'm not happy with that solution. Not sure how differently the app would be behave after testing it with 9.2.


问:
My Magento Extension Install Script Will Not Run
I am trying to create an install script for my extension and for some reason it will not the install script. The extension will show up in the core_resource table, but the attributes I am trying to create will not create.

I am pretty sure that the script is not even being called because I put an exit() at the beginning and the site ran just fine.

Here is what I have in my config XML file. This is placed inside global -> resources path:

```<code><nie_setup>
    <setup>
        <module>Nie_Nie</module>
    </setup>
    <connection>
        <use>core_setup</use>
    </connection>
</nie_setup>
</code>```

My install script is as follows:

```<code>$installer = $this;
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();

$setup->addAttribute('customer', 'nie_admin', array(
    'input'                 => 'text',
    'type'                  => 'text',
    'backend'               => '',
    'visible'               => 0,
    'required'          => 0,
    'user_defined'  => 1,
));

$installer->endSetup();
</code>```

Is there something obvious I am missing here that would be the reason the script will not run?

答:
As per Magento Knowledgebase you could try including a <class> tag in your <setup>. This way you can ensure the correct setup model is used and (if it gets that far) passes the model to your install script negating the need to create a $setup manually.

Check the file permissions of the install script and the directory it is in. I sometimes find deleting the record from core_resources helps kick start the process too.

Body:
I am trying to create an install script for my extension and for some reason it will not the install script. The extension will show up in the core_resource table, but the attributes I am trying to create will not create.

I am pretty sure that the script is not even being called because I put an exit() at the beginning and the site ran just fine.

Here is what I have in my config XML file. This is placed inside global -> resources path:

<nie_setup>
    <setup>
        <module>Nie_Nie</module>
    </setup>
    <connection>
        <use>core_setup</use>
    </connection>
</nie_setup>

My install script is as follows:

$installer = $this;
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();

$setup->addAttribute('customer', 'nie_admin', array(
    'input'                 => 'text',
    'type'                  => 'text',
    'backend'               => '',
    'visible'               => 0,
    'required'          => 0,
    'user_defined'  => 1,
));

$installer->endSetup();

Is there something obvious I am missing here that would be the reason the script will not run?


答:
The fab inherits the colors from the material theme. Make sure that your theme is using the colors you want by changing the primary, primaryDark and acent colors i.e. in res > values > styles.

```<code> <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</code>```

Title: Android Fab icon color is not bright enough

Body:
I am using FloatingActionButton icon for sharing a resource my icon look like this

It looks like gray color is overlapped.

My xml for FloatingActionButton icon is

<android.support.design.widget.FloatingActionButton
       android:id="@+id/fab"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_gravity="bottom|end"
       android:layout_marginBottom="15dp"
       android:layout_marginRight="15dp"
       android:tint="@android:color/white"
       app:backgroundTint="@color/colorPrimary"
       app:srcCompat="@android:drawable/ic_menu_share" />

However I want the white color to be bright enough as in this icon

Body:
The fab inherits the colors from the material theme. Make sure that your theme is using the colors you want by changing the primary, primaryDark and acent colors i.e. in res > values > styles.

 <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>