问:
org.apache.commons.vfs2.FileSystemException: Could not connect to SFTP server
I'm trying to connect to a SFTP host using vfs2 connector, which internally uses jsch.
However, when I try to connect, I get the following exception:

```<code>12:50:31.747  INFO  o.a.c.v.p.sftp.SftpClientFactory - Connecting to <host> port <port>
12:50:32.074  INFO  o.a.c.v.p.sftp.SftpClientFactory - Connection established
12:50:32.376  INFO  o.a.c.v.p.sftp.SftpClientFactory - Remote version string: SSH-2.0-OpenSSH_7.4
12:50:32.376  INFO  o.a.c.v.p.sftp.SftpClientFactory - Local version string: SSH-2.0-JSCH-0.1.54
12:50:32.376  INFO  o.a.c.v.p.sftp.SftpClientFactory - CheckCiphers: aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,3des-ctr,arcfour,arcfour128,arcfour256
12:50:33.489  INFO  o.a.c.v.p.sftp.SftpClientFactory - CheckKexes: diffie-hellman-group14-sha1,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521
12:50:34.192  INFO  o.a.c.v.p.sftp.SftpClientFactory - CheckSignatures: ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
12:50:34.203  INFO  o.a.c.v.p.sftp.SftpClientFactory - SSH_MSG_KEXINIT sent
12:50:34.203  INFO  o.a.c.v.p.sftp.SftpClientFactory - SSH_MSG_KEXINIT received
12:50:34.203  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: server: curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256
12:50:34.203  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: server: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ssh-ed25519
12:50:34.203  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: server: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc,blowfish-cbc,cast128-cbc,3des-cbc
12:50:34.203  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: server: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc,blowfish-cbc,cast128-cbc,3des-cbc
12:50:34.203  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: server: hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com
12:50:34.203  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: server: hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com
12:50:34.203  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: server: none,zlib@openssh.com
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: server: none,zlib@openssh.com
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: server:
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: server:
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: client: ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group1-sha1
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: client: ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: client: aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc,aes192-ctr,aes192-cbc,aes256-ctr,aes256-cbc
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: client: aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc,aes192-ctr,aes192-cbc,aes256-ctr,aes256-cbc
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: client: hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: client: hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: client: none
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: client: none
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: client:
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: client:
12:50:34.205  INFO  o.a.c.v.p.sftp.SftpClientFactory - Disconnecting from <host> port <port>
12:50:34.243  ERROR c.s.saw.export.SFTPUploader - IO SFTP Error:
org.apache.commons.vfs2.FileSystemException: Could not connect to SFTP server at "sftp://<user>@<host>:<port>/".
    at org.apache.commons.vfs2.provider.sftp.SftpFileProvider.createSession(SftpFileProvider.java:72)
    at org.apache.commons.vfs2.provider.sftp.SftpFileProvider.doCreateFileSystem(SftpFileProvider.java:93)
    at org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider.getFileSystem(AbstractOriginatingFileProvider.java:93)
    at org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider.findFile(AbstractOriginatingFileProvider.java:72)
    at org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider.findFile(AbstractOriginatingFileProvider.java:56)
    at org.apache.commons.vfs2.impl.DefaultFileSystemManager.resolveFile(DefaultFileSystemManager.java:717)
    at org.apache.commons.vfs2.impl.DefaultFileSystemManager.resolveFile(DefaultFileSystemManager.java:654)
    at com.synchronoss.saw.export.SFTPUploader.uploadFile(SFTPUploader.java:99)
    at com.synchronoss.saw.export.SFTPUploader.main(SFTPUploader.java:134)
Caused by: org.apache.commons.vfs2.FileSystemException: Could not connect to SFTP server at "<host>".
    at org.apache.commons.vfs2.provider.sftp.SftpClientFactory.createConnection(SftpClientFactory.java:163)
    at org.apache.commons.vfs2.provider.sftp.SftpFileProvider.createSession(SftpFileProvider.java:65)
    ... 8 common frames omitted
Caused by: com.jcraft.jsch.JSchException: Algorithm negotiation fail
    at com.jcraft.jsch.Session.receive_kexinit(Session.java:590)
    at com.jcraft.jsch.Session.connect(Session.java:320)
    at com.jcraft.jsch.Session.connect(Session.java:183)
    at org.apache.commons.vfs2.provider.sftp.SftpClientFactory.createConnection(SftpClientFactory.java:161)
    ... 9 common frames omitted
</code>```

I referred to a few blogs and stackoverflow links and tried multiple things. Still I'm not getting any successful result. Also, tried multiple versions of vfs2 and jsch with no avail.

Here are some of the links I referred:

JSchException: Algorithm negotiation fail

JSch Algorithm negotiation fail

https://dzone.com/articles/install-java-cryptography-extension-jce-unlimited

The cipher 'aes256-cbc' is required, but it is not available

Can someone please help me with this?

答:
Your server supports only these MACs:

hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com
```

<p>Those are not supported by JSch.</p>

<hr>

<p>If you need to connect with JSch, you will have to configure your server to allow some MACs that JSch does support:</p>

<pre class="lang-none prettyprint-override"><code>hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96
</code>```

Use the MACs directive in sshd_config.

Though hmac-sha2-*-etm@openssh.com and hmac-sha2-* are possibly just aliases. So configuring JSch appropriately may help too:

```<code>config.put("hmac-sha2-256-etm@openssh.com", "com.jcraft.jsch.jce.HMACSHA256");
</code>```

But I'm not sure, if vfs2 interface allows such configuration.

Body:
I'm trying to connect to a SFTP host using vfs2 connector, which internally uses jsch.
However, when I try to connect, I get the following exception:

12:50:31.747  INFO  o.a.c.v.p.sftp.SftpClientFactory - Connecting to <host> port <port>
12:50:32.074  INFO  o.a.c.v.p.sftp.SftpClientFactory - Connection established
12:50:32.376  INFO  o.a.c.v.p.sftp.SftpClientFactory - Remote version string: SSH-2.0-OpenSSH_7.4
12:50:32.376  INFO  o.a.c.v.p.sftp.SftpClientFactory - Local version string: SSH-2.0-JSCH-0.1.54
12:50:32.376  INFO  o.a.c.v.p.sftp.SftpClientFactory - CheckCiphers: aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,3des-ctr,arcfour,arcfour128,arcfour256
12:50:33.489  INFO  o.a.c.v.p.sftp.SftpClientFactory - CheckKexes: diffie-hellman-group14-sha1,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521
12:50:34.192  INFO  o.a.c.v.p.sftp.SftpClientFactory - CheckSignatures: ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
12:50:34.203  INFO  o.a.c.v.p.sftp.SftpClientFactory - SSH_MSG_KEXINIT sent
12:50:34.203  INFO  o.a.c.v.p.sftp.SftpClientFactory - SSH_MSG_KEXINIT received
12:50:34.203  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: server: curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256
12:50:34.203  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: server: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ssh-ed25519
12:50:34.203  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: server: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc,blowfish-cbc,cast128-cbc,3des-cbc
12:50:34.203  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: server: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc,blowfish-cbc,cast128-cbc,3des-cbc
12:50:34.203  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: server: hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com
12:50:34.203  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: server: hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com
12:50:34.203  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: server: none,zlib@openssh.com
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: server: none,zlib@openssh.com
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: server:
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: server:
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: client: ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group1-sha1
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: client: ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: client: aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc,aes192-ctr,aes192-cbc,aes256-ctr,aes256-cbc
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: client: aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc,aes192-ctr,aes192-cbc,aes256-ctr,aes256-cbc
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: client: hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: client: hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: client: none
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: client: none
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: client:
12:50:34.204  INFO  o.a.c.v.p.sftp.SftpClientFactory - kex: client:
12:50:34.205  INFO  o.a.c.v.p.sftp.SftpClientFactory - Disconnecting from <host> port <port>
12:50:34.243  ERROR c.s.saw.export.SFTPUploader - IO SFTP Error:
org.apache.commons.vfs2.FileSystemException: Could not connect to SFTP server at "sftp://<user>@<host>:<port>/".
    at org.apache.commons.vfs2.provider.sftp.SftpFileProvider.createSession(SftpFileProvider.java:72)
    at org.apache.commons.vfs2.provider.sftp.SftpFileProvider.doCreateFileSystem(SftpFileProvider.java:93)
    at org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider.getFileSystem(AbstractOriginatingFileProvider.java:93)
    at org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider.findFile(AbstractOriginatingFileProvider.java:72)
    at org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider.findFile(AbstractOriginatingFileProvider.java:56)
    at org.apache.commons.vfs2.impl.DefaultFileSystemManager.resolveFile(DefaultFileSystemManager.java:717)
    at org.apache.commons.vfs2.impl.DefaultFileSystemManager.resolveFile(DefaultFileSystemManager.java:654)
    at com.synchronoss.saw.export.SFTPUploader.uploadFile(SFTPUploader.java:99)
    at com.synchronoss.saw.export.SFTPUploader.main(SFTPUploader.java:134)
Caused by: org.apache.commons.vfs2.FileSystemException: Could not connect to SFTP server at "<host>".
    at org.apache.commons.vfs2.provider.sftp.SftpClientFactory.createConnection(SftpClientFactory.java:163)
    at org.apache.commons.vfs2.provider.sftp.SftpFileProvider.createSession(SftpFileProvider.java:65)
    ... 8 common frames omitted
Caused by: com.jcraft.jsch.JSchException: Algorithm negotiation fail
    at com.jcraft.jsch.Session.receive_kexinit(Session.java:590)
    at com.jcraft.jsch.Session.connect(Session.java:320)
    at com.jcraft.jsch.Session.connect(Session.java:183)
    at org.apache.commons.vfs2.provider.sftp.SftpClientFactory.createConnection(SftpClientFactory.java:161)
    ... 9 common frames omitted

I referred to a few blogs and stackoverflow links and tried multiple things. Still I'm not getting any successful result. Also, tried multiple versions of vfs2 and jsch with no avail.

Here are some of the links I referred:

JSchException: Algorithm negotiation fail

JSch Algorithm negotiation fail

https://dzone.com/articles/install-java-cryptography-extension-jce-unlimited

The cipher 'aes256-cbc' is required, but it is not available

Can someone please help me with this?

Body:
Your server supports only these MACs:

hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com

Those are not supported by JSch.

If you need to connect with JSch, you will have to configure your server to allow some MACs that JSch does support:

hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96

Use the MACs directive in sshd_config.

Though hmac-sha2-*-etm@openssh.com and hmac-sha2-* are possibly just aliases. So configuring JSch appropriately may help too:

config.put("hmac-sha2-256-etm@openssh.com", "com.jcraft.jsch.jce.HMACSHA256");

But I'm not sure, if vfs2 interface allows such configuration.


来源: stackexchange

问:
Array-index-out-of-bounds exception
I am getting an array-out-of-bounds exception error. This is my simple code:

for(int i=0; i<aa.length; i++) {
    String[] event = aa[i].split(" ");
    int mr = 0;
    mr = event[i].length();
    String eventtime = event[mr];
}
```

And this is my error caused:

Caused by: java.lang.ArrayIndexOutOfBoundsException: length=3; index=5.

The length of my events array is 3. Then the index has to be 3, but it shows me 5. Why?

答: I think you are taking the length of an element of the array.</p>

ContentLicense: CC BY-SA 4.0

Title: Array-index-out-of-bounds exception

Body:
I am getting an array-out-of-bounds exception error. This is my simple code:

for(int i=0; i<aa.length; i++) {
    String[] event = aa[i].split(" ");
    int mr = 0;
    mr = event[i].length();
    String eventtime = event[mr];
}

And this is my error caused:

Caused by: java.lang.ArrayIndexOutOfBoundsException: length=3; index=5.

The length of my events array is 3. Then the index has to be 3, but it shows me 5. Why?


问:
Regex match chars not between 2 specific chars or words
i'm trying to make this regex work but i only had an half-success.

So far i could make this work:

match every ';' that is not between '[]'

with this regex: ;(?![^\[]*\])

But now comes my problem... i should also add this limitation:

match every ';' that is not between '[' and ']' or 'XXX' and 'ZZZ'

So for example in this text:

```<code>aaa **;** bbb **;** [ ccc *;* ddd ] eee **;** XXX qweasd *;* qwesad ZZZ
</code>```

the third and last ';' should not match

答:
This pattern seems to be working:

```<code>;(?![^[]*\])(?!((?!XXX).)*ZZZ)
</code>```

Explanation:

```<code>;                   match a semicolon
(?![^[]*\])         assert that we cannot look forward and see a ] without also seeing
                    an opening [
                       -> this implies that the semicolon is not in between []
(?!((?!XXX).)*ZZZ)  assert that we cannot look forward and see ZZZ without
                    first seeing XXX
                       -> this implies that the semicolon is not in between XXX and ZZZ
</code>```

Demo

Note that this solution assumes that you would not have nested [] brackets anywhere, or nested XXX...ZZZ, but rather only single level.

Body:
i'm trying to make this regex work but i only had an half-success.

So far i could make this work:

match every ';' that is not between '[]'

with this regex: ;(?![^\[]*\])

But now comes my problem... i should also add this limitation:

match every ';' that is not between '[' and ']' or 'XXX' and 'ZZZ'

So for example in this text:

aaa **;** bbb **;** [ ccc *;* ddd ] eee **;** XXX qweasd *;* qwesad ZZZ

the third and last ';' should not match

Body:
This pattern seems to be working:

;(?![^[]*\])(?!((?!XXX).)*ZZZ)

Explanation:

;                   match a semicolon
(?![^[]*\])         assert that we cannot look forward and see a ] without also seeing
                    an opening [
                       -> this implies that the semicolon is not in between []
(?!((?!XXX).)*ZZZ)  assert that we cannot look forward and see ZZZ without
                    first seeing XXX
                       -> this implies that the semicolon is not in between XXX and ZZZ

Demo

Note that this solution assumes that you would not have nested [] brackets anywhere, or nested XXX...ZZZ, but rather only single level.


问:
How to maintain an aspect ratio of a div inside another div
So I have a div and which contains two divs one on top of the other. I want the one on top to have an aspect ratio of 4:5 with 100% width as it will contain an image of that ratio and then remaining height goes goes  to the second div.

This is as far I could go

You can find all the code here

note: I wish to maintain that aspect ratio as the user shrink the screen size, try to shrink the width on the sandbox example to see

```<code>&_product{
                    overflow: hidden;
                    padding-top: 800.34px / 591.44px * 100%;
                    background: rgb(207, 206, 206);
                    position: relative;
                    max-width: 232px;
                    // max-height: 317.313px;
                    &_inside {
                      display: grid;
                      // grid-template-columns: 1fr
                      // grid-template-rows: 1fr 80px;;
                      position: absolute;
                      top: 0;
                      left: 0;
                      width: 100%;
                      height: 100%;
                    }

                    border: 1px solid rgb(131, 72, 72);
                    position:relative;
                    width:100%;
                    height:fit-content;
                    box-shadow: 0 5px 15px rgba(0,0,0,.25);
                    overflow:hidden;
                    &_imgbox{
                      height: 100% ;
                      border: 1px solid red;
                      box-sizing:border-box;
                      position: relative;
                      // img{
                      //   width:100%;
                      //   display:block;
                      //   margin:0;
                      // }
                      &_aspect {
                        position: absolute;
                        width: 100%;
                        height: 5px/4px*100%;   // My attempted calculation
                        background: blue;
                        top: 0;
                        // left: 0;

                      }
                  }
                }
</code>```

html

```<code>    <div class="Recommendations_container_recomendation_box_product">
                            <div class="Recommendations_container_recomendation_box_product_inside">
                                <div class="Recommendations_container_recomendation_box_product_imgbox">
                                    <div class="Recommendations_container_recomendation_box_product_imgbox_aspect">

                                        {/* <img src="https://images.sportsdirect.com/images/products/62310640_l.jpg" /> */}
                                    </div>

                                </div>
                                <div class="Recommendations_container_recomendation_box_details">
                                    <div class="Recommendations_container_recomendation_box_details_price">$55.99</div>
                                    <h2>Brand Name<br /><span>Mens Designer T-shirt</span></h2>

                                </div>
                            </div>

                        </div>
</code>```

答:
Flex can really help you here. I attached a simplified version of what you are trying to achieve.

It's just few lines of CSS. Hope it helps.

If you change the height of the box you'll see it maintains the ratio.
The ides is that inside the box, each item got a flex value. So the sum of all the value is then divided by the individual flex value to determine the ratio.

.box {
  display: flex;
  flex-direction: column;
  height: 300px;
  width: 300px;
  border: 1px solid black;
}

.four-fifth {
  flex: 4;
  background-color: red;
}

.remaining-height {
  flex: 1;
  background-color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
    <div class="four-fifth">
        Content
    </div>
    <div class="remaining-height">
        Additional content
    </div>
</div></code>```

Body:
So I have a div and which contains two divs one on top of the other. I want the one on top to have an aspect ratio of 4:5 with 100% width as it will contain an image of that ratio and then remaining height goes goes  to the second div.

This is as far I could go

You can find all the code here

note: I wish to maintain that aspect ratio as the user shrink the screen size, try to shrink the width on the sandbox example to see

&_product{
                    overflow: hidden;
                    padding-top: 800.34px / 591.44px * 100%;
                    background: rgb(207, 206, 206);
                    position: relative;
                    max-width: 232px;
                    // max-height: 317.313px;
                    &_inside {
                      display: grid;
                      // grid-template-columns: 1fr
                      // grid-template-rows: 1fr 80px;;
                      position: absolute;
                      top: 0;
                      left: 0;
                      width: 100%;
                      height: 100%;
                    }

                    border: 1px solid rgb(131, 72, 72);
                    position:relative;
                    width:100%;
                    height:fit-content;
                    box-shadow: 0 5px 15px rgba(0,0,0,.25);
                    overflow:hidden;
                    &_imgbox{
                      height: 100% ;
                      border: 1px solid red;
                      box-sizing:border-box;
                      position: relative;
                      // img{
                      //   width:100%;
                      //   display:block;
                      //   margin:0;
                      // }
                      &_aspect {
                        position: absolute;
                        width: 100%;
                        height: 5px/4px*100%;   // My attempted calculation
                        background: blue;
                        top: 0;
                        // left: 0;

                      }
                  }
                }

html

                                        {/*  */}

$55.99

Brand Name
Mens Designer T-shirt

Body:
Flex can really help you here. I attached a simplified version of what you are trying to achieve.

It's just few lines of CSS. Hope it helps.

If you change the height of the box you'll see it maintains the ratio.
The ides is that inside the box, each item got a flex value. So the sum of all the value is then divided by the individual flex value to determine the ratio.

.box {
  display: flex;
  flex-direction: column;
  height: 300px;
  width: 300px;
  border: 1px solid black;
}

.four-fifth {
  flex: 4;
  background-color: red;
}

.remaining-height {
  flex: 1;
  background-color: green;
}

<div class="box">
    <div class="four-fifth">
        Content
    </div>
    <div class="remaining-height">
        Additional content
    </div>
</div>


问:
logrotate says permission denied when rotating log / re-creating log file
I'm new to logrotate on linux machines... here's what I have set up in my app's logrotate.d file:

```<code>/var/log/myapp.log {
daily
missingok
create 0660 root utmp
rotate 1
}
</code>```

I set owner permissions on the myapp.log file for the account that runs the app in question, using chmod, directly from the bash shell.

when the app first runs, everything is fine. It logs just fine and it's all good. But when the log gets rotated, it deletes the log file and then tries to recreate the log file and it gives a permission denied error:

```<code>/bin/bash: /var/log/myapp.log: Permission denied
</code>```

I know I'm doing something wrong with either the logrotate config file or chmod or something... can someone point me in the right direction and help me fix the problem?

答:
I set owner permissions on the myapp.log file for the account that runs the app in question, using chmod, directly from the bash shell.

...so unless "the account that runs the app in question" is root, the config option

```<code>create 0660 root utmp
</code>```

is wrong, because that is asking logrotate to create a new myapp.log (after it has rotated the original myapp.log to myapp.log.0) with permissions 0660 owned by user root and group utmp.  Replacing these with the attributes required by your app should solve the problem.

ContentLicense: CC BY-SA 3.0

Body:
I'm new to logrotate on linux machines... here's what I have set up in my app's logrotate.d file:

/var/log/myapp.log {
daily
missingok
create 0660 root utmp
rotate 1
}

I set owner permissions on the myapp.log file for the account that runs the app in question, using chmod, directly from the bash shell.

when the app first runs, everything is fine. It logs just fine and it's all good. But when the log gets rotated, it deletes the log file and then tries to recreate the log file and it gives a permission denied error:

/bin/bash: /var/log/myapp.log: Permission denied

I know I'm doing something wrong with either the logrotate config file or chmod or something... can someone point me in the right direction and help me fix the problem?

Body:
I set owner permissions on the myapp.log file for the account that runs the app in question, using chmod, directly from the bash shell.

...so unless "the account that runs the app in question" is root, the config option

create 0660 root utmp

is wrong, because that is asking logrotate to create a new myapp.log (after it has rotated the original myapp.log to myapp.log.0) with permissions 0660 owned by user root and group utmp.  Replacing these with the attributes required by your app should solve the problem.


问:
Super basic question: How does one make an executable program out of java code?
I have only been coding for a few days and I have one question that i just can't seem to find any information on. I was wondering what I would have to do to create an executable application out of my java code. I know that I can run my compiled code from the terminal by typing java helloworld for example when I'm in the right directory, but then I always have to navigate to the file manually and run it. I was hoping there would be a way to create a file that I could just click on and that would automatically run the program in the computer's terminal.

Any explanation would be much appreciated! I'm currently working on MacOS if it makes a difference.
Thanks in advance.

edit: I'm using visual studio code to write my code

edit 2: I now understand that what I'm trying to accomplish is essentially to create a .jar file out of my .class file. Does anyone happen to know if there is a built in function in visual studio code to create a .Jar file? Some people are suggesting maven but I'm hesitant to download anything if im not sure it's necessary.

答:
There are two steps:

javac helloworld.java : This will compile your code.

java helloworld : This will run the .class file created in step 1.


问:
How to run infinite loop and keep getting updates in telegram bot
I'm writing telegram-bot using Go (go-telegram-bot-api). It constantly parses a website and notifies about changes (every minute). Today I added simple keyboard and now can't make them work together.

The problem is that webpage parsing is in the infinite loop and program when it enters the loop ignores updates coming from the "client".

I've tried putting everything in a single loop, changing orders, etc. Maybe there is another or proper way of doing this?

Sample code:

```<code>    u := tgbotapi.NewUpdate(0)
    u.Timeout = 60

    updates, err := bot.GetUpdatesChan(u)

    for update := range updates {
            if update.Message != nil {

                  switch update.Message.Text {
                        case "Show Keyboard":
                              Keyboard is sent
                        case "OptionsForParsing":
                              options.applied
                        case "StartParsing":
                              search bool = true
                        case "StopParsing":
                              search bool = false
                   }
            }

            if search == true{
            for{
                 time.Sleep(1 * time.Minute)
                 AreThereChanges?()
                 if yes{
                         msg := tgbotapi.NewMessage(update.Message.Chat.ID, "help please")
                         bot.Send(msg)
                 }
            }}
     }
</code>```

答:
Thanks to kimgrey I dug a bit into goroutines and channels. Infinite loop is in a separate goroutine and escaping is done through unbuffered channel (check "game changer" comments in the sample code). Now I can enter and escape infinite loop when needed. Here's how I solved my problem:</p>

```<code>u := tgbotapi.NewUpdate(0)
u.Timeout = 60

updates, err := bot.GetUpdatesChan(u)
done := make(chan bool)                       //game changer
for update := range updates {
        if update.Message != nil {

              switch update.Message.Text {
                    case "Show Keyboard":
                          Keyboard is sent
                    case "OptionsForParsing":
                          options.applied
                    case "StartParsing":
                          search bool = true
                    case "StopParsing":
                          search bool = false
                          done<-true                 //game changer
               }

            go func() {
                ticker := time.NewTicker(time.Minute)
                defer ticker.Stop()
                if search{
                for {
                    select {
                        case <-done:                //game changer
                            return
                        case <-ticker.C:
                            AnyChanges?()
                    }
                }}
            }()
        }
 }
</code>```

Body:
I'm writing telegram-bot using Go (go-telegram-bot-api). It constantly parses a website and notifies about changes (every minute). Today I added simple keyboard and now can't make them work together.

The problem is that webpage parsing is in the infinite loop and program when it enters the loop ignores updates coming from the "client".

I've tried putting everything in a single loop, changing orders, etc. Maybe there is another or proper way of doing this?

Sample code:

    u := tgbotapi.NewUpdate(0)
    u.Timeout = 60

    updates, err := bot.GetUpdatesChan(u)

    for update := range updates {
            if update.Message != nil {

                  switch update.Message.Text {
                        case "Show Keyboard":
                              Keyboard is sent
                        case "OptionsForParsing":
                              options.applied
                        case "StartParsing":
                              search bool = true
                        case "StopParsing":
                              search bool = false
                   }
            }

            if search == true{
            for{
                 time.Sleep(1 * time.Minute)
                 AreThereChanges?()
                 if yes{
                         msg := tgbotapi.NewMessage(update.Message.Chat.ID, "help please")
                         bot.Send(msg)
                 }
            }}
     }

Body:
Thanks to kimgrey I dug a bit into goroutines and channels. Infinite loop is in a separate goroutine and escaping is done through unbuffered channel (check "game changer" comments in the sample code). Now I can enter and escape infinite loop when needed. Here's how I solved my problem:

u := tgbotapi.NewUpdate(0)
u.Timeout = 60

updates, err := bot.GetUpdatesChan(u)
done := make(chan bool)                       //game changer
for update := range updates {
        if update.Message != nil {

              switch update.Message.Text {
                    case "Show Keyboard":
                          Keyboard is sent
                    case "OptionsForParsing":
                          options.applied
                    case "StartParsing":
                          search bool = true
                    case "StopParsing":
                          search bool = false
                          done<-true                 //game changer
               }

            go func() {
                ticker := time.NewTicker(time.Minute)
                defer ticker.Stop()
                if search{
                for {
                    select {
                        case <-done:                //game changer
                            return
                        case <-ticker.C:
                            AnyChanges?()
                    }
                }}
            }()
        }
 }


问:
Dismiss keyboard when click outside of EditText in android
I have an EditText called myTextview. I want the soft keyboard to show when I click on the EditText but then dismiss if I click outside of the EditText. So I use the method below. But the keyboard does not dismiss when I click outside the view (I click a TextView). How do I fix this code?

```<code>myTextview.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
            } else {
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(myTextview.getWindowToken(), 0);
            }

        }
    });
</code>```

答:
In Kotlin, I have used bellow code which is working fine

```<code>override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
    val v = currentFocus
    if (v != null && (ev.action == MotionEvent.ACTION_UP || ev.action == MotionEvent.ACTION_MOVE)
        && v is EditText
        && !v.javaClass.name.startsWith("android.webkit.")
    ) {
        val scrcoords = IntArray(2)
        v.getLocationOnScreen(scrcoords)
        val x = ev.rawX + v.getLeft() - scrcoords[0]
        val y = ev.rawY + v.getTop() - scrcoords[1]
        if (x < v.getLeft() || x > v.getRight() || y < v.getTop() || y > v.getBottom()
        ) hideKeyboard(this)
    }
    return super.dispatchTouchEvent(ev)
}

fun hideKeyboard(activity: Activity?) {
    if (activity != null && activity.window != null && activity.window.decorView != null
    ) {
        val imm = activity
            .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(
            activity.window.decorView
                .windowToken, 0
        )
    }
}
</code>```

In Java, I have used bellow code which is working fine

```<code>  @Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    View v = getCurrentFocus();

    if (v != null
            && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE)
            && v instanceof EditText
            && !v.getClass().getName().startsWith("android.webkit.")) {
        int scrcoords[] = new int[2];
        v.getLocationOnScreen(scrcoords);
        float x = ev.getRawX() + v.getLeft() - scrcoords[0];
        float y = ev.getRawY() + v.getTop() - scrcoords[1];

        if (x < v.getLeft() || x > v.getRight() || y < v.getTop()
                || y > v.getBottom())
            hideKeyboard(this);
    }
    return super.dispatchTouchEvent(ev);
}

public static void hideKeyboard(Activity activity) {
    if (activity != null && activity.getWindow() != null
            && activity.getWindow().getDecorView() != null) {
        InputMethodManager imm = (InputMethodManager) activity
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(activity.getWindow().getDecorView()
                .getWindowToken(), 0);
    }
}
</code>```

Body:
I have an EditText called myTextview. I want the soft keyboard to show when I click on the EditText but then dismiss if I click outside of the EditText. So I use the method below. But the keyboard does not dismiss when I click outside the view (I click a TextView). How do I fix this code?

myTextview.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
            } else {
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(myTextview.getWindowToken(), 0);
            }

        }
    });

Body:
In Kotlin, I have used bellow code which is working fine

override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
    val v = currentFocus
    if (v != null && (ev.action == MotionEvent.ACTION_UP || ev.action == MotionEvent.ACTION_MOVE)
        && v is EditText
        && !v.javaClass.name.startsWith("android.webkit.")
    ) {
        val scrcoords = IntArray(2)
        v.getLocationOnScreen(scrcoords)
        val x = ev.rawX + v.getLeft() - scrcoords[0]
        val y = ev.rawY + v.getTop() - scrcoords[1]
        if (x < v.getLeft() || x > v.getRight() || y < v.getTop() || y > v.getBottom()
        ) hideKeyboard(this)
    }
    return super.dispatchTouchEvent(ev)
}

fun hideKeyboard(activity: Activity?) {
    if (activity != null && activity.window != null && activity.window.decorView != null
    ) {
        val imm = activity
            .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(
            activity.window.decorView
                .windowToken, 0
        )
    }
}

In Java, I have used bellow code which is working fine

  @Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    View v = getCurrentFocus();

    if (v != null
            && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE)
            && v instanceof EditText
            && !v.getClass().getName().startsWith("android.webkit.")) {
        int scrcoords[] = new int[2];
        v.getLocationOnScreen(scrcoords);
        float x = ev.getRawX() + v.getLeft() - scrcoords[0];
        float y = ev.getRawY() + v.getTop() - scrcoords[1];

        if (x < v.getLeft() || x > v.getRight() || y < v.getTop()
                || y > v.getBottom())
            hideKeyboard(this);
    }
    return super.dispatchTouchEvent(ev);
}

public static void hideKeyboard(Activity activity) {
    if (activity != null && activity.getWindow() != null
            && activity.getWindow().getDecorView() != null) {
        InputMethodManager imm = (InputMethodManager) activity
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(activity.getWindow().getDecorView()
                .getWindowToken(), 0);
    }
}


问:
Access Azure Key Vault from Azure build/release pipelines
We have some unit tests/integration tests running on Azure build/release pipelines. There are few tests that retrieve secrets from key vault and these are failing because the code is written for fetching secrets from keyvault using MSI and Azure app authentication features. Since pipelines are not enabled for MSI, the keyvault calls are failing and hence the tests are also failing. What is the alternative that exists for this scenario where pipelines can access keyvault successfuly?

Note: I have already gone through articles suggesting to use variable groups and azure keyvault tasks but not helpful in my scenario .Looking for alternatives.

答:
Note: I have already gone through articles suggesting to use variable
  groups and azure keyvault tasks but not helpful in my scenario.Looking
  for alternatives.

You can try two directions:

Configure a self-hosted agent to run your pipeline in local environment. Of course the agent should be configured with your managed identity.

According to step5 from this blog:

AzureServiceTokenProvider will use the developer's security context to get a token to authenticate to Key Vault. This removes the need to create a service principal, and share it with the development team. It also prevents credentials from being checked in to source code. AzureServiceTokenProvider will use Azure CLI or Active Directory Integrated Authentication to authenticate to Azure AD to get a token. That token will be used to fetch the secret from Azure Key Vault.

You can use Azure Cli task to run your tests in command-line. Check this similar issue.


问:
why do I get this error if I return value using questionmark operator in Vue.js
I just tried to return the value using questionmark operator instead of using return twice. But I got an error "Cannot read property 'omitDescription' of undefined" .

```<code>buttonText() {
  return this.omitDescription ? 'プロフィールをもっと見る' : 'プロフィールを閉じる'
  // return function() {
  //   if(this.omitDescription) {
  //     return 'プロフィールをもっと見る'
  //   } else {
  //     return 'プロフィールを閉じる'
  //   }
  // }
}
</code>```

The part where I commented out did work instead, so I could not figure out the difference.
Thank you!

答:
Its not the same, in the previous approach you return an function. Try it like this:</p>

```<code>buttonText() {
    return () => this.omitDescription ? 'プロフィールをもっと見る' : 'プロフィールを閉じる';
}
</code>```

Body:
I just tried to return the value using questionmark operator instead of using return twice. But I got an error "Cannot read property 'omitDescription' of undefined" .

buttonText() {
  return this.omitDescription ? 'プロフィールをもっと見る' : 'プロフィールを閉じる'
  // return function() {
  //   if(this.omitDescription) {
  //     return 'プロフィールをもっと見る'
  //   } else {
  //     return 'プロフィールを閉じる'
  //   }
  // }
}

The part where I commented out did work instead, so I could not figure out the difference.
Thank you!

Body:
Its not the same, in the previous approach you return an function. Try it like this:

buttonText() {
    return () => this.omitDescription ? 'プロフィールをもっと見る' : 'プロフィールを閉じる';
}


问:
extjs4 TypeError: store is undefined
I am a newbie for extjs4. I am reading the application architecture in the extjs offical website which offered a simple example(application_architecture). But I encountered some issues when studying this case.

The app sturcture in eclipse is like above. The question I met is regarding the store.

app\controller\Users.js
please look at the comment in this piece of code.

```<code>Ext.define('AM.controller.Users', {
    extend: 'Ext.app.Controller',
    stores: [
        'AM.store.Users'  //this line of code can't work, unless I update it to `Users`
                          //or it will report the exception 'TypeError: store is undefined'
    ],
    models: [
        'AM.model.User'
    ],
</code>```

Now I pasted the code of the other files related to this issue.

app\store\Users.js

```<code>Ext.define('AM.store.Users', {
    extend: 'Ext.data.Store',
    model: 'AM.model.User',
    autoLoad: true,

    proxy: {
        type: 'ajax',
        api: {
            read: 'data/users.json',
            update: 'data/updateUsers.json'
        },
        reader: {
            type: 'json',
            root: 'users',
            successProperty: 'success'
        }
    }
});
</code>```

I have searched for the exception in google, but got nothing helpful, and I have debugged it in firefox, still nothing, maybe because I am an expert in javascript.
I also checked the source code of other extjs apps in the company I worked, I found the controller can refer to the store like 'AM.store.Users'

Thanks in advance!

答: app.js shouldn't be modified with significant logic as it will be rewritten on every framework update</p>

Title: extjs4 TypeError: store is undefined

Body:
I am a newbie for extjs4. I am reading the application architecture in the extjs offical website which offered a simple example(application_architecture). But I encountered some issues when studying this case.

The app sturcture in eclipse is like above. The question I met is regarding the store.

app\controller\Users.js
please look at the comment in this piece of code.

Ext.define('AM.controller.Users', {
    extend: 'Ext.app.Controller',
    stores: [
        'AM.store.Users'  //this line of code can't work, unless I update it to `Users`
                          //or it will report the exception 'TypeError: store is undefined'
    ],
    models: [
        'AM.model.User'
    ],

Now I pasted the code of the other files related to this issue.

app\store\Users.js

Ext.define('AM.store.Users', {
    extend: 'Ext.data.Store',
    model: 'AM.model.User',
    autoLoad: true,

    proxy: {
        type: 'ajax',
        api: {
            read: 'data/users.json',
            update: 'data/updateUsers.json'
        },
        reader: {
            type: 'json',
            root: 'users',
            successProperty: 'success'
        }
    }
});

I have searched for the exception in google, but got nothing helpful, and I have debugged it in firefox, still nothing, maybe because I am an expert in javascript.
I also checked the source code of other extjs apps in the company I worked, I found the controller can refer to the store like 'AM.store.Users'

Thanks in advance!


问:
restructure elasticsearch index to allow filtering on sum of values
I've an index of products.

Each product, has several variants (can be a few or hundreds, each has a color & size e.g. Red)

Each variant, is available (in a certain quantity) at several warehouses (aronud 100 warehouses).

Warehouses have codes e.g. AB, XY, CD etc.

If I had my choice, I'd index it as:

```<code>stock: {
  Red: {
    S: { AB: 100, XY: 200, CD: 20 },
    M: { AB: 0, XY: 500, CD: 20 },
    2XL: { AB: 5, XY: 0, CD: 9 }
  },
  Blue: {
    ...
  }
}
</code>```

Here's a kind of customer query I might receive:

Show me all products, that have Red.S color in stock (minimum 100) at warehouses AB & XY.

So this would probably be a filter like

```<code>Red.S.AB > 100 AND Red.S.XY > 100
</code>```

I'm not writing whole filter query here, but its straightforward in elastic.

We might also get SUM queries, e.g. the sum of inventories at AB & XY should be > 500.

That'd be easy through a script filter, say Red.S.AB + Red.S.XY > 500

The problem is, given 100 warehouses, 100 sizes, 25 colors, this easily needs 100*100*25 = 250k mappings. Elasticsearch simply can't handle that many number of keys.

The easy answer is use nested documents, but nested documents pose a particular problem. We cannot sum across a given selection of nested documents, and nested docs are slow, specially when we're going to have 250k per product.

I'm open to external solutions than elastic as well. We're rails/postgres stack.

答:
You have your product index with variants, that's fine, but I'd use another index for managing anything related to the multi-warehouse stock. One document per product/size/color/warehouse with the related count. For instance:

```<code>{
  "product": 123,
  "color": "Red",
  "size": "S",
  "warehouse": "AB",
  "quantity": 100
}

{
  "product": 123,
  "color": "Red",
  "size": "S",
  "warehouse": "XY",
  "quantity": 200
}

{
  "product": 123,
  "color": "Red",
  "size": "S",
  "warehouse": "CD",
  "quantity": 20
}
etc...
</code>```

That way, you'll be much more flexible with your stock queries, because all you'll need is to filter on the fields (product, color, size, warehouse) and simply aggregate on the quantity field, sums, averages or whatever you might think of.

You will probably need to leverage the bucket_script pipeline aggregation in order to decide whether sums are above or below a desired threshold.

It's also much easier to maintain the stock movements by simply indexing the new quantity for any given combination than having to update the master product document every time an item gets out of the stock.

No script, no nested documents required.

Body:
I've an index of products.

Each product, has several variants (can be a few or hundreds, each has a color & size e.g. Red)

Each variant, is available (in a certain quantity) at several warehouses (aronud 100 warehouses).

Warehouses have codes e.g. AB, XY, CD etc.

If I had my choice, I'd index it as:

stock: {
  Red: {
    S: { AB: 100, XY: 200, CD: 20 },
    M: { AB: 0, XY: 500, CD: 20 },
    2XL: { AB: 5, XY: 0, CD: 9 }
  },
  Blue: {
    ...
  }
}

Here's a kind of customer query I might receive:

Show me all products, that have Red.S color in stock (minimum 100) at warehouses AB & XY.

So this would probably be a filter like

Red.S.AB > 100 AND Red.S.XY > 100

I'm not writing whole filter query here, but its straightforward in elastic.

We might also get SUM queries, e.g. the sum of inventories at AB & XY should be > 500.

That'd be easy through a script filter, say Red.S.AB + Red.S.XY > 500

The problem is, given 100 warehouses, 100 sizes, 25 colors, this easily needs 100*100*25 = 250k mappings. Elasticsearch simply can't handle that many number of keys.

The easy answer is use nested documents, but nested documents pose a particular problem. We cannot sum across a given selection of nested documents, and nested docs are slow, specially when we're going to have 250k per product.

I'm open to external solutions than elastic as well. We're rails/postgres stack.

Body:
You have your product index with variants, that's fine, but I'd use another index for managing anything related to the multi-warehouse stock. One document per product/size/color/warehouse with the related count. For instance:

{
  "product": 123,
  "color": "Red",
  "size": "S",
  "warehouse": "AB",
  "quantity": 100
}

{
  "product": 123,
  "color": "Red",
  "size": "S",
  "warehouse": "XY",
  "quantity": 200
}

{
  "product": 123,
  "color": "Red",
  "size": "S",
  "warehouse": "CD",
  "quantity": 20
}
etc...

That way, you'll be much more flexible with your stock queries, because all you'll need is to filter on the fields (product, color, size, warehouse) and simply aggregate on the quantity field, sums, averages or whatever you might think of.

You will probably need to leverage the bucket_script pipeline aggregation in order to decide whether sums are above or below a desired threshold.

It's also much easier to maintain the stock movements by simply indexing the new quantity for any given combination than having to update the master product document every time an item gets out of the stock.

No script, no nested documents required.


问:
org.openqa.selenium.WebDriverException: Unable to parse remote response: <!DOCTYPE html>
I created a Selenium standalone Firefox docker container and started the session in Host port:4545
docker run -d -p 4545:4444 --shm-size 2g selenium/standalone-firefox:3.141.59
I checked with http://localhost:4545/ if opening or not. It worked fine.

When I am trying to connect through my Selenium code, it is throwing me error as:

My sample code as below:

Please suggest how I can resolve this issue?

答: Change the RemoteWebDriver url from http://localhost:4545/wb/hub to http://localhost:4545/wd/hub</p>


问:
Enable “Do Not Allow Windows Messenger to be run” group policy using power shell script
I want to perform following tasks on Windows 2008 r2 machine -

1) Enable “Do Not Allow Windows Messenger to be run”.
2) Enable “Do Not Automatically Start Windows Messenger Initially”.

To do this, group policy exists on the following path "Open gpedit.msc >Expand Computer configuration > Administrative Templates > Windows components > Windows Messenger"

Need to do this using PowerShell script. How to do it?

答:
In reality, you can easily control this via the regedit in either:

```<code>HKCU\Software\Policies\Microsoft\Windows\
</code>```

or

```<code>HKLM\Software\Policies\Microsoft\Windows\
</code>```

This would work, AFAIK:

```<code>Set-GPRegistryValue -Name "WindowsMessenger" -Key "PathToYourTheKeyYoudNeed" -ValueName "xxx" -Type String -Value "YourValue"
</code>```

This also works with

```<code>-type DWORD
</code>```

Now, I sadly can not really check, where the necessary keys are located, that you would need to control because I do not have any 2008r2 in my company environment.

Hope I could help!

Body:
In reality, you can easily control this via the regedit in either:

HKCU\Software\Policies\Microsoft\Windows\

or

HKLM\Software\Policies\Microsoft\Windows\

This would work, AFAIK:

Set-GPRegistryValue -Name "WindowsMessenger" -Key "PathToYourTheKeyYoudNeed" -ValueName "xxx" -Type String -Value "YourValue"

This also works with

-type DWORD

Now, I sadly can not really check, where the necessary keys are located, that you would need to control because I do not have any 2008r2 in my company environment.

Hope I could help!


问:
Resize image in Laravel 5.2
Can anyone help me how to implement resizing image in Laravel?

I have this code only:

```<code>if($request->hasFile('image')){
    if (Input::file('image')->isValid()) {
        $file = Input::file('image');
        $destination = base_path() . '/public/images/ServiceImages';
        $extension = Input::file('image')->getClientOriginalExtension();
        $fileName = rand(111,99999).'.'.$extension;

        if(!empty($data['Image'])){
            unlink($destination.$data['Image']);
        }

        $file->move($destination, $fileName);
        $service->image=$fileName;
    }
}
</code>```

答:
I would recommend Intervention Image for this task.

Simply install it with composer

```<code>composer require intervention/image
</code>```

and just use it like this:

```<code>\Intervention\Image\ImageManagerStatic::make('public/foo')->fit(100)->save($path);
</code>```

Remarks

Service Provider
The intervention image provides a Service Provider for Laravel. You may add the service provider manually as explained here. After that, you may push the configuration file to Laravel. However, the configuration has only one option and that is the image driver. gd is default , so if you don't want to change it, there is no need to use the service provider and configuration.

Alias Instead of the service Provider, you could create an alias in config/app:

```<code>'Image' => Intervention\Image\ImageManagerStatic::class
</code>```

Then you can use it like this:

```<code>\Image::make('public/foo')->fit(100)->save($path);
</code>```

Testing You can still Laravel's file upload tests when using intervention image. For details, see How to fake image upload for testing with Intervention image package using Laravel

Title: Resize image in Laravel 5.2

Body:
Can anyone help me how to implement resizing image in Laravel?

I have this code only:

if($request->hasFile('image')){
    if (Input::file('image')->isValid()) {
        $file = Input::file('image');
        $destination = base_path() . '/public/images/ServiceImages';
        $extension = Input::file('image')->getClientOriginalExtension();
        $fileName = rand(111,99999).'.'.$extension;

        if(!empty($data['Image'])){
            unlink($destination.$data['Image']);
        }

        $file->move($destination, $fileName);
        $service->image=$fileName;
    }
}

Body:
I would recommend Intervention Image for this task.

Simply install it with composer

composer require intervention/image

and just use it like this:

\Intervention\Image\ImageManagerStatic::make('public/foo')->fit(100)->save($path);

Remarks

Service Provider
The intervention image provides a Service Provider for Laravel. You may add the service provider manually as explained here. After that, you may push the configuration file to Laravel. However, the configuration has only one option and that is the image driver. gd is default , so if you don't want to change it, there is no need to use the service provider and configuration.

Alias Instead of the service Provider, you could create an alias in config/app:

'Image' => Intervention\Image\ImageManagerStatic::class

Then you can use it like this:

\Image::make('public/foo')->fit(100)->save($path);

Testing You can still Laravel's file upload tests when using intervention image. For details, see How to fake image upload for testing with Intervention image package using Laravel


问:
OpenGL ES Load saved image back into renderbuffer
I did some testing on GLPaint and managed to save the image. But now, my problem for is I have no idea how to load the saved image back to render buffer so I can continue editing. Would be glad if someone can show the code and the idea behind, I am very new to OpenGL ES.</p>

答: If you say, that you saved the image, then to load it back and display you have to create a texture object and map it to some polygons. Check this tutorial.</p>


问:
Mean average precision metrics for evaluation multilabel object detection model
My goal is to evaluate model performance on test dataset for object detection task. Model was trained on dataset with 6 classes with Tensorflow Object Detection API. For some class there are 20 samples of objects and for some it can be only one sample. So data is imbalanced for both train and test sets.
Can I use mean average precision (mAP) as metrics for evaluation?
It seems to me that it is not correct to use it for imbalanced data. Therefore I don't know which other metrics to use. So what kind of metrics is suitable for this case?

I would appreciate any help on this.

答: Mean average precision will still work. As you can see, it is mean average precision, so, since precision will be averaged over all classes their number won't matter.</p>


问:
VBA Script to choose the value from a Drop Down list automatically
I have an Excel Workbook with the 2 sheets.

Sheet 1 contains an Email template and sheet 2 contains the raw data.

Sheet 2 contains the headers as mentioned below.
Name    ERP Employee Date   Email   Start Date  Is Anniversary(Yes/No)  Years Completed

In Sheet 1, I have created a drop-down list where the list will contain the names of the Employees who have the Is Anniversary field (yes)

I have written a VBA script to send an Email to the person who is selected in the drop-down list.

I would like to make it fully automated where the script should be able to select the next value automatically and then send the Email to the person and likewise for the whole list. Please suggest if there is a possibility.

Script for sending the Email

```<code>Sub Send_Anniversary_Email()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Mailer")

Dim lr As Integer
lr = sh.Range("J" & Application.Rows.Count).End(xlUp).Row

sh.Range("E5:L" & lr).Select
With Selection.Parent.MailEnvelope.Item

    .to = sh.Range("B12").Value
    .cc = sh.Range("B13").Value
    .Subject = sh.Range("B14").Value
    .send

    ActiveWorkbook.Save
End With

MsgBox "Done"

End Sub
</code>```

答:
I have tried to create the same coding but once i try to send an email to a second person, i get the "Mailenvelope of object_worksheet failed" from this "With Selection.Parent.MailEnvelope.Item" code.
What am i supposed to do here?</p>

Body:
I have an Excel Workbook with the 2 sheets.

Sheet 1 contains an Email template and sheet 2 contains the raw data.

Sheet 2 contains the headers as mentioned below.
Name    ERP Employee Date   Email   Start Date  Is Anniversary(Yes/No)  Years Completed

In Sheet 1, I have created a drop-down list where the list will contain the names of the Employees who have the Is Anniversary field (yes)

I have written a VBA script to send an Email to the person who is selected in the drop-down list.

I would like to make it fully automated where the script should be able to select the next value automatically and then send the Email to the person and likewise for the whole list. Please suggest if there is a possibility.

Script for sending the Email

Sub Send_Anniversary_Email()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Mailer")

Dim lr As Integer
lr = sh.Range("J" & Application.Rows.Count).End(xlUp).Row

sh.Range("E5:L" & lr).Select
With Selection.Parent.MailEnvelope.Item

    .to = sh.Range("B12").Value
    .cc = sh.Range("B13").Value
    .Subject = sh.Range("B14").Value
    .send

    ActiveWorkbook.Save
End With

MsgBox "Done"

End Sub


问:
data.table conditional join overwrites columns used for condition- R
I'm trying to conditionally join two data.tables df1 and df2, but i get a strange output that I cannot explain.

```<code>> df1 <- data.table(ID = 1, row_unique_identifier = 1:41, date_1 = as.Date(c(rep('2016-11-14',7), '2017-11-02', rep('2017-11-17',7), rep('2018-12-06', 20), rep('2018-12-07', 6))))
> df2=data.table(ID=1, Date_2A=as.Date(c('2016-11-14', '2018-12-06', '2017-11-17')), Date_2B = as.Date(c('2016-11-14', '2018-12-07', '2017-11-17')), Date_2B_EXTENDED = as.Date(c('2016-11-20', '2018-12-13', '2017-11-23')) )

> df2
   ID    Date_2A    Date_2B Date_2B_EXTENDED
1:  1 2016-11-14 2016-11-14       2016-11-20
2:  1 2018-12-06 2018-12-07       2018-12-13
3:  1 2017-11-17 2017-11-17       2017-11-23
</code>```

I want to conditionally join df1 with df2 so that:

all df1 rows should be returned (so it's a left join)

df1.ID= df2.ID(df1 and df2 are samples, in reality there are many IDs)

AND df1.date_1 is between df2.Date_2A  and df2.Date_2B_EXTENDED

I want my output to include all of df1 columns PLUS df2 columns with NAs for entries that couldn't be matched.

but when I do the join as follows, the output is strange. It seems that Date_1 overwrites the other three columns of df2 and some strange NA's as well that don't below there:

```<code>> df1[, c('Date_2A', 'Date_2B', 'Date_2B_EXTENDED') := df2[df1, on= .(ID
                                                                    , Date_2A <= date_1
                                                                    , Date_2B_EXTENDED >= date_1)
                                                               ,.(Date_2A, Date_2B, Date_2B_EXTENDED)
                                                               , mult = "last"]]
> df1
    ID row_unique_identifier     date_1    Date_2A    Date_2B Date_2B_EXTENDED
 1:  1                     1 2016-11-14 2016-11-14 2016-11-14       2016-11-14
 2:  1                     2 2016-11-14 2016-11-14 2016-11-14       2016-11-14
 3:  1                     3 2016-11-14 2016-11-14 2016-11-14       2016-11-14
 4:  1                     4 2016-11-14 2016-11-14 2016-11-14       2016-11-14
 5:  1                     5 2016-11-14 2016-11-14 2016-11-14       2016-11-14
 6:  1                     6 2016-11-14 2016-11-14 2016-11-14       2016-11-14
 7:  1                     7 2016-11-14 2016-11-14 2016-11-14       2016-11-14
 8:  1                     8 2017-11-02 2017-11-02       <NA>       2017-11-02
 9:  1                     9 2017-11-17 2017-11-17 2017-11-17       2017-11-17
10:  1                    10 2017-11-17 2017-11-17 2017-11-17       2017-11-17
11:  1                    11 2017-11-17 2017-11-17 2017-11-17       2017-11-17
12:  1                    12 2017-11-17 2017-11-17 2017-11-17       2017-11-17
13:  1                    13 2017-11-17 2017-11-17 2017-11-17       2017-11-17
14:  1                    14 2017-11-17 2017-11-17 2017-11-17       2017-11-17
15:  1                    15 2017-11-17 2017-11-17 2017-11-17       2017-11-17
16:  1                    16 2018-12-06 2018-12-06 2018-12-07       2018-12-06
17:  1                    17 2018-12-06 2018-12-06 2018-12-07       2018-12-06
18:  1                    18 2018-12-06 2018-12-06 2018-12-07       2018-12-06
19:  1                    19 2018-12-06 2018-12-06 2018-12-07       2018-12-06
20:  1                    20 2018-12-06 2018-12-06 2018-12-07       2018-12-06
21:  1                    21 2018-12-06 2018-12-06 2018-12-07       2018-12-06
22:  1                    22 2018-12-06 2018-12-06 2018-12-07       2018-12-06
23:  1                    23 2018-12-06 2018-12-06 2018-12-07       2018-12-06
24:  1                    24 2018-12-06 2018-12-06 2018-12-07       2018-12-06
25:  1                    25 2018-12-06 2018-12-06 2018-12-07       2018-12-06
26:  1                    26 2018-12-06 2018-12-06 2018-12-07       2018-12-06
27:  1                    27 2018-12-06 2018-12-06 2018-12-07       2018-12-06
28:  1                    28 2018-12-06 2018-12-06 2018-12-07       2018-12-06
29:  1                    29 2018-12-06 2018-12-06 2018-12-07       2018-12-06
30:  1                    30 2018-12-06 2018-12-06 2018-12-07       2018-12-06
31:  1                    31 2018-12-06 2018-12-06 2018-12-07       2018-12-06
32:  1                    32 2018-12-06 2018-12-06 2018-12-07       2018-12-06
33:  1                    33 2018-12-06 2018-12-06 2018-12-07       2018-12-06
34:  1                    34 2018-12-06 2018-12-06 2018-12-07       2018-12-06
35:  1                    35 2018-12-06 2018-12-06 2018-12-07       2018-12-06
36:  1                    36 2018-12-07 2018-12-07 2018-12-07       2018-12-07
37:  1                    37 2018-12-07 2018-12-07 2018-12-07       2018-12-07
38:  1                    38 2018-12-07 2018-12-07 2018-12-07       2018-12-07
39:  1                    39 2018-12-07 2018-12-07 2018-12-07       2018-12-07
40:  1                    40 2018-12-07 2018-12-07 2018-12-07       2018-12-07
41:  1                    41 2018-12-07 2018-12-07 2018-12-07       2018-12-07
</code>```

The way I understand the output is that somehow the comparison is successful but date_1 overwrites the two columns that it's being compared to: Date_2A and Date_2B_EXTENDED.
The NA entry in Date_2B makes sense --> there was no matching.... but date_1 still overwrote date_2A and date_2B_EXTENDED on that row. How do I prevent the overwriting?? I've never had this happened to me before. I'm clearly specifying to add new column names to df1 after matching, so what's going on?

EDITED:
I found a way around this issue by adding two extra columns: Date_2A_dummy and Date_2B_EXTENDED_dummy to df2 which are the same as Date_2A and Date_2B_EXTENDED respectively. Then changed my comparison statements to these two dummy variables and it works. But I'm still wondering if this is the best way?! To me it seems this issue that the two variables are getting over-written is a bug? I can't think of any use case for them to be overwritten.

Body:
I'm trying to conditionally join two data.tables df1 and df2, but i get a strange output that I cannot explain.

> df1 <- data.table(ID = 1, row_unique_identifier = 1:41, date_1 = as.Date(c(rep('2016-11-14',7), '2017-11-02', rep('2017-11-17',7), rep('2018-12-06', 20), rep('2018-12-07', 6))))
> df2=data.table(ID=1, Date_2A=as.Date(c('2016-11-14', '2018-12-06', '2017-11-17')), Date_2B = as.Date(c('2016-11-14', '2018-12-07', '2017-11-17')), Date_2B_EXTENDED = as.Date(c('2016-11-20', '2018-12-13', '2017-11-23')) )

> df2
   ID    Date_2A    Date_2B Date_2B_EXTENDED
1:  1 2016-11-14 2016-11-14       2016-11-20
2:  1 2018-12-06 2018-12-07       2018-12-13
3:  1 2017-11-17 2017-11-17       2017-11-23

I want to conditionally join df1 with df2 so that:

all df1 rows should be returned (so it's a left join)

df1.ID= df2.ID(df1 and df2 are samples, in reality there are many IDs)

AND df1.date_1 is between df2.Date_2A  and df2.Date_2B_EXTENDED

I want my output to include all of df1 columns PLUS df2 columns with NAs for entries that couldn't be matched.

but when I do the join as follows, the output is strange. It seems that Date_1 overwrites the other three columns of df2 and some strange NA's as well that don't below there:

> df1[, c('Date_2A', 'Date_2B', 'Date_2B_EXTENDED') := df2[df1, on= .(ID
                                                                    , Date_2A <= date_1
                                                                    , Date_2B_EXTENDED >= date_1)
                                                               ,.(Date_2A, Date_2B, Date_2B_EXTENDED)
                                                               , mult = "last"]]
> df1
    ID row_unique_identifier     date_1    Date_2A    Date_2B Date_2B_EXTENDED
 1:  1                     1 2016-11-14 2016-11-14 2016-11-14       2016-11-14
 2:  1                     2 2016-11-14 2016-11-14 2016-11-14       2016-11-14
 3:  1                     3 2016-11-14 2016-11-14 2016-11-14       2016-11-14
 4:  1                     4 2016-11-14 2016-11-14 2016-11-14       2016-11-14
 5:  1                     5 2016-11-14 2016-11-14 2016-11-14       2016-11-14
 6:  1                     6 2016-11-14 2016-11-14 2016-11-14       2016-11-14
 7:  1                     7 2016-11-14 2016-11-14 2016-11-14       2016-11-14
 8:  1                     8 2017-11-02 2017-11-02       <NA>       2017-11-02
 9:  1                     9 2017-11-17 2017-11-17 2017-11-17       2017-11-17
10:  1                    10 2017-11-17 2017-11-17 2017-11-17       2017-11-17
11:  1                    11 2017-11-17 2017-11-17 2017-11-17       2017-11-17
12:  1                    12 2017-11-17 2017-11-17 2017-11-17       2017-11-17
13:  1                    13 2017-11-17 2017-11-17 2017-11-17       2017-11-17
14:  1                    14 2017-11-17 2017-11-17 2017-11-17       2017-11-17
15:  1                    15 2017-11-17 2017-11-17 2017-11-17       2017-11-17
16:  1                    16 2018-12-06 2018-12-06 2018-12-07       2018-12-06
17:  1                    17 2018-12-06 2018-12-06 2018-12-07       2018-12-06
18:  1                    18 2018-12-06 2018-12-06 2018-12-07       2018-12-06
19:  1                    19 2018-12-06 2018-12-06 2018-12-07       2018-12-06
20:  1                    20 2018-12-06 2018-12-06 2018-12-07       2018-12-06
21:  1                    21 2018-12-06 2018-12-06 2018-12-07       2018-12-06
22:  1                    22 2018-12-06 2018-12-06 2018-12-07       2018-12-06
23:  1                    23 2018-12-06 2018-12-06 2018-12-07       2018-12-06
24:  1                    24 2018-12-06 2018-12-06 2018-12-07       2018-12-06
25:  1                    25 2018-12-06 2018-12-06 2018-12-07       2018-12-06
26:  1                    26 2018-12-06 2018-12-06 2018-12-07       2018-12-06
27:  1                    27 2018-12-06 2018-12-06 2018-12-07       2018-12-06
28:  1                    28 2018-12-06 2018-12-06 2018-12-07       2018-12-06
29:  1                    29 2018-12-06 2018-12-06 2018-12-07       2018-12-06
30:  1                    30 2018-12-06 2018-12-06 2018-12-07       2018-12-06
31:  1                    31 2018-12-06 2018-12-06 2018-12-07       2018-12-06
32:  1                    32 2018-12-06 2018-12-06 2018-12-07       2018-12-06
33:  1                    33 2018-12-06 2018-12-06 2018-12-07       2018-12-06
34:  1                    34 2018-12-06 2018-12-06 2018-12-07       2018-12-06
35:  1                    35 2018-12-06 2018-12-06 2018-12-07       2018-12-06
36:  1                    36 2018-12-07 2018-12-07 2018-12-07       2018-12-07
37:  1                    37 2018-12-07 2018-12-07 2018-12-07       2018-12-07
38:  1                    38 2018-12-07 2018-12-07 2018-12-07       2018-12-07
39:  1                    39 2018-12-07 2018-12-07 2018-12-07       2018-12-07
40:  1                    40 2018-12-07 2018-12-07 2018-12-07       2018-12-07
41:  1                    41 2018-12-07 2018-12-07 2018-12-07       2018-12-07

The way I understand the output is that somehow the comparison is successful but date_1 overwrites the two columns that it's being compared to: Date_2A and Date_2B_EXTENDED.
The NA entry in Date_2B makes sense --> there was no matching.... but date_1 still overwrote date_2A and date_2B_EXTENDED on that row. How do I prevent the overwriting?? I've never had this happened to me before. I'm clearly specifying to add new column names to df1 after matching, so what's going on?

EDITED:
I found a way around this issue by adding two extra columns: Date_2A_dummy and Date_2B_EXTENDED_dummy to df2 which are the same as Date_2A and Date_2B_EXTENDED respectively. Then changed my comparison statements to these two dummy variables and it works. But I'm still wondering if this is the best way?! To me it seems this issue that the two variables are getting over-written is a bug? I can't think of any use case for them to be overwritten.

Body:
I think this is what you need...

df1[ df2,
     `:=`( Date_2A = i.Date_2A, Date_2B = i.Date_2B, Date_2B_EXTENDED = i.Date_2B_EXTENDED ),
     on = .( ID, date_1 >= Date_2A, date_1 <= Date_2B_EXTENDED ) ][]

output

#     ID row_unique_identifier     date_1    Date_2A    Date_2B Date_2B_EXTENDED
#  1:  1                     1 2016-11-14 2016-11-14 2016-11-14       2016-11-20
#  2:  1                     2 2016-11-14 2016-11-14 2016-11-14       2016-11-20
#  3:  1                     3 2016-11-14 2016-11-14 2016-11-14       2016-11-20
#  4:  1                     4 2016-11-14 2016-11-14 2016-11-14       2016-11-20
#  5:  1                     5 2016-11-14 2016-11-14 2016-11-14       2016-11-20
#  6:  1                     6 2016-11-14 2016-11-14 2016-11-14       2016-11-20
#  7:  1                     7 2016-11-14 2016-11-14 2016-11-14       2016-11-20
#  8:  1                     8 2017-11-02       <NA>       <NA>             <NA>
#  9:  1                     9 2017-11-17 2017-11-17 2017-11-17       2017-11-23
# 10:  1                    10 2017-11-17 2017-11-17 2017-11-17       2017-11-23
# 11:  1                    11 2017-11-17 2017-11-17 2017-11-17       2017-11-23
# 12:  1                    12 2017-11-17 2017-11-17 2017-11-17       2017-11-23
# 13:  1                    13 2017-11-17 2017-11-17 2017-11-17       2017-11-23
# 14:  1                    14 2017-11-17 2017-11-17 2017-11-17       2017-11-23
# 15:  1                    15 2017-11-17 2017-11-17 2017-11-17       2017-11-23
# 16:  1                    16 2018-12-06 2018-12-06 2018-12-07       2018-12-13
# 17:  1                    17 2018-12-06 2018-12-06 2018-12-07       2018-12-13
# 18:  1                    18 2018-12-06 2018-12-06 2018-12-07       2018-12-13
# 19:  1                    19 2018-12-06 2018-12-06 2018-12-07       2018-12-13
# 20:  1                    20 2018-12-06 2018-12-06 2018-12-07       2018-12-13
# 21:  1                    21 2018-12-06 2018-12-06 2018-12-07       2018-12-13
# 22:  1                    22 2018-12-06 2018-12-06 2018-12-07       2018-12-13
# 23:  1                    23 2018-12-06 2018-12-06 2018-12-07       2018-12-13
# 24:  1                    24 2018-12-06 2018-12-06 2018-12-07       2018-12-13
# 25:  1                    25 2018-12-06 2018-12-06 2018-12-07       2018-12-13
# 26:  1                    26 2018-12-06 2018-12-06 2018-12-07       2018-12-13
# 27:  1                    27 2018-12-06 2018-12-06 2018-12-07       2018-12-13
# 28:  1                    28 2018-12-06 2018-12-06 2018-12-07       2018-12-13
# 29:  1                    29 2018-12-06 2018-12-06 2018-12-07       2018-12-13
# 30:  1                    30 2018-12-06 2018-12-06 2018-12-07       2018-12-13
# 31:  1                    31 2018-12-06 2018-12-06 2018-12-07       2018-12-13
# 32:  1                    32 2018-12-06 2018-12-06 2018-12-07       2018-12-13
# 33:  1                    33 2018-12-06 2018-12-06 2018-12-07       2018-12-13
# 34:  1                    34 2018-12-06 2018-12-06 2018-12-07       2018-12-13
# 35:  1                    35 2018-12-06 2018-12-06 2018-12-07       2018-12-13
# 36:  1                    36 2018-12-07 2018-12-06 2018-12-07       2018-12-13
# 37:  1                    37 2018-12-07 2018-12-06 2018-12-07       2018-12-13
# 38:  1                    38 2018-12-07 2018-12-06 2018-12-07       2018-12-13
# 39:  1                    39 2018-12-07 2018-12-06 2018-12-07       2018-12-13
# 40:  1                    40 2018-12-07 2018-12-06 2018-12-07       2018-12-13
# 41:  1                    41 2018-12-07 2018-12-06 2018-12-07       2018-12-13
#     ID row_unique_identifier     date_1    Date_2A    Date_2B Date_2B_EXTENDED


问:
how to extract tables from pdf using camelot?
I want to extract all tables from pdf using camelot in python 3.

```<code>import camelot
# PDF file to extract tables from
file = "./pdf_file/ooo.pdf"
tables = camelot.read_pdf(file)
# number of tables extracted
print("Total tables extracted:", tables.n)
# print the first table as Pandas DataFrame
print(tables[0].df)
# export individually
tables[0].to_csv("./pdf_file/ooo.csv")
</code>```

and then I get only 1 table from the 1st page of the pdf.
how extract the whole tables from the pdf file??

答:
```<code>tables = camelot.read_pdf(file, pages='1-end')
</code>```

If pages parameter is not specified, Camelot analyzes only the first page.
For better explanation, see official documentation.

Body:
I want to extract all tables from pdf using camelot in python 3.

import camelot
# PDF file to extract tables from
file = "./pdf_file/ooo.pdf"
tables = camelot.read_pdf(file)
# number of tables extracted
print("Total tables extracted:", tables.n)
# print the first table as Pandas DataFrame
print(tables[0].df)
# export individually
tables[0].to_csv("./pdf_file/ooo.csv")

and then I get only 1 table from the 1st page of the pdf.
how extract the whole tables from the pdf file??

Body:
tables = camelot.read_pdf(file, pages='1-end')

If pages parameter is not specified, Camelot analyzes only the first page.
For better explanation, see official documentation.


问:
Which is better way to pass data to event handler: by function closure or custom data-attribute
I have a question about passing data to event handlers.
Isn't it better to attach a custom data attribute to a component and get it from the received event object in the handler, instead of creating new functions on each render to closure the data.
What are the drawbacks of this method? Because I couldn't find any information in the official docs.</p>

```<code>const Ids = [0, 1];

const Comp = (props) => {
    const onClick = useCallback((e) => {
        console.log(e.target.dataset.index);
    }, []);

    return (
        Ids.map(id => (
            <div data-id={id} onClick={onClick} />
        ))
    );
};
</code>```

答:
While making use of data- attributes is generally accepted in vanilla JavaScript/HTML development, the React way of doing things would be to pass the required data as part of your event handler method's parameters.

This is actually stated on the react documentation itself:

No. We don’t encourage you to keep data in DOM attributes. Even if you
  have to, data- attributes are probably a better approach, but in most
  cases data should be kept in React component state or external stores.

Therefore, while react does not explicitly restrict you from doing so, the recommended practice would be to avoid using data- attributes unless
necessary.

Building onto your example, this is how it should be done:

```<code>return (
    Ids.map(id => (
        <div data-id={id} onClick={() => onClick(id)} />
    ))
);
</code>```

Body:
I have a question about passing data to event handlers.
Isn't it better to attach a custom data attribute to a component and get it from the received event object in the handler, instead of creating new functions on each render to closure the data.
What are the drawbacks of this method? Because I couldn't find any information in the official docs.

const Ids = [0, 1];

const Comp = (props) => {
    const onClick = useCallback((e) => {
        console.log(e.target.dataset.index);
    }, []);

    return (
        Ids.map(id => (

        ))
    );
};

Body:
While making use of data- attributes is generally accepted in vanilla JavaScript/HTML development, the React way of doing things would be to pass the required data as part of your event handler method's parameters.

This is actually stated on the react documentation itself:

No. We don’t encourage you to keep data in DOM attributes. Even if you
  have to, data- attributes are probably a better approach, but in most
  cases data should be kept in React component state or external stores.

Therefore, while react does not explicitly restrict you from doing so, the recommended practice would be to avoid using data- attributes unless
necessary.

Building onto your example, this is how it should be done:

return (
    Ids.map(id => (
        <div data-id={id} onClick={() => onClick(id)} />
    ))
);


答:
It would be more helpful to know if you are using an IDE like Eclipse or IntelliJ, as these can automatically create executable jar files from your run configurations.
They take care of automatically creating the files that tell your system where to find the main method to execute.</p>

Title: Super basic question: How does one make an executable program out of java code?

Body:
I have only been coding for a few days and I have one question that i just can't seem to find any information on. I was wondering what I would have to do to create an executable application out of my java code. I know that I can run my compiled code from the terminal by typing java helloworld for example when I'm in the right directory, but then I always have to navigate to the file manually and run it. I was hoping there would be a way to create a file that I could just click on and that would automatically run the program in the computer's terminal.

Any explanation would be much appreciated! I'm currently working on MacOS if it makes a difference.
Thanks in advance.

edit: I'm using visual studio code to write my code

edit 2: I now understand that what I'm trying to accomplish is essentially to create a .jar file out of my .class file. Does anyone happen to know if there is a built in function in visual studio code to create a .Jar file? Some people are suggesting maven but I'm hesitant to download anything if im not sure it's necessary.


问:
Tkinter show and hide window and resume execution without destroying in python?
I have a python script which creates a GUI Window using Tkinter. After creation of the window and reading input I expect the execution to proceed to the while loop, but the execution never resumes as the window isn't destroyed. I want it to resume after the input is read. But here after displaying "You entered xxxx" the screen freezes and execution never gets back to the former while loop. How do I fix this? I don't want to create the window everytime

```<code>from PIL import ImageGrab, Image
from glob import glob
from io import BytesIO
import time
import tkinter as tk

window = None
entry = None
window_created = False
x = None
name_of_file = None
input_wait = False

def handle_click(event):
    global name_of_file
    name_of_file = entry.get()
    print("You Entered " + name_of_file)
    entry.delete(0, tk.END)
    hide_window(window)

def show_window(window):
    window.update()
    window.deiconify()

def hide_window(window):
    window.update()
    window.withdraw()

def create_window():
    global window
    global entry
    window = tk.Tk()
    window.geometry("600x600")
    window.title("Name for your image")
    label = tk.Label(text="What do you want to name the image?")
    entry = tk.Entry()
    button = tk.Button(text="Create")
    button.bind("<Button-1>", handle_click)
    window.bind("<Return>", handle_click)
    label.pack()
    entry.pack()
    button.pack()
    window.mainloop()

while True:
    print("Looping")
    image_list = map(Image.open, glob('*.png'))
    presentItem = ImageGrab.grabclipboard()
    if presentItem is not None:
        with BytesIO() as f:
            presentItem.save(f, format='PNG')
            x = Image.open(f)
            if x not in image_list:
                print("New item found")
                if not window_created:
                    create_window()
                    window_created = True
                    print("Resumes")
                else:
                    show_window(window)
                    print("Resumes")
                presentItem.save(name_of_file + '.png', 'PNG')
    else:
        print("No item in clipboard")
    time.sleep(0.1)
</code>```

答:
You can hide a tkinter window with window.wm_attributes("-alpha", 0) and show with window.wm_attributes("-alpha", 0.99). This code adds an alpha value. There is a code which shows that better:

```<code>import time
from tkinter import *

tk = Tk()

def more_alpha():
    global alpha
    alpha += 0.05
    if alpha >= 1:
        alpha = 0.99
    update()

def less_alpha():
    global alpha
    alpha -= 0.05
    if alpha <= 0:
        alpha = 0.01
    update()

def update():
    global alpha
    tk.wm_attributes("-alpha", alpha)

alpha = 0.5
update()

Button(tk, text="More visibility", command=more_alpha).grid(padx=25, pady=5)
Button(tk, text="Less visibility", command=less_alpha).grid(padx=25, pady=5)

tk.mainloop()
</code>```

The window is always active, but not when the alpha value is set to 0.

Body:
I have a python script which creates a GUI Window using Tkinter. After creation of the window and reading input I expect the execution to proceed to the while loop, but the execution never resumes as the window isn't destroyed. I want it to resume after the input is read. But here after displaying "You entered xxxx" the screen freezes and execution never gets back to the former while loop. How do I fix this? I don't want to create the window everytime

from PIL import ImageGrab, Image
from glob import glob
from io import BytesIO
import time
import tkinter as tk

window = None
entry = None
window_created = False
x = None
name_of_file = None
input_wait = False

def handle_click(event):
    global name_of_file
    name_of_file = entry.get()
    print("You Entered " + name_of_file)
    entry.delete(0, tk.END)
    hide_window(window)

def show_window(window):
    window.update()
    window.deiconify()

def hide_window(window):
    window.update()
    window.withdraw()

def create_window():
    global window
    global entry
    window = tk.Tk()
    window.geometry("600x600")
    window.title("Name for your image")
    label = tk.Label(text="What do you want to name the image?")
    entry = tk.Entry()
    button = tk.Button(text="Create")
    button.bind("<Button-1>", handle_click)
    window.bind("<Return>", handle_click)
    label.pack()
    entry.pack()
    button.pack()
    window.mainloop()

while True:
    print("Looping")
    image_list = map(Image.open, glob('*.png'))
    presentItem = ImageGrab.grabclipboard()
    if presentItem is not None:
        with BytesIO() as f:
            presentItem.save(f, format='PNG')
            x = Image.open(f)
            if x not in image_list:
                print("New item found")
                if not window_created:
                    create_window()
                    window_created = True
                    print("Resumes")
                else:
                    show_window(window)
                    print("Resumes")
                presentItem.save(name_of_file + '.png', 'PNG')
    else:
        print("No item in clipboard")
    time.sleep(0.1)

Body:
You can hide a tkinter window with window.wm_attributes("-alpha", 0) and show with window.wm_attributes("-alpha", 0.99). This code adds an alpha value. There is a code which shows that better:

import time
from tkinter import *

tk = Tk()

def more_alpha():
    global alpha
    alpha += 0.05
    if alpha >= 1:
        alpha = 0.99
    update()

def less_alpha():
    global alpha
    alpha -= 0.05
    if alpha <= 0:
        alpha = 0.01
    update()

def update():
    global alpha
    tk.wm_attributes("-alpha", alpha)

alpha = 0.5
update()

Button(tk, text="More visibility", command=more_alpha).grid(padx=25, pady=5)
Button(tk, text="Less visibility", command=less_alpha).grid(padx=25, pady=5)

tk.mainloop()

The window is always active, but not when the alpha value is set to 0.


问:
Jwt spring security antmatchers
Spring security config

```<code>@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UsersDetailsService usersDetailsService;
    @Autowired
    private JwtFilter jwtFilter;

    public SecurityConfig(UsersDetailsService usersDetailsService) {
        this.usersDetailsService = usersDetailsService;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(daoAuthenticationProvider());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().cors().and().authorizeRequests()
                .antMatchers("/api/authenticate").anonymous()
                .antMatchers("/api/generateTPAC").anonymous()
                .antMatchers("/api/register").anonymous()
                .antMatchers("/api/generate2FAcode").anonymous()
                .antMatchers("/api/verify-email**").anonymous()
                .antMatchers("/api/retrieveUserInfo").permitAll()
                .antMatchers("/api/validateToken").permitAll()
                .antMatchers("/api/update**").permitAll()
                .antMatchers("/api/uploadImage").permitAll()
                .antMatchers("/api/image").permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(usersDetailsService);
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        return daoAuthenticationProvider;
    }

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

}
</code>```

Hello i have trouble setting antMatchers authorization.. It is not working as it should. Only what works is permitAll and denyAll, anonymous,hasRole,authenticated are not working.. I tried use .access(hasRole()) but this aint working at all tho..

答:
Since you are using UserDetailsService which returns an instance of the interface org.springframework.security.core.userdetails.UserDetails which uses Authorities .

So you control access like this

```<code>.antMatchers("/api/authenticate").hasAuthority("ROLE_ANONYMOUS")
</code>```

or

```<code>.antMatchers("/api/authenticate").hasAuthority("ROLE_ADMIN")
</code>```

Please verify your bean of UserDetailsService also . It should have loadUserByUsername function which returns instance of org.springframework.security.core.userdetails.UserDetails . Check the authorities in this object.

Title: Jwt spring security antmatchers

Body:
Spring security config

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UsersDetailsService usersDetailsService;
    @Autowired
    private JwtFilter jwtFilter;

    public SecurityConfig(UsersDetailsService usersDetailsService) {
        this.usersDetailsService = usersDetailsService;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(daoAuthenticationProvider());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().cors().and().authorizeRequests()
                .antMatchers("/api/authenticate").anonymous()
                .antMatchers("/api/generateTPAC").anonymous()
                .antMatchers("/api/register").anonymous()
                .antMatchers("/api/generate2FAcode").anonymous()
                .antMatchers("/api/verify-email**").anonymous()
                .antMatchers("/api/retrieveUserInfo").permitAll()
                .antMatchers("/api/validateToken").permitAll()
                .antMatchers("/api/update**").permitAll()
                .antMatchers("/api/uploadImage").permitAll()
                .antMatchers("/api/image").permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(usersDetailsService);
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        return daoAuthenticationProvider;
    }

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

}

Hello i have trouble setting antMatchers authorization.. It is not working as it should. Only what works is permitAll and denyAll, anonymous,hasRole,authenticated are not working.. I tried use .access(hasRole()) but this aint working at all tho..

Body:
Since you are using UserDetailsService which returns an instance of the interface org.springframework.security.core.userdetails.UserDetails which uses Authorities .

So you control access like this

.antMatchers("/api/authenticate").hasAuthority("ROLE_ANONYMOUS")

or

.antMatchers("/api/authenticate").hasAuthority("ROLE_ADMIN")

Please verify your bean of UserDetailsService also . It should have loadUserByUsername function which returns instance of org.springframework.security.core.userdetails.UserDetails . Check the authorities in this object.


问:
Flutter web: how to programmatically close app (browser tab)
I am creating a Flutter web app. When one of buttons is pressed I want to close browser tab when app is running. How to do that?</p>

答:
Just like in JavaScript, you can close the window like so:

```<code>window.close();
</code>```

Here's the documentation.

Body:
Just like in JavaScript, you can close the window like so:

window.close();

Here's the documentation.


问:
Flutter Multiline for text
All I need is my text to be multi-line. Am giving the property of maxLines but its still getting RenderFlex overflowed error to the right as the next is not going to 2nd line,

```<code>      Align( alignment: Alignment.bottomCenter,
      child: new ButtonBar(
        alignment: MainAxisAlignment.center,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.all(20.0),
            child: new Text(
              "This is a very bigggggggg text !!!",textDirection: TextDirection.ltr,
              style: new TextStyle(fontSize: 20.0, color: Colors.white),
              maxLines: 2,
            ),
          )
        ],
      ),
    )
</code>```

答:
You can use this trick.
Text( ''' This is very big text''' ),
Just wrap a text around three single quotes and flutter will format a text as per its length . No need to use max lines and text field.

Title: Flutter Multiline for text

Body:
All I need is my text to be multi-line. Am giving the property of maxLines but its still getting RenderFlex overflowed error to the right as the next is not going to 2nd line,

      Align( alignment: Alignment.bottomCenter,
      child: new ButtonBar(
        alignment: MainAxisAlignment.center,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.all(20.0),
            child: new Text(
              "This is a very bigggggggg text !!!",textDirection: TextDirection.ltr,
              style: new TextStyle(fontSize: 20.0, color: Colors.white),
              maxLines: 2,
            ),
          )
        ],
      ),
    )


问:
Searching embedded documents Mongoose + nodejs
Im new to Mongoose, and i'm facing a problem in searching.

These are my Schemas:

```<code>var CommentSchema = new Schema({
    body       : String
  , comments   : [CommentSchema]
});

var PostSchema = new Schema({
    body        : String
  , comments    : [CommentSchema]
});
</code>```

There is a deep nesting of comments. When somebody answers to the existing comment, how can I find that one?

答:
you can look at the mongoose test suite on github for examples.

model_querying_test

Here is what you are looking for:

test finding based on embedded document fields:

```<code>function () {
    var db = start(), BlogPostB = db.model('BlogPostB', collection);

    BlogPostB.create({comments: [{title: 'i should be queryable'}]}, function (err, created) {
      should.strictEqual(err, null);
      BlogPostB.findOne({'comments.title': 'i should be queryable'}, function (err, found) {
        should.strictEqual(err, null);
        found._id.should.eql(created._id);
        db.close();
      });
    });
    },
</code>```

Body:
Im new to Mongoose, and i'm facing a problem in searching.

These are my Schemas:

var CommentSchema = new Schema({
    body       : String
  , comments   : [CommentSchema]
});

var PostSchema = new Schema({
    body        : String
  , comments    : [CommentSchema]
});

There is a deep nesting of comments. When somebody answers to the existing comment, how can I find that one?

Body:
you can look at the mongoose test suite on github for examples.

model_querying_test

Here is what you are looking for:

test finding based on embedded document fields:

function () {
    var db = start(), BlogPostB = db.model('BlogPostB', collection);

    BlogPostB.create({comments: [{title: 'i should be queryable'}]}, function (err, created) {
      should.strictEqual(err, null);
      BlogPostB.findOne({'comments.title': 'i should be queryable'}, function (err, found) {
        should.strictEqual(err, null);
        found._id.should.eql(created._id);
        db.close();
      });
    });
    },