问:
JBoss FUSE 7.4 with External Active MQ giving AMQ219013: Timed out waiting to receive cluster topology. Group:null
I'm trying to connect to ActiveMQ message broker on JBoss FUSE 7.4 (fuse-karaf-7.4.0.fuse-740028-redhat-00001). I found the following example.

I have downloaded and installed relevant features as instructed in the project. Also I have downloaded and installed ActiveMQ 5.15.11 and created the incomingOrders Queue.

I have added the org.ops4j.connectionfactory-amq7.cfg configuration file in to FUSE_HOME/etc folder with my local user name and password as follows:

```<code>url      = tcp://LAPTOP-E0A1RCAN:61616?maximumConnections=1000&wireFormat.maxFrameSize=10485760
name     = activemq
type     = artemis
user     = admin
password = admin
</code>```

After that when I install the application I'm getting following error.

```<code>java.lang.IllegalArgumentException: AMQ219032: Invalid type: 1
    at org.apache.activemq.artemis.core.protocol.core.impl.PacketDecoder.decode(PacketDecoder.java:475) ~[248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at org.apache.activemq.artemis.core.protocol.ClientPacketDecoder.decode(ClientPacketDecoder.java:67) ~[248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at org.apache.activemq.artemis.core.protocol.ClientPacketDecoder.decode(ClientPacketDecoder.java:42) ~[248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at org.apache.activemq.artemis.core.protocol.core.impl.RemotingConnectionImpl.bufferReceived(RemotingConnectionImpl.java:376) [248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at org.apache.activemq.artemis.core.client.impl.ClientSessionFactoryImpl$DelegatingBufferHandler.bufferReceived(ClientSessionFactoryImpl.java:1191) [248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at org.apache.activemq.artemis.core.remoting.impl.netty.ActiveMQChannelHandler.channelRead(ActiveMQChannelHandler.java:73) [248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:359) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:337) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:323) [239:io.netty.codec:4.1.34.Final-redhat-00001]
    at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:297) [239:io.netty.codec:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:359) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:337) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1408) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:359) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:930) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:163) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:677) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:612) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:529) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:491) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:905) [241:io.netty.common:4.1.34.Final-redhat-00001]
    at org.apache.activemq.artemis.utils.ActiveMQThreadFactory$1.run(ActiveMQThreadFactory.java:118) [248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
2020-02-16 17:41:34,755 | ERROR | lient-netty-threads) | o.a.a.a.c.client                 | 248 - org.apache.activemq.artemis-jms-client-osgi - 2.7.0.redhat-00056 | AMQ214031: Failed to decode buffer, disconnect immediately.
java.lang.IllegalStateException: java.lang.IllegalArgumentException: AMQ219032: Invalid type: 1
    at org.apache.activemq.artemis.core.protocol.core.impl.RemotingConnectionImpl.bufferReceived(RemotingConnectionImpl.java:389) ~[248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at org.apache.activemq.artemis.core.client.impl.ClientSessionFactoryImpl$DelegatingBufferHandler.bufferReceived(ClientSessionFactoryImpl.java:1191) [248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at org.apache.activemq.artemis.core.remoting.impl.netty.ActiveMQChannelHandler.channelRead(ActiveMQChannelHandler.java:73) [248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:359) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:337) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:323) [239:io.netty.codec:4.1.34.Final-redhat-00001]
    at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:297) [239:io.netty.codec:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:359) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:337) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1408) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:359) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:930) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:163) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:677) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:612) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:529) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:491) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:905) [241:io.netty.common:4.1.34.Final-redhat-00001]
    at org.apache.activemq.artemis.utils.ActiveMQThreadFactory$1.run(ActiveMQThreadFactory.java:118) [248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
Caused by: java.lang.IllegalArgumentException: AMQ219032: Invalid type: 1
    at org.apache.activemq.artemis.core.protocol.core.impl.PacketDecoder.decode(PacketDecoder.java:475) ~[248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at org.apache.activemq.artemis.core.protocol.ClientPacketDecoder.decode(ClientPacketDecoder.java:67) ~[248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at org.apache.activemq.artemis.core.protocol.ClientPacketDecoder.decode(ClientPacketDecoder.java:42) ~[248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at org.apache.activemq.artemis.core.protocol.core.impl.RemotingConnectionImpl.bufferReceived(RemotingConnectionImpl.java:376) ~[248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    ... 21 more
</code>```

In ActiveMQ log, I could see following warning .

```<code>2020-02-16 17:44:29,802 | WARN  | Transport Connection to: tcp://127.0.0.1:51000 failed: java.io.IOException: Frame size of 1 GB larger than max allowed 100 MB | org.apache.activemq.broker.TransportConnection.Transport | ActiveMQ Transport: tcp:///127.0.0.1:51000@61616
</code>```

Did any one have similar issues connecting to ActiveMQ with FUSE 7.4 or 7.1+?

答:
The "Summary" from the linked example says:

This quickstart demonstrates how to use the camel-jms component to connect to an AMQ 7 broker and use JMS messaging between two Camel routes. [emphasis added]

AMQ 7 is based on ActiveMQ Artemis, not ActiveMQ 5.x (which you are using). ActiveMQ 5.x doesn't support the "core" protocol which the Artemis JMS client implementation speaks.

Therefore, you should either change the Camel configuration to use the ActiveMQ 5.x OpenWire JMS client implementation or replace your ActiveMQ 5.15.11 instance with ActiveMQ Artemis.

Body:
I'm trying to connect to ActiveMQ message broker on JBoss FUSE 7.4 (fuse-karaf-7.4.0.fuse-740028-redhat-00001). I found the following example.

I have downloaded and installed relevant features as instructed in the project. Also I have downloaded and installed ActiveMQ 5.15.11 and created the incomingOrders Queue.

I have added the org.ops4j.connectionfactory-amq7.cfg configuration file in to FUSE_HOME/etc folder with my local user name and password as follows:

url      = tcp://LAPTOP-E0A1RCAN:61616?maximumConnections=1000&wireFormat.maxFrameSize=10485760
name     = activemq
type     = artemis
user     = admin
password = admin

After that when I install the application I'm getting following error.

java.lang.IllegalArgumentException: AMQ219032: Invalid type: 1
    at org.apache.activemq.artemis.core.protocol.core.impl.PacketDecoder.decode(PacketDecoder.java:475) ~[248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at org.apache.activemq.artemis.core.protocol.ClientPacketDecoder.decode(ClientPacketDecoder.java:67) ~[248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at org.apache.activemq.artemis.core.protocol.ClientPacketDecoder.decode(ClientPacketDecoder.java:42) ~[248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at org.apache.activemq.artemis.core.protocol.core.impl.RemotingConnectionImpl.bufferReceived(RemotingConnectionImpl.java:376) [248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at org.apache.activemq.artemis.core.client.impl.ClientSessionFactoryImpl$DelegatingBufferHandler.bufferReceived(ClientSessionFactoryImpl.java:1191) [248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at org.apache.activemq.artemis.core.remoting.impl.netty.ActiveMQChannelHandler.channelRead(ActiveMQChannelHandler.java:73) [248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:359) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:337) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:323) [239:io.netty.codec:4.1.34.Final-redhat-00001]
    at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:297) [239:io.netty.codec:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:359) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:337) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1408) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:359) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:930) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:163) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:677) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:612) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:529) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:491) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:905) [241:io.netty.common:4.1.34.Final-redhat-00001]
    at org.apache.activemq.artemis.utils.ActiveMQThreadFactory$1.run(ActiveMQThreadFactory.java:118) [248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
2020-02-16 17:41:34,755 | ERROR | lient-netty-threads) | o.a.a.a.c.client                 | 248 - org.apache.activemq.artemis-jms-client-osgi - 2.7.0.redhat-00056 | AMQ214031: Failed to decode buffer, disconnect immediately.
java.lang.IllegalStateException: java.lang.IllegalArgumentException: AMQ219032: Invalid type: 1
    at org.apache.activemq.artemis.core.protocol.core.impl.RemotingConnectionImpl.bufferReceived(RemotingConnectionImpl.java:389) ~[248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at org.apache.activemq.artemis.core.client.impl.ClientSessionFactoryImpl$DelegatingBufferHandler.bufferReceived(ClientSessionFactoryImpl.java:1191) [248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at org.apache.activemq.artemis.core.remoting.impl.netty.ActiveMQChannelHandler.channelRead(ActiveMQChannelHandler.java:73) [248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:359) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:337) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:323) [239:io.netty.codec:4.1.34.Final-redhat-00001]
    at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:297) [239:io.netty.codec:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:359) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:337) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1408) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:359) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:930) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:163) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:677) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:612) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:529) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:491) [244:io.netty.transport:4.1.34.Final-redhat-00001]
    at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:905) [241:io.netty.common:4.1.34.Final-redhat-00001]
    at org.apache.activemq.artemis.utils.ActiveMQThreadFactory$1.run(ActiveMQThreadFactory.java:118) [248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
Caused by: java.lang.IllegalArgumentException: AMQ219032: Invalid type: 1
    at org.apache.activemq.artemis.core.protocol.core.impl.PacketDecoder.decode(PacketDecoder.java:475) ~[248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at org.apache.activemq.artemis.core.protocol.ClientPacketDecoder.decode(ClientPacketDecoder.java:67) ~[248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at org.apache.activemq.artemis.core.protocol.ClientPacketDecoder.decode(ClientPacketDecoder.java:42) ~[248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    at org.apache.activemq.artemis.core.protocol.core.impl.RemotingConnectionImpl.bufferReceived(RemotingConnectionImpl.java:376) ~[248:org.apache.activemq.artemis-jms-client-osgi:2.7.0.redhat-00056]
    ... 21 more

In ActiveMQ log, I could see following warning .

2020-02-16 17:44:29,802 | WARN  | Transport Connection to: tcp://127.0.0.1:51000 failed: java.io.IOException: Frame size of 1 GB larger than max allowed 100 MB | org.apache.activemq.broker.TransportConnection.Transport | ActiveMQ Transport: tcp:///127.0.0.1:51000@61616

Did any one have similar issues connecting to ActiveMQ with FUSE 7.4 or 7.1+?


来源: stackexchange

问:
Javascript on-click toggle
I have some code that when a user clicks away from a side-bar the side-bar closes, How do I change it so when a user clicks a link the side-bar also closes and as well as from the side bar

Example - if I was to click the word Home, it would then hide the side-bar.

//hidding side header on click outside header
$body.on('mousedown touchstart click', function(e) {
  if (!($(e.target).closest('.page_header_side').length) && !($sideHeader.hasClass('header_side_sticked'))) {
    $sideHeader.removeClass('active-slide-side-header');
    $body.removeClass('active-side-header slide-right');
    $body.parent().removeClass('html-active-push-header');
    var $toggler = $('.toggle_menu_side');
    if (($toggler).hasClass('active')) {
      $toggler.removeClass('active');
    }
  }
});
} //sideHeader check```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header class="page_header_side header_slide header-special header_side_right ds">

     <div class="scrollbar-macosx">
      <div class="side_header_inner">
       <p class="text-right mb-0 close-wrapper">×</p>

       <div class="widget widget_recent_posts">

                                <h3 class="widget-title">Home</h3>

       </div>

                            <div class="widget widget_recent_posts">

                                <h3 class="widget-title">Overview</h3>

       </div>

                            <div class="widget widget_recent_posts">

                                <h3 class="widget-title">About</h3>

       </div></code>```

attached is the image of the sidebar when opened

答:
With the given code this is what I have done:

//hidding side header on click outside header
$('.scrollbar-macosx').on('click', function(e) {

    //$sideHeader.removeClass('active-slide-side-header');
    //$body.removeClass('active-side-header slide-right');
    //$body.parent().removeClass('html-active-push-header');
    //if you want to keep playing with adding and removing classes them:
    //if (($toggler).hasClass('active')) {
      $('#elementToHide').fadeOut();
    //}

  });
//sideHeader check
```

<p>And them your html:</p>

<pre class="lang-html prettyprint-override"><code><header class="page_header_side header_slide header-special header_side_right ds">
   <div class="scrollbar-macosx" id="elementToHide">
      <div class="side_header_inner">
         <p class="text-right mb-0 close-wrapper">×</p>
         <div class="widget widget_recent_posts">
            <h3 class="widget-title">Home</h3>
         </div>
         <div class="widget widget_recent_posts">
            <h3 class="widget-title">Overview</h3>
         </div>
         <div class="widget widget_recent_posts">
            <h3 class="widget-title">About</h3>
         </div>
      </div>
   </div>
</header>
</code>```

Here is the fiddle : fiddle

ContentLicense: CC BY-SA 4.0

Title: Javascript on-click toggle

Body:
I have some code that when a user clicks away from a side-bar the side-bar closes, How do I change it so when a user clicks a link the side-bar also closes and as well as from the side bar

Example - if I was to click the word Home, it would then hide the side-bar.

//hidding side header on click outside header
$body.on('mousedown touchstart click', function(e) {
  if (!($(e.target).closest('.page_header_side').length) && !($sideHeader.hasClass('header_side_sticked'))) {
    $sideHeader.removeClass('active-slide-side-header');
    $body.removeClass('active-side-header slide-right');
    $body.parent().removeClass('html-active-push-header');
    var $toggler = $('.toggle_menu_side');
    if (($toggler).hasClass('active')) {
      $toggler.removeClass('active');
    }
  }
});
} //sideHeader check

×

Home

Overview

About

attached is the image of the sidebar when opened

Body:
With the given code this is what I have done:

//hidding side header on click outside header
$('.scrollbar-macosx').on('click', function(e) {

    //$sideHeader.removeClass('active-slide-side-header');
    //$body.removeClass('active-side-header slide-right');
    //$body.parent().removeClass('html-active-push-header');
    //if you want to keep playing with adding and removing classes them:
    //if (($toggler).hasClass('active')) {
      $('#elementToHide').fadeOut();
    //}

  });
//sideHeader check

And them your html:

<header class="page_header_side header_slide header-special header_side_right ds">
   <div class="scrollbar-macosx" id="elementToHide">
      <div class="side_header_inner">
         <p class="text-right mb-0 close-wrapper"><a href="#">×</a></p>
         <div class="widget widget_recent_posts">
            <h3 class="widget-title"><a href="#">Home</a></h3>
         </div>
         <div class="widget widget_recent_posts">
            <h3 class="widget-title"><a href="#">Overview</a></h3>
         </div>
         <div class="widget widget_recent_posts">
            <h3 class="widget-title"><a href="#">About</a></h3>
         </div>
      </div>
   </div>
</header>

Here is the fiddle : fiddle


问:
Add List box to List<ListBox> to pass to foreach loop ASP.NET
Hi I'm trying to create a list of ListBox's in ASP.NET so that I can then iterate it to test if it has been selected.

```<code>    List<string> con = new List<string>();
    List<ListBox> lb = new List<ListBox>();
    foreach (Control c in _pH_Outer_MainCri.Controls)
    {
        if (c is ListBox)
        {
            con.Add(c.ID.ToString());
            lb.Add(c.??);
        }
    }
</code>```

I'm getting caught up on that last part.  Basically then I can

```<code>foreach(ListBox a in lb)
    {
        if(a.TestSelection() == true )
        {
            BuildQuery(a);
        }
    }
</code>```

Thanks in advance for the help ...

答:
When I get overwhelmed, I often find it helpful to take a step back and think about my structures:

List<ListBox> lb - This is a list and each member in the list is of a type ListBox.

In your loop, you want to pull out all of the listboxes, so when you have:
if (c is ListBox)
        { you know that c is already of the type listbox, which is the same type lb is storing.  It is simply a matter of adding c to your collection in lb with lb.Add(c);

Separately - do you really need to store these items only to loop through them again and call BuildQuery?  Looping through, putting them in a list, and then looping through that collection again may be extra overhead depending on what you are doing.

ContentLicense: CC BY-SA 3.0

Body:
Hi I'm trying to create a list of ListBox's in ASP.NET so that I can then iterate it to test if it has been selected.

    List<string> con = new List<string>();
    List<ListBox> lb = new List<ListBox>();
    foreach (Control c in _pH_Outer_MainCri.Controls)
    {
        if (c is ListBox)
        {
            con.Add(c.ID.ToString());
            lb.Add(c.??);
        }
    }

I'm getting caught up on that last part.  Basically then I can

foreach(ListBox a in lb)
    {
        if(a.TestSelection() == true )
        {
            BuildQuery(a);
        }
    }

Thanks in advance for the help ...


问:
Calculate table each row uniquely in jquery
I am working on a POS system. Here I need to calculate the total for each item uniquely. I have written an onKeyUp function to calculate the amount. It's working perfect for a single row. If I modified added discount 2 for the second product it affects the first row.

Screenshot:

HTML :

```<code><table class="table table-striped table-hover" id="item_table">
   <thead id="thead">
      <tr class="bg-primary">
         <th>#</th>
         <th>Product Name</th>
         <th>Quantity</th>
         <th>Unit Price</th>
         <th>Discount</th>
         <th>Discount 2</th>
         <th>Amount</th>
         <th><i class="fa fa-close"></i></th>
      </tr>
   </thead>
   <tbody id="item_list">
      <tr>
         <td><?php echo $n; ?></td>
         <td><?php echo $product_name; ?></td>
         <td><input type="number" class="form-control" name="quantity[]" id="quantity" value="1" min="1" step="1"></td>
         <td id="sprice"><?php echo $selling_price; ?></td>
         <td id="discount"><?php echo $discount_rate; ?>%</td>
         <td><input type="text" class="form-control" name="discount2" id="discount2"></td>
         <td id="total"><?php echo number_format($total,2,'.', ''); ?></td>
         <td><span><i class="fa fa-trash"></i></span></td>
      </tr>
   </tbody>
</table>
</code>```

Here the PHP code used insert the row for the first time to the table.There is no issue with that. Its working with the one record.

JavaScript :

```<code>//Product Row Calculation
function calculateItemPrice() {
    var sprice = $("#item_table #sprice").text();
    var quantity = $("#item_table #item_list #quantity").val();
    var discount = $("#item_table #discount").text().slice(0, -1);
    var discount2 = $("#item_table #item_list #discount2").val();

    $('tr').each(function() {
        var totalDiscount = ((sprice * quantity) * discount / 100);
        var price = ((((sprice * quantity) - totalDiscount)) - discount2);
        var total = parseFloat(price).toFixed(2);

        $("#total").html(total);
    });
}

$("#item_table").on("keyup", "#quantity", function() {
    calculateItemPrice();
});

$("#item_table").on("keyup", "#discount2", function() {
    calculateItemPrice();
});
</code>```

答:
Use class instead of id. You can also calculate the grand total by using this.

$(function(){
    $('body').on("keyup change", ".quantity, .discount2", function() {
        var tr        = $(this).parent().parent();

        var sprice    = tr.find(".sprice").text();
        var quantity  = tr.find(".quantity").val();
        var discount  = tr.find(".discount").text().slice(0, -1);
        var discount2 = tr.find(".discount2").val();

        // calculate total
        var totalDiscount = ((sprice * quantity) * discount / 100);
        var price = ((((sprice * quantity) - totalDiscount)) - discount2);
        var total = parseFloat(price).toFixed(2);
        tr.find(".total").html(total);

        // calculate grand total
        var grandTotal = 0.00;
        $('tr > .total').each(function(i, v){
            grandTotal = (parseFloat(grandTotal)+parseFloat($(this).text())).toFixed(2);
        });

        console.log('Grand Total: ', grandTotal);
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table class="table table-striped table-hover" id="item_table" border="1">
   <thead id="thead">
      <tr class="bg-primary">
         <th>#</th>
         <th>Product Name</th>
         <th>Quantity</th>
         <th>Unit Price</th>
         <th>Discount</th>
         <th>Discount 2</th>
         <th>Amount</th>
         <th><i class="fa fa-close"></i></th>
      </tr>
   </thead>
   <tbody id="item_list">
      <tr>
         <td>1</td>
         <td>Test 1</td>
         <td><input type="number" class="form-control quantity" name="quantity[]" value="1" min="1" step="1"></td>
         <td class="sprice">10</td>
         <td class="discount">2%</td>
         <td><input type="text" class="form-control discount2" name="discount2"></td>
         <td class="total">10</td>
         <td><span><i class="fa fa-trash"></i></span></td>
      </tr>
      <tr>
         <td>2</td>
         <td>Test 2</td>
         <td><input type="number" class="form-control quantity" name="quantity[]" value="1" min="1" step="1"></td>
         <td class="sprice">20</td>
         <td class="discount">5%</td>
         <td><input type="text" class="form-control discount2" name="discount2"></td>
         <td class="total">20</td>
         <td><span><i class="fa fa-trash"></i></span></td>
      </tr>
   </tbody>
</table></code>```

Body:
I am working on a POS system. Here I need to calculate the total for each item uniquely. I have written an onKeyUp function to calculate the amount. It's working perfect for a single row. If I modified added discount 2 for the second product it affects the first row.

Screenshot:

HTML :

         #
         Product Name
         Quantity
         Unit Price
         Discount
         Discount 2
         Amount

         <?php echo $n; ?>
         <?php echo $product_name; ?>
         <input type="number" class="form-control" name="quantity[]" id="quantity" value="1" min="1" step="1">
         <?php echo $selling_price; ?>
         <?php echo $discount_rate; ?>%
         <input type="text" class="form-control" name="discount2" id="discount2">
         <?php echo number_format($total,2,'.', ''); ?>

Here the PHP code used insert the row for the first time to the table.There is no issue with that. Its working with the one record.

JavaScript :

//Product Row Calculation
function calculateItemPrice() {
    var sprice = $("#item_table #sprice").text();
    var quantity = $("#item_table #item_list #quantity").val();
    var discount = $("#item_table #discount").text().slice(0, -1);
    var discount2 = $("#item_table #item_list #discount2").val();

    $('tr').each(function() {
        var totalDiscount = ((sprice * quantity) * discount / 100);
        var price = ((((sprice * quantity) - totalDiscount)) - discount2);
        var total = parseFloat(price).toFixed(2);

        $("#total").html(total);
    });
}

$("#item_table").on("keyup", "#quantity", function() {
    calculateItemPrice();
});

$("#item_table").on("keyup", "#discount2", function() {
    calculateItemPrice();
});

Body:
Use class instead of id. You can also calculate the grand total by using this.

$(function(){
    $('body').on("keyup change", ".quantity, .discount2", function() {
        var tr        = $(this).parent().parent();

        var sprice    = tr.find(".sprice").text();
        var quantity  = tr.find(".quantity").val();
        var discount  = tr.find(".discount").text().slice(0, -1);
        var discount2 = tr.find(".discount2").val();

        // calculate total
        var totalDiscount = ((sprice * quantity) * discount / 100);
        var price = ((((sprice * quantity) - totalDiscount)) - discount2);
        var total = parseFloat(price).toFixed(2);
        tr.find(".total").html(total);

        // calculate grand total
        var grandTotal = 0.00;
        $('tr > .total').each(function(i, v){
            grandTotal = (parseFloat(grandTotal)+parseFloat($(this).text())).toFixed(2);
        });

        console.log('Grand Total: ', grandTotal);
    });
});

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table class="table table-striped table-hover" id="item_table" border="1">
   <thead id="thead">
      <tr class="bg-primary">
         <th>#</th>
         <th>Product Name</th>
         <th>Quantity</th>
         <th>Unit Price</th>
         <th>Discount</th>
         <th>Discount 2</th>
         <th>Amount</th>
         <th><i class="fa fa-close"></i></th>
      </tr>
   </thead>
   <tbody id="item_list">
      <tr>
         <td>1</td>
         <td>Test 1</td>
         <td><input type="number" class="form-control quantity" name="quantity[]" value="1" min="1" step="1"></td>
         <td class="sprice">10</td>
         <td class="discount">2%</td>
         <td><input type="text" class="form-control discount2" name="discount2"></td>
         <td class="total">10</td>
         <td><span><i class="fa fa-trash"></i></span></td>
      </tr>
      <tr>
         <td>2</td>
         <td>Test 2</td>
         <td><input type="number" class="form-control quantity" name="quantity[]" value="1" min="1" step="1"></td>
         <td class="sprice">20</td>
         <td class="discount">5%</td>
         <td><input type="text" class="form-control discount2" name="discount2"></td>
         <td class="total">20</td>
         <td><span><i class="fa fa-trash"></i></span></td>
      </tr>
   </tbody>
</table>


问:
fix problems with strings in kivymd
Hi there I having a problem and i dont understand what it is?
but i think that the problem is on the variable sth, it works without the var variable but is there something that make it works like that?

Here is my code:

KV:

```<code><Main>
    product: product

Screen:
    BoxLayout:
        size_hint: .8, .8
        pos_hint: {"center_x": .5, "y": .7}
        spacing: dp(100)
        orientation: "vertical"
        MDTextFieldRound:
            id: product
            hint_text: 'Enter a product'
            icon_left: 'magnify'
            on_text_validate: app.System()

    FloatLayout:
        MDCard:
            orientation: "vertical"
            size_hint: .43, .3
            height: self.minimum_height
            pos_hint: {"x": .05, "y": .35}

            BoxLayout:
                id: box
                size_hint_y: None
                height: dp(150)

                MDLabel:
                    text: app.sth
</code>```

PY:

```<code>class Main(MDApp):
    Window.size = (310, 520)
    title = "Best Price"
    def build(self):
        return Builder.load_string(KV)

    sth = StringProperty()
    var = "This is a message"

    def System(self):
        self.sth = self.var

if __name__ == "__main__":
    Main().run()
</code>```

here is the error:

```<code>     self.sth = self.var
     File "kivy\properties.pyx", line 497, in
     kivy.properties.Property.__set__
     File "kivy\properties.pyx", line 541, in kivy.properties.Property.set
     File "kivy\properties.pyx", line 532, in kivy.properties.Property.set
     File "kivy\properties.pyx", line 698, in
     kivy.properties.StringProperty.check
     ValueError: Main.sth accept only str
</code>```

答:
I don't have any experience with kivy but from my understanding of the error log, it seems that the sth variable is being assigned a value of type other than string.

Can you try setting the self.sth = "checl" and see if that works?

Update:

From the docs, it suggests initialize the object with default value

```<code>class MyClass(EventDispatcher):
    my_string = StringProperty("default")
</code>```

Can you try initializing it with some string and then see if you code above works.

Title: fix problems with strings in kivymd

Body:
Hi there I having a problem and i dont understand what it is?
but i think that the problem is on the variable sth, it works without the var variable but is there something that make it works like that?

Here is my code:

KV:

    product: product

Screen:
    BoxLayout:
        size_hint: .8, .8
        pos_hint: {"center_x": .5, "y": .7}
        spacing: dp(100)
        orientation: "vertical"
        MDTextFieldRound:
            id: product
            hint_text: 'Enter a product'
            icon_left: 'magnify'
            on_text_validate: app.System()

    FloatLayout:
        MDCard:
            orientation: "vertical"
            size_hint: .43, .3
            height: self.minimum_height
            pos_hint: {"x": .05, "y": .35}

            BoxLayout:
                id: box
                size_hint_y: None
                height: dp(150)

                MDLabel:
                    text: app.sth

PY:

class Main(MDApp):
    Window.size = (310, 520)
    title = "Best Price"
    def build(self):
        return Builder.load_string(KV)

    sth = StringProperty()
    var = "This is a message"

    def System(self):
        self.sth = self.var

if __name__ == "__main__":
    Main().run()

here is the error:

     self.sth = self.var
     File "kivy\properties.pyx", line 497, in
     kivy.properties.Property.__set__
     File "kivy\properties.pyx", line 541, in kivy.properties.Property.set
     File "kivy\properties.pyx", line 532, in kivy.properties.Property.set
     File "kivy\properties.pyx", line 698, in
     kivy.properties.StringProperty.check
     ValueError: Main.sth accept only str

Body:
I don't have any experience with kivy but from my understanding of the error log, it seems that the sth variable is being assigned a value of type other than string.

Can you try setting the self.sth = "checl" and see if that works?

Update:

From the docs, it suggests initialize the object with default value

class MyClass(EventDispatcher):
    my_string = StringProperty("default")

Can you try initializing it with some string and then see if you code above works.


问:
Typescript filter adult and child
The filter is not working properly. I want to filter the adults with their child numbers and include them in the records. How can I fix the code?

.html

```<code><input id="adult" type="number" [(ngModel)]="adult" (ngModelChange)="changeNumberOfAdults()" />
<input id="child" type="number" max="3" min="0" [(ngModel)]="childCount" [(ngModel)]="chd" (ngModelChange)="changeNumberOfChilds()" />
</code>```

.ts

```<code>changeNumberOfAdults() {
    const filtered = this.hotels.filter(x => x.numberOfAd == this.adult);
    this.dsHotels.data = filtered;
}

changeNumberOfChilds() {
    const filtered = this.hotels.filter(x => x.numberOfChd == this.chd);
    this.dsHotels.data = filtered; }
</code>```

答:
Each of your functions should consider both the filters.

```<code>changeNumberOfAdults() {
    const filtered = this.hotels.filter(x => {return this.chd == undefined ? x.numberOfAd == this.adult : x.numberOfAd == this.adult && x.numberOfChd == this.chd } );
    this.dsHotels.data = filtered;
}

changeNumberOfChilds() {
    const filtered = this.hotels.filter(x => {return this.adult == undefined ? x.numberOfChd == this.chd : x.numberOfAd == this.adult && x.numberOfChd == this.chd } );
    this.dsHotels.data = filtered; }
</code>```

Also, this is a very good case to write a custom filter Pipe in angular, and can avoid use of onModelChange.

Title: Typescript filter adult and child

Body:
The filter is not working properly. I want to filter the adults with their child numbers and include them in the records. How can I fix the code?

.html

<input id="adult" type="number" [(ngModel)]="adult" (ngModelChange)="changeNumberOfAdults()" />
<input id="child" type="number" max="3" min="0" [(ngModel)]="childCount" [(ngModel)]="chd" (ngModelChange)="changeNumberOfChilds()" />

.ts

changeNumberOfAdults() {
    const filtered = this.hotels.filter(x => x.numberOfAd == this.adult);
    this.dsHotels.data = filtered;
}

changeNumberOfChilds() {
    const filtered = this.hotels.filter(x => x.numberOfChd == this.chd);
    this.dsHotels.data = filtered; }

Body:
Each of your functions should consider both the filters.

changeNumberOfAdults() {
    const filtered = this.hotels.filter(x => {return this.chd == undefined ? x.numberOfAd == this.adult : x.numberOfAd == this.adult && x.numberOfChd == this.chd } );
    this.dsHotels.data = filtered;
}

changeNumberOfChilds() {
    const filtered = this.hotels.filter(x => {return this.adult == undefined ? x.numberOfChd == this.chd : x.numberOfAd == this.adult && x.numberOfChd == this.chd } );
    this.dsHotels.data = filtered; }

Also, this is a very good case to write a custom filter Pipe in angular, and can avoid use of onModelChange.


问:
Breaking up a string into a list of tokens using another string as a delimiter?
Let's say I have this string:

```<code>char *myTestString = "Hello AND test AND test2";
</code>```

I want to break this down into the set { Hello, test, test2 }, which I can finally iterate over.

Or I have

```<code>char *myTestString2 = "Hi AND there AND test AND test2";
</code>```

I want to break this down into the set { Hi, there, test, test2 }, which I can later iterate over.

How do I achieve this using C?

EDIT:
Another example is splitting "Hello there AND test" should give out set { Hello there, test }.
For clarification "AND" is delimiter here.

答:
Note: As others mentioned, strtok() is no good for string literals, and in this case you should go with Chux's answer (strcspn), but if that's not an issue and you can work with strings stored in arrays, then continue reading. A last resort effort would be to work with a copy of the string literal.

First, you have to decide which data structure you'll use for your set (e.g. a simple linked list, where you check before instertion for duplicates).

Then, use strtok() to your string, and if the current token is different than "AND" (or any other string to be ignored - you'd have an ignore set of strings as well), then insert it in the set, otherwise, continue to the next token.

Here is a basic Complete Minimal Example to get you started:

```<code>#include <stdio.h>
#include <string.h>

#define N 3     // Max size of set
#define LEN 32  // Max length of word - 1

int main ()
{
  char set[N][LEN] = {0};
  char* ignore_str = "AND";
  char str[] ="Hello AND test AND test2";
  char* pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ");
  int i = 0;
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    if(strcmp(pch, ignore_str))
      strcpy(set[i++], pch);
    pch = strtok (NULL, " ");
  }
  printf("My set is: {");
  for(int j = 0; j < i; ++j)
    printf("%s, ", set[j]);
  printf("}\n");
  return 0;
}
</code>```

Output:

```<code>Splitting string "Hello AND test AND test2" into tokens:
Hello
AND
test
AND
test2
My set is: {Hello, test, test2, }
</code>```

Here, I used an array to represent the set, assuming that the maximum size of the set would be 3. Of course, you could use more dynamic approach instead (e.g. dynamic memory allocated array or list).

Body:
Let's say I have this string:

char *myTestString = "Hello AND test AND test2";

I want to break this down into the set { Hello, test, test2 }, which I can finally iterate over.

Or I have

char *myTestString2 = "Hi AND there AND test AND test2";

I want to break this down into the set { Hi, there, test, test2 }, which I can later iterate over.

How do I achieve this using C?

EDIT:
Another example is splitting "Hello there AND test" should give out set { Hello there, test }.
For clarification "AND" is delimiter here.

Body:
Note: As others mentioned, strtok() is no good for string literals, and in this case you should go with Chux's answer (strcspn), but if that's not an issue and you can work with strings stored in arrays, then continue reading. A last resort effort would be to work with a copy of the string literal.

First, you have to decide which data structure you'll use for your set (e.g. a simple linked list, where you check before instertion for duplicates).

Then, use strtok() to your string, and if the current token is different than "AND" (or any other string to be ignored - you'd have an ignore set of strings as well), then insert it in the set, otherwise, continue to the next token.

Here is a basic Complete Minimal Example to get you started:

#include <stdio.h>
#include <string.h>

#define N 3     // Max size of set
#define LEN 32  // Max length of word - 1

int main ()
{
  char set[N][LEN] = {0};
  char* ignore_str = "AND";
  char str[] ="Hello AND test AND test2";
  char* pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ");
  int i = 0;
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    if(strcmp(pch, ignore_str))
      strcpy(set[i++], pch);
    pch = strtok (NULL, " ");
  }
  printf("My set is: {");
  for(int j = 0; j < i; ++j)
    printf("%s, ", set[j]);
  printf("}\n");
  return 0;
}

Output:

Splitting string "Hello AND test AND test2" into tokens:
Hello
AND
test
AND
test2
My set is: {Hello, test, test2, }

Here, I used an array to represent the set, assuming that the maximum size of the set would be 3. Of course, you could use more dynamic approach instead (e.g. dynamic memory allocated array or list).


问:
Process (NSTask) fileHandleForReading readabilityHandler closure not being called on Linux
When compiling the following code in macOS it runs and gives output.

```<code>import Foundation

let runloop = RunLoop.current

let process = Process()
process.launchPath = "/bin/echo"
process.arguments = ["hello world"]

let output = Pipe()
process.standardOutput = output

output.fileHandleForReading.readabilityHandler = { fileHandle in
    let data = fileHandle.availableData
    print("received data: \(data.count)")
    print(String(data: data, encoding: .utf8) ?? "")
}

print("starting")
process.launch()

while runloop.run(mode: .default, before: Date(timeIntervalSinceNow: 2)) { }
</code>```

output:

```<code>received data: 12
hello world\n
</code>```

But when I compile and run this in a Ubuntu Swift docker image (Swift version 5.0.1), the readabilityHandler closure doesn't get called at all.

答: This appears to be fixed in the swift:latest Docker image (5.1.4 at the time of writing). It looks like readabilityHandler was implemented in Linux and merged in the run-up to Swift 5.1.

Body:
When compiling the following code in macOS it runs and gives output.

import Foundation

let runloop = RunLoop.current

let process = Process()
process.launchPath = "/bin/echo"
process.arguments = ["hello world"]

let output = Pipe()
process.standardOutput = output

output.fileHandleForReading.readabilityHandler = { fileHandle in
    let data = fileHandle.availableData
    print("received data: \(data.count)")
    print(String(data: data, encoding: .utf8) ?? "")
}

print("starting")
process.launch()

while runloop.run(mode: .default, before: Date(timeIntervalSinceNow: 2)) { }

output:

received data: 12
hello world\n

But when I compile and run this in a Ubuntu Swift docker image (Swift version 5.0.1), the readabilityHandler closure doesn't get called at all.


问:
How can I set a TextBox text programmatically in XAML (Silverlight)
I have a TextBox inside a DataTemplate in my XAML:

```<code>    <DataTemplate x:Key="aproved" >
        <StackPanel Orientation="Vertical" Width="70" Height="70" VerticalAlignment="Center" HorizontalAlignment="Center"  >
            <Image Source="/PF;component/Images/checked_checked.png" Width="50" Height="50"></Image>
            <TextBlock Name="tbAproved" HorizontalAlignment="Center" Text="Aproved" />
        </StackPanel>
    </DataTemplate>
</code>```

I want to translate the text "Aproved" in my TextBlock using my translator class (LanguageManager), who is responsable to get strings from my resources files:

```<code>public class LanguageManager {
    public static String GetString(String resourceName) {
        if (Singleton.Instance().IdLanguage == 2) {
            return ResourceEnglish.ResourceManager.GetString(resourceName);
        } else {
            return ResourcePortuguese.ResourceManager.GetString(resourceName);
        }
    }
}
</code>```

So in my textbox I was trying to do something like this:

```<code><TextBlock Name="tbAproved" HorizontalAlignment="Center" Text="LanguageManager.GetString('resourceName')"/>
</code>```

Geting the string direcly from my class and passing a parameter with the resourceName.

I am using Silverlight 4.

Is there any way to do this? I have to do something complety different in my code?

答:
You can do it as simple as this:

```<code>tbApproved.Text = LanguageManager.GetString("resourceName");
</code>```

If you want use Binding in XAML (recommended):

```<code><DataTemplate x:Key="aproved" >
    <StackPanel Orientation="Vertical" Width="70" Height="70" VerticalAlignment="Center" HorizontalAlignment="Center"  >
        <Image Source="/PF;component/Images/checked_checked.png" Width="50" Height="50"></Image>
        <TextBlock Name="tbAproved" HorizontalAlignment="Center" Text="{Binding ApprovedLabel}" />
    </StackPanel>
</DataTemplate>
</code>```

Set DataContext to View Model that has ApprovedLabel Property:

```<code>    public string ApprovedLabel
    {
        get {return LanguageManager.GetString("resourceName");}
        set {}
    }
</code>```

Body:
I have a TextBox inside a DataTemplate in my XAML:

    <DataTemplate x:Key="aproved" >
        <StackPanel Orientation="Vertical" Width="70" Height="70" VerticalAlignment="Center" HorizontalAlignment="Center"  >
            <Image Source="/PF;component/Images/checked_checked.png" Width="50" Height="50"></Image>
            <TextBlock Name="tbAproved" HorizontalAlignment="Center" Text="Aproved" />
        </StackPanel>
    </DataTemplate>

I want to translate the text "Aproved" in my TextBlock using my translator class (LanguageManager), who is responsable to get strings from my resources files:

public class LanguageManager {
    public static String GetString(String resourceName) {
        if (Singleton.Instance().IdLanguage == 2) {
            return ResourceEnglish.ResourceManager.GetString(resourceName);
        } else {
            return ResourcePortuguese.ResourceManager.GetString(resourceName);
        }
    }
}

So in my textbox I was trying to do something like this:

<TextBlock Name="tbAproved" HorizontalAlignment="Center" Text="LanguageManager.GetString('resourceName')"/>

Geting the string direcly from my class and passing a parameter with the resourceName.

I am using Silverlight 4.

Is there any way to do this? I have to do something complety different in my code?

Body:
You can do it as simple as this:

tbApproved.Text = LanguageManager.GetString("resourceName");

If you want use Binding in XAML (recommended):

<DataTemplate x:Key="aproved" >
    <StackPanel Orientation="Vertical" Width="70" Height="70" VerticalAlignment="Center" HorizontalAlignment="Center"  >
        <Image Source="/PF;component/Images/checked_checked.png" Width="50" Height="50"></Image>
        <TextBlock Name="tbAproved" HorizontalAlignment="Center" Text="{Binding ApprovedLabel}" />
    </StackPanel>
</DataTemplate>

Set DataContext to View Model that has ApprovedLabel Property:

    public string ApprovedLabel
    {
        get {return LanguageManager.GetString("resourceName");}
        set {}
    }


问:
List cannot be converted to List
Why this is not allowed?

error: incompatible types: List<TextBook> cannot be
  converted to List<Book>

process(textBooks);

```<code>import java.util.*;

class Book {}

class TextBook extends Book {}

public class Sample {
    public static void process(List<Book> books) {}

    public static void main(String[] args) {
        List<Book> books = new ArrayList<>();
        process(books);
        System.out.println(“OK”)

        List<TextBook> textBooks = new ArrayList<>();
        process(textBooks); # what is the problem in this statement?
        System.out.println(“OK”);
    }
}
</code>```

答:
You are trying to pass a List<TextBook> into a method whose signature expects a List<Book>.  This fails at compile time, because if the Java compiler were to allow it, then your process() method might try to use the contents of the list in the wrong way.  Instead, use this version of process():

```<code>public static void process(List<? extends Book> books) {}
</code>```

Now you may pass in any instance of Book, or any subclass of Book.

Title: List cannot be converted to List

Body:
Why this is not allowed?

error: incompatible types: List<TextBook> cannot be
  converted to List<Book>

process(textBooks);

import java.util.*;

class Book {}

class TextBook extends Book {}

public class Sample {
    public static void process(List<Book> books) {}

    public static void main(String[] args) {
        List<Book> books = new ArrayList<>();
        process(books);
        System.out.println(“OK”)

        List<TextBook> textBooks = new ArrayList<>();
        process(textBooks); # what is the problem in this statement?
        System.out.println(“OK”);
    }
}

Body:
You are trying to pass a List<TextBook> into a method whose signature expects a List<Book>.  This fails at compile time, because if the Java compiler were to allow it, then your process() method might try to use the contents of the list in the wrong way.  Instead, use this version of process():

public static void process(List<? extends Book> books) {}

Now you may pass in any instance of Book, or any subclass of Book.


问:
Java 8 Lambda: Comparator
I want to sort a list with Lambda:

```<code>List<Message> messagesByDeviceType = new ArrayList<Message>();
messagesByDeviceType.sort((Message o1, Message o2)->o1.getTime()-o2.getTime());
</code>```

But I got this compilation error:

```<code> Multiple markers at this line
    - Type mismatch: cannot convert from long to int
    - The method sort(Comparator<? super Message>) in the type List<Message> is not applicable for the arguments ((Message o1, Message o2)
     -> {})
</code>```

答:
lamda comparator

```<code>In the place of Developer write your class name

    Comparator<Developer> byName =
        (Developer o1, Developer o2)->o1.getName().compareTo(o2.getName());
</code>```

Title: Java 8 Lambda: Comparator

Body:
I want to sort a list with Lambda:

List<Message> messagesByDeviceType = new ArrayList<Message>();
messagesByDeviceType.sort((Message o1, Message o2)->o1.getTime()-o2.getTime());

But I got this compilation error:

 Multiple markers at this line
    - Type mismatch: cannot convert from long to int
    - The method sort(Comparator<? super Message>) in the type List<Message> is not applicable for the arguments ((Message o1, Message o2)
     -> {})

Body:
lamda comparator

In the place of Developer write your class name

    Comparator<Developer> byName =
        (Developer o1, Developer o2)->o1.getName().compareTo(o2.getName());


问:
How do i compare the dates read from csv file, such that I will only count those post with that month?
I am currently stumped in filtering out the dates that I have retrieved from 2 CSV file via opencsv. I wish to filter out the dates by month such that I could count the number of posts of each month and display it via javaFX line chart. E.g. y-axis would be number of post, x-axis would be the month.
So far, as per my codes below, it just prints out a list of "is it not comparing". So far I have manage to convert the date to string format such that it would print out just the month, Feb, Jan, Dec, etc...

Format of the dates in csv files are:

```<code>csv file 1: Feb 14, 2020, 8:03 pm

csv file 2: 2020-01-20T16:34:57+0800
</code>```

CODE

```<code>int febCounter = 0;
int janCounter = 0;
int decCounter = 0;
String pattern = "MMM";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);

try (Reader reader = Files.newBufferedReader(Paths.get("file_path"));
            CSVReader csvReader = new CSVReader(reader);){
    String [] nextRecord;
    while((nextRecord = csvReader.readNext()) != null) {
        String retrievedate = nextRecord[2];
        Date date = sdf.parse(retrievedate);
        String strDate = sdf.format(date);
        if(strDate.equals("Feb")) {
            febCounter++;
        }
        else {
            System.out.println("it is not comparing");
        }
        System.out.println(febCounter);
    }
} catch(IOException e) {
    System.out.print("File can't be found");
}
</code>```

EXPECTED OUTPUT

```<code>Feburary: 50

January: 20

December: 10
</code>```

Current OUTPUT

```<code>it is not comparing
it is not comparing
it is not comparing
it is not comparing
</code>```

so on....

UPDATE

So I am able to fix my error, I needed to format the retrieved date twice, once is to format the date such that I would only have the month, second format is to convert the date into a string, such that "strDate.equals("Feb")" will work.

答:
You need to read the value from the CSV file and use logic similar to the one given to get the value of month counters. For the purpose of the demo, I have put some dates in an array.

```<code>import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.List;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        List<String> monthList = List.of("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov",
                "Dec");
        int[] months = new int[12];
        String[] dateStrs = { "Feb 14, 2020, 8:03 pm", "Jan 20, 2020, 9:03 am", "Mar 6, 2020, 2:03 pm",
                "Feb 15, 2020, 11:03 am", "Jul 18, 2020, 4:03 am", "Jan 21, 2020, 5:03 pm", "Mar 11, 2020, 6:03 pm" };
        for (String dateStr : dateStrs) {
            months[monthList.indexOf(LocalDate.parse(dateStr, DateTimeFormatter.ofPattern("MMM d, yyyy, h:mm a"))
                    .getMonth().getDisplayName(TextStyle.SHORT, Locale.US))]++;
        }
        for (int i = 0; i < months.length; i++) {
            System.out.println(monthList.get(i) + ":" + months[i]);
        }

        //Similarly apply the following format for the second CSV file
        // DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXX")
        // String[] dateStr2 = {"2020-01-20T16:34:57+0800",...};
    }
}
</code>```

Output:

```<code>Jan:2
Feb:2
Mar:2
Apr:0
May:0
Jun:0
Jul:1
Aug:0
Sep:0
Oct:0
Nov:0
Dec:0
</code>```

I hope, this is enough hint for you to complete your task. Feel free to comment in case of any issue.

Body:
I am currently stumped in filtering out the dates that I have retrieved from 2 CSV file via opencsv. I wish to filter out the dates by month such that I could count the number of posts of each month and display it via javaFX line chart. E.g. y-axis would be number of post, x-axis would be the month.
So far, as per my codes below, it just prints out a list of "is it not comparing". So far I have manage to convert the date to string format such that it would print out just the month, Feb, Jan, Dec, etc...

Format of the dates in csv files are:

csv file 1: Feb 14, 2020, 8:03 pm

csv file 2: 2020-01-20T16:34:57+0800

CODE

int febCounter = 0;
int janCounter = 0;
int decCounter = 0;
String pattern = "MMM";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);

try (Reader reader = Files.newBufferedReader(Paths.get("file_path"));
            CSVReader csvReader = new CSVReader(reader);){
    String [] nextRecord;
    while((nextRecord = csvReader.readNext()) != null) {
        String retrievedate = nextRecord[2];
        Date date = sdf.parse(retrievedate);
        String strDate = sdf.format(date);
        if(strDate.equals("Feb")) {
            febCounter++;
        }
        else {
            System.out.println("it is not comparing");
        }
        System.out.println(febCounter);
    }
} catch(IOException e) {
    System.out.print("File can't be found");
}

EXPECTED OUTPUT

Feburary: 50

January: 20

December: 10

Current OUTPUT

it is not comparing
it is not comparing
it is not comparing
it is not comparing

so on....

UPDATE

So I am able to fix my error, I needed to format the retrieved date twice, once is to format the date such that I would only have the month, second format is to convert the date into a string, such that "strDate.equals("Feb")" will work.

Body:
You need to read the value from the CSV file and use logic similar to the one given to get the value of month counters. For the purpose of the demo, I have put some dates in an array.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.List;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        List<String> monthList = List.of("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov",
                "Dec");
        int[] months = new int[12];
        String[] dateStrs = { "Feb 14, 2020, 8:03 pm", "Jan 20, 2020, 9:03 am", "Mar 6, 2020, 2:03 pm",
                "Feb 15, 2020, 11:03 am", "Jul 18, 2020, 4:03 am", "Jan 21, 2020, 5:03 pm", "Mar 11, 2020, 6:03 pm" };
        for (String dateStr : dateStrs) {
            months[monthList.indexOf(LocalDate.parse(dateStr, DateTimeFormatter.ofPattern("MMM d, yyyy, h:mm a"))
                    .getMonth().getDisplayName(TextStyle.SHORT, Locale.US))]++;
        }
        for (int i = 0; i < months.length; i++) {
            System.out.println(monthList.get(i) + ":" + months[i]);
        }

        //Similarly apply the following format for the second CSV file
        // DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXX")
        // String[] dateStr2 = {"2020-01-20T16:34:57+0800",...};
    }
}

Output:

Jan:2
Feb:2
Mar:2
Apr:0
May:0
Jun:0
Jul:1
Aug:0
Sep:0
Oct:0
Nov:0
Dec:0

I hope, this is enough hint for you to complete your task. Feel free to comment in case of any issue.


问:
How to implement OneToMany, ManyToOne and ManyToMany with R2DBC in a project which previously used JPA?
I have to re-implement a few back-end services and one of the main requirement is to make the whole flow reactive. Previously the services used hibernate with PostgreSQL so the mentioned connections were provided by the framework.

Since I have to keep the original DB and just change the service implementation I have to use r2dbc-postgresql. I couldn't find any resource about this topic, but my best guess is to do something similar what I would do with JDBC and introduce some new connection tables between my entities.

Is this would be a correct approach or should I consider some different solutions?

What would be the steps to achieve the mentioned connections?

答:
I am looking into something similar and have come to the same conclusion (1), since there is no support for relations in R2DBC.
To migrate a one-to-many relation I first made the collection containing the "many" entities to @Transient in the "one" entity.
Persisting the "one" entity is accomplished using the following steps in a reactive sequence:

Persist the "many" entities. This in order to be able to update these in the "one" entity so that the "many" entities are assigned ids.

Persist the "one" entity.

Persist the relationships. I can do this at this stage since I now have the ids of all involved entities. For the relationships I have introduced a helper entity, something along the lines of OneManyRelation and a corresponding repository.

In code it looks like this:

```<code>public <S extends Drawing> Mono<S> save(final S inDrawing) {
    final List<Shape> theDrawingShapes = inDrawing.getShapes();

    return Mono.defer(() -> {
        return Flux.fromIterable(theDrawingShapes)
            .log()
            .flatMap(theDrawingShape -> {
                /* Save the shapes contained in the drawing. */
                if (theDrawingShape instanceof Circle) {
                    final Circle theUnsavedCircle = (Circle) theDrawingShape;
                    return mCircleRepository.save(theUnsavedCircle);
                } else if (theDrawingShape instanceof Rectangle) {
                    final Rectangle theUnsavedRectangle = (Rectangle) theDrawingShape;
                    return mRectangleRepository.save(theUnsavedRectangle);
                } else {
                    LOGGER.warn("Unrecognized entity type: {}",
                        theDrawingShape.getClass().getName());
                    return Mono.just(theDrawingShape);
                }
            })
            /* Update the drawing, setting the shapes of the drawing to the saved shapes. */
            .collectList()
            .map(theSavedShapesList -> {
                inDrawing.setShapes(new ArrayList<>(theSavedShapesList));
                return inDrawing;
            })
            /* Save the drawing itself. */
            .flatMap(theDrawing -> super.save(theDrawing))
            .flatMap(theDrawing -> {
                /* Save the relations between the drawing and the shapes of the drawing. */
                return Flux.fromIterable(theDrawing.getShapes())
                    .flatMap(theDrawingShape -> {
                        final var theDrawingShapeRelation = new DrawingShapesRelation();
                        theDrawingShapeRelation.setDrawingId(theDrawing.getId());
                        theDrawingShapeRelation.setShapeId(theDrawingShape.getId());
                        theDrawingShapeRelation.setShapeType(theDrawingShape.getClass()
                            .getName());
                        return mDrawingShapesRelationRepository.save(theDrawingShapeRelation);
                    })
                    .collectList()
                    .map(theDrawingShapesRelationList -> theDrawing);
            });
    });
}
</code>```

My conclusion this far is that unless you are certain that there are major gains to be made from switching to R2DBC, I would settle for using Spring Data JPA and executing calls to repositories in a separate thread using subscribeOn.

Good luck and happy coding!

Body:
I am looking into something similar and have come to the same conclusion (1), since there is no support for relations in R2DBC.
To migrate a one-to-many relation I first made the collection containing the "many" entities to @Transient in the "one" entity.
Persisting the "one" entity is accomplished using the following steps in a reactive sequence:

Persist the "many" entities. This in order to be able to update these in the "one" entity so that the "many" entities are assigned ids.

Persist the "one" entity.

Persist the relationships. I can do this at this stage since I now have the ids of all involved entities. For the relationships I have introduced a helper entity, something along the lines of OneManyRelation and a corresponding repository.

In code it looks like this:

public <S extends Drawing> Mono<S> save(final S inDrawing) {
    final List<Shape> theDrawingShapes = inDrawing.getShapes();

    return Mono.defer(() -> {
        return Flux.fromIterable(theDrawingShapes)
            .log()
            .flatMap(theDrawingShape -> {
                /* Save the shapes contained in the drawing. */
                if (theDrawingShape instanceof Circle) {
                    final Circle theUnsavedCircle = (Circle) theDrawingShape;
                    return mCircleRepository.save(theUnsavedCircle);
                } else if (theDrawingShape instanceof Rectangle) {
                    final Rectangle theUnsavedRectangle = (Rectangle) theDrawingShape;
                    return mRectangleRepository.save(theUnsavedRectangle);
                } else {
                    LOGGER.warn("Unrecognized entity type: {}",
                        theDrawingShape.getClass().getName());
                    return Mono.just(theDrawingShape);
                }
            })
            /* Update the drawing, setting the shapes of the drawing to the saved shapes. */
            .collectList()
            .map(theSavedShapesList -> {
                inDrawing.setShapes(new ArrayList<>(theSavedShapesList));
                return inDrawing;
            })
            /* Save the drawing itself. */
            .flatMap(theDrawing -> super.save(theDrawing))
            .flatMap(theDrawing -> {
                /* Save the relations between the drawing and the shapes of the drawing. */
                return Flux.fromIterable(theDrawing.getShapes())
                    .flatMap(theDrawingShape -> {
                        final var theDrawingShapeRelation = new DrawingShapesRelation();
                        theDrawingShapeRelation.setDrawingId(theDrawing.getId());
                        theDrawingShapeRelation.setShapeId(theDrawingShape.getId());
                        theDrawingShapeRelation.setShapeType(theDrawingShape.getClass()
                            .getName());
                        return mDrawingShapesRelationRepository.save(theDrawingShapeRelation);
                    })
                    .collectList()
                    .map(theDrawingShapesRelationList -> theDrawing);
            });
    });
}

My conclusion this far is that unless you are certain that there are major gains to be made from switching to R2DBC, I would settle for using Spring Data JPA and executing calls to repositories in a separate thread using subscribeOn.

Good luck and happy coding!


问:
Autowire not working with controller Spring Boot
Whenever I am trying to autowire a custom repository implementing JPA Repository within my controller class it is unable to do so and throwing a no bean def found error whereas if I am doing the same with any Service Class its working fine. Can anyone please explain to me why is it so?</p>

```<code>
Spring Boot
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
    2020-02-15 13:01:50.169 ERROR 16304 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

    ***************************
    APPLICATION FAILED TO START
    ***************************

    Description:

    Field customerRepo in Controllers.MainController required a bean of type 'Repository.CustomerRepo' that could not be found.

    The injection point has the following annotations:
        - @org.springframework.beans.factory.annotation.Autowired(required=true)

    Action:

    Consider defining a bean of type 'Repository.CustomerRepo' in your configuration.

    ```
    @SpringBootApplication
    @ComponentScan(basePackages = "Controllers")
    public class DemoApplication {

        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }

    }
    ``````````````````
    @RestController
    @RequestMapping("/")
    public class MainController {

        @Autowired
        private CustomerRepo customerRepo;

        @RequestMapping(value = "/home", method = RequestMethod.GET)
        public String homePage() {
            Customer testCustomer = new Customer();
            testCustomer.setFirstName("csdcsdccs");
            testCustomer.setLastName("csdcsdccs");
            testCustomer.setMiddleName("csdcsdccs");
            testCustomer.setAddressLine("csdcsdccs");
            testCustomer.setCountry("csdcsdccs");
            testCustomer.setPincode(713201);
            testCustomer.setState("csdcsdccs");
            testCustomer.setDateOfBirth(new Date(2019, 5, 13));

            customerRepo.save(testCustomer);

            return "inserted";
        }
    }

    `````````````
    @Repository
    public interface CustomerRepo extends CrudRepository<Customer, Long> {

    }
    ``````````````````````````

</code>```

答: Can you try @Component or @Repository annotations on you Repo?

Body:
Whenever I am trying to autowire a custom repository implementing JPA Repository within my controller class it is unable to do so and throwing a no bean def found error whereas if I am doing the same with any Service Class its working fine. Can anyone please explain to me why is it so?

Spring Boot
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
    2020-02-15 13:01:50.169 ERROR 16304 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

    ***************************
    APPLICATION FAILED TO START
    ***************************

    Description:

    Field customerRepo in Controllers.MainController required a bean of type 'Repository.CustomerRepo' that could not be found.

    The injection point has the following annotations:
        - @org.springframework.beans.factory.annotation.Autowired(required=true)

    Action:

    Consider defining a bean of type 'Repository.CustomerRepo' in your configuration.

    ```
    @SpringBootApplication
    @ComponentScan(basePackages = "Controllers")
    public class DemoApplication {

        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }

    }
    ``````````````````
    @RestController
    @RequestMapping("/")
    public class MainController {

        @Autowired
        private CustomerRepo customerRepo;

        @RequestMapping(value = "/home", method = RequestMethod.GET)
        public String homePage() {
            Customer testCustomer = new Customer();
            testCustomer.setFirstName("csdcsdccs");
            testCustomer.setLastName("csdcsdccs");
            testCustomer.setMiddleName("csdcsdccs");
            testCustomer.setAddressLine("csdcsdccs");
            testCustomer.setCountry("csdcsdccs");
            testCustomer.setPincode(713201);
            testCustomer.setState("csdcsdccs");
            testCustomer.setDateOfBirth(new Date(2019, 5, 13));

            customerRepo.save(testCustomer);

            return "inserted";
        }
    }

    `````````````
    @Repository
    public interface CustomerRepo extends CrudRepository<Customer, Long> {

    }
    ``````````````````````````


问:
Print the Result of a mysqli SELECT Query
I am trying to search my database for a result, and display all the columns relating to that result. My connection to the database works fine, but I don't know how to print the result of my query.

I tried accessing it as an array, but it did not work. What I want is to be able to search the database for the username 'TEST', and to return the password, email and username (to check the username exists).

My current code is this

```<code>$user = mysqli_query($con,"SELECT * FROM user_list where username = '$username'");
print_r($user);
</code>```

$username is the username. It returns this

```<code>(
    [current_field] => 0
    [field_count] => 4
    [lengths] =>
    [num_rows] => 2
    [type] => 0
)
</code>```

答:
To get the result of the mysqli_query() you need to use one of the functions, which return the rows. For example fetch_all() to get all the rows or fetch_array() to get a single row.

You can also loop on the object directly.

```<code>$result = mysqli_query($con, 'SELECT ...');
foreach($result as $row) {
    print_r($row);
    // do something with each row
}
</code>```

However, in your case you should not be using mysqli_query() at all! This leaves you vulnerable to SQL injection. You must use parameter binding, which is available with prepared statements.

For example your fixed query would look like this:

```<code>$stmt = $con->prepare('SELECT * FROM user_list where username = ?');
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result();
foreach ($result as $row) {
    print_r($row);
}
</code>```

The difference is that my variable is not separate from the SQL, so there is no risk of injection. You should never allow any variable input directly in SQL query. Doing this properly is really not that difficult.

Body:
I am trying to search my database for a result, and display all the columns relating to that result. My connection to the database works fine, but I don't know how to print the result of my query.

I tried accessing it as an array, but it did not work. What I want is to be able to search the database for the username 'TEST', and to return the password, email and username (to check the username exists).

My current code is this

$user = mysqli_query($con,"SELECT * FROM user_list where username = '$username'");
print_r($user);

$username is the username. It returns this

(
    [current_field] => 0
    [field_count] => 4
    [lengths] =>
    [num_rows] => 2
    [type] => 0
)

Body:
To get the result of the mysqli_query() you need to use one of the functions, which return the rows. For example fetch_all() to get all the rows or fetch_array() to get a single row.

You can also loop on the object directly.

$result = mysqli_query($con, 'SELECT ...');
foreach($result as $row) {
    print_r($row);
    // do something with each row
}

However, in your case you should not be using mysqli_query() at all! This leaves you vulnerable to SQL injection. You must use parameter binding, which is available with prepared statements.

For example your fixed query would look like this:

$stmt = $con->prepare('SELECT * FROM user_list where username = ?');
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result();
foreach ($result as $row) {
    print_r($row);
}

The difference is that my variable is not separate from the SQL, so there is no risk of injection. You should never allow any variable input directly in SQL query. Doing this properly is really not that difficult.