问:
Groovy HTTP Builder: Empty POST response causes SAXParseException
I am implementing REST client for YouTrack API. I am getting an exception whenever my POST requests return empty response (there's just a valid header). The HTTP status code is 200.
That's the stacktrace:

```<code>[Fatal Error] :-1:-1: Premature end of file.
gru 03, 2013 10:34:49 AM groovyx.net.http.HTTPBuilder doRequest
WARNING: Error parsing 'application/xml; charset=UTF-8' response
org.xml.sax.SAXParseException; Premature end of file.
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at groovy.util.XmlSlurper.parse(XmlSlurper.java:181)
at groovy.util.XmlSlurper.parse(XmlSlurper.java:234)
at groovyx.net.http.ParserRegistry.parseXML(ParserRegistry.java:267)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1085)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:952)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:909)
at groovy.lang.Closure.call(Closure.java:423)
at groovy.lang.Closure.call(Closure.java:439)
at groovyx.net.http.HTTPBuilder.parseResponse(HTTPBuilder.java:561)
at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:494)
at groovyx.net.http.RESTClient.post(RESTClient.java:140)
at groovyx.net.http.RESTClient$post.callCurrent(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:49)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:133)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
at groovy.YouTrackRest.releaseVersion(YouTrackRest.groovy:66)
at groovy.YouTrackRest$releaseVersion$0.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at YouTrack.run(YouTrack.groovy:13)
[...]
</code>```

I have debugged and found out what's the direct cause for that. I noticed that in groovyx.net.http.HTTPBuilder:492 before parsing it is checked whether response is empty but in my case the call entity.getContentLength() returns -1. After Apache documentation for HttpEntity
the number of bytes of the content, or a negative number if unknown

My client implementation is very plain. I have worked the problem around by catching the HttpResponseException and asserting statusCode 200. I am still getting the stacktrace in my console, but that's probably just the logger setting.

My implementation:

```<code>import groovyx.net.http.RESTClient

class YouTrackRest extends RESTClient {
[...]
def activateVersion(versionNumber) {
    try {
        post(
                path: getVersionPath(versionNumber),
                body: [
                        colorIndex: ACTIVE_COLOR_INDEX,
                        released: false,
                        releaseDate: null,
                        archived: false,
                        newName: versionNumber

                ]
        )
    } catch (HttpResponseException ex) {
        assert ex.response.status == 200
    }
}
</code>```

EDIT:
These are the response headers

```<code>Server: nginx
Date: Fri, 06 Dec 2013 10:36:10 GMT
Content-Type: application/xml; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
Set-Cookie: JSESSIONID=ny2s3cxwsvveya6vgwj2fmig;Path=/youtrack
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Cache-Control: no-cache, no-store, no-transform, must-revalidate
</code>```

Present Transfer-Encoding: chunked header explains missing 'Content-Length' header. That has to be the reason for unknown Content Length.
Now, according to Wikipedia The data transfer is terminated by a final chunk of length zero. So maybe is this case the first chunk is also the last one?

Both, the Web Server and the Http client library are third party for me. I would like to raise an issue by whoever misbehaves:

either YouTrack REST WS promisses XML and returns nothing

or groovyx.net.http.HTTPBuilder fails to process chunked encoded responses.

I will be very helpful for some expertise to help me understand the problem.

答:
I just ran into this same problem using httpbuilder. I was able to work around it with:

```<code>def service = new HTTPBuilder(...)
service.request(Method.POST, ContentType.JSON) {
    uri.path = ...
    body = ...

    response.'200' = { resp ->
            logInfo resp.statusLine
    }

    response.success = { resp, result ->
            logInfo resp.statusLine
    }

    response.failure = { resp ->
            logError resp.statusLine
    }
}
</code>```

Essentially do not try to parse the body, if response is 200.

Body:
I am implementing REST client for YouTrack API. I am getting an exception whenever my POST requests return empty response (there's just a valid header). The HTTP status code is 200.
That's the stacktrace:

[Fatal Error] :-1:-1: Premature end of file.
gru 03, 2013 10:34:49 AM groovyx.net.http.HTTPBuilder doRequest
WARNING: Error parsing 'application/xml; charset=UTF-8' response
org.xml.sax.SAXParseException; Premature end of file.
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at groovy.util.XmlSlurper.parse(XmlSlurper.java:181)
at groovy.util.XmlSlurper.parse(XmlSlurper.java:234)
at groovyx.net.http.ParserRegistry.parseXML(ParserRegistry.java:267)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1085)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:952)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:909)
at groovy.lang.Closure.call(Closure.java:423)
at groovy.lang.Closure.call(Closure.java:439)
at groovyx.net.http.HTTPBuilder.parseResponse(HTTPBuilder.java:561)
at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:494)
at groovyx.net.http.RESTClient.post(RESTClient.java:140)
at groovyx.net.http.RESTClient$post.callCurrent(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:49)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:133)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
at groovy.YouTrackRest.releaseVersion(YouTrackRest.groovy:66)
at groovy.YouTrackRest$releaseVersion$0.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at YouTrack.run(YouTrack.groovy:13)
[...]

I have debugged and found out what's the direct cause for that. I noticed that in groovyx.net.http.HTTPBuilder:492 before parsing it is checked whether response is empty but in my case the call entity.getContentLength() returns -1. After Apache documentation for HttpEntity
the number of bytes of the content, or a negative number if unknown

My client implementation is very plain. I have worked the problem around by catching the HttpResponseException and asserting statusCode 200. I am still getting the stacktrace in my console, but that's probably just the logger setting.

My implementation:

import groovyx.net.http.RESTClient

class YouTrackRest extends RESTClient {
[...]
def activateVersion(versionNumber) {
    try {
        post(
                path: getVersionPath(versionNumber),
                body: [
                        colorIndex: ACTIVE_COLOR_INDEX,
                        released: false,
                        releaseDate: null,
                        archived: false,
                        newName: versionNumber

                ]
        )
    } catch (HttpResponseException ex) {
        assert ex.response.status == 200
    }
}

EDIT:
These are the response headers

Server: nginx
Date: Fri, 06 Dec 2013 10:36:10 GMT
Content-Type: application/xml; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
Set-Cookie: JSESSIONID=ny2s3cxwsvveya6vgwj2fmig;Path=/youtrack
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Cache-Control: no-cache, no-store, no-transform, must-revalidate

Present Transfer-Encoding: chunked header explains missing 'Content-Length' header. That has to be the reason for unknown Content Length.
Now, according to Wikipedia The data transfer is terminated by a final chunk of length zero. So maybe is this case the first chunk is also the last one?

Both, the Web Server and the Http client library are third party for me. I would like to raise an issue by whoever misbehaves:

either YouTrack REST WS promisses XML and returns nothing

or groovyx.net.http.HTTPBuilder fails to process chunked encoded responses.

I will be very helpful for some expertise to help me understand the problem.

Body:
I just ran into this same problem using httpbuilder. I was able to work around it with:

def service = new HTTPBuilder(...)
service.request(Method.POST, ContentType.JSON) {
    uri.path = ...
    body = ...

    response.'200' = { resp ->
            logInfo resp.statusLine
    }

    response.success = { resp, result ->
            logInfo resp.statusLine
    }

    response.failure = { resp ->
            logError resp.statusLine
    }
}

Essentially do not try to parse the body, if response is 200.


来源: stackexchange

问:
How to get the filename without the extension in Java?
Can anyone tell me how to get the filename without the extension?
Example:</p>

```<code>fileNameWithExt = "test.xml";
fileNameWithOutExt = "test";
</code>```

答:
Keeping it simple, use Java's String.replaceAll() method as follows:

```<code>String fileNameWithExt = "test.xml";
String fileNameWithoutExt
   = fileNameWithExt.replaceAll( "^.*?(([^/\\\\\\.]+))\\.[^\\.]+$", "$1" );
</code>```

This also works when fileNameWithExt includes the fully qualified path.

ContentLicense: CC BY-SA 3.0

Body:
Can anyone tell me how to get the filename without the extension?
Example:

fileNameWithExt = "test.xml";
fileNameWithOutExt = "test";

Body:
Keeping it simple, use Java's String.replaceAll() method as follows:

String fileNameWithExt = "test.xml";
String fileNameWithoutExt
   = fileNameWithExt.replaceAll( "^.*?(([^/\\\\\\.]+))\\.[^\\.]+$", "$1" );

This also works when fileNameWithExt includes the fully qualified path.

ContentLicense: CC BY-SA 4.0


问:
How do I convert this loop into a LINQ expression?
How do I convert this loop into a LINQ expression?</p>

```<code>foreach (var user in customer.Users)
{
    repositoryManager.Users.Delete(user);
}
</code>```

答:
You can't.

LINQ is for Queries, not for actions.

Body:
How do I convert this loop into a LINQ expression?

foreach (var user in customer.Users)
{
    repositoryManager.Users.Delete(user);
}


问:
query retrieve data
i have data in a table like this

```<code>insert into mytable (col1,col2,col3,col4) values(a,2,100,501);
insert into mytable (col1,col2,col3,col4) values(a,4,200,555);
insert into mytable (col1,col2,col3,col4) values(a,3,80,500);
insert into mytable (col1,col2,col3,col4) values(a,3,44,443);
</code>```

Now i want a one select to retrieve data like this:

amnt1 will assigned to col3 if col1=a and col2=2.

amnt2 will assigned to col3 if col1=a and col2=3 and col4=500.

Results:

```<code>| amnt1 | amnt2 |
|---------------|
|   100 |    80 |
</code>```

thnx

答:
Is this what you want?

```<code>select
    (select col3 from mytable where col1 = 'a' and col2 = 2) amnt1,
    (select col3 from mytable where col1 = 'a' and col2 = 3 and col4 = 500) amnt2
from dual
</code>```

Note that this requires that only one record matches the two sets of conditions. In the event of multiple matching records, the above query would raise a runtime error; to avoid that, you can use conditional aggregation instead:

```<code>select
    sum(case when col1 = 'a' and col2 = 2 then col3 end) amnt1,
    sum(case when col1 = 'a' and col2 = 3 and col4 = 500 then col3 end) amnt2
from mytable
</code>```

Title: query retrieve data

Body:
i have data in a table like this

insert into mytable (col1,col2,col3,col4) values(a,2,100,501);
insert into mytable (col1,col2,col3,col4) values(a,4,200,555);
insert into mytable (col1,col2,col3,col4) values(a,3,80,500);
insert into mytable (col1,col2,col3,col4) values(a,3,44,443);

Now i want a one select to retrieve data like this:

amnt1 will assigned to col3 if col1=a and col2=2.

amnt2 will assigned to col3 if col1=a and col2=3 and col4=500.

Results:

| amnt1 | amnt2 |
|---------------|
|   100 |    80 |

thnx

Body:
Is this what you want?

select
    (select col3 from mytable where col1 = 'a' and col2 = 2) amnt1,
    (select col3 from mytable where col1 = 'a' and col2 = 3 and col4 = 500) amnt2
from dual

Note that this requires that only one record matches the two sets of conditions. In the event of multiple matching records, the above query would raise a runtime error; to avoid that, you can use conditional aggregation instead:

select
    sum(case when col1 = 'a' and col2 = 2 then col3 end) amnt1,
    sum(case when col1 = 'a' and col2 = 3 and col4 = 500 then col3 end) amnt2
from mytable


问:
CakePHP patchEntity() and save() not updating specific fields in database
So I have added a few additional fields to an Orders table, payment_type and order_status.

I have added them to the Accessible array for the related Model, but after a Save(), I'm not seeing the two fields populated in the Database. What could be happening here?

FWIW, here's a print_r() of the Save() return:

```<code>App\Model\Entity\Order Object
(
   [grand_total] => 99.99
   [payment_type] => Paypal
   [order_status] => Accepted
   [transaction_id] => 123
   [[new]] =>
   [[accessible]] => Array
       (
           [grand_total] => 1
           [payment_type] => 1
           [order_status] => 1
           [transaction_id] => 1
       )

   [[dirty]] => Array
       (
       )

   [[original]] => Array
       (
       )

   [[virtual]] => Array
       (
       )

   [[hasErrors]] =>
   [[errors]] => Array
       (
       )

   [[invalid]] => Array
       (
       )

   [[repository]] => Orders
)
</code>```

Strangely though, when I run this command on my local environment, it updates those columns with no issues. Live server and my local are duplicate repositories, so it must be a database or server config setting? And, I can't find anything in the logs pointing to any errors.

Any ideas?

答:
Turns out my live environment ORM cache was still reflecting the old schema.

Until now I had no idea this was a thing, and honestly I'm beyond frustrated not understanding /why/. I'll have to do some reading on this to get a better understanding.

For anyone from the future having the similar issues, cross check your buggy environment's "/tmp/cache/models/" folder and either remove or update the table schema file in question.

Body:
So I have added a few additional fields to an Orders table, payment_type and order_status.

I have added them to the Accessible array for the related Model, but after a Save(), I'm not seeing the two fields populated in the Database. What could be happening here?

FWIW, here's a print_r() of the Save() return:

App\Model\Entity\Order Object
(
   [grand_total] => 99.99
   [payment_type] => Paypal
   [order_status] => Accepted
   [transaction_id] => 123
   [[new]] =>
   [[accessible]] => Array
       (
           [grand_total] => 1
           [payment_type] => 1
           [order_status] => 1
           [transaction_id] => 1
       )

   [[dirty]] => Array
       (
       )

   [[original]] => Array
       (
       )

   [[virtual]] => Array
       (
       )

   [[hasErrors]] =>
   [[errors]] => Array
       (
       )

   [[invalid]] => Array
       (
       )

   [[repository]] => Orders
)

Strangely though, when I run this command on my local environment, it updates those columns with no issues. Live server and my local are duplicate repositories, so it must be a database or server config setting? And, I can't find anything in the logs pointing to any errors.

Any ideas?


问:
Azure functions / Durable Functions / global.asax
I'm attempting to move a web app that I have been working on for some years.  I load up a list of configs in the global.asax for future access.  I see that the global.asax doesn't have an equivalent in durable functions so that's what made me start looking at durable functions; but I'm not sure this is the best way to handle the loads either.  There could be well over 10,000 records that get loaded in my current environment so loading them on the fly wouldn't work well either.

This is a sample of what my global.asax configuration looks like; not that it really matters...:

```<code>            if (query.Count() > 0)
            {
                foreach (var item in query)
                {
                    bool bActive = false;
                    bool.TryParse(item.IsActive.ToString(), out bActive);

                    if (item.ProviderName != string.Empty && bActive)
                    {
                        try
                        {
                            bool bEncrypt = false;
                            bool bSign = false;

                            // yes, I know these are bools anyway; this is to catch possible nulls...
                            bool.TryParse(item.Sign.ToString(), out bSign);
                            bool.TryParse(item.Encrypt.ToString(), out bEncrypt);

                            SConfiguration.AddServiceProvider(
                                new ServiceProvider()
                                {
                                    Name = item.PartnerEntity,
                                    NameIDFormat = item.NameFormat,
                                    SignSAMLResponse = bSign,
                                    Sign = bSign,
                                    Encrypt = bEncrypt

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

So this config needs to persist through multiple http sendoffs (it's SAML).

Is there a way to preload a configuration and have it available to all future azure functions calls?

答:
You can use Dependency Injection with Service lifetime Singleton:

```<code>using System;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Http;
using Microsoft.Extensions.Logging;

[assembly: FunctionsStartup(typeof(MyNamespace.Startup))]

namespace MyNamespace
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {

            builder.Services.AddSingleton<ILoggerProvider, MyLoggerProvider>();
        }
    }
}
</code>```

source: https://learn.microsoft.com/bs-cyrl-ba/azure/azure-functions/functions-dotnet-dependency-injection

Body:
I'm attempting to move a web app that I have been working on for some years.  I load up a list of configs in the global.asax for future access.  I see that the global.asax doesn't have an equivalent in durable functions so that's what made me start looking at durable functions; but I'm not sure this is the best way to handle the loads either.  There could be well over 10,000 records that get loaded in my current environment so loading them on the fly wouldn't work well either.

This is a sample of what my global.asax configuration looks like; not that it really matters...:

            if (query.Count() > 0)
            {
                foreach (var item in query)
                {
                    bool bActive = false;
                    bool.TryParse(item.IsActive.ToString(), out bActive);

                    if (item.ProviderName != string.Empty && bActive)
                    {
                        try
                        {
                            bool bEncrypt = false;
                            bool bSign = false;

                            // yes, I know these are bools anyway; this is to catch possible nulls...
                            bool.TryParse(item.Sign.ToString(), out bSign);
                            bool.TryParse(item.Encrypt.ToString(), out bEncrypt);

                            SConfiguration.AddServiceProvider(
                                new ServiceProvider()
                                {
                                    Name = item.PartnerEntity,
                                    NameIDFormat = item.NameFormat,
                                    SignSAMLResponse = bSign,
                                    Sign = bSign,
                                    Encrypt = bEncrypt

                                });
                        }
                   }

So this config needs to persist through multiple http sendoffs (it's SAML).

Is there a way to preload a configuration and have it available to all future azure functions calls?

Body:
You can use Dependency Injection with Service lifetime Singleton:

using System;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Http;
using Microsoft.Extensions.Logging;

[assembly: FunctionsStartup(typeof(MyNamespace.Startup))]

namespace MyNamespace
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {

            builder.Services.AddSingleton<ILoggerProvider, MyLoggerProvider>();
        }
    }
}

source: https://learn.microsoft.com/bs-cyrl-ba/azure/azure-functions/functions-dotnet-dependency-injection


问:
Formatting multiple arguments passed to a function in Java
Often the number of arguments passed to a function can be large. Consider the following case:

```<code>calculate(dataManager.getLastUpdate().getNumberOfChildren(),
          dataManager.getLastUpdate().getNumberOfParents(),
          dataManager.getLastUpdate().getNumberOfGrandChildren(),
          long milliseconds,
          int somethingelse)
</code>```

Is there a guideline in Java that offers a way to align the arguments? Fitting all arguments in a line would not look pretty.

答:
According to Sun's Java coding conventions, section "Wrapping Lines":

When an expression will not fit on a single line, break it according to these general principles:

Break after a comma.

Break before an operator.

Prefer higher-level breaks to lower-level breaks.

Align the new line with the beginning of the expression at the same level on the previous line.

If the above rules lead to confusing code or to code that’s squished up against the right margin, just indent 8 spaces instead.

The document also includes some examples for method calls:

```<code>function(longExpression1, longExpression2, longExpression3,
         longExpression4, longExpression5);

var = function1(longExpression1,
                function2(longExpression2,
                          longExpression3));
</code>```

Body:
Often the number of arguments passed to a function can be large. Consider the following case:

calculate(dataManager.getLastUpdate().getNumberOfChildren(),
          dataManager.getLastUpdate().getNumberOfParents(),
          dataManager.getLastUpdate().getNumberOfGrandChildren(),
          long milliseconds,
          int somethingelse)

Is there a guideline in Java that offers a way to align the arguments? Fitting all arguments in a line would not look pretty.

Body:
According to Sun's Java coding conventions, section "Wrapping Lines":

When an expression will not fit on a single line, break it according to these general principles:

Break after a comma.

Break before an operator.

Prefer higher-level breaks to lower-level breaks.

Align the new line with the beginning of the expression at the same level on the previous line.

If the above rules lead to confusing code or to code that’s squished up against the right margin, just indent 8 spaces instead.

The document also includes some examples for method calls:

function(longExpression1, longExpression2, longExpression3,
         longExpression4, longExpression5);

var = function1(longExpression1,
                function2(longExpression2,
                          longExpression3));


问:
Hugo theme link refers to container port in Docker/Nginx
I've got a simple static site, generated with Hugo, that I'm building to a Docker container running Nginx. Nginx is listening on port 90. I'm encountering strange behavior where certain links try to open the container port rather than the host port (in the case of localhost, it's 8000). So for example, this link:

```<code><a href="/documents">Docs</a>
</code>```

...when moused-over shows that it will attempt to open localhost:8000/documents, which is correct, but when clicked it attempts instead to open http://localhost:90/documents/ (If I manually change the URL in the browser to http://localhost:8000/documents/, it responds fine.)

What makes this even stranger:

Only certain links, specifically in the header menu, do this.

I've used dozens of Hugo themes, and I've only encountered this issue with one of them: ZDoc. Could it be specific to this theme? That seems strange to me.

What could be causing this? I'm struggling to even know what this phenomenon is called. "Host/container port confusion"?

I'm certain it's not a misconfiguration of Nginx or Docker. I'm exposing port 90 properly in my Dockerfile:

```<code>EXPOSE 90
</code>```

nginx.conf is set to listen on that port:

```<code>http {
    include    /etc/nginx/mime.types;
    sendfile on;
    server {
        root /usr/share/nginx/html/;
        index index.html;
        server_name localhost;
        listen 90;
    }
}
</code>```

And I'm starting the Docker container with the host port 8000 forwarding to the port Nginx is listening on:

```<code>docker run --name my-simple-site -p 8000:90 -d simple-site

$ docker ps
CONTAINER ID    IMAGE          COMMAND                  CREATED          STATUS          PORTS                   NAMES
de9cd1526034    simple-site    "nginx -g 'daemon of…"   41 minutes ago   Up 41 minutes   0.0.0.0:8000->90/tcp    my-simple-site
</code>```

答:
Strangely, the fix for this was to change the link to point directly to the file: Docs

I'm unclear why and would love some insight into this. Does Nginx infer a port when pointing to a directory?

Body:
I've got a simple static site, generated with Hugo, that I'm building to a Docker container running Nginx. Nginx is listening on port 90. I'm encountering strange behavior where certain links try to open the container port rather than the host port (in the case of localhost, it's 8000). So for example, this link:

Docs

...when moused-over shows that it will attempt to open localhost:8000/documents, which is correct, but when clicked it attempts instead to open http://localhost:90/documents/ (If I manually change the URL in the browser to http://localhost:8000/documents/, it responds fine.)

What makes this even stranger:

Only certain links, specifically in the header menu, do this.

I've used dozens of Hugo themes, and I've only encountered this issue with one of them: ZDoc. Could it be specific to this theme? That seems strange to me.

What could be causing this? I'm struggling to even know what this phenomenon is called. "Host/container port confusion"?

I'm certain it's not a misconfiguration of Nginx or Docker. I'm exposing port 90 properly in my Dockerfile:

EXPOSE 90

nginx.conf is set to listen on that port:

http {
    include    /etc/nginx/mime.types;
    sendfile on;
    server {
        root /usr/share/nginx/html/;
        index index.html;
        server_name localhost;
        listen 90;
    }
}

And I'm starting the Docker container with the host port 8000 forwarding to the port Nginx is listening on:

docker run --name my-simple-site -p 8000:90 -d simple-site

$ docker ps
CONTAINER ID    IMAGE          COMMAND                  CREATED          STATUS          PORTS                   NAMES
de9cd1526034    simple-site    "nginx -g 'daemon of…"   41 minutes ago   Up 41 minutes   0.0.0.0:8000->90/tcp    my-simple-site

Body:
Strangely, the fix for this was to change the link to point directly to the file: <a href="/documents/index.html">Docs</a>

I'm unclear why and would love some insight into this. Does Nginx infer a port when pointing to a directory?


问:
Does spark load the entire table in memory if select condition is based on RDD transformation?
```<code>DataSet<Row> a = spark.read().format("com.memsql.spark.connector").option("query", "select * from a");
a = a.filter((row)-> row.x = row.y)
Sring xstring = "...select all values of x from a and make comma separated string"
DataSet<Row> b = spark.read().format("com.memsql.spark.connector").option("query", "select * from b where x in " + xstring);
b.show()
</code>```

In this case as spark would load the entire b table in memory and then filter out xtring rows or it actually create that xstring and then load a subset of table b in memory when we call show

答:
When memsql is queried using option("query", "select * from .......") the entire result (not table) will be read from memsql into executors. The MemSQL Spark Connector 2.0 supports column and filter pushdown for which the SQL needs to have the filter and join condition rather than applying filter and join on dataframe. In your example predicate push down will be used. In your example - entire table 'a' will be read because there is no filter condition, xstring will be build, then only that part of table 'b' is read that matches x in (...) condition.

Here is memsql documentation explaining this.

Body:
DataSet<Row> a = spark.read().format("com.memsql.spark.connector").option("query", "select * from a");
a = a.filter((row)-> row.x = row.y)
Sring xstring = "...select all values of x from a and make comma separated string"
DataSet<Row> b = spark.read().format("com.memsql.spark.connector").option("query", "select * from b where x in " + xstring);
b.show()

In this case as spark would load the entire b table in memory and then filter out xtring rows or it actually create that xstring and then load a subset of table b in memory when we call show


问:
Declaring an int in C++ with <<
Can someone explain to me what this declaration means in C++; I have never seen something declared like this, and was just confused on what it meant and how it works:

```<code>int ix((dx > 0) - (dx < 0));
</code>```

Same with this declaration, too:

```<code>int error(dy - (dx >> 1));
</code>```

答:
You may declare a scalar object using an initializer in parentheses or braces.

In this declaration

```<code>int ix((dx > 0) - (dx < 0));
</code>```

there is used the expression (dx > 0) - (dx < 0) as an initializer.

if dx is greater than 0 then the sub-expression (dx > 0) evaluates to boolean true while this sub-expression (dx < 0) to boolean false. As a result the expression is true - false where the boolean values are implicitly converted to 1 for true and to 0 for false. So you will get 1 if dx is greater than 0.

If dx is less than 0 you will get -1.

If dx is equal to 0 then the both sub-expressions evaluate to false and you will get 0.

So the variable ix is initialized either 1 or 0 or -1 depending on whether dx is greater than equal to or less than 0.

In this declaration

```<code>int error(dy - (dx >> 1));
</code>```

there is used the bit-wise shift right operator dx >> 1 that shifts bits of the variable dx one position right. It is equivalent to the expression dx / 2.

For example if dx is equal to 6 then its binary representation is (I will use only one byte for simplicity)

```<code>0000 0110
</code>```

shifting right one position you will get

```<code>0000 0011
</code>```

that is the binary representation of 3.

It is difficult to say why this initializer is used in this declaration

```<code>int error(dy - (dx >> 1));
</code>```

without knowing the context where it is used.

Title: Declaring an int in C++ with <<

Body:
Can someone explain to me what this declaration means in C++; I have never seen something declared like this, and was just confused on what it meant and how it works:

int ix((dx > 0) - (dx < 0));

Same with this declaration, too:

int error(dy - (dx >> 1));

Body:
You may declare a scalar object using an initializer in parentheses or braces.

In this declaration

int ix((dx > 0) - (dx < 0));

there is used the expression (dx > 0) - (dx < 0) as an initializer.

if dx is greater than 0 then the sub-expression (dx > 0) evaluates to boolean true while this sub-expression (dx < 0) to boolean false. As a result the expression is true - false where the boolean values are implicitly converted to 1 for true and to 0 for false. So you will get 1 if dx is greater than 0.

If dx is less than 0 you will get -1.

If dx is equal to 0 then the both sub-expressions evaluate to false and you will get 0.

So the variable ix is initialized either 1 or 0 or -1 depending on whether dx is greater than equal to or less than 0.

In this declaration

int error(dy - (dx >> 1));

there is used the bit-wise shift right operator dx >> 1 that shifts bits of the variable dx one position right. It is equivalent to the expression dx / 2.

For example if dx is equal to 6 then its binary representation is (I will use only one byte for simplicity)

0000 0110

shifting right one position you will get

0000 0011

that is the binary representation of 3.

It is difficult to say why this initializer is used in this declaration

int error(dy - (dx >> 1));

without knowing the context where it is used.


问:
Unable to print output on powershell window which will be used for further read-host input
AM trying to get an array output (which has names and indexing) on PS screen so that user can choose from the options he has for input to next steps (Read-host)
Am adding indexing (index numbering) to an array so I can output index number and Name which can be used by used to input for next steps.
But the output on screen is not recorded and is stored somewhere on background and is given along with my "return" statement for that function at the very end of script

Need help form you folks to see why the output is not written on powershell screen (both ISE and powershell 5.1)

```<code>function CLoneBranch
{
Param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)][ValidateNotNullOrEmpty()]
[string]$url,
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=1)][ValidateNotNullOrEmpty()]
[String]$GitConnectionUserName,
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=2)][ValidateNotNullOrEmpty()]
[securestring]$GitConnectionUserPassword
)
try
{
    $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($GitConnectionUserPassword)
    $plainpwd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
    # Retrieve list of all repositories
    $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $GitConnectionUserName,$plainpwd)))
    $headers = @{
        "Authorization" = ("Basic {0}" -f $base64AuthInfo)
        "Accept" = "application/json"}

    Add-Type -AssemblyName System.Web
    $gitcred = ("{0}:{1}" -f  [System.Web.HttpUtility]::UrlEncode($GitConnectionUserName),$plainpwd)

    $resp = Invoke-WebRequest -Headers $headers -Uri ("{0}/_apis/git/repositories?api-version=1.0" -f $url)
    $json = convertFrom-JSON $resp.Content
    If($resp)
    {
        [Array]$RepoArray = Add-IndexNumberToArray ($json.value)

        [int]$Selectedrepo = 0
        # use the current repo if there is only one repo available
        if ($RepoArray.Count -eq 1)
        {
            $Selectedrepo = 1
        }
        while($Selectedrepo -gt $RepoArray.Count -or $Selectedrepo -lt 1)
        {

            Write-host "Please select a Repo from the list"
            $RepoArray | Select-Object IndexNumber , Name | Format-Table -verbose
**###### This is not written on the screen for user to look for what he has to input but some how at the end of function it returns the output using retun statement which I don't want ##########**

            try
            {
                $Selectedrepo = Read-Host "Please enter a selection from 1 to $($RepoArray.count)"
            }
            catch
            {
                Write-Warning -Message 'Invalid option, please try again.'
            }
        }
        if($($RepoArray[$Selectedrepo - 1].Name))
        {
            $RepoName = $($RepoArray[$Selectedrepo - 1].Name)
        }
        #write-verbose "You Selected Repo to download : $RepoName"
    }
}
       catch
 {
     Write-Error " Exception while cloning the repo or a specific branch"
     Write-Error $_.Exception.Message
     Write-Error " ErrorStack: $Error[0]"
     exit 1;
 }
 Return $RepoName
 }

function Add-IndexNumberToArray (
[Parameter(Mandatory=$True)]
[array]$array
)
{
for($i=0; $i -lt $array.Count; $i++)
{
    Add-Member -InputObject $array[$i] -Name "IndexNumber" -Value ($i+1) -MemberType NoteProperty
}
$array
</code>```

}

答:
Distilling your code down to a minimal repro, we get this:

function Invoke-MyFunction
{
   write-host "here 1"
   @("aaa", "bbb") | format-table -Verbose
   write-host "here 2"
   return "ccc"
}

$x = Invoke-MyFunction
"---"
$x
```

<p>which outputs:</p>

```here 1
here 2
---
aaa
bbb
ccc
```

<p>The reason you don't see the output from <code>@("aaa", "bbb") | format-table -Verbose</code> between <code>here 1</code> and <code>here 2</code> on the console is that it's being returned from the function as part of the output pipeline and assigned to <code>$x</code>, and <em>not</em> written to the console inside the <code>Invoke-MyFunction</code> function.</p>

<p>Like most programming languages, PowerShell's <code>return</code> will return a value and exit the function, <em>but</em> you can also stream values into the "output pipeline" by simply not capturing expressions into a variable. For example:</p>

<pre class="lang-bsh prettyprint-override"><code>function Invoke-MultipleOutputs
{
    1
    "aaa"
    return "ccc"
}
$x = Invoke-MultipleOutputs
$x
</code>```

$x will contain an array of values - in this case @( 1, "aaa", "ccc" ).

This is equivalent to

function Invoke-MultipleOutputs
{
    Write-Output 1
    Write-Output "aaa"
    return "ccc"
}
$x = Invoke-MultipleOutputs
$x
```

<p>In your code, your're doing this: <code>$RepoArray | Select-Object IndexNumber , Name | Format-Table -verbose</code> which is converting <code>$RepoArray</code> into a set of formatted table objects, but then because the result is an unassigned expression it's being written to the output pipeline rather than being displayed on the console.</p>

<p>To fix this, you need to render the output of <code>Format-Table</code> as a string and then write it to the console which you can do with <code>out-host</code>...</p>

<pre class="lang-bsh prettyprint-override"><code>$RepoArray | Select-Object IndexNumber , Name | Format-Table -verbose | out-host
</code>```

or out-string...

$text = $RepoArray | Select-Object IndexNumber , Name | Format-Table -verbose | out-string
write-host $text
```

<p>Going right back to my first example, we get:</p>

<pre class="lang-bsh prettyprint-override"><code>function Invoke-MyFunction
{
   write-host "here 1"
   @("aaa", "bbb") | format-table -Verbose | out-host
   write-host "here 2"
   return "ccc"
}

$x = Invoke-MyFunction
"---"
$x
</code>```

which now outputs:

```<code>here 1
aaa
bbb
here 2
---
ccc
</code>```

If you update your $RepoArray | ... line in the same way you should see it being displayed on the console where you expect it to be.

Hope this helps...

Body:
AM trying to get an array output (which has names and indexing) on PS screen so that user can choose from the options he has for input to next steps (Read-host)
Am adding indexing (index numbering) to an array so I can output index number and Name which can be used by used to input for next steps.
But the output on screen is not recorded and is stored somewhere on background and is given along with my "return" statement for that function at the very end of script

Need help form you folks to see why the output is not written on powershell screen (both ISE and powershell 5.1)

function CLoneBranch
{
Param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)][ValidateNotNullOrEmpty()]
[string]$url,
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=1)][ValidateNotNullOrEmpty()]
[String]$GitConnectionUserName,
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=2)][ValidateNotNullOrEmpty()]
[securestring]$GitConnectionUserPassword
)
try
{
    $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($GitConnectionUserPassword)
    $plainpwd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
    # Retrieve list of all repositories
    $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $GitConnectionUserName,$plainpwd)))
    $headers = @{
        "Authorization" = ("Basic {0}" -f $base64AuthInfo)
        "Accept" = "application/json"}

    Add-Type -AssemblyName System.Web
    $gitcred = ("{0}:{1}" -f  [System.Web.HttpUtility]::UrlEncode($GitConnectionUserName),$plainpwd)

    $resp = Invoke-WebRequest -Headers $headers -Uri ("{0}/_apis/git/repositories?api-version=1.0" -f $url)
    $json = convertFrom-JSON $resp.Content
    If($resp)
    {
        [Array]$RepoArray = Add-IndexNumberToArray ($json.value)

        [int]$Selectedrepo = 0
        # use the current repo if there is only one repo available
        if ($RepoArray.Count -eq 1)
        {
            $Selectedrepo = 1
        }
        while($Selectedrepo -gt $RepoArray.Count -or $Selectedrepo -lt 1)
        {

            Write-host "Please select a Repo from the list"
            $RepoArray | Select-Object IndexNumber , Name | Format-Table -verbose
**###### This is not written on the screen for user to look for what he has to input but some how at the end of function it returns the output using retun statement which I don't want ##########**

            try
            {
                $Selectedrepo = Read-Host "Please enter a selection from 1 to $($RepoArray.count)"
            }
            catch
            {
                Write-Warning -Message 'Invalid option, please try again.'
            }
        }
        if($($RepoArray[$Selectedrepo - 1].Name))
        {
            $RepoName = $($RepoArray[$Selectedrepo - 1].Name)
        }
        #write-verbose "You Selected Repo to download : $RepoName"
    }
}
       catch
 {
     Write-Error " Exception while cloning the repo or a specific branch"
     Write-Error $_.Exception.Message
     Write-Error " ErrorStack: $Error[0]"
     exit 1;
 }
 Return $RepoName
 }

function Add-IndexNumberToArray (
[Parameter(Mandatory=$True)]
[array]$array
)
{
for($i=0; $i -lt $array.Count; $i++)
{
    Add-Member -InputObject $array[$i] -Name "IndexNumber" -Value ($i+1) -MemberType NoteProperty
}
$array

}

Body:
Distilling your code down to a minimal repro, we get this:

function Invoke-MyFunction
{
   write-host "here 1"
   @("aaa", "bbb") | format-table -Verbose
   write-host "here 2"
   return "ccc"
}

$x = Invoke-MyFunction
"---"
$x

which outputs:

here 1
here 2
---
aaa
bbb
ccc

The reason you don't see the output from @("aaa", "bbb") | format-table -Verbose between here 1 and here 2 on the console is that it's being returned from the function as part of the output pipeline and assigned to $x, and not written to the console inside the Invoke-MyFunction function.

Like most programming languages, PowerShell's return will return a value and exit the function, but you can also stream values into the "output pipeline" by simply not capturing expressions into a variable. For example:

function Invoke-MultipleOutputs
{
    1
    "aaa"
    return "ccc"
}
$x = Invoke-MultipleOutputs
$x

$x will contain an array of values - in this case @( 1, "aaa", "ccc" ).

This is equivalent to

function Invoke-MultipleOutputs
{
    Write-Output 1
    Write-Output "aaa"
    return "ccc"
}
$x = Invoke-MultipleOutputs
$x

In your code, your're doing this: $RepoArray | Select-Object IndexNumber , Name | Format-Table -verbose which is converting $RepoArray into a set of formatted table objects, but then because the result is an unassigned expression it's being written to the output pipeline rather than being displayed on the console.

To fix this, you need to render the output of Format-Table as a string and then write it to the console which you can do with out-host...

$RepoArray | Select-Object IndexNumber , Name | Format-Table -verbose | out-host

or out-string...

$text = $RepoArray | Select-Object IndexNumber , Name | Format-Table -verbose | out-string
write-host $text

Going right back to my first example, we get:

function Invoke-MyFunction
{
   write-host "here 1"
   @("aaa", "bbb") | format-table -Verbose | out-host
   write-host "here 2"
   return "ccc"
}

$x = Invoke-MyFunction
"---"
$x

which now outputs:

here 1
aaa
bbb
here 2
---
ccc

If you update your $RepoArray | ... line in the same way you should see it being displayed on the console where you expect it to be.

Hope this helps...


问:
how to turn nested foreach loop with C# linq
I have a private method as follow:

```<code>private Dictionary<string, decimal> GetRateByYear(IEnumerable<EmployerCu> cuList,
    HashSet<long> activeCuSet, int year)
{
    Dictionary<string, decimal> cuDict = new Dictionary<string, decimal>();
    foreach (EmployerCu cu in cuList)
    {
        decimal rate = 0;    // rate maintains 0 if year is not match

        if (activeCuSet.Contains(cu.PayrollClassId))    // ignore inactive CUs
        {
            foreach (Rate r in cu.Rates)
            {
                if (r.Year == year)
                {
                    rate =  r.Value / Percentile;
                }
            }

            cuDict.Add(cu.Code.ToString(), rate);
        }
    }

    return cuDict;
}
</code>```

The logic works as expected. I just wanna challenge myself a little bit more with C# Linq.
I am trying to filter the input "cuList" with "activeCuSet", and add the cu.code and the rate for this year in a dictionary.

Here is the data model:

```<code>public class EmployerCu
{
    public long ClassId { get; set; }
    public long Code { get; set; }
    public string Name { get; set; }
    public long PayrollClassId { get; set; }
    public Rate[] Rates { get; set; }
}

public class Rate
{
    public RateType Type { get; set; }
    public decimal Value { get; set; }
    public long Year { get; set; }
}
</code>```

答:
Truth be told, not everything needs to be Linq. Sometimes it just makes code less maintainable and readable.

However this is potentially what a Linq solution would look like using ToDictionary

Creates a Dictionary<TKey,TValue> from an IEnumerable<T>.

```<code>private Dictionary<string, decimal> GetRateByYear(IEnumerable<EmployerCu> cuList, HashSet<long> activeCuSet, int year)
  => cuList.Where(x => activeCuSet.Contains(x.PayrollClassId))
                .ToDictionary(
                    x => x.Code,
                    x => x.Rates.LastOrDefault(y => y.Year == year)?.Value / Percentile ?? 0);
</code>```

Note : i used LastOrDefault as that was what your loop was doing

Body:
I have a private method as follow:

private Dictionary<string, decimal> GetRateByYear(IEnumerable<EmployerCu> cuList,
    HashSet<long> activeCuSet, int year)
{
    Dictionary<string, decimal> cuDict = new Dictionary<string, decimal>();
    foreach (EmployerCu cu in cuList)
    {
        decimal rate = 0;    // rate maintains 0 if year is not match

        if (activeCuSet.Contains(cu.PayrollClassId))    // ignore inactive CUs
        {
            foreach (Rate r in cu.Rates)
            {
                if (r.Year == year)
                {
                    rate =  r.Value / Percentile;
                }
            }

            cuDict.Add(cu.Code.ToString(), rate);
        }
    }

    return cuDict;
}

The logic works as expected. I just wanna challenge myself a little bit more with C# Linq.
I am trying to filter the input "cuList" with "activeCuSet", and add the cu.code and the rate for this year in a dictionary.

Here is the data model:

public class EmployerCu
{
    public long ClassId { get; set; }
    public long Code { get; set; }
    public string Name { get; set; }
    public long PayrollClassId { get; set; }
    public Rate[] Rates { get; set; }
}

public class Rate
{
    public RateType Type { get; set; }
    public decimal Value { get; set; }
    public long Year { get; set; }
}

Body:
Truth be told, not everything needs to be Linq. Sometimes it just makes code less maintainable and readable.

However this is potentially what a Linq solution would look like using ToDictionary

Creates a Dictionary<TKey,TValue> from an IEnumerable<T>.

private Dictionary<string, decimal> GetRateByYear(IEnumerable<EmployerCu> cuList, HashSet<long> activeCuSet, int year)
  => cuList.Where(x => activeCuSet.Contains(x.PayrollClassId))
                .ToDictionary(
                    x => x.Code,
                    x => x.Rates.LastOrDefault(y => y.Year == year)?.Value / Percentile ?? 0);

Note : i used LastOrDefault as that was what your loop was doing


问:
I need a Jquery caroussel that support content of different size
My problem is quite simple. I need a jquery add-on that will provide me a carousel but this carousel need to support different element size.

Ex: Note the following list contain more tant 3 element but carousel hide them

```<code>''''''''''   ''''''''''   ''''''''''''''''''    '''''''''''''''''''''''''''  ''''''''
'previous'   'Element1'   '    Element2    '    '        Element 3        '  ' Next '
''''''''''   ''''''''''   ''''''''''''''''''    '''''''''''''''''''''''''''  ''''''''
</code>```

Something like jCarousel would be perfect because he works perfectly in all browser execpt for Chrome where he generate me a Uncaught Error: jCarousel: No width/height set for items. This will cause an infinite loop. Aborting...

答:
In fact jCarousel support box of deferent size. The problem was that boxes have to be force to be floated and the ul item have to be set at a fixed size in the page.

Note: The image scroll will be a bit imprecise at the end of the list.

Body:
My problem is quite simple. I need a jquery add-on that will provide me a carousel but this carousel need to support different element size.

Ex: Note the following list contain more tant 3 element but carousel hide them

''''''''''   ''''''''''   ''''''''''''''''''    '''''''''''''''''''''''''''  ''''''''
'previous'   'Element1'   '    Element2    '    '        Element 3        '  ' Next '
''''''''''   ''''''''''   ''''''''''''''''''    '''''''''''''''''''''''''''  ''''''''

Something like jCarousel would be perfect because he works perfectly in all browser execpt for Chrome where he generate me a Uncaught Error: jCarousel: No width/height set for items. This will cause an infinite loop. Aborting...


问:
comparing two strings and their index seeing if all of string 2 is in string 1 with same order but different letter in between
Assume all letters in the given words are lowercase.
You may use string methods if any are useful.

```<code>>>> occurs_within('aaacaabxyt', 'cat')
True

>>> occurs_within('tac', 'cat')
False

>>> occurs_within('oboe', 'bob')
False

>>> occurs_within('ecxbtalt', 'exalt')
True

>>> occurs_within('ecxbtal', 'exalt')
False

if len(word1) > len(word2):
    for i in range(0,len(word1)):
        if word2[i] < word2[i+1]:
            return True
        else:
            return False
else:
    return False
</code>```

I tried using a nested for loop inside an if function comparing the two strings and looping to find if the next index of string 2 that is with in string 1 is greater than that of the previous index, but it turns out my result are all True somehow, and I cant figure out what seem to be the problem.

答:
I have tested it with plenty examples of words and sub-words and this works for every one of them.

```<code>def occurs_within(word, sub_word):
    letter_at = -1
    for letter in sub_word:
        temp = letter_at
        letter_at = word.find(letter, temp + 1)
        if 0 < letter_at <= temp or letter_at == -1:
            return False
    return True
</code>```

Basically the logic behind is that, in order for the function to returns True, you need to loop over sub_word and test, for each letter, if that letter exists in word and the index of the letter in that string (word) must be greater than the last letter of sub_word tested.

Body:
Assume all letters in the given words are lowercase.
You may use string methods if any are useful.

>>> occurs_within('aaacaabxyt', 'cat')
True

>>> occurs_within('tac', 'cat')
False

>>> occurs_within('oboe', 'bob')
False

>>> occurs_within('ecxbtalt', 'exalt')
True

>>> occurs_within('ecxbtal', 'exalt')
False

if len(word1) > len(word2):
    for i in range(0,len(word1)):
        if word2[i] < word2[i+1]:
            return True
        else:
            return False
else:
    return False

I tried using a nested for loop inside an if function comparing the two strings and looping to find if the next index of string 2 that is with in string 1 is greater than that of the previous index, but it turns out my result are all True somehow, and I cant figure out what seem to be the problem.

Body:
I have tested it with plenty examples of words and sub-words and this works for every one of them.

def occurs_within(word, sub_word):
    letter_at = -1
    for letter in sub_word:
        temp = letter_at
        letter_at = word.find(letter, temp + 1)
        if 0 < letter_at <= temp or letter_at == -1:
            return False
    return True

Basically the logic behind is that, in order for the function to returns True, you need to loop over sub_word and test, for each letter, if that letter exists in word and the index of the letter in that string (word) must be greater than the last letter of sub_word tested.


问:
Summing over lists of arbitrary levels of nestedness in F#
I'm trying to create an F# function that will return the sum of a list of ints of arbitrary nestedness. Ie. it will work for a list<int>, a list<list<int>> and a list<list<list<list<list<list<int>>>>>>.

In Haskell I would write something like:

```<code>class HasSum a where
    getSum :: a -> Integer

instance HasSum Integer where
    getSum = id

instance HasSum a => HasSum [a] where
    getSum = sum . map getSum
</code>```

which would let me do:

```<code>list :: a -> [a]
list = replicate 6

nestedList :: [[[[[[[[[[Integer]]]]]]]]]]
nestedList =
    list $ list $ list $ list $ list $
    list $ list $ list $ list $ list (1 :: Integer)

sumNestedList :: Integer
sumNestedList = getSum nestedList
</code>```

Link to runnable code.

How can I achieve this in F#?

答:
Here is the runtime version, would work with all .net collections. However, exchanges compiler errors in AMieres' answer for runtime exceptions and AMieres' is 36x faster too.

```<code>let list v = List.replicate 6 v

let rec getSum (input:IEnumerable) =
    match input with
    | :? IEnumerable<int> as l -> l |> Seq.sum
    | e ->
        e
        |> Seq.cast<IEnumerable> // will runtime exception if not nested IEnumerable Types
        |> Seq.sumBy getSum

1 |> list |> list |> list |> list |> list
|> list |> list |> list |> list |> list |> getSum // = 60466176
</code>```

Benchmarks

```<code>|    Method |        Mean |     Error |    StdDev |
|---------- |------------:|----------:|----------:|
| WeirdSumC |    76.09 ms |  0.398 ms |  0.373 ms |
| WeirdSumR | 2,779.98 ms | 22.849 ms | 21.373 ms |

// * Legends *
  Mean   : Arithmetic mean of all measurements
  Error  : Half of 99.9% confidence interval
  StdDev : Standard deviation of all measurements
  1 ms   : 1 Millisecond (0.001 sec)
</code>```

Body:
I'm trying to create an F# function that will return the sum of a list of ints of arbitrary nestedness. Ie. it will work for a list<int>, a list<list<int>> and a list<list<list<list<list<list<int>>>>>>.

In Haskell I would write something like:

class HasSum a where
    getSum :: a -> Integer

instance HasSum Integer where
    getSum = id

instance HasSum a => HasSum [a] where
    getSum = sum . map getSum

which would let me do:

list :: a -> [a]
list = replicate 6

nestedList :: [[[[[[[[[[Integer]]]]]]]]]]
nestedList =
    list $ list $ list $ list $ list $
    list $ list $ list $ list $ list (1 :: Integer)

sumNestedList :: Integer
sumNestedList = getSum nestedList

Link to runnable code.

How can I achieve this in F#?

Body:
Here is the runtime version, would work with all .net collections. However, exchanges compiler errors in AMieres' answer for runtime exceptions and AMieres' is 36x faster too.

let list v = List.replicate 6 v

let rec getSum (input:IEnumerable) =
    match input with
    | :? IEnumerable<int> as l -> l |> Seq.sum
    | e ->
        e
        |> Seq.cast<IEnumerable> // will runtime exception if not nested IEnumerable Types
        |> Seq.sumBy getSum

1 |> list |> list |> list |> list |> list
|> list |> list |> list |> list |> list |> getSum // = 60466176

Benchmarks

|    Method |        Mean |     Error |    StdDev |
|---------- |------------:|----------:|----------:|
| WeirdSumC |    76.09 ms |  0.398 ms |  0.373 ms |
| WeirdSumR | 2,779.98 ms | 22.849 ms | 21.373 ms |

// * Legends *
  Mean   : Arithmetic mean of all measurements
  Error  : Half of 99.9% confidence interval
  StdDev : Standard deviation of all measurements
  1 ms   : 1 Millisecond (0.001 sec)


问:
Pygsheets and AWS Lambda
I am sure the suggestions here will be to use an S3 bucket and I am aware of this. My question is a bit more difficult, from what I am gathering, in that I want to use Pygsheets, a python library, to write to a Google Sheet. However, after getting through all the deployment and layer steps... what is stopping me is a pesky .json file needs to be read by one of the functions in Pygsheets. I do believe it is reading and writing something else on the fly which may not be allowed in and of itself but I am asking regardless.

Link directly to the function that needs to be used in conjunction with the secret.json from Google: Pygsheets Github

Sample code:

```<code>  print("-->Using the library pygsheets to update...")

  print(f"-->Accessing client_secret.json")
  gc = pygsheets.authorize(service_file='client_secret.json')

  print(f"-->Opening Google Sheets")
  #open the google spreadsheet
  sh = gc.open_by_url('https://...')

  print(f"-->Accessing")
  #select the first sheet
  wks = sh[0]

  print(f"-->Updating selected cells... ")
  #update the first sheet with df, starting at cell A11.
  wks.set_dataframe(df, 'J14')
</code>```

Again, I am close to my final product of automating my sheets using this script/library/lambda that I can taste it :). If the absolute best workaround is S3 please be gentle I am a first year analyst trying to get my feet wet. Superior is telling me it would take a while to hook up a connection to S3 so thats also a reason to avoid. Thanks!

答: Fixed. Simply added the .json creds to the deployment package. I had ran into an issue with pandas so I have a blend of layers and a deployment package with my .py script (and, again, with secret.json). Thanks!</p>

Title: Pygsheets and AWS Lambda

Body:
I am sure the suggestions here will be to use an S3 bucket and I am aware of this. My question is a bit more difficult, from what I am gathering, in that I want to use Pygsheets, a python library, to write to a Google Sheet. However, after getting through all the deployment and layer steps... what is stopping me is a pesky .json file needs to be read by one of the functions in Pygsheets. I do believe it is reading and writing something else on the fly which may not be allowed in and of itself but I am asking regardless.

Link directly to the function that needs to be used in conjunction with the secret.json from Google: Pygsheets Github

Sample code:

  print("-->Using the library pygsheets to update...")

  print(f"-->Accessing client_secret.json")
  gc = pygsheets.authorize(service_file='client_secret.json')

  print(f"-->Opening Google Sheets")
  #open the google spreadsheet
  sh = gc.open_by_url('https://...')

  print(f"-->Accessing")
  #select the first sheet
  wks = sh[0]

  print(f"-->Updating selected cells... ")
  #update the first sheet with df, starting at cell A11.
  wks.set_dataframe(df, 'J14')

Again, I am close to my final product of automating my sheets using this script/library/lambda that I can taste it :). If the absolute best workaround is S3 please be gentle I am a first year analyst trying to get my feet wet. Superior is telling me it would take a while to hook up a connection to S3 so thats also a reason to avoid. Thanks!


问:
Is there a way to download the entire SBIR awards as a JSON file?
For my work I need to create a Python program to download all the results for "awards" from SBIR automatically.

There are as of now, 171616 results.

I have two possible options. I can download 1,000 at a time but I need to verify that I am not a robot with the reCAPTCHA, therefore I can not automate the download.

Or I could use their API, which would be great! But it only downloads a 100 results when searching for everything available. Is there I way I could iterate through chunks and then compile it into one big JSON file?

This is the documentation.

This is where I say file>save as>filename.json

Any help/advice would really help me out.

答:
I wish they have better documentation. It seems we can do pagination via:</p>

```<code>https://www.sbir.gov/api/awards.json?agency=DOE&start=100

https://www.sbir.gov/api/awards.json?agency=DOE&start=200

https://www.sbir.gov/api/awards.json?agency=DOE&start=300
</code>```

Body:
I wish they have better documentation. It seems we can do pagination via:

https://www.sbir.gov/api/awards.json?agency=DOE&start=100

https://www.sbir.gov/api/awards.json?agency=DOE&start=200

https://www.sbir.gov/api/awards.json?agency=DOE&start=300


问:
How do I create a remove item image button for a dynamic list of data entries in JavaScript
I have a list of user submitted data displaying on my website using the code below. How do I add a small image of an x, used as a button, to the left or right of each line of displayed data for the purpose of removing that line of data and the button itself.</p>

```<code>updateAllDataDisplay(false);
function updateAllDataDisplay(addOne) {

    // Updating the entire display
    if (!addOne) {
        for (var i = 0; i < allData.length; i++) {
            let a = document.createElement("p");
            let b = document.createTextNode(`${allData[i].month}/${allData[i].day}/${allData[i].year} (${allData[i].hours}:${allData[i].mins}:${allData[i].secs}): ${allData[i].exerciseHours}. ${allData[i].food}. ${allData[i].weight}. ${allData[i].mood}.`);
            a.appendChild(b);
            document.body.appendChild(a);
        }

    // Updating the last item of the display
    } else if (addOne) {
        let a = document.createElement("p");
        if (allData.length > 0) {
        let b = document.createTextNode(`${allData[allData.length - 1].month}/${allData[allData.length - 1].day}/${allData[allData.length - 1].year} (${allData[allData.length - 1].hours}:${allData[allData.length - 1].mins}:${allData[allData.length - 1].secs}): ${allData[allData.length - 1].exerciseHours}. ${allData[allData.length - 1].food}. ${allData[allData.length - 1].weight}. ${allData[allData.length - 1].mood}.`);
        a.appendChild(b);
        document.body.appendChild(a);
        }
    }
}
</code>```

答:
I have created a quick work-around using a simple list<string> of strings.

var allData = [
 "I was so happy when I wrote my very first Hello World in C#",
  "It felt the Giant awaken in me",
  "But I knew it was going to take hard, consistent, long hours of learning to be great at coding"];

function updateAllDataDisplay(addOne) {

    // Updating the entire display
    if (!addOne) {
        for (var i = 0; i < allData.length; i++) {

              //First the container or List item -
              // - Added item class for styling
              // - added id for referencing
            let container = document.createElement("div");
            container.classList.add("item");
            container.id = `item${i}`;

            // Second the button for deleting the list Item
            let button = document.createElement("button");
            button.appendChild(document.createTextNode("X"));
            button.value = i;

            button.addEventListener('click',
              (e)=>{
        document.getElementById("root").removeChild(
                 document.getElementById(`item${e.target.value}`)
                );
              }
            );
            // The the actual information represented with a span
            let textElement = document.createElement("span");
            let text = document.createTextNode(`${allData[i]}`);

            // Now append all your elements accordingly
            textElement.appendChild(text);
            container.appendChild(textElement);
            container.appendChild(button);
            document.getElementById("root").appendChild(container);
        }
    }
}
updateAllDataDisplay(false);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.item {
  position: relative;
  display: block;
  background-color: #f1f1f1;
  min-height: 40px;
  padding-right: 40px;
  padding-left: 15px;
  margin-bottom: 15px;
  line-height: 40px;
}

// Style Span element holding the data
div>span {
  display: block;
  line-height: 40px;
  width: 100%;
}

div>button {
  padding: 15px;
  position: absolute;
  right: 0;
  width: 40px;
  height: 40px;
  top: 0;
}</code>```

```

Body:
I have a list of user submitted data displaying on my website using the code below. How do I add a small image of an x, used as a button, to the left or right of each line of displayed data for the purpose of removing that line of data and the button itself.

updateAllDataDisplay(false);
function updateAllDataDisplay(addOne) {

    // Updating the entire display
    if (!addOne) {
        for (var i = 0; i < allData.length; i++) {
            let a = document.createElement("p");
            let b = document.createTextNode(`${allData[i].month}/${allData[i].day}/${allData[i].year} (${allData[i].hours}:${allData[i].mins}:${allData[i].secs}): ${allData[i].exerciseHours}. ${allData[i].food}. ${allData[i].weight}. ${allData[i].mood}.`);
            a.appendChild(b);
            document.body.appendChild(a);
        }

    // Updating the last item of the display
    } else if (addOne) {
        let a = document.createElement("p");
        if (allData.length > 0) {
        let b = document.createTextNode(`${allData[allData.length - 1].month}/${allData[allData.length - 1].day}/${allData[allData.length - 1].year} (${allData[allData.length - 1].hours}:${allData[allData.length - 1].mins}:${allData[allData.length - 1].secs}): ${allData[allData.length - 1].exerciseHours}. ${allData[allData.length - 1].food}. ${allData[allData.length - 1].weight}. ${allData[allData.length - 1].mood}.`);
        a.appendChild(b);
        document.body.appendChild(a);
        }
    }
}

Body:
I have created a quick work-around using a simple list<string> of strings.

var allData = [
 "I was so happy when I wrote my very first Hello World in C#",
  "It felt the Giant awaken in me",
  "But I knew it was going to take hard, consistent, long hours of learning to be great at coding"];

function updateAllDataDisplay(addOne) {

    // Updating the entire display
    if (!addOne) {
        for (var i = 0; i < allData.length; i++) {

              //First the container or List item -
              // - Added item class for styling
              // - added id for referencing
            let container = document.createElement("div");
            container.classList.add("item");
            container.id = `item${i}`;

            // Second the button for deleting the list Item
            let button = document.createElement("button");
            button.appendChild(document.createTextNode("X"));
            button.value = i;

            button.addEventListener('click',
              (e)=>{
        document.getElementById("root").removeChild(
                 document.getElementById(`item${e.target.value}`)
                );
              }
            );
            // The the actual information represented with a span
            let textElement = document.createElement("span");
            let text = document.createTextNode(`${allData[i]}`);

            // Now append all your elements accordingly
            textElement.appendChild(text);
            container.appendChild(textElement);
            container.appendChild(button);
            document.getElementById("root").appendChild(container);
        }
    }
}
updateAllDataDisplay(false);

div.item {
  position: relative;
  display: block;
  background-color: #f1f1f1;
  min-height: 40px;
  padding-right: 40px;
  padding-left: 15px;
  margin-bottom: 15px;
  line-height: 40px;
}

// Style Span element holding the data
div>span {
  display: block;
  line-height: 40px;
  width: 100%;
}

div>button {
  padding: 15px;
  position: absolute;
  right: 0;
  width: 40px;
  height: 40px;
  top: 0;
}

<div id="root">
</div>


答:
```<code>customer.Users.ForEach(user => repositoryManager.Users.Delete(user));
</code>```

Body:
How do I convert this loop into a LINQ expression?

foreach (var user in customer.Users)
{
    repositoryManager.Users.Delete(user);
}


问:
(Tcl) what character encoding set should I use?
So I'm trying to open and parse some old Visual Studio compilation log files with Tcl; my only problem is the files are in a strange encoding. Upon examining them with Notepad++ it seems they are in the 'UCS-2 Little Endian' encoding. Two questions:

Is there any command in Tcl that allows me to look at the character encoding of a file? I know there is encoding system which tells me the system encoding.

Using encoding names Tcl tells me the available encoding names are the following list:

cp860 cp861 cp862 cp863 tis-620 cp864 cp865 cp866 gb12345 gb2312-raw cp949 cp950 cp869 dingbats ksc5601 macCentEuro cp874 macUkraine jis0201 gb2312 euc-cn euc-jp macThai iso8859-10 jis0208 iso2022-jp macIceland iso2022 iso8859-13 jis0212 iso8859-14 iso8859-15 cp737 iso8859-16 big5 euc-kr macRomania macTurkish gb1988 iso2022-kr macGreek ascii cp437 macRoman iso8859-1 iso8859-2 iso8859-3 macCroatian koi8-r iso8859-4 ebcdic iso8859-5 cp1250 macCyrillic iso8859-6 cp1251 macDingbats koi8-u iso8859-7 cp1252 iso8859-8 cp1253 iso8859-9 cp1254 cp1255 cp850 cp1256 cp932 identity cp1257 cp852 macJapan cp1258 shiftjis utf-8 cp855 cp936 symbol cp775 unicode cp857

Given this, what would be the appropriate name to use in the fconfigure -encoding command to read these UCS-2 Little Endianencoded files and convert them to UTF-8 for use? If I understand the fconfigure command correctly, I need to specify the encoding type of the source file rather than what I want it to be; I just don't know which of the options in the above list corresponds to UCS-2 Little Endian. After reading a little bit, I see that UCS-2 is a predecessor of the UTF-16 character encoding, but that option isn't here either.

Thanks!

答: In Tcl v8.6.8 I could solve the same issue with fconfigure channelId -encoding unicode.</p>


问:
WordPress WC_Meta_Data full variation values
I have fairly complex products in my webshop with all kinds of variation values. The length of these values is quite low. The problem is that Wordpress automatically shortens them. So that means that:

Value A: This is a fairly long value chosen for this option

Gets shorten to:

Value A: This is a fairly...is option

I've tried to find the full length values, but can't seem to display them on my Thank You page. It uses this function to show the values:

```<code>wc_display_item_meta( $item ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
</code>```

However, even printing the entire $item output doesn't result in a usable object in which I can find the full-length values. There is the WC_Meta_Data, but it only holds these short values. Any ideas on how to tackle this?

Thank you!

答:
What theme are you using? Using Twenty Nineteen as a test. A long variation completely displays.

If I had to guess, It maybe something in the theme causing it to shorten it.

Body:
I have fairly complex products in my webshop with all kinds of variation values. The length of these values is quite low. The problem is that Wordpress automatically shortens them. So that means that:

Value A: This is a fairly long value chosen for this option

Gets shorten to:

Value A: This is a fairly...is option

I've tried to find the full length values, but can't seem to display them on my Thank You page. It uses this function to show the values:

wc_display_item_meta( $item ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

However, even printing the entire $item output doesn't result in a usable object in which I can find the full-length values. There is the WC_Meta_Data, but it only holds these short values. Any ideas on how to tackle this?

Thank you!


问:
what is difference between rtmp and rtsp protocol?
i just want to know what is the difference between rtsp and rtmp protocol and if  there are mp3s on my server and i am playing it in my android using http,how these differs in work.

In android if i want to implement rtmp or rtsp ,which is the best?
what are the limitation of rtmp & rtsp in android?

can anybody give me brief answer for above?

答:
They are both protocols for Streaming Media and on a high level achieve the same thing - Specify a standard to stream media.
Although  RTMP was developed and owned by Adobe before being made public , whereas RTSP was a public standard from the beginning.
Since RTMP is mostly used by Flash player , i would assume that the android media player class  streams using RTSP. </p>


问:
How can I display the comment of the specific row that I want to edit?
This is a commenting system using jQuery, Ajax, PHP, MySQL, and HTML.  When I click the Edit button, it displays the comment of the first row of the table of MySQL instead of the row that I selected.   However, once I edit it, it does correct the correct row.   I can’t figure out a way to display the comment of the row that I want to edit.

I can display the correct comment_id of the row into the textarea, but it displays the comment of the first row into the textarea.

Here is the test case code:

MySQL table has two rows: comment_id as primary row and comment for text.  I named the database: testcaseedit_db, and the table: tbl_comment.

index.php

```<code><?php $connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', ''); ?>

<div id="display_comment"></div>
<div id="comment_message"></div>

<div id="display_edit"></div>

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

<script>

$(document).ready(function() {

let count = 0;

$(document).on('click change', '.edit, .submit', function(e) {

  if ($(this).is('.edit')) {

    var comment_id = $(this).attr("id");
    $('#comment_id').val(comment_id);

    var closestDiv = $('button').closest('div.panel');
    $('.div.panel').not(closestDiv.next('.div.panel')).hide();
    closestDiv.next('div.panel').slideToggle(100);

    var commentEdit = $('#display_comment').find('#editable').html();

  ++count;

  const htmlString =
  `<form id="comment_form${count}" class="input-group form-row" action="edit.php" method="post" enctype="multipart/form-data">

    <div class="input-group-prepend">
      <textarea name="comment" id="comment${count}" class="form-control" rows="30" cols="160">
        ${commentEdit} ${comment_id}
      </textarea>
    </div>

    <div class="input-group-prepend">
     <input type="hidden" name="comment_id" id="comment_id" value="${comment_id}" />
     <input type="submit" name="submit" id="submit" class="submit btn btn-info" value="Save" form="comment_form${count}" />
    </div>
  </form>`;

  $('#display_comment')[0].insertAdjacentHTML('afterend', htmlString);

    } else if ($(this).is('.submit')) {

    $.ajax({
     url:"edit.php",
     method:"POST",
     data: new FormData(this),
     contentType: false,
     processData: false,
     success:function(data)
     {
      if(data.error != '') {
       $('#comment_form')[0].reset();
       $('#comment_id').val(comment_id);
       $('#comment').val(comment);
      }
     }
    });

   location.reload();

      $(this).closest('form').submit();
      e.stopPropagation();
    } else {
      return false;
    }

});

 // Fetch comment
 function load_comment(){
        $.ajax({
         url:"fetch.php",
         method:"POST",
         success:function(data){
          $('#display_comment').html(data);
         }
        })
 };

 load_comment();

// End of (document).ready(function){}
});
</script>

 </body>
</html>

</code>```

fetch.php

```<code><?php

$connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', '');

$query = "
SELECT * FROM tbl_comment WHERE comment_id = comment_id
";

$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';

foreach($result as $row) {
 $output .= '
 <div class="panel panel-default">
  <div class="panel-heading"> <b> comment_id: </b> '.$row["comment_id"].' </div>
  <div class="panel-body"><b> Comment: </b> <br> <span id="editable">  '.$row["comment"].'  </span> </div>
  <div class="panel-footer" align="right">

  <button type="button" class="btn btn-default edit" id="'.$row["comment_id"].'">Edit</button>

  </div>
 </div>
 ';
}

echo $output;

?>
</code>```

edit.php

```<code><?php

$connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', '');

$comment_id = $_POST["comment_id"];
$comment = $_POST["comment"];

if ( $error == '' && !empty($_POST["comment"]) ) {

 $query = "UPDATE tbl_comment SET comment = :comment WHERE comment_id = :comment_id ";

 $statement = $connect->prepare($query);
 $statement->execute(
  array(
   ':comment_id' => $comment_id,
   ':comment'    => $comment
  )
 );

  header("Location: index.php");

}

$data = array(
 'error'  => $error
);

echo $error;

?>

</code>```

答:
Here is the solution:

In fetch.php file, I made the id for each variable into an array as follows:

<button type="button" class="btn btn-default edit" id[1]="'.$row["comment_id"].'"  id[2]="'.$row["comment"].'">Edit</button>

And in index.php file, I grabbed the value of each variable as follows:

```<code>    var comment_id = $(this).attr("id[1]");
    $('#comment_id').val(comment_id);

    var comment = $(this).attr("id[2]");
    $('#comment').val(comment);
</code>```

Then I displayed the comment variable inside the textarea as follows:

<textarea name="comment" id="comment${count}" class="form-control" rows="15" cols="120">${comment}</textarea>

Here is the full code for index.php and fetch.php.  I left edit.php untouched:

index.php

```<code><?php $connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', ''); ?>

<div id="display_comment"></div>

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

<script>

$(document).ready(function() {

let count = 0;

$(document).on('click change', '.edit, .submit', function(e) {

  if ($(this).is('.edit')) {

    var comment_id = $(this).attr("id[1]");
    $('#comment_id').val(comment_id);

    var comment = $(this).attr("id[2]");
    $('#comment').val(comment);

    var closestDiv = $('button').closest('div.panel');
    $('div.panel').not(closestDiv.next('div.panel')).hide();
    closestDiv.next('div.panel').slideToggle(100);

  ++count;

  const htmlString =
  `<form id="comment_form${count}" class="input-group form-row" action="edit.php" method="post" enctype="multipart/form-data">

    <div class="input-group-prepend">
      <textarea name="comment" id="comment${count}" class="form-control" rows="15" cols="120">
        ${comment}
      </textarea>
    </div>

    <div class="input-group-prepend">
     <input type="hidden" name="comment_id" id="comment_id" value="${comment_id}" />
     <input type="submit" name="submit" id="submit" class="submit btn btn-info" value="Save" form="comment_form${count}" />
    </div>
  </form>`;

  $('#display_comment')[0].insertAdjacentHTML('afterend', htmlString);

    } else if ($(this).is('.submit')) {

    $.ajax({
     url:"edit.php",
     method:"POST",
     data: new FormData(this),
     contentType: false,
     processData: false,
     success:function(data)
     {
      if(data.error != '') {
       $('#comment_form')[0].reset();
       $('#comment_id').val(comment_id);
       $('#comment').val(comment);
      }
     }
    });

   location.reload();

      $(this).closest('form').submit();
      e.stopPropagation();
    } else {
      return false;
    }

});

 // Fetch comment
 function load_comment(){
        $.ajax({
         url:"fetch.php",
         method:"POST",
         success:function(data){
          $('#display_comment').html(data);
         }
        })
 };

 load_comment();

// End of (document).ready(function){}
});
</script>

 </body>
</html>
</code>```

fetch.php

```<code><?php

$connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', '');

$query = "
SELECT * FROM tbl_comment WHERE comment_id = comment_id
";

$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';

foreach($result as $row) {
 $output .= '
 <div class="panel panel-default">
  <div class="panel-heading"> <b> comment_id: </b> '.$row["comment_id"].' </div>
  <div class="panel-body"><b> Comment: </b> <br>  '.$row["comment"].' </div>
  <div class="panel-footer" align="right">

  <button type="button" class="btn btn-default edit" id[1]="'.$row["comment_id"].'"  id[2]="'.$row["comment"].'">Edit</button>

  </div>
 </div>
 ';
}

echo $output;

?>
</code>```

Body:
This is a commenting system using jQuery, Ajax, PHP, MySQL, and HTML.  When I click the Edit button, it displays the comment of the first row of the table of MySQL instead of the row that I selected.   However, once I edit it, it does correct the correct row.   I can’t figure out a way to display the comment of the row that I want to edit.

I can display the correct comment_id of the row into the textarea, but it displays the comment of the first row into the textarea.

Here is the test case code:

MySQL table has two rows: comment_id as primary row and comment for text.  I named the database: testcaseedit_db, and the table: tbl_comment.

index.php

<?php $connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', ''); ?>

fetch.php

<?php

$connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', '');

$query = "
SELECT * FROM tbl_comment WHERE comment_id = comment_id
";

$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';

foreach($result as $row) {
 $output .= '

  comment_id:  '.$row["comment_id"].'

 Comment:
   '.$row["comment"].'

  <button type="button" class="btn btn-default edit" id="'.$row["comment_id"].'">Edit</button>

 ';
}

echo $output;

?>

edit.php

<?php

$connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', '');

$comment_id = $_POST["comment_id"];
$comment = $_POST["comment"];

if ( $error == '' && !empty($_POST["comment"]) ) {

 $query = "UPDATE tbl_comment SET comment = :comment WHERE comment_id = :comment_id ";

 $statement = $connect->prepare($query);
 $statement->execute(
  array(
   ':comment_id' => $comment_id,
   ':comment'    => $comment
  )
 );

  header("Location: index.php");

}

$data = array(
 'error'  => $error
);

echo $error;

?>

Body:
Here is the solution:

In fetch.php file, I made the id for each variable into an array as follows:

<button type="button" class="btn btn-default edit" id[1]="'.$row["comment_id"].'"  id[2]="'.$row["comment"].'">Edit</button>

And in index.php file, I grabbed the value of each variable as follows:

    var comment_id = $(this).attr("id[1]");
    $('#comment_id').val(comment_id);

    var comment = $(this).attr("id[2]");
    $('#comment').val(comment);

Then I displayed the comment variable inside the textarea as follows:

<textarea name="comment" id="comment${count}" class="form-control" rows="15" cols="120">${comment}</textarea>

Here is the full code for index.php and fetch.php.  I left edit.php untouched:

index.php

<?php $connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', ''); ?>

<div id="display_comment"></div>

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

<script>

$(document).ready(function() {

let count = 0;

$(document).on('click change', '.edit, .submit', function(e) {

  if ($(this).is('.edit')) {

    var comment_id = $(this).attr("id[1]");
    $('#comment_id').val(comment_id);

    var comment = $(this).attr("id[2]");
    $('#comment').val(comment);

    var closestDiv = $('button').closest('div.panel');
    $('div.panel').not(closestDiv.next('div.panel')).hide();
    closestDiv.next('div.panel').slideToggle(100);

  ++count;

  const htmlString =
  `<form id="comment_form${count}" class="input-group form-row" action="edit.php" method="post" enctype="multipart/form-data">

    <div class="input-group-prepend">
      <textarea name="comment" id="comment${count}" class="form-control" rows="15" cols="120">
        ${comment}
      </textarea>
    </div>

    <div class="input-group-prepend">
     <input type="hidden" name="comment_id" id="comment_id" value="${comment_id}" />
     <input type="submit" name="submit" id="submit" class="submit btn btn-info" value="Save" form="comment_form${count}" />
    </div>
  </form>`;

  $('#display_comment')[0].insertAdjacentHTML('afterend', htmlString);

    } else if ($(this).is('.submit')) {

    $.ajax({
     url:"edit.php",
     method:"POST",
     data: new FormData(this),
     contentType: false,
     processData: false,
     success:function(data)
     {
      if(data.error != '') {
       $('#comment_form')[0].reset();
       $('#comment_id').val(comment_id);
       $('#comment').val(comment);
      }
     }
    });

   location.reload();

      $(this).closest('form').submit();
      e.stopPropagation();
    } else {
      return false;
    }

});

 // Fetch comment
 function load_comment(){
        $.ajax({
         url:"fetch.php",
         method:"POST",
         success:function(data){
          $('#display_comment').html(data);
         }
        })
 };

 load_comment();

// End of (document).ready(function){}
});
</script>

 </body>
</html>

fetch.php

<?php

$connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', '');

$query = "
SELECT * FROM tbl_comment WHERE comment_id = comment_id
";

$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';

foreach($result as $row) {
 $output .= '
 <div class="panel panel-default">
  <div class="panel-heading"> <b> comment_id: </b> '.$row["comment_id"].' </div>
  <div class="panel-body"><b> Comment: </b> <br>  '.$row["comment"].' </div>
  <div class="panel-footer" align="right">

  <button type="button" class="btn btn-default edit" id[1]="'.$row["comment_id"].'"  id[2]="'.$row["comment"].'">Edit</button>

  </div>
 </div>
 ';
}

echo $output;

?>


问:
Take photo when pattern is detected in image with Android OpenCV
Hello stackoverflow community I would like if someone can guide me a little regarding my next question, I want to make an application that takes a photo when it detects a sheet with 3 marks (black squares in the corners) similar to what a QR would have. I have read a little about opencv that I think could help me more however I am not very clear yet.

Here my example

答:
Once you obtain your binary image, you can find contours and filter using contour approximation and contour area. If the approximated contour has a length of four then it must be a square and if it is within a lower and upper area range then we have detected a mark. We keep a counter of the mark and if there are three marks in the image, we can take the photo. Here's the visualization of the process.

We Otsu's threshold to obtain a binary image with the objects to detect in white.

From here we find contours using cv2.findContours and filter using contour approximation cv2.approxPolyDP in addition to contour area cv2.contourArea.

Detected marks highlighted in teal

I implemented it in Python but you can adapt the same approach

Code

```<code>import cv2

# Load image, grayscale, Otsu's threshold
image = cv2.imread('1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Find contours and filter using contour approximation and contour area
marks = 0
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    area = cv2.contourArea(c)
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.04 * peri, True)
    if len(approx) == 4 and area > 250 and area < 400:
        x,y,w,h = cv2.boundingRect(c)
        cv2.rectangle(image, (x, y), (x + w, y + h), (200,255,12), 2)
        marks += 1

# Sheet has 3 marks
if marks == 3:
    print('Take photo')

cv2.imshow('thresh', thresh)
cv2.imshow('image', image)
cv2.waitKey()
</code>```

Body:
Once you obtain your binary image, you can find contours and filter using contour approximation and contour area. If the approximated contour has a length of four then it must be a square and if it is within a lower and upper area range then we have detected a mark. We keep a counter of the mark and if there are three marks in the image, we can take the photo. Here's the visualization of the process.

We Otsu's threshold to obtain a binary image with the objects to detect in white.

From here we find contours using cv2.findContours and filter using contour approximation cv2.approxPolyDP in addition to contour area cv2.contourArea.

Detected marks highlighted in teal

I implemented it in Python but you can adapt the same approach

Code

import cv2

# Load image, grayscale, Otsu's threshold
image = cv2.imread('1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Find contours and filter using contour approximation and contour area
marks = 0
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    area = cv2.contourArea(c)
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.04 * peri, True)
    if len(approx) == 4 and area > 250 and area < 400:
        x,y,w,h = cv2.boundingRect(c)
        cv2.rectangle(image, (x, y), (x + w, y + h), (200,255,12), 2)
        marks += 1

# Sheet has 3 marks
if marks == 3:
    print('Take photo')

cv2.imshow('thresh', thresh)
cv2.imshow('image', image)
cv2.waitKey()


问:
Why has this file I/O operation in Java caused NullPointerException
I was writing code for a small tool that removes a user-given string from a file whose name is fed to the program from the command line. But when run, it throws a NullPointerException. I can't figure out why. Please help me solve this mystery. Thank you very much. This code is as follows.</p>

```<code>/**
 * Remove certain lines from a text file.
 */

import java.util.*;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

public class LineCutter {
    public static void main(String[] args) {

        if (args.length < 1) {
            System.out.println("Usage: java LineCutter filename");
            System.exit(1);
        }
        System.out.println("Enter the line to be removed:");
        Scanner lineToRemove = new Scanner(System.in);
        lineToRemove.nextLine();
        FileReader fr = null;
        FileWriter fw = null;
        BufferedReader br = null;
        BufferedWriter bw = null;

        try {
            fr = new FileReader(args[1]);
            br = new BufferedReader(fr);
            fw = new FileWriter(new File("output.txt"));
            bw = new BufferedWriter(fw);

            String line = br.readLine();
            while(line != null) {
                if (!line.equals(lineToRemove))
                    bw.write(line);
                line = br.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                br.close(); // NullPointerException
                fw.close();
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Operations finished.");
    }
}
</code>```

答:
If fr = new FileReader(args[1]) throws an exception then br will be null when you attempt to call br.close() and the NullPointerException will hide the actual problem. Your problem is most likely the use of 1 as the index causing an ArrayIndexOutOfBoundsException. You expect only one element in the args array, so you should be using args[0]. Remember, arrays are zero-based.

Also, you should be using a try-with-resources statement. It handles closing everything for you automatically in a null-safe manner. For example:

try (BufferedReader br = new BufferedReader(new FileReader(args[0]));
     BufferedWriter bw = new BufferedWriter(new FileWriter(new File("output.txt")))) {
  // I/O code...
} catch (IOException ex) {
  ex.printStackTrace();
}
```

<hr>

<p>Not sure what the following code is supposed to be doing:</p>

<pre class="lang-java prettyprint-override"><code>System.out.println("Enter the line to be removed:");
Scanner lineToRemove = new Scanner(System.in);
lineToRemove.nextLine();
</code>```

You don't do anything with result of lineToRemove.nextLine(). Though later you test if a String is equal to lineToRemove, which will always be false. Perhaps you mean:

String lineToRemove = new Scanner(System.in).nextLine();
```

Body:
I was writing code for a small tool that removes a user-given string from a file whose name is fed to the program from the command line. But when run, it throws a NullPointerException. I can't figure out why. Please help me solve this mystery. Thank you very much. This code is as follows.

/**
 * Remove certain lines from a text file.
 */

import java.util.*;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

public class LineCutter {
    public static void main(String[] args) {

        if (args.length < 1) {
            System.out.println("Usage: java LineCutter filename");
            System.exit(1);
        }
        System.out.println("Enter the line to be removed:");
        Scanner lineToRemove = new Scanner(System.in);
        lineToRemove.nextLine();
        FileReader fr = null;
        FileWriter fw = null;
        BufferedReader br = null;
        BufferedWriter bw = null;

        try {
            fr = new FileReader(args[1]);
            br = new BufferedReader(fr);
            fw = new FileWriter(new File("output.txt"));
            bw = new BufferedWriter(fw);

            String line = br.readLine();
            while(line != null) {
                if (!line.equals(lineToRemove))
                    bw.write(line);
                line = br.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                br.close(); // NullPointerException
                fw.close();
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Operations finished.");
    }
}

Body:
If fr = new FileReader(args[1]) throws an exception then br will be null when you attempt to call br.close() and the NullPointerException will hide the actual problem. Your problem is most likely the use of 1 as the index causing an ArrayIndexOutOfBoundsException. You expect only one element in the args array, so you should be using args[0]. Remember, arrays are zero-based.

Also, you should be using a try-with-resources statement. It handles closing everything for you automatically in a null-safe manner. For example:

try (BufferedReader br = new BufferedReader(new FileReader(args[0]));
     BufferedWriter bw = new BufferedWriter(new FileWriter(new File("output.txt")))) {
  // I/O code...
} catch (IOException ex) {
  ex.printStackTrace();
}

Not sure what the following code is supposed to be doing:

System.out.println("Enter the line to be removed:");
Scanner lineToRemove = new Scanner(System.in);
lineToRemove.nextLine();

You don't do anything with result of lineToRemove.nextLine(). Though later you test if a String is equal to lineToRemove, which will always be false. Perhaps you mean:

String lineToRemove = new Scanner(System.in).nextLine();