问:
com.sun.mail.iap.ParsingException: BODYSTRUCTURE parse error: bad ``size'' element
I am trying to read the Bounce mails from an email inbox and I always get the following exception:

```<code>2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com) DEBUG IMAPS: ignoring bad response, THROW:
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com) com.sun.mail.iap.ParsingException: BODYSTRUCTURE parse error: bad ``size'' element
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.protocol.BODYSTRUCTURE.<init>(BODYSTRUCTURE.java:266)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.protocol.BODYSTRUCTURE.<init>(BODYSTRUCTURE.java:291)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.protocol.BODYSTRUCTURE.<init>(BODYSTRUCTURE.java:110)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.protocol.FetchResponse.parseItem(FetchResponse.java:258)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.protocol.FetchResponse.parse(FetchResponse.java:213)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.protocol.FetchResponse.<init>(FetchResponse.java:96)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.protocol.IMAPProtocol.readResponse(IMAPProtocol.java:392)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.iap.Protocol.command(Protocol.java:354)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.protocol.IMAPProtocol.fetch(IMAPProtocol.java:2113)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.protocol.IMAPProtocol.fetch(IMAPProtocol.java:2105)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.protocol.IMAPProtocol.fetchBodyStructure(IMAPProtocol.java:1680)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.IMAPMessage.loadBODYSTRUCTURE(IMAPMessage.java:1476)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.IMAPMessage.getDataHandler(IMAPMessage.java:746)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at javax.mail.internet.MimeMessage.getContent(MimeMessage.java:1454)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at org.apache.camel.component.mail.MailBinding.extractBodyFromMail(MailBinding.java:250)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at org.apache.camel.component.mail.MailMessage.createBody(MailMessage.java:105)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at org.apache.camel.component.mail.MailMessageRobust.createBody(MailMessageRobust.java:39)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at org.apache.camel.impl.MessageSupport.getBody(MessageSupport.java:47)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at org.apache.camel.component.mail.MailConsumer.createExchanges(MailConsumer.java:354)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at org.apache.camel.component.mail.MailConsumer.poll(MailConsumer.java:128)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at org.apache.camel.impl.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:175)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at org.apache.camel.impl.ScheduledPollConsumer.run(ScheduledPollConsumer.java:102)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPool
Executor.java:180)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecuto
r.java:294)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at java.lang.Thread.run(Thread.java:748)
</code>```

I have tried to look up on the internet so what this error means, but I am not really getting any useful results. Any recommendation or hint in the direction would be helpful.

Thanks in advance!

After reading the comment from @arnt I have extracted the response which throws this error and it is as follows:

```<code>robustimaps://abc@test.com) * 1 FETCH (BODYSTRUCTURE (((("text" "plain" ("charset" "UTF-8") NIL NIL "7BIT" 143 7 NIL NIL NIL NIL)("text"
 "html" ("charset" "UTF-8") NIL NIL "7BIT" 1209 33 NIL NIL NIL NIL) "alternative" ("boundary" "0000000000006a31d605898e6fe4") NIL NIL)("image" "png" ("name" "icon.png") "<icon.png>" NIL "base64" 7864 NIL ("attachment" ("filename"
"icon.png")) NIL NIL) "related" ("boundary" "0000000000006a31d305898e6fe3") NIL NIL)("message" "delivery-status" NIL NIL NIL "7BIT" 355 NIL NIL NIL NIL)("message" "rfc822" NIL NIL NIL "7BIT" 0 ("Thu, 23 May 2019 15:55:30 +0200" "=
?UTF-8?Q?Ihr_blah_blah_blah_bald._when_and_where_m=C3=B6c?= =?UTF-8?Q?hten_Sie_es_empfangen=3F_Jetzt_festlegen_...?=" (("ABC Paket" NIL "abc" "test.com")) NIL (("ABC Paket" NIL "abc" "test.com")) ((NIL NIL "3011941477" "xyz.
de")) NIL NIL NIL "<2066153904.661086.1558619730208@rnd-02.broadmail.live>") ("multipart" "signed" ("protocol" "application/pkcs7-signature" "micalg" "sha-256" "boundary" "----=_Part_661085_623173410.1558619730208") NIL NIL "7BIT"
 -1 NIL NIL NIL NIL) 0 NIL NIL NIL NIL) "report" ("boundary" "0000000000006a30fa05898e6fdb" "report-type" "delivery-status") NIL NIL))
</code>```

答:
Javamail was parsing a bodystructure, which is a very long line with many parens, numbers, NILs and strings. At a point where it expected a size it found a negative number. Why was there a negative number there? Well, IMAP servers don't have many occasions to send negative numbers, so I suspect a server bug.

(For completeness: The alternative would be that the server's number was correct and that the client was wrong to expect a size at that point. But we now know that it was a server bug.)

Body:
I am trying to read the Bounce mails from an email inbox and I always get the following exception:

2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com) DEBUG IMAPS: ignoring bad response, THROW:
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com) com.sun.mail.iap.ParsingException: BODYSTRUCTURE parse error: bad ``size'' element
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.protocol.BODYSTRUCTURE.<init>(BODYSTRUCTURE.java:266)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.protocol.BODYSTRUCTURE.<init>(BODYSTRUCTURE.java:291)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.protocol.BODYSTRUCTURE.<init>(BODYSTRUCTURE.java:110)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.protocol.FetchResponse.parseItem(FetchResponse.java:258)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.protocol.FetchResponse.parse(FetchResponse.java:213)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.protocol.FetchResponse.<init>(FetchResponse.java:96)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.protocol.IMAPProtocol.readResponse(IMAPProtocol.java:392)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.iap.Protocol.command(Protocol.java:354)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.protocol.IMAPProtocol.fetch(IMAPProtocol.java:2113)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.protocol.IMAPProtocol.fetch(IMAPProtocol.java:2105)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.protocol.IMAPProtocol.fetchBodyStructure(IMAPProtocol.java:1680)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.IMAPMessage.loadBODYSTRUCTURE(IMAPMessage.java:1476)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at com.sun.mail.imap.IMAPMessage.getDataHandler(IMAPMessage.java:746)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at javax.mail.internet.MimeMessage.getContent(MimeMessage.java:1454)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at org.apache.camel.component.mail.MailBinding.extractBodyFromMail(MailBinding.java:250)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at org.apache.camel.component.mail.MailMessage.createBody(MailMessage.java:105)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at org.apache.camel.component.mail.MailMessageRobust.createBody(MailMessageRobust.java:39)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at org.apache.camel.impl.MessageSupport.getBody(MessageSupport.java:47)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at org.apache.camel.component.mail.MailConsumer.createExchanges(MailConsumer.java:354)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at org.apache.camel.component.mail.MailConsumer.poll(MailConsumer.java:128)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at org.apache.camel.impl.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:175)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at org.apache.camel.impl.ScheduledPollConsumer.run(ScheduledPollConsumer.java:102)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPool
Executor.java:180)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecuto
r.java:294)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
2019-05-23 16:05:42 INFO  [stdio.AbstractLoggingWriter] (Camel (camel-inbound) thread #24 - robustimaps://abc@test.com)       at java.lang.Thread.run(Thread.java:748)

I have tried to look up on the internet so what this error means, but I am not really getting any useful results. Any recommendation or hint in the direction would be helpful.

Thanks in advance!

After reading the comment from @arnt I have extracted the response which throws this error and it is as follows:

robustimaps://abc@test.com) * 1 FETCH (BODYSTRUCTURE (((("text" "plain" ("charset" "UTF-8") NIL NIL "7BIT" 143 7 NIL NIL NIL NIL)("text"
 "html" ("charset" "UTF-8") NIL NIL "7BIT" 1209 33 NIL NIL NIL NIL) "alternative" ("boundary" "0000000000006a31d605898e6fe4") NIL NIL)("image" "png" ("name" "icon.png") "<icon.png>" NIL "base64" 7864 NIL ("attachment" ("filename"
"icon.png")) NIL NIL) "related" ("boundary" "0000000000006a31d305898e6fe3") NIL NIL)("message" "delivery-status" NIL NIL NIL "7BIT" 355 NIL NIL NIL NIL)("message" "rfc822" NIL NIL NIL "7BIT" 0 ("Thu, 23 May 2019 15:55:30 +0200" "=
?UTF-8?Q?Ihr_blah_blah_blah_bald._when_and_where_m=C3=B6c?= =?UTF-8?Q?hten_Sie_es_empfangen=3F_Jetzt_festlegen_...?=" (("ABC Paket" NIL "abc" "test.com")) NIL (("ABC Paket" NIL "abc" "test.com")) ((NIL NIL "3011941477" "xyz.
de")) NIL NIL NIL "<2066153904.661086.1558619730208@rnd-02.broadmail.live>") ("multipart" "signed" ("protocol" "application/pkcs7-signature" "micalg" "sha-256" "boundary" "----=_Part_661085_623173410.1558619730208") NIL NIL "7BIT"
 -1 NIL NIL NIL NIL) 0 NIL NIL NIL NIL) "report" ("boundary" "0000000000006a30fa05898e6fdb" "report-type" "delivery-status") NIL NIL))


来源: stackexchange

问:
How to authorise a role to perform "execute-api:Invoke"?
I'm attempting to move a suite of end-to-end tests so that they are fully contained within AWS. I've done this through code build and gotten everything running up to the point of running the tests, which invoke an API to reset the database before every test run. I keep running into this error message when the first test attempts to run.

StatusCodeError: 403 - "{\"Message\":\"User: anonymous is not authorized to perform: execute-api:Invoke on resource: arn:aws:execute-api:eu-west-2:*:*"}"
```

<p>At first, I thought the error was being caused by a lack of permissions on the role that was being used to build everything. I tried adding the correct permissions to IAM Role being used, eventual making them more open than I would like. </p>

```"Effect": "Allow",
"Action": [
    "execute-api:Invoke",
    "execute-api:ManageConnections"
],
"Resource": "arn:aws:execute-api:*:*:*"
```

<p>Obviously didn't fix things but I did notice that the access advisor shows that the particular policy isn't being accessed.</p>

<p>Next, I went into the resource policy in API Gateway to see if there was something there. I removed some Ip Address conditions that were set up to restrict access to the office's Ip Addresses. </p>

<p>I've look inside of WAF and Shield and can't see anything that would be related to invoking the API. At this point I am at a lost on where my next investigation should start.</p>

<p><strong><em>Edit</em></strong></p>

<p>Here's the responce I'm getting back.</p>

```"requestId": "********-82f8-11e9-a732-0b550cf3fcd6",
"ip": "*.*.*.*",
"caller": "-",
"user": "-",
"requestTime": "30/May/2019:16:32:50 +0000",
"httpMethod": "GET",
"resourcePath": "/*/ref-data/{proxy+}", "status": "403", "protocol": "HTTP/1.1", "responseLength": "185"
```

答:
Below are the steps you need to perform.

For API method - Make Auth =  IAM

For API resource policy make sure you allow traffic coming from selected IAM role for specific/all methods

```<code>{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::###############:role/###########"
        },
        "Action": "execute-api:Invoke",
        "Resource": "arn:aws:execute-api:ap-southeast-1:###########:/#########/*/POST/####/####/"
    }
]
</code>```

}

Make sure same IAM role is attached to entities from where this API is being called e.g. EC2 - if your code resides on EC2

Make sure your API calls are not plain curl calls, they are aws sigv4 signed

Hope this works!

ContentLicense: CC BY-SA 4.0

Body:
I'm attempting to move a suite of end-to-end tests so that they are fully contained within AWS. I've done this through code build and gotten everything running up to the point of running the tests, which invoke an API to reset the database before every test run. I keep running into this error message when the first test attempts to run.

StatusCodeError: 403 - "{\"Message\":\"User: anonymous is not authorized to perform: execute-api:Invoke on resource: arn:aws:execute-api:eu-west-2:*:*"}"

At first, I thought the error was being caused by a lack of permissions on the role that was being used to build everything. I tried adding the correct permissions to IAM Role being used, eventual making them more open than I would like.

"Effect": "Allow",
"Action": [
    "execute-api:Invoke",
    "execute-api:ManageConnections"
],
"Resource": "arn:aws:execute-api:*:*:*"

Obviously didn't fix things but I did notice that the access advisor shows that the particular policy isn't being accessed.

Next, I went into the resource policy in API Gateway to see if there was something there. I removed some Ip Address conditions that were set up to restrict access to the office's Ip Addresses.

I've look inside of WAF and Shield and can't see anything that would be related to invoking the API. At this point I am at a lost on where my next investigation should start.

Edit

Here's the responce I'm getting back.

"requestId": "********-82f8-11e9-a732-0b550cf3fcd6",
"ip": "*.*.*.*",
"caller": "-",
"user": "-",
"requestTime": "30/May/2019:16:32:50 +0000",
"httpMethod": "GET",
"resourcePath": "/*/ref-data/{proxy+}", "status": "403", "protocol": "HTTP/1.1", "responseLength": "185"

Body:
Below are the steps you need to perform.

For API method - Make Auth =  IAM

For API resource policy make sure you allow traffic coming from selected IAM role for specific/all methods

{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::###############:role/###########"
        },
        "Action": "execute-api:Invoke",
        "Resource": "arn:aws:execute-api:ap-southeast-1:###########:/#########/*/POST/####/####/"
    }
]

}

Make sure same IAM role is attached to entities from where this API is being called e.g. EC2 - if your code resides on EC2

Make sure your API calls are not plain curl calls, they are aws sigv4 signed

Hope this works!


问:
SQLiteDatabase vs File storage
I want to store structure type data (i.e. information of call logs like name, number, type of number, date, time, duration). Which is the best way and which is faster? SQLiteDatabase (make table and insert, delete logs in it) or use file storage (means make one class for all parameters and write their objects in file using input/output Stream and serializable) or the another way i heard about it is XML parser but i don't know this.

Please help me. Thanks in advance.

答:
It depends on what you are trying to do.

If your goal is speed, the SQLite will give you a serious run for your money (especially if you wrap multiple inserts into transactions). SQLite has been optimized for everything you mentioned and it would be very easy to leverage the speed it can give you.

If portability is your goal, then files may be a slight bit easier. Files can be moved back and forth very easily easily, whereas SQLite might take some more effort.

If being able to search is your goal, then you'd be a fool not to use SQLite, as it is extremely good at searching and filtering results.

ContentLicense: CC BY-SA 3.0

Title: SQLiteDatabase vs File storage


问:
Allow user to delete textfield text but restrict maximum text length
I have UITextField and i want allow user to type only up to 4 symbols. But i also want to allow them to erase symbols with keyboard (i mean, delete last and move caret for left. Symbol look like rectangle left arrow with cross on iOS keyboard).

For now i ended up with:

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let text = textField.text, text.count < 4 else { return false }
    return true
  }
</code>```

But i have no idea, how to let users to delete symbols. When text count become 4, i am not allowed to type or do any actions.

答:
You can use below code to get updated string and compare with that to your length,</p>

```<code>func textField(_ textFieldToChange: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
  // limit to 4 characters
  let characterCountLimit = 4

  // We need to figure out how many characters would be in the string after the change happens
  let startingLength = textFieldToChange.text?.count ?? 0
  let lengthToAdd = string.count
  let lengthToReplace = range.length

  let newLength = startingLength + lengthToAdd - lengthToReplace

  return newLength <= characterCountLimit
}
</code>```

Body:
I have UITextField and i want allow user to type only up to 4 symbols. But i also want to allow them to erase symbols with keyboard (i mean, delete last and move caret for left. Symbol look like rectangle left arrow with cross on iOS keyboard).

For now i ended up with:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let text = textField.text, text.count < 4 else { return false }
    return true
  }

But i have no idea, how to let users to delete symbols. When text count become 4, i am not allowed to type or do any actions.

Body:
You can use below code to get updated string and compare with that to your length,

func textField(_ textFieldToChange: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
  // limit to 4 characters
  let characterCountLimit = 4

  // We need to figure out how many characters would be in the string after the change happens
  let startingLength = textFieldToChange.text?.count ?? 0
  let lengthToAdd = string.count
  let lengthToReplace = range.length

  let newLength = startingLength + lengthToAdd - lengthToReplace

  return newLength <= characterCountLimit
}


问:
R exact selection based on %in%
I am having some trouble doing a simple operation.

What I want is to simply select the rows, grouped by id, that have all of the values (-1, -2, -3, -4), and apply a tag based on this condition.

```<code>   id time
1   1   -4
2   1   -3
3   1   -2
4   1   -1
5   2   -1
6   2   -2
7   3   -1
8   3   -3
9   4   -1
10  4   -2
11  4   -3
12  4   -4
</code>```

Intuitively I was going for

```<code>rb[rb$time %in% c(-1, -2, -3, -4), ]
</code>```

However, when I do that, all id are selected. So, the %in% operator uses the OR | operator.

So, I thought I could do this then, to use the AND & operator

```<code>rb[rb$time == -1 &
 rb$time == -2 &
 rb$time == -3 &
 rb$time == -4, ]
</code>```

But it does not work.

Any clue how I could tag or subset these id, such that

```<code>   id time tag
1   1   -4   1
2   1   -3   1
3   1   -2   1
4   1   -1   1
5   2   -1   0
6   2   -2   0
7   3   -1   0
8   3   -3   0
9   4   -1   1
10  4   -2   1
11  4   -3   1
12  4   -4   1
</code>```

答:
Here is another base solution using vapply and .subset2 (less readable than $ or [] but far more efficient)

```<code>rb[['tag']] <- 0L
id_col <- .subset2(rb, 1L)
vapply(unique(rb$id),
       function (id) {
         index <- id_col == id
         test <- all(sort(.subset2(rb, 2L)[index]) == -4:-1)
         rb[['tag']][index] <<- as.integer(test)
         test
         },
       logical(1))
rb
#    id time tag
# 1   1   -4   1
# 2   1   -3   1
# 3   1   -2   1
# 4   1   -1   1
# 5   2   -1   0
# 6   2   -2   0
# 7   3   -1   0
# 8   3   -3   0
# 9   4   -1   1
# 10  4   -2   1
# 11  4   -3   1
# 12  4   -4   1
</code>```

Title: R exact selection based on %in%

Body:
I am having some trouble doing a simple operation.

What I want is to simply select the rows, grouped by id, that have all of the values (-1, -2, -3, -4), and apply a tag based on this condition.

   id time
1   1   -4
2   1   -3
3   1   -2
4   1   -1
5   2   -1
6   2   -2
7   3   -1
8   3   -3
9   4   -1
10  4   -2
11  4   -3
12  4   -4

Intuitively I was going for

rb[rb$time %in% c(-1, -2, -3, -4), ]

However, when I do that, all id are selected. So, the %in% operator uses the OR | operator.

So, I thought I could do this then, to use the AND & operator

rb[rb$time == -1 &
 rb$time == -2 &
 rb$time == -3 &
 rb$time == -4, ]

But it does not work.

Any clue how I could tag or subset these id, such that

   id time tag
1   1   -4   1
2   1   -3   1
3   1   -2   1
4   1   -1   1
5   2   -1   0
6   2   -2   0
7   3   -1   0
8   3   -3   0
9   4   -1   1
10  4   -2   1
11  4   -3   1
12  4   -4   1

Body:
Here is another base solution using vapply and .subset2 (less readable than $ or [] but far more efficient)

rb[['tag']] <- 0L
id_col <- .subset2(rb, 1L)
vapply(unique(rb$id),
       function (id) {
         index <- id_col == id
         test <- all(sort(.subset2(rb, 2L)[index]) == -4:-1)
         rb[['tag']][index] <<- as.integer(test)
         test
         },
       logical(1))
rb
#    id time tag
# 1   1   -4   1
# 2   1   -3   1
# 3   1   -2   1
# 4   1   -1   1
# 5   2   -1   0
# 6   2   -2   0
# 7   3   -1   0
# 8   3   -3   0
# 9   4   -1   1
# 10  4   -2   1
# 11  4   -3   1
# 12  4   -4   1


问:
Plotly boxplot outliners not getting rendered properly
I am trying to display boxplot in Angular 6 app using Plotly.js. I am having problem with my generated graph. I want only the box and lines to be displayed in the graph and not the points. So I have set 'boxpoints' to 'outliners' in my data array. I have around 10 arrays for which I have to display boxplot. The generated graph contains lines for some of the data and point for some other. I need to generate the graph with only boxes(outliers). Here is image of generated Boxplot.

Thanks in advance

答: I found the solution. Instead of setting 'boxpoints' property to 'outliners', I just had to set it to false</p>


问:
Haystack indexes not all items
I am using django haystack with whoosh for full-text search. There are nine different models to index, but when I search for indexed entries, it seems that none or not all of them get indexed for some models.

I try this at django shell, but I get 0 for some of the models when all nine models are indexed, whereas I get all of them if I index just some models.

```<code>from haystack.query import SearchQuerySet
SearchQuerySet().models(OneOfMyModels).count()
</code>```

For example, I have Article model which is correctly indexed and all 1029 items are found if I rebuild index just for Article. But I get 0 results of Article items, when I rebuild index for all 9 my searchable models.

Versions of software that I am using:

python 2.6

django 1.3

haystack 1.1

whoosh 1.8

Are there any limitations in whoosh for the amount of indexed models or found items? What could cause such strange behavior? Have you experienced anything similar? How did you solve it?

答: Haystack search seems to work well when I downgrade whoosh to 1.3.3.</p>

Title: Haystack indexes not all items

Body:
I am using django haystack with whoosh for full-text search. There are nine different models to index, but when I search for indexed entries, it seems that none or not all of them get indexed for some models.

I try this at django shell, but I get 0 for some of the models when all nine models are indexed, whereas I get all of them if I index just some models.

from haystack.query import SearchQuerySet
SearchQuerySet().models(OneOfMyModels).count()

For example, I have Article model which is correctly indexed and all 1029 items are found if I rebuild index just for Article. But I get 0 results of Article items, when I rebuild index for all 9 my searchable models.

Versions of software that I am using:

python 2.6

django 1.3

haystack 1.1

whoosh 1.8

Are there any limitations in whoosh for the amount of indexed models or found items? What could cause such strange behavior? Have you experienced anything similar? How did you solve it?


问:
Azure Search Service a field that has . or # not decoding no results
We are using the .net library for azure search, I have successfully built the index and stored data in the index. One of our fields is called Tags which is a collection of strings and it is marked as searchable. So we put values in this field such as C# .NET.

The problem is when searching the search service will not hit on C#, it will on C, nor will it hit on .NET but it will on NET. I can see thru fiddler that the search term is encoding the # and also the ., but it doesn't seem like it's getting decoded on the azure side.

答: You could try using Regex search, like searching for this string: /.*c\#.*/. Also make sure you set SearchParameters.QueryType = QueryType.Full.


问:
How do I go back to the finished activity dynamically?
For example, user passed between activities A to B. Now finish A and pass B to C, then finish B. Then click to the back button and go B again. Because B is the activity that the user comes from to current(ActivityC) activity.If the user go to the C from A directly, then finish A. If press the back button, then goes to the A again. Because A is the activity that the user comes from to current(ActivityC) activity.
   I want to set the onBackPress button to start activities that started before orderly. If I don't finish activities that started before when I start another activity, I can show the activity that started before with finish() current activity. This is possible. Because I don't finish any activity. So finish() current activity will cause show activity that started before. But, RAM will be overload when I open 50 activities may be. So because of this problem I need to finish() activity that started before. On the other hand, I want to start the activity that started before orderly when clicking to the back button. For example

```<code>  ActivityA --> ActivityB --> ActivityC --> ActivityD
</code>```

In this scenario, I finish ActivityA, ActivityB, ActivityC orderly. But I want to start ActivityC back press of the ActivityD and I want to start ActivityB on the back press of ActivityC.

Lastly, I have a complex path in the application. And, I navigate to the ActivityD and I finished the ActivityF when my current activity is ActivityF

```<code>ActivityF --> ActivityD
ActivityF finished
</code>```

Current activity:

```<code>ActivityD
</code>```

In this scenario, I want to start the ActivityF not the ActivityC on back button of the ActivityD.

Normally:

```<code>ActivityA --> ActivityB --> ActivityC --> ActivityD /// click back button
ActivityA --> ActivityB --> ActivityC /// click back button
ActivityA --> ActivityB /// click back button
ActivityA
</code>```

or

```<code>ActivityA --> ActivityF --> ActivityD /// click back button
ActivityA --> ActivityF /// click back button
ActivityA
</code>```

But I want to generate this scenario:

```<code>ActivityA
--> ActivityB
--> ActivityC
--> ActivityD /// click back button
ActivityC <-- /// click back button
ActivityB <-- /// click back button
ActivityA
</code>```

or

```<code>ActivityA
--> ActivityF
--> ActivityD /// click back button
ActivityF <-- /// click back button
ActivityA <--
</code>```

答:
You can use</p>

```<code> if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
   finish();
 } else {
   ActivityCompat.finishAffinity(RatingReviewActivity.this);
 }
</code>```

Body:
For example, user passed between activities A to B. Now finish A and pass B to C, then finish B. Then click to the back button and go B again. Because B is the activity that the user comes from to current(ActivityC) activity.If the user go to the C from A directly, then finish A. If press the back button, then goes to the A again. Because A is the activity that the user comes from to current(ActivityC) activity.
   I want to set the onBackPress button to start activities that started before orderly. If I don't finish activities that started before when I start another activity, I can show the activity that started before with finish() current activity. This is possible. Because I don't finish any activity. So finish() current activity will cause show activity that started before. But, RAM will be overload when I open 50 activities may be. So because of this problem I need to finish() activity that started before. On the other hand, I want to start the activity that started before orderly when clicking to the back button. For example

  ActivityA --> ActivityB --> ActivityC --> ActivityD

In this scenario, I finish ActivityA, ActivityB, ActivityC orderly. But I want to start ActivityC back press of the ActivityD and I want to start ActivityB on the back press of ActivityC.

Lastly, I have a complex path in the application. And, I navigate to the ActivityD and I finished the ActivityF when my current activity is ActivityF

ActivityF --> ActivityD
ActivityF finished

Current activity:

ActivityD

In this scenario, I want to start the ActivityF not the ActivityC on back button of the ActivityD.

Normally:

ActivityA --> ActivityB --> ActivityC --> ActivityD /// click back button
ActivityA --> ActivityB --> ActivityC /// click back button
ActivityA --> ActivityB /// click back button
ActivityA

or

ActivityA --> ActivityF --> ActivityD /// click back button
ActivityA --> ActivityF /// click back button
ActivityA

But I want to generate this scenario:

ActivityA
--> ActivityB
--> ActivityC
--> ActivityD /// click back button
ActivityC <-- /// click back button
ActivityB <-- /// click back button
ActivityA

or

ActivityA
--> ActivityF
--> ActivityD /// click back button
ActivityF <-- /// click back button
ActivityA <--

Body:
You can use

 if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
   finish();
 } else {
   ActivityCompat.finishAffinity(RatingReviewActivity.this);
 }


问:
Chaquopy not initializing class
When using chaquopy for android, calling a module from java does not run the __init__ method.

```<code>PyObject utilModule = py.getModule("utils.Utils").get("Utils");
</code>```

Creates an object reference to python without the constructor. Is there any way to do this without an additional "init" function and calling that after creation?

答:
Assuming utils.Utils is a module, and Utils is a class within that module, your code is just getting a reference to that class. If you want to actually instantiate the class, you can either do this:

```<code>PyObject utilObj = py.getModule("utils.Utils").callAttr("Utils");
</code>```

or this:

```<code>PyObject utilClass = py.getModule("utils.Utils").get("Utils");
PyObject utilObj = utilClass.call();
</code>```

If you want to pass constructor parameters, just add them at the end of the parameter list of callAttr or call.

See the ZipFile example in the documentation.

Title: Chaquopy not initializing class

Body:
When using chaquopy for android, calling a module from java does not run the __init__ method.

PyObject utilModule = py.getModule("utils.Utils").get("Utils");

Creates an object reference to python without the constructor. Is there any way to do this without an additional "init" function and calling that after creation?

Body:
Assuming utils.Utils is a module, and Utils is a class within that module, your code is just getting a reference to that class. If you want to actually instantiate the class, you can either do this:

PyObject utilObj = py.getModule("utils.Utils").callAttr("Utils");

or this:

PyObject utilClass = py.getModule("utils.Utils").get("Utils");
PyObject utilObj = utilClass.call();

If you want to pass constructor parameters, just add them at the end of the parameter list of callAttr or call.

See the ZipFile example in the documentation.


问:
Returning async ElasticSearch data in REST service
I'm trying to develop a REST resource that forwards the request to the responsible service over the event bus. Then the service tries to get some data from Elastic Search asynchronously with JavaRX.

I'm using io.reactiverse's ElasticSearch client implementation for Vert.x

I can't figure out how to return ElasticSearch data to the client

ElasticResource

import io.reactivex.Single;
import io.vertx.core.json.JsonObject;
import io.vertx.reactivex.core.eventbus.EventBus;
import io.vertx.reactivex.core.eventbus.Message;
import org.elasticsearch.action.get.GetResponse;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/elastic")
@ApplicationScoped
public class ElasticResource {

    @Inject
    EventBus eventBus;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("bank-es")
    public void greetingVertx(@Suspended final AsyncResponse inAsyncResponse) {

        Single<Message<GetResponse>> single = eventBus.<GetResponse>rxSend("QuarkusElasticService.getReq", new JsonObject().put("index", "bank").put("id", "1"));

        single.subscribe((mex) -> {
            inAsyncResponse.resume(Response.ok(mex.body()).build());
        });
    }
}
```

<p><strong>QuarkusElasticServiceImpl</strong></p>

<pre class="lang-java prettyprint-override"><code>import com.sourcesense.sisal.socialbetting.dev.example.elastic.service.QuarkusElasticService;
import io.quarkus.vertx.ConsumeEvent;
import io.reactiverse.elasticsearch.client.reactivex.RestHighLevelClient;
import io.reactivex.Single;
import io.vertx.core.json.JsonObject;
import io.vertx.reactivex.core.Vertx;
import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.concurrent.ExecutorService;

public class QuarkusElasticServiceImpl implements QuarkusElasticService {

    @Inject
    Vertx vertx;

    @Inject
    ExecutorService executor;

    private RestHighLevelClient esClient;

    @PostConstruct
    public void init() {
        RestClientBuilder builder = RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http"));
        esClient = RestHighLevelClient.create(vertx, builder);

    }

    @Override
    @ConsumeEvent("QuarkusElasticService.getReq")
    public Single getReq(JsonObject jsonObject) {

        GetRequest getRequest = new GetRequest(
                jsonObject.getString("index"),
                jsonObject.getString("id"));

        return esClient.rxGetAsync(getRequest, RequestOptions.DEFAULT);
    }
}
</code>```

答:
After reasoning on Clement's comment, I found the solution.

First of all, I switched between the 2 io.reactiverse's modules choosing the non RxJava version io.reactiverse.elasticsearch-client.

Then I came back to the io.vertx.axle's versions of the EventBus and Message.

Then I changed my code as follows:

ElasticResource

import io.vertx.axle.core.eventbus.EventBus;
import io.vertx.core.json.JsonObject;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.concurrent.ExecutionException;

@Path("/elastic")
@ApplicationScoped
public class ElasticResource {

    @Inject
    EventBus eventBus;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("bank-es")
    public JsonObject greetingVertx() throws ExecutionException, InterruptedException {

        JsonObject req = new JsonObject().put("index", "bank").put("id", "1");

        return eventBus.<JsonObject>send("QuarkusElasticService.getReq", req)
                .toCompletableFuture().get().body();
    }
}
```

<p><strong>QuarkusElasticServiceImpl</strong></p>

<pre class="lang-java prettyprint-override"><code>import com.sourcesense.sisal.socialbetting.dev.example.elastic.service.QuarkusElasticService;
import io.quarkus.vertx.ConsumeEvent;
import io.reactiverse.elasticsearch.client.RestHighLevelClient;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;

public class QuarkusElasticServiceImpl implements QuarkusElasticService {

    @Inject
    Vertx vertx;

    private RestHighLevelClient esClient;

    @PostConstruct
    public void init() {

        RestClientBuilder builder = RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http"));
        esClient = RestHighLevelClient.create(vertx, builder);

    }

    @Override
    @ConsumeEvent("QuarkusElasticService.getReq")
    public CompletionStage<JsonObject> getReq(JsonObject jsonObject) {

        CompletableFuture future = new CompletableFuture();

        GetRequest getRequest = new GetRequest(
                jsonObject.getString("index"),
                jsonObject.getString("id"));

        esClient.getAsync(getRequest, RequestOptions.DEFAULT, ar -> {
            if (ar.failed()) {
                future.completeExceptionally(new Exception("erroraccio"));
            } else {
                future.complete(JsonObject.mapFrom(ar.result()));
            }
        });

        return future;
    }
}
</code>```

Body:
I'm trying to develop a REST resource that forwards the request to the responsible service over the event bus. Then the service tries to get some data from Elastic Search asynchronously with JavaRX.

I'm using io.reactiverse's ElasticSearch client implementation for Vert.x

I can't figure out how to return ElasticSearch data to the client

ElasticResource

import io.reactivex.Single;
import io.vertx.core.json.JsonObject;
import io.vertx.reactivex.core.eventbus.EventBus;
import io.vertx.reactivex.core.eventbus.Message;
import org.elasticsearch.action.get.GetResponse;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/elastic")
@ApplicationScoped
public class ElasticResource {

    @Inject
    EventBus eventBus;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("bank-es")
    public void greetingVertx(@Suspended final AsyncResponse inAsyncResponse) {

        Single<Message<GetResponse>> single = eventBus.<GetResponse>rxSend("QuarkusElasticService.getReq", new JsonObject().put("index", "bank").put("id", "1"));

        single.subscribe((mex) -> {
            inAsyncResponse.resume(Response.ok(mex.body()).build());
        });
    }
}

QuarkusElasticServiceImpl

import com.sourcesense.sisal.socialbetting.dev.example.elastic.service.QuarkusElasticService;
import io.quarkus.vertx.ConsumeEvent;
import io.reactiverse.elasticsearch.client.reactivex.RestHighLevelClient;
import io.reactivex.Single;
import io.vertx.core.json.JsonObject;
import io.vertx.reactivex.core.Vertx;
import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.concurrent.ExecutorService;

public class QuarkusElasticServiceImpl implements QuarkusElasticService {

    @Inject
    Vertx vertx;

    @Inject
    ExecutorService executor;

    private RestHighLevelClient esClient;

    @PostConstruct
    public void init() {
        RestClientBuilder builder = RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http"));
        esClient = RestHighLevelClient.create(vertx, builder);

    }

    @Override
    @ConsumeEvent("QuarkusElasticService.getReq")
    public Single getReq(JsonObject jsonObject) {

        GetRequest getRequest = new GetRequest(
                jsonObject.getString("index"),
                jsonObject.getString("id"));

        return esClient.rxGetAsync(getRequest, RequestOptions.DEFAULT);
    }
}

Body:
After reasoning on Clement's comment, I found the solution.

First of all, I switched between the 2 io.reactiverse's modules choosing the non RxJava version io.reactiverse.elasticsearch-client.

Then I came back to the io.vertx.axle's versions of the EventBus and Message.

Then I changed my code as follows:

ElasticResource

import io.vertx.axle.core.eventbus.EventBus;
import io.vertx.core.json.JsonObject;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.concurrent.ExecutionException;

@Path("/elastic")
@ApplicationScoped
public class ElasticResource {

    @Inject
    EventBus eventBus;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("bank-es")
    public JsonObject greetingVertx() throws ExecutionException, InterruptedException {

        JsonObject req = new JsonObject().put("index", "bank").put("id", "1");

        return eventBus.<JsonObject>send("QuarkusElasticService.getReq", req)
                .toCompletableFuture().get().body();
    }
}

QuarkusElasticServiceImpl

import com.sourcesense.sisal.socialbetting.dev.example.elastic.service.QuarkusElasticService;
import io.quarkus.vertx.ConsumeEvent;
import io.reactiverse.elasticsearch.client.RestHighLevelClient;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;

public class QuarkusElasticServiceImpl implements QuarkusElasticService {

    @Inject
    Vertx vertx;

    private RestHighLevelClient esClient;

    @PostConstruct
    public void init() {

        RestClientBuilder builder = RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http"));
        esClient = RestHighLevelClient.create(vertx, builder);

    }

    @Override
    @ConsumeEvent("QuarkusElasticService.getReq")
    public CompletionStage<JsonObject> getReq(JsonObject jsonObject) {

        CompletableFuture future = new CompletableFuture();

        GetRequest getRequest = new GetRequest(
                jsonObject.getString("index"),
                jsonObject.getString("id"));

        esClient.getAsync(getRequest, RequestOptions.DEFAULT, ar -> {
            if (ar.failed()) {
                future.completeExceptionally(new Exception("erroraccio"));
            } else {
                future.complete(JsonObject.mapFrom(ar.result()));
            }
        });

        return future;
    }
}


问:
How can I filter an Iterable based upon a Predicate?
I want to do a string list filter function using an Iterable<String> and a predicate to select the strings to keep, the other ones must be removed from the list, but I'm not understating how I do the remove.

```<code>static <T> Iterable<T> select(Iterable<T> it, Predicate<T> pred) {
    for (T s: it) {
        if (pred.test(s)==false) {
            // what to do here?
        }
    }
    return ...;
}
</code>```

For this input:

```<code>{"a","","b",""}
</code>```

I expect

```<code>{"a","b"}
</code>```

答:
An Iterable represents the capability to provide an Iterator on request. So, to decorate an existing iterable with a filtering logic, you have to implement the decorating Iterator.

```<code>static <T> Iterable<T> select(Iterable<T> it, Predicate<T> pred) {
    return () -> new Iterator<T>() {
        Iterator<T> sourceIterator = it.iterator();
        T current;
        boolean hasCurrent;

        @Override
        public boolean hasNext() {
            while(!hasCurrent) {
                if(!sourceIterator.hasNext()) {
                    return false;
                }
                T next = sourceIterator.next();
                if(pred.test(next)) {
                    current = next;
                    hasCurrent = true;
                }
            }
            return true;
        }

        @Override
        public T next() {
            if(!hasNext()) throw new NoSuchElementException();
            T next = current;
            current = null;
            hasCurrent = false;
            return next;
        }
    };
}
</code>```

which you may test via

```<code>List<String> original = new ArrayList<>();
Collections.addAll(original, "foo", "bar", "baz");
Iterable<String> filter = select(original, s -> s.startsWith("b"));
System.out.println(String.join(", ", filter));
original.removeIf(s -> !s.endsWith("r"));
System.out.println(String.join(", ", filter));
</code>```

The biggest challenge when implementing such an Iterator, is to provide the two methods hasNext and next with the correct semantics, without any guaranty regarding how the caller will invoke them, i.e. you can not assume that it will never invoke hasNext() twice nor that next() will always be invoked with a preceding hasNext().

The same logic can be implemented much easier using the Stream API:

```<code>static <T> Iterable<T> select(Iterable<T> it, Predicate<T> pred) {
    return () -> StreamSupport.stream(it.spliterator(), false)
        .filter(pred).iterator();
}
</code>```

Body:
I want to do a string list filter function using an Iterable<String> and a predicate to select the strings to keep, the other ones must be removed from the list, but I'm not understating how I do the remove.

static <T> Iterable<T> select(Iterable<T> it, Predicate<T> pred) {
    for (T s: it) {
        if (pred.test(s)==false) {
            // what to do here?
        }
    }
    return ...;
}

For this input:

{"a","","b",""}

I expect

{"a","b"}

Body:
An Iterable represents the capability to provide an Iterator on request. So, to decorate an existing iterable with a filtering logic, you have to implement the decorating Iterator.

static <T> Iterable<T> select(Iterable<T> it, Predicate<T> pred) {
    return () -> new Iterator<T>() {
        Iterator<T> sourceIterator = it.iterator();
        T current;
        boolean hasCurrent;

        @Override
        public boolean hasNext() {
            while(!hasCurrent) {
                if(!sourceIterator.hasNext()) {
                    return false;
                }
                T next = sourceIterator.next();
                if(pred.test(next)) {
                    current = next;
                    hasCurrent = true;
                }
            }
            return true;
        }

        @Override
        public T next() {
            if(!hasNext()) throw new NoSuchElementException();
            T next = current;
            current = null;
            hasCurrent = false;
            return next;
        }
    };
}

which you may test via

List<String> original = new ArrayList<>();
Collections.addAll(original, "foo", "bar", "baz");
Iterable<String> filter = select(original, s -> s.startsWith("b"));
System.out.println(String.join(", ", filter));
original.removeIf(s -> !s.endsWith("r"));
System.out.println(String.join(", ", filter));

The biggest challenge when implementing such an Iterator, is to provide the two methods hasNext and next with the correct semantics, without any guaranty regarding how the caller will invoke them, i.e. you can not assume that it will never invoke hasNext() twice nor that next() will always be invoked with a preceding hasNext().

The same logic can be implemented much easier using the Stream API:

static <T> Iterable<T> select(Iterable<T> it, Predicate<T> pred) {
    return () -> StreamSupport.stream(it.spliterator(), false)
        .filter(pred).iterator();
}


问:
Problem with loading image in java with FileChooser
I have write a class filechooser where I can choose files. I had searched for a class that loads images but nothing. My filechooser class  can made a panel with button open and save. When I press button open I can search in my documents and when I'm going to open the image my image load class not responding I need some class that can synchronize with me filechooser and load my image from my documents and show it in the panel.

```<code>package project;

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.*;

public class FileChooserDemo extends JPanel
                         implements ActionListener {
    static private final String newline = "\n";
    JButton openButton, saveButton;
    JTextArea log;
    JFileChooser fc;

public FileChooserDemo() {
    super(new BorderLayout());

    //Create the log first, because the action listeners
    //need to refer to it.
    log = new JTextArea(5,20);
    log.setMargin(new Insets(5,5,5,5));
    log.setEditable(false);
    JScrollPane logScrollPane = new JScrollPane(log);

    //Create a file chooser
    fc = new JFileChooser();

    openButton = new JButton("Open a File...");

    openButton.addActionListener(this);

    //Create the save button.  We use the image from the JLF
    //Graphics Repository (but we extracted it from the jar).
    saveButton = new JButton("Save a File...");

    saveButton.addActionListener(this);

    //For layout purposes, put the buttons in a separate panel
    JPanel buttonPanel = new JPanel(); //use FlowLayout
    buttonPanel.add(openButton);
    buttonPanel.add(saveButton);

    //Add the buttons and the log to this panel.
    add(buttonPanel, BorderLayout.PAGE_START);
    add(logScrollPane, BorderLayout.CENTER);
}

public void actionPerformed(ActionEvent e) {

    //Handle open button action.
    if (e.getSource() == openButton) {
        int returnVal = fc.showOpenDialog(FileChooserDemo.this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would open the file.
            log.append("Opening: " + file.getName() + "." + newline);

        } else {
            log.append("Open command cancelled by user." + newline);
        }
        log.setCaretPosition(log.getDocument().getLength());

    //Handle save button action.
    } else if (e.getSource() == saveButton) {
        int returnVal = fc.showSaveDialog(FileChooserDemo.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would save the file.
            log.append("Saving: " + file.getName() + "." + newline);
        } else {
            log.append("Save command cancelled by user." + newline);
        }
        log.setCaretPosition(log.getDocument().getLength());
    }
}

/**
 * Create the GUI and show it.  For thread safety,
 * this method should be invoked from the
 * event dispatch thread.
 */
public static void createLoad() {
    //Create and set up the window.
    JFrame frame = new JFrame("FileChooserDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Add content to the window.
    frame.add(new FileChooserDemo());

    //Display the window.
    frame.pack();
    frame.setVisible(true);
}

}
</code>```

this is the class file chooser i need a class that can load the picture i open

and this is the imageload code.

```<code>  import java.awt.*;
  import java.awt.event.*;
  import java.awt.image.*;
  import java.io.*;
  import javax.imageio.*;
  import javax.swing.*;

/**
 * This class demonstrates how to load an Image from an external file
*/
public class LoadImageApp extends Component {

   BufferedImage img;

public void paint(Graphics g) {
    g.drawImage(img, 0, 0, null);
}

public LoadImageApp() {
   try {
       img = ImageIO.read(new File("strawberry.jpg"));
   } catch (IOException e) {
   }

}

public Dimension getPreferredSize() {
    if (img == null) {
         return new Dimension(100,100);
    } else {
       return new Dimension(img.getWidth(null), img.getHeight(null));
   }
}

public static void main(String[] args) {

    JFrame f = new JFrame("Load Image Sample");

    f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

    f.add(new LoadImageApp());
    f.pack();
    f.setVisible(true);
}
}
</code>```

what i want is the image code read the file.aboslutepath and load the picture when i click it

答:
All the file choose is used for is to get the name of the file you want to load. You still need to load the file.

Start by reading the section from the Swing tutorial on How to Use Icons for example code on how to read the image.

Body:
I have write a class filechooser where I can choose files. I had searched for a class that loads images but nothing. My filechooser class  can made a panel with button open and save. When I press button open I can search in my documents and when I'm going to open the image my image load class not responding I need some class that can synchronize with me filechooser and load my image from my documents and show it in the panel.

package project;

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.*;

public class FileChooserDemo extends JPanel
                         implements ActionListener {
    static private final String newline = "\n";
    JButton openButton, saveButton;
    JTextArea log;
    JFileChooser fc;

public FileChooserDemo() {
    super(new BorderLayout());

    //Create the log first, because the action listeners
    //need to refer to it.
    log = new JTextArea(5,20);
    log.setMargin(new Insets(5,5,5,5));
    log.setEditable(false);
    JScrollPane logScrollPane = new JScrollPane(log);

    //Create a file chooser
    fc = new JFileChooser();

    openButton = new JButton("Open a File...");

    openButton.addActionListener(this);

    //Create the save button.  We use the image from the JLF
    //Graphics Repository (but we extracted it from the jar).
    saveButton = new JButton("Save a File...");

    saveButton.addActionListener(this);

    //For layout purposes, put the buttons in a separate panel
    JPanel buttonPanel = new JPanel(); //use FlowLayout
    buttonPanel.add(openButton);
    buttonPanel.add(saveButton);

    //Add the buttons and the log to this panel.
    add(buttonPanel, BorderLayout.PAGE_START);
    add(logScrollPane, BorderLayout.CENTER);
}

public void actionPerformed(ActionEvent e) {

    //Handle open button action.
    if (e.getSource() == openButton) {
        int returnVal = fc.showOpenDialog(FileChooserDemo.this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would open the file.
            log.append("Opening: " + file.getName() + "." + newline);

        } else {
            log.append("Open command cancelled by user." + newline);
        }
        log.setCaretPosition(log.getDocument().getLength());

    //Handle save button action.
    } else if (e.getSource() == saveButton) {
        int returnVal = fc.showSaveDialog(FileChooserDemo.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would save the file.
            log.append("Saving: " + file.getName() + "." + newline);
        } else {
            log.append("Save command cancelled by user." + newline);
        }
        log.setCaretPosition(log.getDocument().getLength());
    }
}

/**
 * Create the GUI and show it.  For thread safety,
 * this method should be invoked from the
 * event dispatch thread.
 */
public static void createLoad() {
    //Create and set up the window.
    JFrame frame = new JFrame("FileChooserDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Add content to the window.
    frame.add(new FileChooserDemo());

    //Display the window.
    frame.pack();
    frame.setVisible(true);
}

}

this is the class file chooser i need a class that can load the picture i open

and this is the imageload code.

  import java.awt.*;
  import java.awt.event.*;
  import java.awt.image.*;
  import java.io.*;
  import javax.imageio.*;
  import javax.swing.*;

/**
 * This class demonstrates how to load an Image from an external file
*/
public class LoadImageApp extends Component {

   BufferedImage img;

public void paint(Graphics g) {
    g.drawImage(img, 0, 0, null);
}

public LoadImageApp() {
   try {
       img = ImageIO.read(new File("strawberry.jpg"));
   } catch (IOException e) {
   }

}

public Dimension getPreferredSize() {
    if (img == null) {
         return new Dimension(100,100);
    } else {
       return new Dimension(img.getWidth(null), img.getHeight(null));
   }
}

public static void main(String[] args) {

    JFrame f = new JFrame("Load Image Sample");

    f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

    f.add(new LoadImageApp());
    f.pack();
    f.setVisible(true);
}
}

what i want is the image code read the file.aboslutepath and load the picture when i click it


问:
html link tag color not changing after clicked
Link color not changing after i clicked.
I used side navigation bar css style with links.
Here is my css styling:

i tried with active but still not working.

```<code>.sidenav
{
height: 100%;
width: 200px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #06799f;
overflow-x: hidden;
padding-top: 20px;
}

.sidenav a
{
padding: 15px 20px 4px 18px;
text-decoration: none;
font-size: 25px;
color: #f1f1f1;
display: block;
}

.sidenav a:hover
{
color: #000000;
}

.sidenav a: active
{
color: black;
}

@media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}
</code>```

expected:
is the change of link color when cliked

答:
You have to change the visited color, in anchor tag, by using css,
example given below,</p>

```<code>a:visited {
color: #999999;
}
</code>```

Body:
Link color not changing after i clicked.
I used side navigation bar css style with links.
Here is my css styling:

i tried with active but still not working.

.sidenav
{
height: 100%;
width: 200px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #06799f;
overflow-x: hidden;
padding-top: 20px;
}

.sidenav a
{
padding: 15px 20px 4px 18px;
text-decoration: none;
font-size: 25px;
color: #f1f1f1;
display: block;
}

.sidenav a:hover
{
color: #000000;
}

.sidenav a: active
{
color: black;
}

@media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}

expected:
is the change of link color when cliked

Body:
You have to change the visited color, in anchor tag, by using css,
example given below,

a:visited {
color: #999999;
}


问:
Can floating point numbers ending with `.0` be considered as mathematical integers
We all know that using floating point numbers can lead to strange results:

```<code>>>> 0.1*3
0.30000000000000004
</code>```

My question: can all floating point numbers ending with .0 be considered as mathematical integers?

My use case:

```<code>>>> x = 3.4296875
>>> 2*x*(128*x-695)+1856
100.0
</code>```

Is it possible to assert that there is no quirk and that the result is a true and precise 100? I mean without doing the calculation by hand!

Thanks!

答:
There are several possible interpretations to this question or variant questions that might be asked, so I have listed some and addressed them individually.

If the fractional portion of a floating-point number is zero, does the number represent a mathematical integer?

Yes. Per the IEEE-754 floating-point standard, and commonly with other floating-point formats, a floating-point object represents a single specific number (or an infinity or a NaN). It does not represent an interval of numbers. So, if a floating-point object is not a NaN or infinity, and its fractional portion is zero, then the value it represents is an integer.

When proofs are written about floating-point arithmetic, the fact that various values are integers is commonly used as part of a proof.

If the result of a floating-point calculation is an integer, would the same calculation performed with real-number arithmetic produce an integer?

Not in general. Due to limited precision and rounding, floating-point calculations and real-number calculations may differ by arbitrary amounts.

In specific cases, it may be possible to analyze the floating-point operations and derive statements about what the floating-point results imply about the real-number results.

If a floating-point number is displayed with “.0”, is it an integer?

Not necessarily. When floating-point numbers are formatted for display, they are commonly rounded to a limited number of decimal digits. This may conceal the exact value, and some numbers with non-zero fraction portions may be displayed with “.0”.

If a floating-point number is an integer, can it be used as an integer type?

This depends on the programming language being used. In strongly typed languages, no, the value remains a floating-point type. In scripting languages, it is somewhat common to have some flexibility in using floating-point results as integers.

In the code in the question, is the result an integer?

In the code shown in the question, there are no rounding errors. The value for x, 3.4296875, is exactly 439/128, and this is representable without error in all common floating-point formats. So multiplying it by 128 produces an exact result, 439. Subtracting 695 from that produces −256, and multiplying 2*x*-256 produces exactly −1756, and then adding 1856 produces exactly 100. It is an integer. This may not be true in other cases where non-integer data is used.

Body:
We all know that using floating point numbers can lead to strange results:

>>> 0.1*3
0.30000000000000004

My question: can all floating point numbers ending with .0 be considered as mathematical integers?

My use case:

>>> x = 3.4296875
>>> 2*x*(128*x-695)+1856
100.0

Is it possible to assert that there is no quirk and that the result is a true and precise 100? I mean without doing the calculation by hand!

Thanks!


问:
Google Firebase Error(Function returned undefined, expected Promise or value)
I'm developing Server with Firebase.

I had copied Google Developer's Video on Youtube.

It works well, but on log there is an error:

Function returned undefined, expected Promise or value

It says function returned undefined, but I make function return a promise `set``

How can I solve this?

```<code>function sanitize(s) {
    var sanitizedText = s;
    console.log('sanitize params: ', sanitizedText);
    sanitizedText = sanitizedText.replace(/\bstupid\b/ig, "wonderful");
    return sanitizedText;
}
exports.sanitizePost = functions.database
    .ref('/posts/{pushId}')
    .onWrite(event => {
        const post = event.data.val();
        if (post.sanitized) return;

        console.log('Sanitizing new post', event.params.pushId);
        console.log(post);
        post.sanitized = true;
        post.title = sanitize(post.title);
        post.body = sanitize(post.body);
        return event.data.ref.set(post);
    })
</code>```

I'm beginner of Firebase, Nodejs.

答:
Adding to what @bob-snyder said, your problem is that your returning undefined under a condition.

```<code>if (post.sanitized) return;
</code>```

My suggestion is to use a single exit point, which is a common tip when programming. Article.

Example

```<code>// code...
const SUCCESS_CODE = 0;

exports.sanitizePost = functions.database
    .ref('/posts/{pushId}')
    .onWrite(event => {
        const post = event.data.val();

        let response = Promise.resolve(SUCCESS_CODE);

        if (!post.sanitized) {
            console.log('Sanitizing new post', event.params.pushId);
            console.log(post);
            post.sanitized = true;
            post.title = sanitize(post.title);
            post.body = sanitize(post.body);
            response = event.data.ref.set(post);
        }

        return response;
    })
</code>```

Body:
I'm developing Server with Firebase.

I had copied Google Developer's Video on Youtube.

It works well, but on log there is an error:

Function returned undefined, expected Promise or value

It says function returned undefined, but I make function return a promise `set``

How can I solve this?

function sanitize(s) {
    var sanitizedText = s;
    console.log('sanitize params: ', sanitizedText);
    sanitizedText = sanitizedText.replace(/\bstupid\b/ig, "wonderful");
    return sanitizedText;
}
exports.sanitizePost = functions.database
    .ref('/posts/{pushId}')
    .onWrite(event => {
        const post = event.data.val();
        if (post.sanitized) return;

        console.log('Sanitizing new post', event.params.pushId);
        console.log(post);
        post.sanitized = true;
        post.title = sanitize(post.title);
        post.body = sanitize(post.body);
        return event.data.ref.set(post);
    })

I'm beginner of Firebase, Nodejs.

Body:
Adding to what @bob-snyder said, your problem is that your returning undefined under a condition.

if (post.sanitized) return;

My suggestion is to use a single exit point, which is a common tip when programming. Article.

Example

// code...
const SUCCESS_CODE = 0;

exports.sanitizePost = functions.database
    .ref('/posts/{pushId}')
    .onWrite(event => {
        const post = event.data.val();

        let response = Promise.resolve(SUCCESS_CODE);

        if (!post.sanitized) {
            console.log('Sanitizing new post', event.params.pushId);
            console.log(post);
            post.sanitized = true;
            post.title = sanitize(post.title);
            post.body = sanitize(post.body);
            response = event.data.ref.set(post);
        }

        return response;
    })


问:
Select the correct element
I'm trying to setup with GTM a event when someone add this product to 'my favourite' section. I get all the elements to setup the event except the 'product name'.

The url is this -> https://www.silversanz.com/categoria/1/subcategoria/10/productos

Here are some code:

```<code><article class="product cmp-product   " data-product-id="2166" data-gtm-name="Funda Shockwave anti-impactos iPad 9.7\" Silver HT" data-gtm-id="111943640199" data-gtm-price="24.1879" data-gtm-brand="Silver HT" data-gtm-category="Apple-ipad" data-gtm-variant="" data-gtm-list="Fundas tablets" data-gtm-position="1" id="cmp-product_1" data-state="rendered">
    <a href="/producto/2166" class="product__content-link" title="Funda Shockwave anti-impactos iPad 9.7" Silver HT">
      <section class="product__content">
        <div class="img-wrapper">
          <img alt="Funda Shockwave anti-impactos iPad 9.7" Silver HT | Silver Sanz" src="//s3-eu-west-1.amazonaws.com/silversanz.com/product_images/images/product_images_2533_grid.png?1548836431" class="">
        </div>
        <h4 class="title">Funda Shockwave anti-impactos iPad 9.7" Silver HT</h4>
      </section>
    </a>

<article class="product cmp-product   " data-product-id="519" data-gtm-name="Funda Wave azul marino para iPad Air 1,2, y iPad Pro 9,7\"" data-gtm-id="111933840199" data-gtm-price="19.9892" data-gtm-brand="Silver HT" data-gtm-category="Apple-ipad" data-gtm-variant="" data-gtm-list="Fundas tablets" data-gtm-position="2" id="cmp-product_2" data-state="rendered">
    <a href="/producto/519" class="product__content-link" title="Funda Wave azul marino para iPad Air 1,2, y iPad Pro 9,7"">
      <section class="product__content">
        <div class="img-wrapper">
          <img alt="Funda  iPad Air 1,2,  iPad Pro 9,7" src="//s3-eu-west-1.amazonaws.com/silversanz.com/product_images/images/product_images_1378_grid.png?1528287248" class="">
        </div>
        <h4 class="title">Funda Wave azul marino para iPad Air 1,2, y iPad Pro 9,7"</h4>
      </section>
    </a>
</code>```

With tihis code, I tried in GTM to make an Element Dom Variable to get the title with this element selector -> article#cmp-product_1.product.cmp-product

But my problem is that the number, in this case the 1, is depending of the product's position in the grid, therefore, with the 1, the variable only get the name of first grid product.

How can I get the product name correctly?

Thanks in advance!

答:
If you would like your CSS to select any element which has an id which starts with

```<code>cmp-product_
</code>```

then the selector is:

```<code>[id^="cmp-product_"]
</code>```

In this case ^= means any id beginning with these characters.

Further Reading on Attribute Selectors:

https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

Title: Select the correct element

Body:
I'm trying to setup with GTM a event when someone add this product to 'my favourite' section. I get all the elements to setup the event except the 'product name'.

The url is this -> https://www.silversanz.com/categoria/1/subcategoria/10/productos

Here are some code:

Funda Shockwave anti-impactos iPad 9.7" Silver HT

Funda Wave azul marino para iPad Air 1,2, y iPad Pro 9,7"

With tihis code, I tried in GTM to make an Element Dom Variable to get the title with this element selector -> article#cmp-product_1.product.cmp-product

But my problem is that the number, in this case the 1, is depending of the product's position in the grid, therefore, with the 1, the variable only get the name of first grid product.

How can I get the product name correctly?

Thanks in advance!

Body:
If you would like your CSS to select any element which has an id which starts with

cmp-product_

then the selector is:

[id^="cmp-product_"]

In this case ^= means any id beginning with these characters.

Further Reading on Attribute Selectors:

https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors


问:
Asp.net .core web api versioning does not work for Url path segment
I searched for my problem beforehand in various sources but the answers did not provide me with a solution.

I implemetend Url based web api versioning in a .net core 2.2 project with the way presented here. The version that I used for versioning is the latest Microsoft.AspNetCore.Mvc.Versioning 3.1.2.
I also tried to understand how it works from the following sources: source1, source2, source3, source4.

I am having a ValueController with a GET method in a folder called Initial and a Value2Controller in a folder called New. Both folders are subfolders of the 'Controllers' folder.

The structure is as follows:

The routing in ValueController is
[Route("api/v{version:apiVersion}/[controller]")]

and in Value2Controller is:
[Route("api/v{version:apiVersion}/value")]

I have also set options.EnableEndpointRouting = false; in the Startup.cs and I tried calling api/v1/value or api/v2/value. Both times I get the error: Multiple actions matched. It cannot differentiate between the two controllers actions.

I tried using services.AddApiVersioning(); with no options at all and remove AddVersionedApiExplorer. It does not work. The only thing that works is
putting
[Route("api/v{version:apiVersion}/[controller]")]
in both controllers and make the following api calls:

api/v1/value and api/v2/value2.

The configuration in my startup.cs is as follows:

```<code>services.AddApiVersioning(options =>
    {
        options.ReportApiVersions = true;
        options.AssumeDefaultVersionWhenUnspecified = true;
        options.DefaultApiVersion = new ApiVersion(1, 0);
        options.ApiVersionReader = new UrlSegmentApiVersionReader();
        options.UseApiBehavior = true;
    });

services.AddVersionedApiExplorer(
    options =>
    {
        options.GroupNameFormat = "'v'VVV";
        options.SubstituteApiVersionInUrl = true;
        options.AssumeDefaultVersionWhenUnspecified = true;
        options.DefaultApiVersion = new ApiVersion(1, 0);
    });
</code>```

What am I missing to call either api/v1/value or api/v2/value and go to the correct request?

答:
After some more debugging, I finally figured out why it wasn't working, so I am posting the solution to anyone who will face a similar problem. The problem was within the Controller Inheritance.

I had created a CustomBaseController (which I had completely disregarded as problematic for some reason) with some methods for global exception handling, the inheritance goes as follows:

```<code>[ApiVersionNeutral]
[Route("api/[controller]")]
[ApiController]
CustomBaseController : Controller
</code>```

and

```<code>[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
ValuesController : CustomBaseController { // http method implementations}

[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/values")]
[ApiController]
ValuesController : CustomBaseController { // updated http method implementations}
</code>```

The versioning mechanism did not agree with [ApiVersionNeutral] attribute even though it made sense to me that the the base controller would not need to change at all. Moreover I only had the basic routing in the base controller.

Thus I got the error with "Multiple actions matched".

I also found out that the version 1 controller, can inherit the routing from the base controller and had no reason to have a routing there. For all subsequent controllers, the routing must be:
[Route("api/v{version:apiVersion}/values")].

The working solution along with the initial configuration posted above, is the following:

```<code>[Route("api/v{version:ApiVersion}/[controller]")]
[ApiController]
CustomBaseController: Controller {}

[ApiVersion("1.0")]
[ApiController]
ValuesController: CustomBaseController { //code }

[ApiVersion("2.0")]
[ApiController]
[Route("api/v{version:ApiVersion}/values")]
Values2Controller: CustomBaseController { //code }

[ApiVersion("3.0")]
[ApiController]
[Route("api/v{version:ApiVersion}/values")]
Values3Controller: CustomBaseController { //code }
</code>```

Getting values from the following urls:

```<code>api/v1/values
api/v2/values
api/v3/values
</code>```

Even though my issue was resolved, I still don't understand why [ApiVersionNeutral] would cause the routing to not be able to detect the versions of the other controllers correctly. Any explanation would be highly appreciated.
Thank you @Matt Stannett for your comments, they led me to the right direction.

Body:
I searched for my problem beforehand in various sources but the answers did not provide me with a solution.

I implemetend Url based web api versioning in a .net core 2.2 project with the way presented here. The version that I used for versioning is the latest Microsoft.AspNetCore.Mvc.Versioning 3.1.2.
I also tried to understand how it works from the following sources: source1, source2, source3, source4.

I am having a ValueController with a GET method in a folder called Initial and a Value2Controller in a folder called New. Both folders are subfolders of the 'Controllers' folder.

The structure is as follows:

The routing in ValueController is
[Route("api/v{version:apiVersion}/[controller]")]

and in Value2Controller is:
[Route("api/v{version:apiVersion}/value")]

I have also set options.EnableEndpointRouting = false; in the Startup.cs and I tried calling api/v1/value or api/v2/value. Both times I get the error: Multiple actions matched. It cannot differentiate between the two controllers actions.

I tried using services.AddApiVersioning(); with no options at all and remove AddVersionedApiExplorer. It does not work. The only thing that works is
putting
[Route("api/v{version:apiVersion}/[controller]")]
in both controllers and make the following api calls:

api/v1/value and api/v2/value2.

The configuration in my startup.cs is as follows:

services.AddApiVersioning(options =>
    {
        options.ReportApiVersions = true;
        options.AssumeDefaultVersionWhenUnspecified = true;
        options.DefaultApiVersion = new ApiVersion(1, 0);
        options.ApiVersionReader = new UrlSegmentApiVersionReader();
        options.UseApiBehavior = true;
    });

services.AddVersionedApiExplorer(
    options =>
    {
        options.GroupNameFormat = "'v'VVV";
        options.SubstituteApiVersionInUrl = true;
        options.AssumeDefaultVersionWhenUnspecified = true;
        options.DefaultApiVersion = new ApiVersion(1, 0);
    });

What am I missing to call either api/v1/value or api/v2/value and go to the correct request?

Body:
After some more debugging, I finally figured out why it wasn't working, so I am posting the solution to anyone who will face a similar problem. The problem was within the Controller Inheritance.

I had created a CustomBaseController (which I had completely disregarded as problematic for some reason) with some methods for global exception handling, the inheritance goes as follows:

[ApiVersionNeutral]
[Route("api/[controller]")]
[ApiController]
CustomBaseController : Controller

and

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
ValuesController : CustomBaseController { // http method implementations}

[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/values")]
[ApiController]
ValuesController : CustomBaseController { // updated http method implementations}

The versioning mechanism did not agree with [ApiVersionNeutral] attribute even though it made sense to me that the the base controller would not need to change at all. Moreover I only had the basic routing in the base controller.

Thus I got the error with "Multiple actions matched".

I also found out that the version 1 controller, can inherit the routing from the base controller and had no reason to have a routing there. For all subsequent controllers, the routing must be:
[Route("api/v{version:apiVersion}/values")].

The working solution along with the initial configuration posted above, is the following:

[Route("api/v{version:ApiVersion}/[controller]")]
[ApiController]
CustomBaseController: Controller {}

[ApiVersion("1.0")]
[ApiController]
ValuesController: CustomBaseController { //code }

[ApiVersion("2.0")]
[ApiController]
[Route("api/v{version:ApiVersion}/values")]
Values2Controller: CustomBaseController { //code }

[ApiVersion("3.0")]
[ApiController]
[Route("api/v{version:ApiVersion}/values")]
Values3Controller: CustomBaseController { //code }

Getting values from the following urls:

api/v1/values
api/v2/values
api/v3/values

Even though my issue was resolved, I still don't understand why [ApiVersionNeutral] would cause the routing to not be able to detect the versions of the other controllers correctly. Any explanation would be highly appreciated.
Thank you @Matt Stannett for your comments, they led me to the right direction.


问:
Kotlin compiler throwing annotation errors after changes made to the build.gradle file
I have made the following changes to my build.gradle(app) file.

apply plugin: 'kotlin-kapt'

and

```<code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.recyclerview:recyclerview:1.1.0-alpha05'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'com.google.android.material:material:1.1.0-alpha07'

    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0-alpha01'
    kapt 'androidx.lifecycle:lifecycle-compiler:2.0.0-rc01'

    implementation 'androidx.room:room-runtime:2.1.0-rc01'
    kapt  'androidx.room:room-compiler:2.0.0-rc01'

    implementation 'androidx.paging:paging-runtime:2.1.0'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'

    implementation 'io.sentry:sentry-android:1.7.16'
    implementation 'org.slf4j:slf4j-nop:1.7.25'
}
</code>```

And now the Kotlin compiler is throwing the following error about my EntryDAO.kt and EntryDatabase.kt files:

答:
The error message is quite clear.
The room’s Delete, Update methods signature has changed. It needs to return void or int.

Edit: I checked again, your gradle file mixed androidx library and pre-AndroidX versions of Lifecycle.

Please follow the link to use the correct library combination: https://developer.android.com/jetpack/androidx/releases/lifecycle

Body:
I have made the following changes to my build.gradle(app) file.

apply plugin: 'kotlin-kapt'

and

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.recyclerview:recyclerview:1.1.0-alpha05'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'com.google.android.material:material:1.1.0-alpha07'

    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0-alpha01'
    kapt 'androidx.lifecycle:lifecycle-compiler:2.0.0-rc01'

    implementation 'androidx.room:room-runtime:2.1.0-rc01'
    kapt  'androidx.room:room-compiler:2.0.0-rc01'

    implementation 'androidx.paging:paging-runtime:2.1.0'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'

    implementation 'io.sentry:sentry-android:1.7.16'
    implementation 'org.slf4j:slf4j-nop:1.7.25'
}

And now the Kotlin compiler is throwing the following error about my EntryDAO.kt and EntryDatabase.kt files:


问:
Fragments inside NestedScrollView
I'm trying to put fragments into NestedSrollView. Since it's child of FrameLayout I assume It's possible. This is xml:

```<code><android.support.v4.widget.NestedScrollView
    android:id="@+id/fragmentContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">
</android.support.v4.widget.NestedScrollView>
</code>```

After first transaction everything is fine, fragment is attached to NestedScrollView:

```<code>getSupportFragmentManager()
            .beginTransaction()
            .setCustomAnimations(R.anim.slide_right, R.anim.fade_out, R.anim.slide_left, R.anim.fade_out)
            .add(R.id.fragmentContainer, new RankingFragment(), RANKING_FRAGMENT)
            .commit();
</code>```

But then when I want to replace first fragment I get this error:

ScrollView can host only one direct child

Second transaction:

```<code>getSupportFragmentManager()
                .beginTransaction()
                .setCustomAnimations(R.anim.slide_right, R.anim.fade_out, R.anim.slide_left, R.anim.fade_out)
                .replace(R.id.fragmentContainer, new com.steveq.photoquiz.ui.fragments.PreparationFragment(), PREPARATION_FRAGMENT)
                .addToBackStack(PREPARATION_FRAGMENT)
                .commit();
</code>```

Can anyone help with this?

答:
Try to set this attr 'android:fillViewport' as true, then you will find your fragment is attached to activity</p>

```<code><android.support.v4.widget.NestedScrollView
    android:id="@+id/feed_club_tab_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/feedui_pager_tab"
    android:fillViewport="true"
    app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior"/>
</code>```

Title: Fragments inside NestedScrollView

Body:
I'm trying to put fragments into NestedSrollView. Since it's child of FrameLayout I assume It's possible. This is xml:

<android.support.v4.widget.NestedScrollView
    android:id="@+id/fragmentContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">
</android.support.v4.widget.NestedScrollView>

After first transaction everything is fine, fragment is attached to NestedScrollView:

getSupportFragmentManager()
            .beginTransaction()
            .setCustomAnimations(R.anim.slide_right, R.anim.fade_out, R.anim.slide_left, R.anim.fade_out)
            .add(R.id.fragmentContainer, new RankingFragment(), RANKING_FRAGMENT)
            .commit();

But then when I want to replace first fragment I get this error:

ScrollView can host only one direct child

Second transaction:

getSupportFragmentManager()
                .beginTransaction()
                .setCustomAnimations(R.anim.slide_right, R.anim.fade_out, R.anim.slide_left, R.anim.fade_out)
                .replace(R.id.fragmentContainer, new com.steveq.photoquiz.ui.fragments.PreparationFragment(), PREPARATION_FRAGMENT)
                .addToBackStack(PREPARATION_FRAGMENT)
                .commit();

Can anyone help with this?

Body:
Try to set this attr 'android:fillViewport' as true, then you will find your fragment is attached to activity

<android.support.v4.widget.NestedScrollView
    android:id="@+id/feed_club_tab_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/feedui_pager_tab"
    android:fillViewport="true"
    app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior"/>


问:
.NET library for typesetting documents (PDF or similar)?
EDIT: Better explanation:
Before setting a bounty for this question I want to state clearer what I need:

I need .NET library for generating printable documents. Users should be able to print exactly the same document that they see either using my application or using external tool (like Adobe Acrobat reader). It does not have to be library for generating PDF documents, any document format that satisfies above condition will do.

I need the library to support following scenarios:

Scenario 1:

I create text in some font and color.

I ask the library for the width if this text if printed.

I compute position([X,Y] coordinates on page) of this text based on information from 2. and have the library to print in at this position on a page.

Scenario 2:

I create a text with some parts of it in superscript. All parts of text (normal and superscript) are in same (but variable) font.

I ask the library what is the width if this text when printed. I get correct answer that also takes kerning between normal text and superscript into account.

I compute position([X,Y] coordinates) on a page where this text should be printed (using its width from step 2.). I let the library to print it at this position. Printed on the page it has exactly the width that was returned by library in previous step.

Note for second scenario: I have text with some parts in superscript - example AAA{v-superscript text}BBB (where text in {} braces is superscript). The library needs to be able to print this text using correct kerning. Without right kerning there will be the same gap between last A and first superscript v as between last superscript t and first B. For the user it will look like there is a space between A and superscript v but no space after the last superscript letter. So the text will look ugly. If the library is to handle this correctly it would have method to print the whole text AAA{v-superscript text}BBB at once with specification that a part of it is in superscript. Then it would use correct kerning between normal text and superscript.

Scenario 3:

I want to print picture that consists of lines, circles, filled circles, letters  and bezier curves on exact point in a page. I need to specify width of lines and circles. All shapes needs to be printed in pixel precision.

The library should be free of charge and not GPL (LGPL is ok). Is there something that allows me to do what I need ? Can it be done with iTextSharp (version 4.1.6 that is LGPL not AGPL)? Or perhaps with Fixed document ? Thank you for any suggestions.

Original question:

I need to typeset complex documents in .NET (C#) application for the user. Primary use of those documents will be for printing.

Documents will contain text and simple generated graphics. Layout of text and graphic will be complex and needs to be computed (in another words text position in document needs to be controlled by my code, it will not be done automatically by chosen library).

Here are my API requirements:

function that returns exact width for given string and given font in which text should appear

ability to position text to exact position on the page

have text with some part of it in super script

function to get exact width of some text that has some part of it in superscript

ability to add pictures or even better option to draw simple graphics (line of given thickness, filled circle of given radius/diameter)

It does not have to be library for creating PDF documents - any other "what you see is what will be printed" document format will also do. If there is WPF component that can displays such documents it is an advantage. I know there is iTextSharp but is not easy to achieve 4. requirement with iTextSharp. Of course some PDF generation library that satisfies requirements above will be great solution too.

Thank you for ANY suggestions, I'm also happy to provide details or clearer explanation.

答:
You can look to Docotic.Pdf Library (disclaimer: I work for Bit Miracle).
It has user-friendly API and good set of samples that you can view online or run in sample viewer application.

Also it satisfies your requirements:

function that returns exact width for given string and given font in which text should appear

You can use the PdfCanvas.MeasureText() method for this.

ability to position text to exact position on the page

There are many overloads that allows to show text in arbitrary position or area.

http://bitmiracle.com/pdf-library/help/pdfcanvas.drawstring.aspx

http://bitmiracle.com/pdf-library/help/pdfcanvas.drawtext.aspx

have text with some part of it in super script

The PdfCanvas.TextRise property allows to show superscript text. You can use it in combination with PdfCanvas.FontSize property for control a size of superscript text.
The sample:
http://bitmiracle.com/pdf-library/help/text-rise.aspx

function to get exact width of some text that has some part of it in superscript

If you will use different font or font size for superscript text the direct call of PdfCanvas.MeasureText() method will produce incorrect results.

There are workarounds:

-measure each part of string drawn with different fonts separately and then sum all widths.

-if you want to get width of drawn text you can simply subtract initial text position from the final text position after drawing.

ability to add pictures or even better option to draw simple graphics (line of given thickness, filled circle of given radius/diameter)

Supported. Look at these samples:

https://github.com/BitMiracle/Docotic.Pdf.Samples/tree/master/Samples/Graphics

https://github.com/BitMiracle/Docotic.Pdf.Samples/tree/master/Samples/Images

PDF viewer component is in our plans, but currently Docotic.Pdf doesn't offer such functionality.

Update: You can now rasterize, render, or print PDF documents using Docotic.Pdf. Look at the following articles:

https://bitmiracle.com/pdf-library/convert-pdf-to-image.aspx

https://bitmiracle.com/pdf-library/draw-print-pdf.aspx