问:
How to return bool value with navigator.pop?
I'm trying to return a bool value from the dialogbox but I do not understand why the value does not return as need. I have tried returning as a future value and returning the values together with context after popping the dialogbox.</p>

```<code>final bool delete = await _showDialog();
print(delete);

Future<bool> _showDialog() {
bool result;

showDialog(
  context: context,
  builder: (BuildContext context) {
    return AlertDialog(
      title: Text('Delete Appointment'),
      content: Text(
        'Are you sure? \nThis action cannot undo.',
        style: TextStyle(
          color: Colors.red,
          fontSize: 20
        ),
      ),
      actions: <Widget>[
        FlatButton(
          color: Colors.blue,
          child: Text(
            'CANCEL',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20
            ),
          ),
          onPressed: () {
            setState(() => result = false);
            //print(result);
            Navigator.pop(context, result);
            return Future.value(result);
          },
        ),
        SizedBox(
          width: 50,
        ),
        FlatButton(
          color: Colors.red,
          child: Text(
            'CONFIRM',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20
            ),
          ),
          onPressed: () {
            setState(() => result = true);
            //print(result);
            Navigator.pop(context, result);
            return Future.value(result);
          },
        )
      ],
    );
  }
);
}
</code>```

答:
For Return True

```<code> Navigator.of(context).pop(true);
</code>```

For Return False

```<code> Navigator.of(context).pop(false);
</code>```

Body:
I'm trying to return a bool value from the dialogbox but I do not understand why the value does not return as need. I have tried returning as a future value and returning the values together with context after popping the dialogbox.

final bool delete = await _showDialog();
print(delete);

Future<bool> _showDialog() {
bool result;

showDialog(
  context: context,
  builder: (BuildContext context) {
    return AlertDialog(
      title: Text('Delete Appointment'),
      content: Text(
        'Are you sure? \nThis action cannot undo.',
        style: TextStyle(
          color: Colors.red,
          fontSize: 20
        ),
      ),
      actions: <Widget>[
        FlatButton(
          color: Colors.blue,
          child: Text(
            'CANCEL',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20
            ),
          ),
          onPressed: () {
            setState(() => result = false);
            //print(result);
            Navigator.pop(context, result);
            return Future.value(result);
          },
        ),
        SizedBox(
          width: 50,
        ),
        FlatButton(
          color: Colors.red,
          child: Text(
            'CONFIRM',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20
            ),
          ),
          onPressed: () {
            setState(() => result = true);
            //print(result);
            Navigator.pop(context, result);
            return Future.value(result);
          },
        )
      ],
    );
  }
);
}

Body:
For Return True

 Navigator.of(context).pop(true);

For Return False

 Navigator.of(context).pop(false);


来源: stackexchange

问:
How i can fix legend ? (MPAndroidChart)
I used legend.setPosition(Legend.LegendPosition.RIGHT_OF_CHART_CENTER); it works, but I want that the legend was at the top

if i use legend.setPosition(Legend.LegendPosition.RIGHT_OF_CHART); the legend and the graph overlap

maybe there is a way to change the position of the chart?

答:
This method deprecated better to use this.

```<code>l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
l.setDrawInside(false);
</code>```

for reference you can check here The legend can't display when call setPosition(LegendPosition.BELOW_CHART_CENTER)

ContentLicense: CC BY-SA 3.0

Title: How i can fix legend ? (MPAndroidChart)

Body:
This method deprecated better to use this.

l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
l.setDrawInside(false);

for reference you can check here The legend can't display when call setPosition(LegendPosition.BELOW_CHART_CENTER)

ContentLicense: CC BY-SA 4.0


问:
Nested Group Owner - LDAP Query
let's assume I have the user

CN=testuser1,OU=Users,DC=corp,DC=com

and I want to receive all groups where the user is registered as the owner. I am currently using the following filter:

(|(ManagedBy=CN=testuser1,OU=Users,DC=corp,DC=com)(msExchCoManagedByLink=CN=testuser1,OU=Users,DC=corp,DC=com))

However, it can happen that security groups are also entered as owners. How can I adjust the filter so that I can still find the right groups, even if the user is indirectly entered as the owner via a security group? Can this possibly be done with the matching rule OID 1.2.840.113556.1.4.1941 (LDAP_MATCHING_RULE_IN_CHAIN)?

thanks in advance!

答:
As ManagedBy is a dn Syntax and has a LinkID of 72, an even value implying that it is a forward link, then you should be able to use something similar to: (or in combination with others)

```<code>(ManagedBy:1.2.840.113556.1.4.1941:=N=testuser1,OU=Users,DC=corp,DC=com)
</code>```

I have not tried this filter and there are limitations as to the depth of links that will be traversed in larger implementations.

Title: Nested Group Owner - LDAP Query

Body:
As ManagedBy is a dn Syntax and has a LinkID of 72, an even value implying that it is a forward link, then you should be able to use something similar to: (or in combination with others)

(ManagedBy:1.2.840.113556.1.4.1941:=N=testuser1,OU=Users,DC=corp,DC=com)

I have not tried this filter and there are limitations as to the depth of links that will be traversed in larger implementations.


问:
PrimeFaces: dealing with incomplete components.js
I'm getting some complaints that the p:toolbar of my applications is not working. Looking personally on one of the workstations that the problem happened, Firefox 49 console had the following error:

```<code>SyntaxError: missing ) after argument list[Learn More]components.js.jsf:21:18950
</code>```

Opening components.js I could see that the file was incomplete, it stopped loading on this line:

```<code>PrimeFaces.widget.Menu=PrimeFaces.widget.BaseWidget.extend ...
</code>```

PrimeFaces version is 6.0.5.

I'd like to understand two things:

Why it happens

If it happens, how to fix it inside the
application

1) My applications are not open to general public, so the first page the user will see is login. When I update the PrimeFaces version, the download of the new version of components.js will be triggered on the login page right? My best guess is that the user has saved his credentials on the browser and his connection was slow, so the page didn't even completed loading when he submitted the login form, aborting the components.js download, but since the file exists locally the browser tries to use it.

Considering that there is a pattern on the problem (file stops loading approximately on the middle), could it be some server issue? I'm using Apache TomEE 7.0.1(Tomcat 8.5.3). Server log has the following exceptions several times:

```<code>16-Oct-2016 22:08:08.469 SEVERE [http-nio-8080-exec-11] org.apache.myfaces.application.ResourceHandlerImpl.handleResourceRequest Error trying to load resource components.js with library primefaces :java.io.IOException: Pipe quebrado
 org.apache.catalina.connector.ClientAbortException: java.io.IOException: Pipe quebrado
    at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:380)
    at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:420)
    at org.apache.catalina.connector.OutputBuffer.doFlush(OutputBuffer.java:329)
    at org.apache.catalina.connector.OutputBuffer.close(OutputBuffer.java:281)
    at org.apache.catalina.connector.CoyoteOutputStream.close(CoyoteOutputStream.java:150)
    at org.apache.myfaces.application.ResourceHandlerImpl.handleResourceRequest(ResourceHandlerImpl.java:620)
    at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:59)
    at org.primefaces.application.resource.PrimeResourceHandler.handleResourceRequest(PrimeResourceHandler.java:87)
    at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:59)
    at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:59)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:190)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:100)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.openejb.server.httpd.EEFilter.doFilter(EEFilter.java:65)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at br.com.spdata.filter.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:21)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
    at org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:522)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.tomee.catalina.OpenEJBSecurityListener$RequestCapturer.invoke(OpenEJBSecurityListener.java:97)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:1110)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:785)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1425)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.IOException: Pipe quebrado
    at sun.nio.ch.FileDispatcherImpl.write0(Native Method)
    at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:47)
    at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93)
    at sun.nio.ch.IOUtil.write(IOUtil.java:65)
    at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:471)
    at org.apache.tomcat.util.net.NioChannel.write(NioChannel.java:134)
    at org.apache.tomcat.util.net.NioBlockingSelector.write(NioBlockingSelector.java:101)
    at org.apache.tomcat.util.net.NioSelectorPool.write(NioSelectorPool.java:157)
    at org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper.doWrite(NioEndpoint.java:1241)
    at org.apache.tomcat.util.net.SocketWrapperBase.writeBlocking(SocketWrapperBase.java:355)
    at org.apache.tomcat.util.net.SocketWrapperBase.write(SocketWrapperBase.java:324)
    at org.apache.coyote.http11.Http11OutputBuffer$SocketOutputBuffer.doWrite(Http11OutputBuffer.java:580)
    at org.apache.coyote.http11.filters.ChunkedOutputFilter.doWrite(ChunkedOutputFilter.java:112)
    at org.apache.coyote.http11.Http11OutputBuffer.doWrite(Http11OutputBuffer.java:213)
    at org.apache.coyote.Response.doWrite(Response.java:502)
    at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:375)
    ... 43 more

17-Oct-2016 08:34:32.650 SEVERE [http-nio-8080-exec-8] org.apache.myfaces.application.ResourceHandlerImpl.handleResourceRequest Error trying to load resource components.js with library primefaces :Stream closed
 java.io.IOException: Stream closed
    at java.util.zip.InflaterInputStream.ensureOpen(InflaterInputStream.java:67)
    at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:142)
    at java.io.FilterInputStream.read(FilterInputStream.java:107)
    at org.apache.catalina.webresources.AbstractArchiveResource$JarInputStreamWrapper.read(AbstractArchiveResource.java:249)
    at org.apache.myfaces.application.ResourceHandlerImpl.pipeBytes(ResourceHandlerImpl.java:655)
    at org.apache.myfaces.application.ResourceHandlerImpl.handleResourceRequest(ResourceHandlerImpl.java:605)
    at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:59)
    at org.primefaces.application.resource.PrimeResourceHandler.handleResourceRequest(PrimeResourceHandler.java:87)
    at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:59)
    at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:59)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:190)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:100)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.openejb.server.httpd.EEFilter.doFilter(EEFilter.java:65)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at br.com.spdata.filter.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:21)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
    at org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:522)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.tomee.catalina.OpenEJBSecurityListener$RequestCapturer.invoke(OpenEJBSecurityListener.java:97)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:1110)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:785)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1425)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
</code>```

2) Considering that at least jQuery loaded, I came with the following script, but it doesn't replaces the corrupted cached file.

```<code>    <script type="text/javascript">
        //<![CDATA[
        $(document).ready(function()
        {
            try
            {
                var ctx = "#{request.contextPath}";

                if(typeof PrimeFaces == 'undefined')
                {
                    $.getScript(ctx + '/javax.faces.resource/core.js.jsf?ln=primefaces')
                }

                if(typeof PrimeFaces.widget.TriStateCheckbox == 'undefined') // last component on the file
                {
                    $.getScript(ctx + '/javax.faces.resource/components.js.jsf?ln=primefaces')
                }
            }
            catch(e)
            {
                console.log(e);
            }
        });
        //]]>
    </script>
</h:body>
</code>```

Any ideas?

Thanks in advance

答:
I faced the same problem, since I was receiving the same error trace and it only happened to me in Firefox.
The error says that some fonts or styles of Primefaces were not loaded, but verifying the application it seems that everything was loaded well although this error was shown.
After much research I have found the problem here.

The log messages correspond to HTTP requests that are canceled immediately after submitting them, before the server could send the response.
the "Cache Race With Red" feature was activated in Firefox 59 (released March 13) and seems to be the cause.

With this feature, Firefox send requests for cached resources concurrently to the local disk cache and the actual network server.
Whichever result arrives first is used, the other request is canceled (which would cause a log message about a "Broken pipe", as with other connection aborts).

This feature can be disabled in Firefox in about:config by setting network.http.rcwn.enabled to false. So I stopped getting log messages after setting this to false.
In my case the log messages seem to be benign and this I could be ignored.

I hope this can help others who encountered the same problem.

Body:
I'm getting some complaints that the p:toolbar of my applications is not working. Looking personally on one of the workstations that the problem happened, Firefox 49 console had the following error:

SyntaxError: missing ) after argument list[Learn More]components.js.jsf:21:18950

Opening components.js I could see that the file was incomplete, it stopped loading on this line:

PrimeFaces.widget.Menu=PrimeFaces.widget.BaseWidget.extend ...

PrimeFaces version is 6.0.5.

I'd like to understand two things:

Why it happens

If it happens, how to fix it inside the
application

1) My applications are not open to general public, so the first page the user will see is login. When I update the PrimeFaces version, the download of the new version of components.js will be triggered on the login page right? My best guess is that the user has saved his credentials on the browser and his connection was slow, so the page didn't even completed loading when he submitted the login form, aborting the components.js download, but since the file exists locally the browser tries to use it.

Considering that there is a pattern on the problem (file stops loading approximately on the middle), could it be some server issue? I'm using Apache TomEE 7.0.1(Tomcat 8.5.3). Server log has the following exceptions several times:

16-Oct-2016 22:08:08.469 SEVERE [http-nio-8080-exec-11] org.apache.myfaces.application.ResourceHandlerImpl.handleResourceRequest Error trying to load resource components.js with library primefaces :java.io.IOException: Pipe quebrado
 org.apache.catalina.connector.ClientAbortException: java.io.IOException: Pipe quebrado
    at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:380)
    at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:420)
    at org.apache.catalina.connector.OutputBuffer.doFlush(OutputBuffer.java:329)
    at org.apache.catalina.connector.OutputBuffer.close(OutputBuffer.java:281)
    at org.apache.catalina.connector.CoyoteOutputStream.close(CoyoteOutputStream.java:150)
    at org.apache.myfaces.application.ResourceHandlerImpl.handleResourceRequest(ResourceHandlerImpl.java:620)
    at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:59)
    at org.primefaces.application.resource.PrimeResourceHandler.handleResourceRequest(PrimeResourceHandler.java:87)
    at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:59)
    at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:59)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:190)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:100)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.openejb.server.httpd.EEFilter.doFilter(EEFilter.java:65)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at br.com.spdata.filter.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:21)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
    at org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:522)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.tomee.catalina.OpenEJBSecurityListener$RequestCapturer.invoke(OpenEJBSecurityListener.java:97)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:1110)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:785)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1425)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.IOException: Pipe quebrado
    at sun.nio.ch.FileDispatcherImpl.write0(Native Method)
    at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:47)
    at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93)
    at sun.nio.ch.IOUtil.write(IOUtil.java:65)
    at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:471)
    at org.apache.tomcat.util.net.NioChannel.write(NioChannel.java:134)
    at org.apache.tomcat.util.net.NioBlockingSelector.write(NioBlockingSelector.java:101)
    at org.apache.tomcat.util.net.NioSelectorPool.write(NioSelectorPool.java:157)
    at org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper.doWrite(NioEndpoint.java:1241)
    at org.apache.tomcat.util.net.SocketWrapperBase.writeBlocking(SocketWrapperBase.java:355)
    at org.apache.tomcat.util.net.SocketWrapperBase.write(SocketWrapperBase.java:324)
    at org.apache.coyote.http11.Http11OutputBuffer$SocketOutputBuffer.doWrite(Http11OutputBuffer.java:580)
    at org.apache.coyote.http11.filters.ChunkedOutputFilter.doWrite(ChunkedOutputFilter.java:112)
    at org.apache.coyote.http11.Http11OutputBuffer.doWrite(Http11OutputBuffer.java:213)
    at org.apache.coyote.Response.doWrite(Response.java:502)
    at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:375)
    ... 43 more

17-Oct-2016 08:34:32.650 SEVERE [http-nio-8080-exec-8] org.apache.myfaces.application.ResourceHandlerImpl.handleResourceRequest Error trying to load resource components.js with library primefaces :Stream closed
 java.io.IOException: Stream closed
    at java.util.zip.InflaterInputStream.ensureOpen(InflaterInputStream.java:67)
    at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:142)
    at java.io.FilterInputStream.read(FilterInputStream.java:107)
    at org.apache.catalina.webresources.AbstractArchiveResource$JarInputStreamWrapper.read(AbstractArchiveResource.java:249)
    at org.apache.myfaces.application.ResourceHandlerImpl.pipeBytes(ResourceHandlerImpl.java:655)
    at org.apache.myfaces.application.ResourceHandlerImpl.handleResourceRequest(ResourceHandlerImpl.java:605)
    at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:59)
    at org.primefaces.application.resource.PrimeResourceHandler.handleResourceRequest(PrimeResourceHandler.java:87)
    at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:59)
    at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:59)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:190)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:100)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.openejb.server.httpd.EEFilter.doFilter(EEFilter.java:65)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at br.com.spdata.filter.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:21)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
    at org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:522)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.tomee.catalina.OpenEJBSecurityListener$RequestCapturer.invoke(OpenEJBSecurityListener.java:97)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:1110)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:785)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1425)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

2) Considering that at least jQuery loaded, I came with the following script, but it doesn't replaces the corrupted cached file.

</h:body>

Any ideas?

Thanks in advance


问:
Explicit line joining in Python
I am reading a file, line-by-line and doing some text processing in order to get output in a certain format
My string processing code goes as follows:

```<code>file1=open('/myfolder/testfile.txt')
scanlines=file1.readlines()
string = ''

 for line in scanlines:
    if line.startswith('>from'):
         continue
    if line.startswith('*'):
        continue
    string.join(line.rstrip('\n'))
</code>```

The output of this code is as follows:

abc

def

ghi

Is there a way to join these physical lines into one logical line, e.g:

abcdefghi

Basically, how can I concatenate multiple strings into one large string?

If I was reading from a file with very long strings is there the risk of an overflow by concatenating multiple physical lines into one logical line?

答:
I would prefer:

```<code>oneLine = reduce(lambda x,y: x+y, \
                 [line[:-1] for line in open('/myfolder/testfile.txt')
                            if not line.startswith('>from') and \
                               not line.startswith('*')])
</code>```

line[:-1] in order to remove all the \n

the second argument of reduce is a list comprehension which extracts all the lines you are interested in and removes the \n from the lines.

the reduce (just if you actually need that) to make one string from the list of strings.

Title: Explicit line joining in Python

Body:
I am reading a file, line-by-line and doing some text processing in order to get output in a certain format
My string processing code goes as follows:

file1=open('/myfolder/testfile.txt')
scanlines=file1.readlines()
string = ''

 for line in scanlines:
    if line.startswith('>from'):
         continue
    if line.startswith('*'):
        continue
    string.join(line.rstrip('\n'))

The output of this code is as follows:

abc

def

ghi

Is there a way to join these physical lines into one logical line, e.g:

abcdefghi

Basically, how can I concatenate multiple strings into one large string?

If I was reading from a file with very long strings is there the risk of an overflow by concatenating multiple physical lines into one logical line?

Body:
I would prefer:

oneLine = reduce(lambda x,y: x+y, \
                 [line[:-1] for line in open('/myfolder/testfile.txt')
                            if not line.startswith('>from') and \
                               not line.startswith('*')])

line[:-1] in order to remove all the \n

the second argument of reduce is a list comprehension which extracts all the lines you are interested in and removes the \n from the lines.

the reduce (just if you actually need that) to make one string from the list of strings.


问:
Workers in javascript not so fast
I am giving a try to workers in js and I tried to make a simple sort using the same js sort function. The comparison i am making is just using an async function which will sort 60000 random numbers. The first will sort the random numbers as traditionally we are used to do it.

```<code>async function normalSort(arr) {
    return new Promise((res) => {
        let copy = arr;
        copy.sort((a, b) => a > b ? 1 : -1);
        return res(copy)
    })
}
</code>```

the other is a normal function which will be called for a workersHandler function

```<code>const { Worker, parentPort, workerData } = require('worker_threads');

function sort(data) {
    let copy = data;
    copy.sort((a, b) => a > b ? 1 : -1);
    parentPort.postMessage(copy)
    process.exit();
}

sort(workerData);

</code>```

the workers handler function

```<code>const os = require('os');
const path = require('path');
const { Worker } = require('worker_threads');

async function workersHandler(arr) {
    const startTime = Date.now();
    const cpusAmount = os.cpus().length;
    const chSize = Math.ceil(arr.length / cpusAmount)
    let promises = [];
    for (let i = 0; i < arr.length; i += chSize) {
        const end = i + chSize;
        const currentChunk = arr.slice(i, end);
        const promise = new Promise((res, rej) => {
            //@ts-ignore
            const worker = new Worker(path.join(__dirname, '..', '/utils/sort.js'), { workerData: currentChunk })

            worker.on('message', res)
            worker.on('error', rej)
        })
        promises.push(promise);
    }
    let result = await Promise.all(promises)
    return result;
}

</code>```

and the main function which will call the others functions

```<code>function main() {
    let arr = new Array(60000).fill(0).map((_, i) => Math.round(Math.random() * 100));
    const startTime = Date.now();

    workersHandler(arr).then(r => console.log('workers sort', Date.now() - startTime + ' ms'))
    normalSort(arr).then(r => console.log('normal sort', Date.now() - startTime + ' ms'))
}
main();
</code>```

Surprisingly the normal sort function is way faster and is working in one thread.
I am receiving for the workers function 101 ms
for the normal sort function 53 ms
Someone could explain me why these weird results?. Are workers not so fast or I am making a wrong implementation?.

答:
Basically, using a single worker thread and waiting for it to do the work will always be slower than doing the work in the local thread, because:

Creating threads takes time.

Sending data between threads takes time.

Where you might get gains is if you have isolated pieces of work that can be handled in parallel, and multiple CPU cores to work with. In that situation, you can send different pieces of work to multiple workers (up to as many CPU cores as are available), provided the work isn't constrained by some other single resource they'd all be competing for.

Below I've posted a program that sorts 12 arrays locally and via workers with repeated races. (When sorting in workers, it transfers the array data to the worker and then back rather than copying it.) It starts the workers in advance and reuses them, and but it includes the time that took when determining the average time the workers took to do their work, so we're including all overhead.

On my workstation, with four CPU cores and letting it have a worker for each core, workers easily win:

```
# of workers:     4
Local average:    8790.010573029518ms
Workers' average: 3550.658817946911ms
Workers win, taking 40.39425% of the time local did
```

If I limit it to one worker, though, the worker is pure overhead and the local thread wins:

```
# of workers:     1
Local average:    8907.022233068943ms
Workers' average: 8953.339844942093ms
Local wins, taking 99.48268% of the time workers did
```

Even just two workers wins, because they can work in parallel on this multi-core machine:

```
# of workers:     2
Local average:    8782.853852927685ms
Workers' average: 4754.60275799036ms
Workers win, taking 54.13505% of the time local did
```

On a single core machine (if you can find one anymore), those two workers would be pure overhead again, and the local thread would win.

Here's main.js:

```<code>const os = require('os');
const { Worker } = require('worker_threads');
const { performance } = require('perf_hooks');

const MAX_UINT32 = (2**32)-1;
const ARRAY_SIZE = 100000;
const ARRAY_COUNT = 12;
const workerCount = +process.argv[2] || os.cpus().length;
const raceCount = +process.argv[3] || 5;

class WorkerQueue {
    #workers;
    #available;
    #pending;
    #checkPending = () => { // private methods still aren't unflagged in v13, so...
        if (this.#available.length && this.#pending.length) {
            const resolve = this.#pending.shift();
            const worker = this.#available.shift();
            resolve(worker);
        }
    };

    constructor(...workers) {
        this.#workers = new Set(workers);
        this.#available = [...this.#workers];
        this.#pending = [];
    }

    get() {
        return new Promise(resolve => {
            this.#pending.push(resolve);
            this.#checkPending();
        });
    }

    release(worker) {
        if (!this.#workers.has(worker)) {
            throw new Error("Uknown worker");
        }
        this.#available.push(worker);
        this.#checkPending();
    }

    terminate() {
        for (const worker of this.#workers) {
            worker.terminate();
        }
        this.#workers = new Set();
        this.#available = [];
        this.#pending = [];
    }
}

const {workers, workerCreationTime} = createWorkers();

main();

function createWorkers() {
    const start = performance.now();
    const workers = new WorkerQueue(
        ...Array.from({length: workerCount}, () => new Worker("./worker.js"))
    );
    const workerCreationTime = performance.now() - start;
    return {workers, workerCreationTime};
}

async function main() {
    try {
        console.log(`Workers: ${workerCount} (in ${workerCreationTime}ms), races: ${raceCount}`);
        let localAverage = 0;
        let workersAverage = 0;
        for (let n = 1; n <= raceCount; ++n) {
            console.log(`Race #${n}:`);
            const {localTime, workersTime} = await sortRace();
            localAverage += localTime;
            workersAverage += workersTime;
        }
        // Include the time it took to create the workers in the workers' average, as
        // though we'd created them for each race. (We didn't because doing so would
        // have given the local thread an advantage: after the first race, it's warmed
        // up, but a new worker would be cold. So we let the workers be warm but add
        // the full creation time into each race.
        workersAverage += workerCreationTime;
        console.log("----");
        console.log(`# of workers:     ${workerCount}`);
        console.log(`Local average:    ${localAverage}ms`);
        console.log(`Workers' average: ${workersAverage}ms`);
        if (localAverage > workersAverage) {
            showWinner("Workers win", "local", workersAverage, localAverage);
        } else {
            showWinner("Local wins", "workers", localAverage, workersAverage);
        }
        workers.terminate();
    } catch (e) {
        console.error(e.message, e.stack);
    }
}

function showWinner(msg, loser, winnerAverage, loserAverage) {
    const percentage = (winnerAverage * 100) / loserAverage;
    console.log(`${msg}, taking ${percentage.toFixed(5)}% of the time ${loser} did`);
}

async function sortRace() {
    // Create a bunch of arrays for local to sort
    const localArrays = Array.from({length: ARRAY_COUNT}, () => createRandomArray(ARRAY_SIZE));
    // Copy those array so the workers are dealing with the same values
    const workerArrays = localArrays.map(array => new Uint32Array(array));

    const localStart = performance.now();
    const localResults = await Promise.all(localArrays.map(sortLocal));
    const localTime = performance.now() - localStart;
    checkResults(localResults);
    console.log(`Local time:    ${localTime}ms`);

    const workerStart = performance.now();
    const workersResults = await Promise.all(workerArrays.map(sortViaWorker));
    const workersTime = performance.now() - workerStart;
    checkResults(workersResults);
    console.log(`Workers' time: ${workersTime}ms`);

    return {localTime, workersTime};
}

async function sortLocal(array) {
    await Promise.resolve(); // To make it start asynchronously, like `sortViaWorker` does
    array.sort((a, b) => a - b);
    return array;
}

async function sortViaWorker(array) {
    const worker = await workers.get();
    return new Promise(resolve => {
        worker.once("message", result => {
            workers.release(worker);
            resolve(result.array);
        });
        worker.postMessage({array}, [array.buffer]);
    });
}

function checkResults(arrays) {
    for (const array of arrays) {
        const badIndex = array.findIndex((value, index) => index > 0 && array[index-1] > value);
        if (badIndex !== -1) {
            throw new Error(
                `Error, array entry ${badIndex} has value ${array[badIndex]} ` +
                `which is > previous value ${array[badIndex-1]}`
            );
        }
    }
}

function createRandomArray(length) {
    const array = new Uint32Array(Uint32Array.BYTES_PER_ELEMENT * length);
    return randomFillArray(array);
}

function randomFillArray(array) {
    for (let length = array.length, i = 0; i < length; ++i) {
        array[i] = Math.random() * MAX_UINT32;
    }
    return array;
}
</code>```

and worker.js:

```<code>const { parentPort } = require("worker_threads");

parentPort.on("message", ({array}) => {
    array.sort((a, b) => a - b);
    parentPort.postMessage({array}, [array.buffer]);
});
</code>```

Title: Workers in javascript not so fast

Body:
I am giving a try to workers in js and I tried to make a simple sort using the same js sort function. The comparison i am making is just using an async function which will sort 60000 random numbers. The first will sort the random numbers as traditionally we are used to do it.

async function normalSort(arr) {
    return new Promise((res) => {
        let copy = arr;
        copy.sort((a, b) => a > b ? 1 : -1);
        return res(copy)
    })
}

the other is a normal function which will be called for a workersHandler function

const { Worker, parentPort, workerData } = require('worker_threads');

function sort(data) {
    let copy = data;
    copy.sort((a, b) => a > b ? 1 : -1);
    parentPort.postMessage(copy)
    process.exit();
}

sort(workerData);

the workers handler function

const os = require('os');
const path = require('path');
const { Worker } = require('worker_threads');

async function workersHandler(arr) {
    const startTime = Date.now();
    const cpusAmount = os.cpus().length;
    const chSize = Math.ceil(arr.length / cpusAmount)
    let promises = [];
    for (let i = 0; i < arr.length; i += chSize) {
        const end = i + chSize;
        const currentChunk = arr.slice(i, end);
        const promise = new Promise((res, rej) => {
            //@ts-ignore
            const worker = new Worker(path.join(__dirname, '..', '/utils/sort.js'), { workerData: currentChunk })

            worker.on('message', res)
            worker.on('error', rej)
        })
        promises.push(promise);
    }
    let result = await Promise.all(promises)
    return result;
}

and the main function which will call the others functions

function main() {
    let arr = new Array(60000).fill(0).map((_, i) => Math.round(Math.random() * 100));
    const startTime = Date.now();

    workersHandler(arr).then(r => console.log('workers sort', Date.now() - startTime + ' ms'))
    normalSort(arr).then(r => console.log('normal sort', Date.now() - startTime + ' ms'))
}
main();

Surprisingly the normal sort function is way faster and is working in one thread.
I am receiving for the workers function 101 ms
for the normal sort function 53 ms
Someone could explain me why these weird results?. Are workers not so fast or I am making a wrong implementation?.

Body:
Basically, using a single worker thread and waiting for it to do the work will always be slower than doing the work in the local thread, because:

Creating threads takes time.

Sending data between threads takes time.

Where you might get gains is if you have isolated pieces of work that can be handled in parallel, and multiple CPU cores to work with. In that situation, you can send different pieces of work to multiple workers (up to as many CPU cores as are available), provided the work isn't constrained by some other single resource they'd all be competing for.

Below I've posted a program that sorts 12 arrays locally and via workers with repeated races. (When sorting in workers, it transfers the array data to the worker and then back rather than copying it.) It starts the workers in advance and reuses them, and but it includes the time that took when determining the average time the workers took to do their work, so we're including all overhead.

On my workstation, with four CPU cores and letting it have a worker for each core, workers easily win:

# of workers:     4
Local average:    8790.010573029518ms
Workers' average: 3550.658817946911ms
Workers win, taking 40.39425% of the time local did

If I limit it to one worker, though, the worker is pure overhead and the local thread wins:

# of workers:     1
Local average:    8907.022233068943ms
Workers' average: 8953.339844942093ms
Local wins, taking 99.48268% of the time workers did

Even just two workers wins, because they can work in parallel on this multi-core machine:

# of workers:     2
Local average:    8782.853852927685ms
Workers' average: 4754.60275799036ms
Workers win, taking 54.13505% of the time local did

On a single core machine (if you can find one anymore), those two workers would be pure overhead again, and the local thread would win.

Here's main.js:

const os = require('os');
const { Worker } = require('worker_threads');
const { performance } = require('perf_hooks');

const MAX_UINT32 = (2**32)-1;
const ARRAY_SIZE = 100000;
const ARRAY_COUNT = 12;
const workerCount = +process.argv[2] || os.cpus().length;
const raceCount = +process.argv[3] || 5;

class WorkerQueue {
    #workers;
    #available;
    #pending;
    #checkPending = () => { // private methods still aren't unflagged in v13, so...
        if (this.#available.length && this.#pending.length) {
            const resolve = this.#pending.shift();
            const worker = this.#available.shift();
            resolve(worker);
        }
    };

    constructor(...workers) {
        this.#workers = new Set(workers);
        this.#available = [...this.#workers];
        this.#pending = [];
    }

    get() {
        return new Promise(resolve => {
            this.#pending.push(resolve);
            this.#checkPending();
        });
    }

    release(worker) {
        if (!this.#workers.has(worker)) {
            throw new Error("Uknown worker");
        }
        this.#available.push(worker);
        this.#checkPending();
    }

    terminate() {
        for (const worker of this.#workers) {
            worker.terminate();
        }
        this.#workers = new Set();
        this.#available = [];
        this.#pending = [];
    }
}

const {workers, workerCreationTime} = createWorkers();

main();

function createWorkers() {
    const start = performance.now();
    const workers = new WorkerQueue(
        ...Array.from({length: workerCount}, () => new Worker("./worker.js"))
    );
    const workerCreationTime = performance.now() - start;
    return {workers, workerCreationTime};
}

async function main() {
    try {
        console.log(`Workers: ${workerCount} (in ${workerCreationTime}ms), races: ${raceCount}`);
        let localAverage = 0;
        let workersAverage = 0;
        for (let n = 1; n <= raceCount; ++n) {
            console.log(`Race #${n}:`);
            const {localTime, workersTime} = await sortRace();
            localAverage += localTime;
            workersAverage += workersTime;
        }
        // Include the time it took to create the workers in the workers' average, as
        // though we'd created them for each race. (We didn't because doing so would
        // have given the local thread an advantage: after the first race, it's warmed
        // up, but a new worker would be cold. So we let the workers be warm but add
        // the full creation time into each race.
        workersAverage += workerCreationTime;
        console.log("----");
        console.log(`# of workers:     ${workerCount}`);
        console.log(`Local average:    ${localAverage}ms`);
        console.log(`Workers' average: ${workersAverage}ms`);
        if (localAverage > workersAverage) {
            showWinner("Workers win", "local", workersAverage, localAverage);
        } else {
            showWinner("Local wins", "workers", localAverage, workersAverage);
        }
        workers.terminate();
    } catch (e) {
        console.error(e.message, e.stack);
    }
}

function showWinner(msg, loser, winnerAverage, loserAverage) {
    const percentage = (winnerAverage * 100) / loserAverage;
    console.log(`${msg}, taking ${percentage.toFixed(5)}% of the time ${loser} did`);
}

async function sortRace() {
    // Create a bunch of arrays for local to sort
    const localArrays = Array.from({length: ARRAY_COUNT}, () => createRandomArray(ARRAY_SIZE));
    // Copy those array so the workers are dealing with the same values
    const workerArrays = localArrays.map(array => new Uint32Array(array));

    const localStart = performance.now();
    const localResults = await Promise.all(localArrays.map(sortLocal));
    const localTime = performance.now() - localStart;
    checkResults(localResults);
    console.log(`Local time:    ${localTime}ms`);

    const workerStart = performance.now();
    const workersResults = await Promise.all(workerArrays.map(sortViaWorker));
    const workersTime = performance.now() - workerStart;
    checkResults(workersResults);
    console.log(`Workers' time: ${workersTime}ms`);

    return {localTime, workersTime};
}

async function sortLocal(array) {
    await Promise.resolve(); // To make it start asynchronously, like `sortViaWorker` does
    array.sort((a, b) => a - b);
    return array;
}

async function sortViaWorker(array) {
    const worker = await workers.get();
    return new Promise(resolve => {
        worker.once("message", result => {
            workers.release(worker);
            resolve(result.array);
        });
        worker.postMessage({array}, [array.buffer]);
    });
}

function checkResults(arrays) {
    for (const array of arrays) {
        const badIndex = array.findIndex((value, index) => index > 0 && array[index-1] > value);
        if (badIndex !== -1) {
            throw new Error(
                `Error, array entry ${badIndex} has value ${array[badIndex]} ` +
                `which is > previous value ${array[badIndex-1]}`
            );
        }
    }
}

function createRandomArray(length) {
    const array = new Uint32Array(Uint32Array.BYTES_PER_ELEMENT * length);
    return randomFillArray(array);
}

function randomFillArray(array) {
    for (let length = array.length, i = 0; i < length; ++i) {
        array[i] = Math.random() * MAX_UINT32;
    }
    return array;
}

and worker.js:

const { parentPort } = require("worker_threads");

parentPort.on("message", ({array}) => {
    array.sort((a, b) => a - b);
    parentPort.postMessage({array}, [array.buffer]);
});


问:
Copying the adjacent cell text of Excel
I need to have a Macro in Microsoft Word in which I search for a specified word in Excel (a name for example), but copy the text of the cell at the right (email). This is what I've done trying to solve the problem:

```<code>Dim xlApp As New Excel.Application, xlWkBk As Excel.Workbook
Dim StrWkBkNm As String, StrWkShtNm As String, LRow As Long, i As Long
StrWkBkNm = ActiveDocument.Path & "\BD.xlsx"
StrWkShtNm = "Hoja2"
With xlApp
  Set xlWkBk = .Workbooks.Open(StrWkBkNm) '''''''''''''''''''
  With xlWkBk
      With .Worksheets(StrWkShtNm)
        .Cells.Find(What:="Prueba", After:=ActiveCell, LookAt _
    :=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:= _
    False, SearchFormat:=False).Activate
    Selection.Copy
      End With
    .Close False
  End With
  .Quit
End With
Selection.Paste
</code>```

For example, I need to search for the name "AAAA", but copy aaaa@gmail.com" in the word document. See the image for better understanding.

答:
For a different approach, try:

```<code>Sub BulkFindReplace()
Application.ScreenUpdating = False
Dim xlApp As Object, xlWkBk As Object, StrWkBkNm As String, StrWkSht As String
Dim iDataRow As Long, xlFList As String, xlRList As String, i As Long
StrWkBkNm = ActiveDocument.Path & "\BD.xlsx"
StrWkSht = "Hoja2"
If Dir(StrWkBkNm) = "" Then
  MsgBox "Cannot find the designated workbook: " & StrWkBkNm, vbExclamation
  Exit Sub
End If
On Error Resume Next
'Start Excel
Set xlApp = CreateObject("Excel.Application")
If xlApp Is Nothing Then
  MsgBox "Can't start Excel.", vbExclamation
  Exit Sub
End If
On Error GoTo 0
With xlApp
  'Hide our Excel session
  .Visible = False
  ' The file is available, so open it.
  Set xlWkBk = .Workbooks.Open(FileName:=StrWkBkNm, ReadOnly:=True, AddToMru:=False)
  If xlWkBk Is Nothing Then
    MsgBox "Cannot open:" & vbCr & StrWkBkNm, vbExclamation
    .Quit: Set xlApp = Nothing: Exit Sub
  End If
  ' Process the workbook.
  With xlWkBk
    With .Worksheets(StrWkSht)
      ' Find the last-used row in column A.
      iDataRow = .Cells(.Rows.Count, 1).End(-4162).Row ' -4162 = xlUp
      ' Capture the F/R data.
      For i = 1 To iDataRow
        ' Skip over empty fields to preserve the underlying cell contents.
        If Trim(.Range("A" & i)) <> vbNullString Then
          xlFList = xlFList & "|" & Trim(.Range("A" & i))
          xlRList = xlRList & "|" & Trim(.Range("B" & i))
        End If
      Next
    End With
  .Close False
  End With
  .Quit
End With
' Release Excel object memory
Set xlWkBk = Nothing: Set xlApp = Nothing
'Exit if there are no data
If xlFList = "" Then Exit Sub
'Process each word from the F/R List
With ActiveDocument.Range.Find
  .ClearFormatting
  .Replacement.ClearFormatting
  .MatchWholeWord = True
  .MatchCase = True
  .Wrap = wdFindContinue
  For i = 1 To UBound(Split(xlFList, "|"))
    .Text = Split(xlFList, "|")(i)
    .Replacement.Text = Split(xlRList, "|")(i)
    .Execute Replace:=wdReplaceAll
  Next
End With
Application.ScreenUpdating = True
End Sub
</code>```

With the above code, you don't need to specify the search term - the macro simply processes all potential terms in column A and replaces them with the corresponding email addresses from Column B (you can change the column references if you wish).

As coded, the email addresses are inserted as simple text strings. If you want them to be formatted as hyperlinks, insert:

```<code>'Get current autoformat options
With Options
  bHead = .AutoFormatApplyHeadings
  bList = .AutoFormatApplyLists
  bBullet = .AutoFormatApplyBulletedLists
  bOther = .AutoFormatApplyOtherParas
  bQuote = .AutoFormatReplaceQuotes
  bSymbol = .AutoFormatReplaceSymbols
  bOrdinal = .AutoFormatReplaceOrdinals
  bFraction = .AutoFormatReplaceFractions
  bEmphasis = .AutoFormatReplacePlainTextEmphasis
  bHLink = .AutoFormatReplaceHyperlinks
  bStyle = .AutoFormatPreserveStyles
  bMail = .AutoFormatPlainTextWordMail
  bTag = .LabelSmartTags
End With
'Restrict autoformat options to emails
With Options
  .AutoFormatApplyHeadings = False
  .AutoFormatApplyLists = False
  .AutoFormatApplyBulletedLists = False
  .AutoFormatApplyOtherParas = False
  .AutoFormatReplaceQuotes = False
  .AutoFormatReplaceSymbols = False
  .AutoFormatReplaceOrdinals = False
  .AutoFormatReplaceFractions = False
  .AutoFormatReplacePlainTextEmphasis = False
  .AutoFormatReplaceHyperlinks = False
  .AutoFormatPreserveStyles = False
  .AutoFormatPlainTextWordMail = True
  .LabelSmartTags = False
End With
</code>```

after:

```<code>If xlFList = "" Then Exit Sub
</code>```

and insert:

```<code>'Restore the original autoformat options
With Options
  .AutoFormatApplyHeadings = bHead
  .AutoFormatApplyLists = bList
  .AutoFormatApplyBulletedLists = bBullet
  .AutoFormatApplyOtherParas = bOther
  .AutoFormatReplaceQuotes = bQuote
  .AutoFormatReplaceSymbols = bSymbol
  .AutoFormatReplaceOrdinals = bOrdinal
  .AutoFormatReplaceFractions = bFraction
  .AutoFormatReplacePlainTextEmphasis = bEmphasis
  .AutoFormatReplaceHyperlinks = bHLink
  .AutoFormatPreserveStyles = bStyle
  .AutoFormatPlainTextWordMail = bMail
  .LabelSmartTags = bTag
End With
</code>```

before:

```<code>Application.ScreenUpdating = True
</code>```

Title: Copying the adjacent cell text of Excel

Body:
I need to have a Macro in Microsoft Word in which I search for a specified word in Excel (a name for example), but copy the text of the cell at the right (email). This is what I've done trying to solve the problem:

Dim xlApp As New Excel.Application, xlWkBk As Excel.Workbook
Dim StrWkBkNm As String, StrWkShtNm As String, LRow As Long, i As Long
StrWkBkNm = ActiveDocument.Path & "\BD.xlsx"
StrWkShtNm = "Hoja2"
With xlApp
  Set xlWkBk = .Workbooks.Open(StrWkBkNm) '''''''''''''''''''
  With xlWkBk
      With .Worksheets(StrWkShtNm)
        .Cells.Find(What:="Prueba", After:=ActiveCell, LookAt _
    :=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:= _
    False, SearchFormat:=False).Activate
    Selection.Copy
      End With
    .Close False
  End With
  .Quit
End With
Selection.Paste

For example, I need to search for the name "AAAA", but copy aaaa@gmail.com" in the word document. See the image for better understanding.

Body:
For a different approach, try:

Sub BulkFindReplace()
Application.ScreenUpdating = False
Dim xlApp As Object, xlWkBk As Object, StrWkBkNm As String, StrWkSht As String
Dim iDataRow As Long, xlFList As String, xlRList As String, i As Long
StrWkBkNm = ActiveDocument.Path & "\BD.xlsx"
StrWkSht = "Hoja2"
If Dir(StrWkBkNm) = "" Then
  MsgBox "Cannot find the designated workbook: " & StrWkBkNm, vbExclamation
  Exit Sub
End If
On Error Resume Next
'Start Excel
Set xlApp = CreateObject("Excel.Application")
If xlApp Is Nothing Then
  MsgBox "Can't start Excel.", vbExclamation
  Exit Sub
End If
On Error GoTo 0
With xlApp
  'Hide our Excel session
  .Visible = False
  ' The file is available, so open it.
  Set xlWkBk = .Workbooks.Open(FileName:=StrWkBkNm, ReadOnly:=True, AddToMru:=False)
  If xlWkBk Is Nothing Then
    MsgBox "Cannot open:" & vbCr & StrWkBkNm, vbExclamation
    .Quit: Set xlApp = Nothing: Exit Sub
  End If
  ' Process the workbook.
  With xlWkBk
    With .Worksheets(StrWkSht)
      ' Find the last-used row in column A.
      iDataRow = .Cells(.Rows.Count, 1).End(-4162).Row ' -4162 = xlUp
      ' Capture the F/R data.
      For i = 1 To iDataRow
        ' Skip over empty fields to preserve the underlying cell contents.
        If Trim(.Range("A" & i)) <> vbNullString Then
          xlFList = xlFList & "|" & Trim(.Range("A" & i))
          xlRList = xlRList & "|" & Trim(.Range("B" & i))
        End If
      Next
    End With
  .Close False
  End With
  .Quit
End With
' Release Excel object memory
Set xlWkBk = Nothing: Set xlApp = Nothing
'Exit if there are no data
If xlFList = "" Then Exit Sub
'Process each word from the F/R List
With ActiveDocument.Range.Find
  .ClearFormatting
  .Replacement.ClearFormatting
  .MatchWholeWord = True
  .MatchCase = True
  .Wrap = wdFindContinue
  For i = 1 To UBound(Split(xlFList, "|"))
    .Text = Split(xlFList, "|")(i)
    .Replacement.Text = Split(xlRList, "|")(i)
    .Execute Replace:=wdReplaceAll
  Next
End With
Application.ScreenUpdating = True
End Sub

With the above code, you don't need to specify the search term - the macro simply processes all potential terms in column A and replaces them with the corresponding email addresses from Column B (you can change the column references if you wish).

As coded, the email addresses are inserted as simple text strings. If you want them to be formatted as hyperlinks, insert:

'Get current autoformat options
With Options
  bHead = .AutoFormatApplyHeadings
  bList = .AutoFormatApplyLists
  bBullet = .AutoFormatApplyBulletedLists
  bOther = .AutoFormatApplyOtherParas
  bQuote = .AutoFormatReplaceQuotes
  bSymbol = .AutoFormatReplaceSymbols
  bOrdinal = .AutoFormatReplaceOrdinals
  bFraction = .AutoFormatReplaceFractions
  bEmphasis = .AutoFormatReplacePlainTextEmphasis
  bHLink = .AutoFormatReplaceHyperlinks
  bStyle = .AutoFormatPreserveStyles
  bMail = .AutoFormatPlainTextWordMail
  bTag = .LabelSmartTags
End With
'Restrict autoformat options to emails
With Options
  .AutoFormatApplyHeadings = False
  .AutoFormatApplyLists = False
  .AutoFormatApplyBulletedLists = False
  .AutoFormatApplyOtherParas = False
  .AutoFormatReplaceQuotes = False
  .AutoFormatReplaceSymbols = False
  .AutoFormatReplaceOrdinals = False
  .AutoFormatReplaceFractions = False
  .AutoFormatReplacePlainTextEmphasis = False
  .AutoFormatReplaceHyperlinks = False
  .AutoFormatPreserveStyles = False
  .AutoFormatPlainTextWordMail = True
  .LabelSmartTags = False
End With

after:

If xlFList = "" Then Exit Sub

and insert:

'Restore the original autoformat options
With Options
  .AutoFormatApplyHeadings = bHead
  .AutoFormatApplyLists = bList
  .AutoFormatApplyBulletedLists = bBullet
  .AutoFormatApplyOtherParas = bOther
  .AutoFormatReplaceQuotes = bQuote
  .AutoFormatReplaceSymbols = bSymbol
  .AutoFormatReplaceOrdinals = bOrdinal
  .AutoFormatReplaceFractions = bFraction
  .AutoFormatReplacePlainTextEmphasis = bEmphasis
  .AutoFormatReplaceHyperlinks = bHLink
  .AutoFormatPreserveStyles = bStyle
  .AutoFormatPlainTextWordMail = bMail
  .LabelSmartTags = bTag
End With

before:

Application.ScreenUpdating = True


问:
app.box .NET SDK returning empty collection of items
I have followed the steps in .NET SDK documenation for JWT authenticated app, but keep getting empty items collection on GetFolderItemsAsync method.

I have configured it with Enterprise application access and authorized it...

Authentication seems ok, because I don't get an exception when creating the BoxJWTAuth object.

```<code>        var reader = new StreamReader(@"PathToJSONConfigFile");
        var json = reader
            .ReadToEnd();
        var config = BoxConfig
            .CreateFromJsonString(json);
        var sdk = new BoxJWTAuth(config);
        var token = sdk
            .AdminToken();

        var adminClient = sdk
            .AdminClient(token);

        var folders = await adminClient
            .FoldersManager
            .GetFolderItemsAsync("0", 500, fields: new string[] { BoxCollection.FieldEntries });
</code>```

答:
Figured it out on my own.

Just in case somebody faces the same problem. I was trying to access folders with a automatically generated admin client. Apparently this type of client doesn't have authorization to get folder lists.

You have to get your enterprise users and instantiate a user client object with user id.

```<code>var boxUsers = await adminClient.UsersManager.GetEnterpriseUsersAsync();
        var user= boxUsers
            .Entries
            .FirstOrDefault(x => x.Login.Contains("user"));

        var cli = new BoxClient(config, auth, asUser: user.Id);
        try
        {
            var fold = await cli
            .FoldersManager
            .GetFolderItemsAsync("0", 500, fields: new string[] { BoxCollection.FieldEntries, BoxItem.FieldName, BoxItem.FieldSharedLink, BoxItem.FieldPathCollection });
</code>```

Body:
I have followed the steps in .NET SDK documenation for JWT authenticated app, but keep getting empty items collection on GetFolderItemsAsync method.

I have configured it with Enterprise application access and authorized it...

Authentication seems ok, because I don't get an exception when creating the BoxJWTAuth object.

        var reader = new StreamReader(@"PathToJSONConfigFile");
        var json = reader
            .ReadToEnd();
        var config = BoxConfig
            .CreateFromJsonString(json);
        var sdk = new BoxJWTAuth(config);
        var token = sdk
            .AdminToken();

        var adminClient = sdk
            .AdminClient(token);

        var folders = await adminClient
            .FoldersManager
            .GetFolderItemsAsync("0", 500, fields: new string[] { BoxCollection.FieldEntries });

Body:
Figured it out on my own.

Just in case somebody faces the same problem. I was trying to access folders with a automatically generated admin client. Apparently this type of client doesn't have authorization to get folder lists.

You have to get your enterprise users and instantiate a user client object with user id.

var boxUsers = await adminClient.UsersManager.GetEnterpriseUsersAsync();
        var user= boxUsers
            .Entries
            .FirstOrDefault(x => x.Login.Contains("user"));

        var cli = new BoxClient(config, auth, asUser: user.Id);
        try
        {
            var fold = await cli
            .FoldersManager
            .GetFolderItemsAsync("0", 500, fields: new string[] { BoxCollection.FieldEntries, BoxItem.FieldName, BoxItem.FieldSharedLink, BoxItem.FieldPathCollection });


问:
Spring use Computer name instead of supplied username for jdbc database access
Reading Pro Spring 5, an example that show Spring JDBC is using MySQL DB. I use the book source code. Here is the code

```<code>@Configuration
@PropertySource("classpath:db/jdbc2.properties")
@ComponentScan(basePackages = "com.apress.prospring5.ch6")
public class AppConfig {

    private static Logger logger = LoggerFactory.getLogger(AppConfig.class);
    @Value("${driverClassName}")
    private String driverClassName;
    @Value("${url}")
    private String url;
    @Value("${username}")
    private String username;
    @Value("${password}")
    private String password;

@Bean(destroyMethod = "close")
    public DataSource dataSource() {
        try {
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName(driverClassName);
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            return dataSource;
        } catch (Exception e) {
            logger.error("DBCP DataSource bean cannot be created!", e);
            return null;
        }
    }
</code>```

jdbc2.properties

```<code>driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/musicdb?useSSL=true
username=prospring5
password=prospring5
</code>```

The test

```<code>public class AnnotationJdbcTest {

    private GenericApplicationContext ctx;
    private SingerDao singerDao;

    @Before
    public void setUp() {
        ctx = new AnnotationConfigApplicationContext(AppConfig.class);
        singerDao = ctx.getBean(SingerDao.class);
        assertNotNull(singerDao);
    }

    @Test
    public void testFindAll() {
        List<Singer> singers = singerDao.findAll();
        assertTrue(singers.size() == 3);
        listSingers(singers);
        ctx.close();
    }
</code>```

My MySQL instance already have the user prospring5 and the schema created and populated

When I try to run AnnotationJdbcTest, I get this exception:

```<code>Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Cannot create PoolableConnectionFactory (Access denied for user 'Mehdi'@'localhost' (using password: YES))
org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Cannot create PoolableConnectionFactory (Access denied for user 'Mehdi'@'localhost' (using password: YES))
    at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:82)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:612)
</code>```

As you can see the project is using my computer name 'Mehdi' instead of the one in the .properties file 'prospring5' . Why is That? and how Can I fix it?

You can yourself download the source code and run it from here: https://github.com/Apress/pro-spring-5
the project is: chapter6/spring-jdbc-annotations

EDIT:
I printed the values as suggested by @STaefi and here is the output:

```<code>com.mysql.cj.jdbc.Driver
jdbc:mysql://localhost:3306/musicdb?useSSL=false
Mehdi
prospring5
</code>```

Code

```<code>@Bean()
    public DataSource dataSource() {
        try {
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName(driverClassName);
            System.out.println(driverClassName);
            dataSource.setUrl(url);
            System.out.println(url);
            dataSource.setUsername(username);
            System.out.println(username);
            dataSource.setPassword(password);
            System.out.println(password);
            return dataSource;
</code>```

First I tried setting the values at initialization and that was no good. but after I used username = "prospring5"; dataSource.setUsername(username); it worked. so what does this mean. why Spring cannot load the username like it successfully loaded the url and the password.

答:
Could you please try by giving a default value as :

```<code>@Value("${driverClassName:com.mysql.cj.jdbc.Driver}")
private String driverClassName;
@Value("${url:jdbc:mysql://localhost:3306/musicdb?useSSL=true}")
private String url;
@Value("${username:prospring5}")
private String username;
@Value("${password:prospring5}")
private String password;
</code>```

And remove the @PropertySource("classpath:db/jdbc2.properties") at the top. If this works then you can try with the propertySource again

Body:
Reading Pro Spring 5, an example that show Spring JDBC is using MySQL DB. I use the book source code. Here is the code

@Configuration
@PropertySource("classpath:db/jdbc2.properties")
@ComponentScan(basePackages = "com.apress.prospring5.ch6")
public class AppConfig {

    private static Logger logger = LoggerFactory.getLogger(AppConfig.class);
    @Value("${driverClassName}")
    private String driverClassName;
    @Value("${url}")
    private String url;
    @Value("${username}")
    private String username;
    @Value("${password}")
    private String password;

@Bean(destroyMethod = "close")
    public DataSource dataSource() {
        try {
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName(driverClassName);
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            return dataSource;
        } catch (Exception e) {
            logger.error("DBCP DataSource bean cannot be created!", e);
            return null;
        }
    }

jdbc2.properties

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/musicdb?useSSL=true
username=prospring5
password=prospring5

The test

public class AnnotationJdbcTest {

    private GenericApplicationContext ctx;
    private SingerDao singerDao;

    @Before
    public void setUp() {
        ctx = new AnnotationConfigApplicationContext(AppConfig.class);
        singerDao = ctx.getBean(SingerDao.class);
        assertNotNull(singerDao);
    }

    @Test
    public void testFindAll() {
        List<Singer> singers = singerDao.findAll();
        assertTrue(singers.size() == 3);
        listSingers(singers);
        ctx.close();
    }

My MySQL instance already have the user prospring5 and the schema created and populated

When I try to run AnnotationJdbcTest, I get this exception:

Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Cannot create PoolableConnectionFactory (Access denied for user 'Mehdi'@'localhost' (using password: YES))
org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Cannot create PoolableConnectionFactory (Access denied for user 'Mehdi'@'localhost' (using password: YES))
    at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:82)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:612)

As you can see the project is using my computer name 'Mehdi' instead of the one in the .properties file 'prospring5' . Why is That? and how Can I fix it?

You can yourself download the source code and run it from here: https://github.com/Apress/pro-spring-5
the project is: chapter6/spring-jdbc-annotations

EDIT:
I printed the values as suggested by @STaefi and here is the output:

com.mysql.cj.jdbc.Driver
jdbc:mysql://localhost:3306/musicdb?useSSL=false
Mehdi
prospring5

Code

@Bean()
    public DataSource dataSource() {
        try {
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName(driverClassName);
            System.out.println(driverClassName);
            dataSource.setUrl(url);
            System.out.println(url);
            dataSource.setUsername(username);
            System.out.println(username);
            dataSource.setPassword(password);
            System.out.println(password);
            return dataSource;

First I tried setting the values at initialization and that was no good. but after I used username = "prospring5"; dataSource.setUsername(username); it worked. so what does this mean. why Spring cannot load the username like it successfully loaded the url and the password.

Body:
Could you please try by giving a default value as :

@Value("${driverClassName:com.mysql.cj.jdbc.Driver}")
private String driverClassName;
@Value("${url:jdbc:mysql://localhost:3306/musicdb?useSSL=true}")
private String url;
@Value("${username:prospring5}")
private String username;
@Value("${password:prospring5}")
private String password;

And remove the @PropertySource("classpath:db/jdbc2.properties") at the top. If this works then you can try with the propertySource again


问:
AnyChart android refreshing a chart
I am using anychart library for android to display a pie chart, it gets the data from a mysql using volley and a node JS api to facilitate the crud operation

I am just facing a problem refresing the chart when new data is available from the data base.
I used Log.d to make sure the data is actually being updated it, I checked anycharts github and tried the solutions they listed, mainly that I just need to set the data again with the new data, that didn't work
Please any help is greatly appreciated.
I even tried creating a button and try to set the graph with complety new and hardcoded data. but that didn't work, I tried to use gone and visible and that didn't work

here is my code:

```<code> package com.dana.baizaty_frontend.fragments

import Transaction
import android.os.Bundle
import android.provider.ContactsContract
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.anychart.APIlib
import com.anychart.AnyChart
import com.anychart.AnyChartView
import com.anychart.chart.common.dataentry.DataEntry
import com.anychart.chart.common.dataentry.ValueDataEntry
import com.anychart.enums.Align
import com.anychart.enums.LegendLayout
import com.dana.baizaty_frontend.R
import com.dana.baizaty_frontend.singleton.AppSingleton
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.fragment_pfm.*

class PFM : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

//        val anyChartView: AnyChartView? = any_chart_view

        // Inflate the layout for this fragment
//        createChart()

        var v = inflater.inflate(R.layout.fragment_pfm, container, false)

        return v

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
//        getTransactions()
        button.setOnClickListener{
            updateChart()
        }

    }

    override fun onStart() {

        super.onStart()
        getTransactions()

        Toast.makeText(context, "testing", "testing".length).show()
    }
    fun createChart (data1: MutableList<DataEntry>
    ) {
//        var anyChartView: AnyChartView? = any_chart_view

//        APIlib.getInstance().setActiveAnyChartView(any_chart_view)
//        any_chart_view.clear()
        any_chart_view.visibility=View.GONE

        any_chart_view.setProgressBar(progress_bar)
        var pie = AnyChart.pie3d()
//        anyChartView?.setProgressBar(progress_bar)

//        data.add(ValueDataEntry("Restarant", 30))
//        data.add(ValueDataEntry("transportation", 23))
//        data.add(ValueDataEntry("cafe", 10))
        Log.d("catagor3",data1.toString())

        pie.data(data1)
        pie.title("spending")
        pie.labels().position("outside")
        pie.legend().title().enabled(true)

        pie.legend()
            .position("center-bottom")
            .itemsLayout(LegendLayout.HORIZONTAL)
            .align(Align.CENTER);

        any_chart_view?.setChart(pie);
        any_chart_view.visibility=View.VISIBLE
        data1.clear()

    }
    fun updateChart(){
        var data1 = mutableListOf<DataEntry>()
        data1.add(ValueDataEntry("Restarant", 30))
        data1.add(ValueDataEntry("transportation", 23))
        data1.add(ValueDataEntry("cafe", 10))
        var pie=AnyChart.pie3d()
        any_chart_view.setChart(pie)

    }

    fun getTransactions() {
        var data = mutableListOf<DataEntry>()
        any_chart_view.invalidate()
        var queue = AppSingleton.instance.getQueue(context)
        var transactionsRequest = StringRequest(
            Request.Method.GET,
            AppSingleton.instance.getBaseUrl() + "transactions/3",
            Response.Listener<String> { response ->
                // Success case

                var transactionList = Gson().fromJson<List<Transaction>>(response, object :
                    TypeToken<List<Transaction>>() {}.type)

                var catagories = mutableListOf<String>()
                var values = mutableListOf<Double>()

                transactionList.forEach {
//                    Log.d("catgor",it.toString())
                    if (catagories.contains(it.catagorie)) {
                        var idx = catagories.indexOf(it.catagorie)
//                        Log.d("catgor1",idx.toString())
//                        Log.d("catgor2",catagories.toString())

                        values[idx] += it.amount

                    }else{
                        catagories.add(it.catagorie)
                        values.add(it.amount)
                        var idx=catagories.indexOf(it.catagorie)
//                        values[idx]=0.0
                    }
                }
                Log.d("catagor",catagories.toString())
                Log.d("catagor",values.toString())

                catagories.forEach{
                    var idx=catagories.indexOf(it)
                    data.add(ValueDataEntry(it,values[idx]))
                }
                Log.d("catagor3",data.toString())

                createChart(data)
                data.clear()
                Log.d("catagor3",data.toString())

            },
            Response.ErrorListener {
                // Error case
            })
        queue?.add(transactionsRequest)
    }
}
</code>```

and here is my xml

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragments.PFM">

    <com.anychart.AnyChartView
        android:id="@+id/any_chart_view"
        android:layout_width="389dp"
        android:layout_height="333dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <ProgressBar
        android:id="@+id/progress_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="144dp"
        android:layout_marginTop="78dp"
        android:text="Button"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/any_chart_view" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

答:
Directly it's not possible , You need to add Socket for it SocketIO for it. So you need to integrate socketIO server side and client side both .
Please check this :-

https://stackoverflow.com/a/25229881/11393364

Title: AnyChart android refreshing a chart

Body:
I am using anychart library for android to display a pie chart, it gets the data from a mysql using volley and a node JS api to facilitate the crud operation

I am just facing a problem refresing the chart when new data is available from the data base.
I used Log.d to make sure the data is actually being updated it, I checked anycharts github and tried the solutions they listed, mainly that I just need to set the data again with the new data, that didn't work
Please any help is greatly appreciated.
I even tried creating a button and try to set the graph with complety new and hardcoded data. but that didn't work, I tried to use gone and visible and that didn't work

here is my code:

 package com.dana.baizaty_frontend.fragments

import Transaction
import android.os.Bundle
import android.provider.ContactsContract
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.anychart.APIlib
import com.anychart.AnyChart
import com.anychart.AnyChartView
import com.anychart.chart.common.dataentry.DataEntry
import com.anychart.chart.common.dataentry.ValueDataEntry
import com.anychart.enums.Align
import com.anychart.enums.LegendLayout
import com.dana.baizaty_frontend.R
import com.dana.baizaty_frontend.singleton.AppSingleton
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.fragment_pfm.*

class PFM : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

//        val anyChartView: AnyChartView? = any_chart_view

        // Inflate the layout for this fragment
//        createChart()

        var v = inflater.inflate(R.layout.fragment_pfm, container, false)

        return v

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
//        getTransactions()
        button.setOnClickListener{
            updateChart()
        }

    }

    override fun onStart() {

        super.onStart()
        getTransactions()

        Toast.makeText(context, "testing", "testing".length).show()
    }
    fun createChart (data1: MutableList<DataEntry>
    ) {
//        var anyChartView: AnyChartView? = any_chart_view

//        APIlib.getInstance().setActiveAnyChartView(any_chart_view)
//        any_chart_view.clear()
        any_chart_view.visibility=View.GONE

        any_chart_view.setProgressBar(progress_bar)
        var pie = AnyChart.pie3d()
//        anyChartView?.setProgressBar(progress_bar)

//        data.add(ValueDataEntry("Restarant", 30))
//        data.add(ValueDataEntry("transportation", 23))
//        data.add(ValueDataEntry("cafe", 10))
        Log.d("catagor3",data1.toString())

        pie.data(data1)
        pie.title("spending")
        pie.labels().position("outside")
        pie.legend().title().enabled(true)

        pie.legend()
            .position("center-bottom")
            .itemsLayout(LegendLayout.HORIZONTAL)
            .align(Align.CENTER);

        any_chart_view?.setChart(pie);
        any_chart_view.visibility=View.VISIBLE
        data1.clear()

    }
    fun updateChart(){
        var data1 = mutableListOf<DataEntry>()
        data1.add(ValueDataEntry("Restarant", 30))
        data1.add(ValueDataEntry("transportation", 23))
        data1.add(ValueDataEntry("cafe", 10))
        var pie=AnyChart.pie3d()
        any_chart_view.setChart(pie)

    }

    fun getTransactions() {
        var data = mutableListOf<DataEntry>()
        any_chart_view.invalidate()
        var queue = AppSingleton.instance.getQueue(context)
        var transactionsRequest = StringRequest(
            Request.Method.GET,
            AppSingleton.instance.getBaseUrl() + "transactions/3",
            Response.Listener<String> { response ->
                // Success case

                var transactionList = Gson().fromJson<List<Transaction>>(response, object :
                    TypeToken<List<Transaction>>() {}.type)

                var catagories = mutableListOf<String>()
                var values = mutableListOf<Double>()

                transactionList.forEach {
//                    Log.d("catgor",it.toString())
                    if (catagories.contains(it.catagorie)) {
                        var idx = catagories.indexOf(it.catagorie)
//                        Log.d("catgor1",idx.toString())
//                        Log.d("catgor2",catagories.toString())

                        values[idx] += it.amount

                    }else{
                        catagories.add(it.catagorie)
                        values.add(it.amount)
                        var idx=catagories.indexOf(it.catagorie)
//                        values[idx]=0.0
                    }
                }
                Log.d("catagor",catagories.toString())
                Log.d("catagor",values.toString())

                catagories.forEach{
                    var idx=catagories.indexOf(it)
                    data.add(ValueDataEntry(it,values[idx]))
                }
                Log.d("catagor3",data.toString())

                createChart(data)
                data.clear()
                Log.d("catagor3",data.toString())

            },
            Response.ErrorListener {
                // Error case
            })
        queue?.add(transactionsRequest)
    }
}

and here is my xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragments.PFM">

    <com.anychart.AnyChartView
        android:id="@+id/any_chart_view"
        android:layout_width="389dp"
        android:layout_height="333dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <ProgressBar
        android:id="@+id/progress_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="144dp"
        android:layout_marginTop="78dp"
        android:text="Button"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/any_chart_view" />
</androidx.constraintlayout.widget.ConstraintLayout>


问:
Laravel group by, count and access and eloquent relationship
I'd like to group by a foreign key ID, count that group and then in the view be able to access the relationship of that foreign key ID. The first two things (group by and count) succeed with the following query:

```<code>$collection = Example::selectRaw('count(*) AS total, foreign_key')
->groupBy('foreign_key')
->orderBy('total', 'DESC')
->get();
</code>```

But I can't figure out how I can access the eloquent relationship of the foreign key, so that in the view I can do something like

```<code>foreach($collection as $c)
{
  $c->total;
  $c->foreign->title
  $c->foreign->address
}
</code>```

Note that the Example Model has the relationship defined:

```<code>class Example extends Model
{
  public function foreign()
  {
    return $this->hasOne('App\Models\Foreign', 'id', 'foreign_key')
  }
}
</code>```

答:
Try this:

```<code>$collection = Example::selectRaw('count(*) AS total, foreign_key')
->with('foreign')
->orderBy('total', 'DESC')
->get();
</code>```

Also, you probably don't need groupBy() since it is a one to one relationship and thus would return only one result (as @DilipHirapara suggested).

Body:
I'd like to group by a foreign key ID, count that group and then in the view be able to access the relationship of that foreign key ID. The first two things (group by and count) succeed with the following query:

$collection = Example::selectRaw('count(*) AS total, foreign_key')
->groupBy('foreign_key')
->orderBy('total', 'DESC')
->get();

But I can't figure out how I can access the eloquent relationship of the foreign key, so that in the view I can do something like

foreach($collection as $c)
{
  $c->total;
  $c->foreign->title
  $c->foreign->address
}

Note that the Example Model has the relationship defined:

class Example extends Model
{
  public function foreign()
  {
    return $this->hasOne('App\Models\Foreign', 'id', 'foreign_key')
  }
}

Body:
Try this:

$collection = Example::selectRaw('count(*) AS total, foreign_key')
->with('foreign')
->orderBy('total', 'DESC')
->get();

Also, you probably don't need groupBy() since it is a one to one relationship and thus would return only one result (as @DilipHirapara suggested).


问:
Send Newsletter to Users at 9:00 AM in their Local Time Zone
I am using the following gems:

timezone

tzinfo

I am trying to have a newsletter sent at user's time zone, so that they get the newsletter at their 9:00:00; not 09:00:00 PST where my server is.

I am storing the time zones by name, like "Pacific Time (US & Canada)".  Each user has a column user.time_zone where their specific time zone is stored.

I have built a job that checks every hour for users who could receive the newsletter (i.e. users whose local time is 9:00 AM).

```<code>class NewsletterTimezoneJob < ActiveJob::Base
  def self.perform
      users = User.all.gets_newsletter
      users.each do |user|
      d = Date.current
      t = "09:00:00 -0700"
      t = t.to_time
      newsletter_sendtime = DateTime.new(d.year, d.month, d.day, t.hour, t.min, t.sec, t.zone)
      newsletter_sendtime = newsletter_sendtime.to_s
      if user.is_in_time_around(newsletter_sendtime)
        NewsletterMailer.send_mailer(user, newsletter_sendtime).deliver_later
      end
    end
  end
end
</code>```

I have built a method on user that tries to see if the user's local time matches newsletter_sendtime.

I added a +/- 5 minute window to account for slow servers.

User.rb:

```<code>def is_in_time_around(timeofday)
   timeofday = timeofday.to_time
   user_zoned =  timeofday.in_time_zone(self.time_zone)
   user_zoned = user_zoned.strftime("%r").to_time
   timeofday = timeofday.strftime("%r").to_time
   if user_zoned >= (timeofday - 5.minutes) && user_zoned <= (timeofday + 5.minutes)
    true
   end
 end
</code>```

This job and method should run every hour and send to different users in different time zones each hour; and yet it currently only sends to users in "Pacific Time (US & Canada)," each hour and never sends it to any other `users.

答:
Incase if it helps someone, following might help

Schedule a job to run at 8pm (UTC) on previous day, as 8pm UTC is 9am in NewZealand and a few more timezones. And UTC 8pm is when first 9am happens for any timezone.

```<code># group time_zones by utc_offset (In hours)
ActiveSupport::TimeZone.all.group_by { |tz| tz.utc_offset/3600.0 }.each do |utc_offset_in_hrs, time_zones|
  User.where(time_zone: time_zones).each do |user|
    # Schedule the email as per time_zone, using delayed_job's run_at param
    # Using +13, as that is the highest/first timezone to have 9AM
    NewsletterMailer.send_mailer(user).deliver_later(wait_until: 13.0 - utc_offset_in_hrs)
  end
end
</code>```

Body:
I am using the following gems:

timezone

tzinfo

I am trying to have a newsletter sent at user's time zone, so that they get the newsletter at their 9:00:00; not 09:00:00 PST where my server is.

I am storing the time zones by name, like "Pacific Time (US & Canada)".  Each user has a column user.time_zone where their specific time zone is stored.

I have built a job that checks every hour for users who could receive the newsletter (i.e. users whose local time is 9:00 AM).

class NewsletterTimezoneJob < ActiveJob::Base
  def self.perform
      users = User.all.gets_newsletter
      users.each do |user|
      d = Date.current
      t = "09:00:00 -0700"
      t = t.to_time
      newsletter_sendtime = DateTime.new(d.year, d.month, d.day, t.hour, t.min, t.sec, t.zone)
      newsletter_sendtime = newsletter_sendtime.to_s
      if user.is_in_time_around(newsletter_sendtime)
        NewsletterMailer.send_mailer(user, newsletter_sendtime).deliver_later
      end
    end
  end
end

I have built a method on user that tries to see if the user's local time matches newsletter_sendtime.

I added a +/- 5 minute window to account for slow servers.

User.rb:

def is_in_time_around(timeofday)
   timeofday = timeofday.to_time
   user_zoned =  timeofday.in_time_zone(self.time_zone)
   user_zoned = user_zoned.strftime("%r").to_time
   timeofday = timeofday.strftime("%r").to_time
   if user_zoned >= (timeofday - 5.minutes) && user_zoned <= (timeofday + 5.minutes)
    true
   end
 end

This job and method should run every hour and send to different users in different time zones each hour; and yet it currently only sends to users in "Pacific Time (US & Canada)," each hour and never sends it to any other `users.

Body:
Incase if it helps someone, following might help

Schedule a job to run at 8pm (UTC) on previous day, as 8pm UTC is 9am in NewZealand and a few more timezones. And UTC 8pm is when first 9am happens for any timezone.

# group time_zones by utc_offset (In hours)
ActiveSupport::TimeZone.all.group_by { |tz| tz.utc_offset/3600.0 }.each do |utc_offset_in_hrs, time_zones|
  User.where(time_zone: time_zones).each do |user|
    # Schedule the email as per time_zone, using delayed_job's run_at param
    # Using +13, as that is the highest/first timezone to have 9AM
    NewsletterMailer.send_mailer(user).deliver_later(wait_until: 13.0 - utc_offset_in_hrs)
  end
end


问:
Slow lottie animation video rendering with AVAssetWriter and AVAssetWriterInputPixelBufferAdaptor on iPhone X
I'm using this code (thanks damikdk) to render lottie animation to video:
https://github.com/damikdk/LottieExportDemo/blob/master/LottieExportDemo/ViewController.swift

I'm using the oldExport() in the previous file and these two methods (append and fill) to fill the pixelbuffer with the image:
https://github.com/damikdk/LottieExportDemo/blob/master/LottieExportDemo/Helpers.swift

It works great on a iphone 5s and exports 30sec video in approximately 1min. But on a iPhone X it takes up to 10 min to export the same video with the same resolution settings. Is there a way to optimize this to work better on newer devices?

答:
This repository was created as demonstration of bugs, you should not use it even as start point. Sorry if it's not obvious from description.

I am not sure what was wrong in your case, but I will check, if you share your code in issues.