问:
Why string with System.lineSeparator() not equal in Java Eclipse
I am writing a function to capitalize the first letter of each line of a string. So the following input:

```<code>String test="this is a test" + System.lineSeparator() +
                    "write some words" + System.lineSeparator() +
                    "and sentences";
</code>```

output should be:

```<code>String expected="This is a test" + System.lineSeparator() +
                    "Write some words" + System.lineSeparator()+
            "And sentences";
</code>```

However, when I run with Eclipse. The output is:

```<code>This is a test[
Write some words]
And sentences
</code>```

Its byte:

```<code>54686973206973206120746573740a577269746520736f6d6520776f726473416e642073656e74656e636573
</code>```

The expected string in Eclipse is:

```<code>This is a test[
Write some words
]
And sentences
</code>```

Its byte:

```<code>54686973206973206120746573740d0a577269746520736f6d6520776f7264730d0a416e642073656e74656e636573
</code>```

So two strings are not equal. I run some code in an online Java compiler, two strings are equal.

I am wondering if any specific system command should be set to accomodate with lineSeparator() and make two Strings (output and expected) be equal?

Thanks;

答:
The issue you should be solving is not really with Eclipse.  Your code should be written so that it is platform independent.

For your command-line/linux environment, the line separator is a line-feed (LF) often referred to as a new-line (NL; "\n"; '0a').  For Eclipse/Windows/DOS, the separator is carriage-return, line-feed (CRLF; "\r\n"; {'0d','0a'}).

Based on you hex output, it shows the Eclipse line separator is indeed CRLF, while the edited string you constructed only has LF; i.e. you are doing something that incorrectly changes the CRLF of the test string to a LF.

For example, you may be splitting the test string into multiple strings and then constructing the edited string with "\n"; e.g. str1 + "\n" + str2 -OR- String.format("%s\n%s", str1, str2).  Instead, you should construct it with the System.LineSeperator(); e.g. String.format("%s%s%s", str1, System.LineSeperator(), str2).

If you really wish to change the Eclipse behavior, as I mentioned before, I'd suggest looking here.

REFERENCE:
We don't see your code used to create the updated text.  But you might try dumping the bytes of your two strings to see how they differ.  Also take a look here.

For example, in Eclipse I see a carriage return and line feed.

```<code>
    false
    4162630a446566
    4162630d0a446566
</code>```

```<code>

    public static void main(String args[])
    {
       String s = "Abc\nDef";
       String t = "Abc"+System.lineSeparator()+"Def";
       System.out.println(s.equals(t));
       System.out.println(hexStr(s.getBytes()));
       System.out.println((hexStr(t.getBytes())));
    }
    static String hexStr(byte[] bytes) {
        try (Formatter formatter = new Formatter()) {
            for (byte b : bytes) formatter.format("%02x", b);
            return formatter.toString();
        }
    }

</code>```

Body:
I am writing a function to capitalize the first letter of each line of a string. So the following input:

String test="this is a test" + System.lineSeparator() +
                    "write some words" + System.lineSeparator() +
                    "and sentences";

output should be:

String expected="This is a test" + System.lineSeparator() +
                    "Write some words" + System.lineSeparator()+
            "And sentences";

However, when I run with Eclipse. The output is:

This is a test[
Write some words]
And sentences

Its byte:

54686973206973206120746573740a577269746520736f6d6520776f726473416e642073656e74656e636573

The expected string in Eclipse is:

This is a test[
Write some words
]
And sentences

Its byte:

54686973206973206120746573740d0a577269746520736f6d6520776f7264730d0a416e642073656e74656e636573

So two strings are not equal. I run some code in an online Java compiler, two strings are equal.

I am wondering if any specific system command should be set to accomodate with lineSeparator() and make two Strings (output and expected) be equal?

Thanks;

Body:
The issue you should be solving is not really with Eclipse.  Your code should be written so that it is platform independent.

For your command-line/linux environment, the line separator is a line-feed (LF) often referred to as a new-line (NL; "\n"; '0a').  For Eclipse/Windows/DOS, the separator is carriage-return, line-feed (CRLF; "\r\n"; {'0d','0a'}).

Based on you hex output, it shows the Eclipse line separator is indeed CRLF, while the edited string you constructed only has LF; i.e. you are doing something that incorrectly changes the CRLF of the test string to a LF.

For example, you may be splitting the test string into multiple strings and then constructing the edited string with "\n"; e.g. str1 + "\n" + str2 -OR- String.format("%s\n%s", str1, str2).  Instead, you should construct it with the System.LineSeperator(); e.g. String.format("%s%s%s", str1, System.LineSeperator(), str2).

If you really wish to change the Eclipse behavior, as I mentioned before, I'd suggest looking here.

REFERENCE:
We don't see your code used to create the updated text.  But you might try dumping the bytes of your two strings to see how they differ.  Also take a look here.

For example, in Eclipse I see a carriage return and line feed.

    false
    4162630a446566
    4162630d0a446566

    public static void main(String args[])
    {
       String s = "Abc\nDef";
       String t = "Abc"+System.lineSeparator()+"Def";
       System.out.println(s.equals(t));
       System.out.println(hexStr(s.getBytes()));
       System.out.println((hexStr(t.getBytes())));
    }
    static String hexStr(byte[] bytes) {
        try (Formatter formatter = new Formatter()) {
            for (byte b : bytes) formatter.format("%02x", b);
            return formatter.toString();
        }
    }


来源: stackexchange

问:
$.getJSON returns undefined then returns requested data
I got myself stuck in a situation. I was coding a Wikipedia search tool for a personal practice project, but I've ran into a small error. When a user enters a word into the search bar, the input will be store into the data parameter of $.getJSON, then the response will return a array of title and description objects based on the word entered in the search bar. The $.getJSON function will display 5 sets of a title and it's description in a list format in the designated HTML. Simple enough, but the issue is the $.getJSON function will display the wording "undefined", then continue to display the required set of titles and descriptions. Below I have listed my JS coding for your viewing. Also, the full code can be viewed at my codepen.

Can anyone give me a heads up of what might be the issue. As $.getJSON is asynchronous, that might be the issue, but I can't quite put my finger on it. Thanks in advance!

```<code>$("#search-word").on("keydown", function(event) {
if(event.keyCode == 13) {
  event.preventDefault();
  var input = {search: $(this).val()};
  getWikiInfo(input);
}
});//search end

function getWikiInfo(input) {
var wikipApi = "https://en.wikipedia.org/w/api.php?format=json&action=opensearch&callback=?";
var getWikipHtml = function(response) {
  console.log(response);
  var wikipHtml;
  for(var i = 1; i < 6; i++) {
    wikipHtml += '<div class="list"><h3>' + response[1][i] + '</h3><p>' + response[2][i] + '</p></div>';
  }
  $("#list-container").html(wikipHtml);
  }
$.getJSON(wikipApi, input, getWikipHtml);
}//getWikiInfo end
</code>```

答:
You need to do minor change. Initialize wikipHtml to empty string and check if the response[1][i] is not undefined. Below is the updated code:

```<code>var wikipHtml = '';
for (var i = 1; i < 6; i++) {
  if (response[1][i] !== undefined)
    wikipHtml += '<div class="list"><h3>' + response[1][i] + '</h3><p>' + response[2][i] + '</p></div>';
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I got myself stuck in a situation. I was coding a Wikipedia search tool for a personal practice project, but I've ran into a small error. When a user enters a word into the search bar, the input will be store into the data parameter of $.getJSON, then the response will return a array of title and description objects based on the word entered in the search bar. The $.getJSON function will display 5 sets of a title and it's description in a list format in the designated HTML. Simple enough, but the issue is the $.getJSON function will display the wording "undefined", then continue to display the required set of titles and descriptions. Below I have listed my JS coding for your viewing. Also, the full code can be viewed at my codepen.

Can anyone give me a heads up of what might be the issue. As $.getJSON is asynchronous, that might be the issue, but I can't quite put my finger on it. Thanks in advance!

$("#search-word").on("keydown", function(event) {
if(event.keyCode == 13) {
  event.preventDefault();
  var input = {search: $(this).val()};
  getWikiInfo(input);
}
});//search end

function getWikiInfo(input) {
var wikipApi = "https://en.wikipedia.org/w/api.php?format=json&action=opensearch&callback=?";
var getWikipHtml = function(response) {
  console.log(response);
  var wikipHtml;
  for(var i = 1; i < 6; i++) {
    wikipHtml += '

' + response[1][i] + '

' + response[2][i] + '

';
  }
  $("#list-container").html(wikipHtml);
  }
$.getJSON(wikipApi, input, getWikipHtml);
}//getWikiInfo end

Body:
You need to do minor change. Initialize wikipHtml to empty string and check if the response[1][i] is not undefined. Below is the updated code:

var wikipHtml = '';
for (var i = 1; i < 6; i++) {
  if (response[1][i] !== undefined)
    wikipHtml += '<div class="list"><h3>' + response[1][i] + '</h3><p>' + response[2][i] + '</p></div>';
}


问:
How can I make this Oracle SQL query More efficient and less redundant to avoid a "snapshot" error on large datasets?
I'm trying to improve my skills querying large data sets.

I want payments during a specific date range with an 'xyz' paycode,
where the "id1" is not 0 and not null, and if there are more than 13 payments to a specific "id1" This should be in the result of my query.

I feel like I'm being redundant querying the payment table twice, but I'm not sure how to get the id1 count and the payments with the specific paycode in a single query.

If I run this on a lot of data it's extremely slow and will not complete. I get a "snapshot" error.

All the table / data relations are indicated correctly in my joins / queries below, but how can I make this more elegant and more performant?

```<code>SELECT
    emp.emp_fname first_name,
    emp.emp_lname last_name,
    pmt.id1,
    pmt.id2,
    pmt.pay_date,
    pmt.pay_key,
    pmt.check_num,
    case.file_num
FROM

/*query to collect all valid id1s that occur more than 13 times */
    (
        SELECT
            id1
        FROM
            (
                SELECT
                    id1,
                    COUNT(*) AS cnt
                FROM
                    payment pmt
                WHERE
                        pay_key IN (
                            SELECT DISTINCT
                                pay_key
                            FROM
                                allotment
                            WHERE
                                pay_code = 'xyz'
                        )
                    AND
                        id1 <> 0
                    AND
                        id1 IS NOT NULL
                    AND
                        trunc(pmt.pay_date) BETWEEN TO_DATE('01-JUL-17') AND TO_DATE('01-OCT-17')
                    AND
                        upper(TRIM(deleted) ) = 'N'
                GROUP BY
                    id1
            )
        WHERE
            cnt > 13
    ) ptxids

    /*join these to full-payment records with matchinig id1s during this time*/
    INNER JOIN (
        SELECT
            *
        FROM
            payment
        WHERE
                upper(TRIM(deleted) ) = 'N'
            AND
                id1 <> 0
            AND
                id1 IS NOT NULL
            AND
                trunc(payment.pay_date) BETWEEN TO_DATE('01-JUL-17') AND TO_DATE('01-OCT-17')
    ) pmt ON pmt.id1 = ptxids.id1

    /*join on allotments where pay_key matches and allotment pay_code is xyz*/
    INNER JOIN allotment alt ON
        upper(TRIM(alt.deleted) ) = 'N'
    AND
        alt.pay_code = 'xyz'
    AND
        alt.pay_key = pmt.pay_key
   /*join on case to return the requested file-num*/
    INNER JOIN case ON case.event_num = alt.event_num
  /*join on emp to return payee / employee name */
    INNER JOIN  emp ON emp.event_num = case.event_num;
</code>```

答:
This join:

```<code>FROM

/*query to collect all valid id1s that occur more than 13 times */
    (
        SELECT
            id1
        FROM
            (
                SELECT
                    id1,
                    COUNT(*) AS cnt
                FROM
                    payment pmt
                WHERE
                        pay_key IN (
                            SELECT DISTINCT
                                pay_key
                            FROM
                                allotment
                            WHERE
                                pay_code = 'xyz'
                        )
                    AND
                        id1 <> 0
                    AND
                        id1 IS NOT NULL
                    AND
                        trunc(pmt.pay_date) BETWEEN TO_DATE('01-JUL-17') AND TO_DATE('01-OCT-17')
                    AND
                        upper(TRIM(deleted) ) = 'N'
                GROUP BY
                    id1
            )
        WHERE
            cnt > 13
    ) ptxids

    /*join these to full-payment records with matchinig id1s during this time*/
    INNER JOIN (
        SELECT
            *
        FROM
            payment
        WHERE
                upper(TRIM(deleted) ) = 'N'
            AND
                id1 <> 0
            AND
                id1 IS NOT NULL
            AND
                trunc(payment.pay_date) BETWEEN TO_DATE('01-JUL-17') AND TO_DATE('01-OCT-17')
    ) pmt ON pmt.id1 = ptxids.id1
</code>```

can be eliminated with a help of count(*) over analytic function. Just one subquery:

```<code> FROM
 /*query to collect all valid id1s that occur more than 13 times */
        (
            SELECT pmt.*,
                COUNT(*) Over( Partition by id1) AS cnt
            FROM
                payment pmt
            WHERE
                    pay_key IN (
                        SELECT
                            pay_key
                        FROM
                            allotment
                        WHERE
                            pay_code = 'xyz'
                    )
                AND
                    id1 <> 0
                AND
                    id1 IS NOT NULL
                AND pmt.pay_date >= TO_DATE('01-JUL-17')
                AND pmt.pay_date < TO_DATE('01-OCT-17')+1
                AND
                    upper(TRIM(deleted) ) = 'N'
        ) xx
    WHERE
        xx.cnt > 13
</code>```

Some minor changes:

removed redundant DISTINCT from the subquery

removed trunc(pmt.pay_date) because it prevents RDBMS from using an index
on this column

Body:
I'm trying to improve my skills querying large data sets.

I want payments during a specific date range with an 'xyz' paycode,
where the "id1" is not 0 and not null, and if there are more than 13 payments to a specific "id1" This should be in the result of my query.

I feel like I'm being redundant querying the payment table twice, but I'm not sure how to get the id1 count and the payments with the specific paycode in a single query.

If I run this on a lot of data it's extremely slow and will not complete. I get a "snapshot" error.

All the table / data relations are indicated correctly in my joins / queries below, but how can I make this more elegant and more performant?

SELECT
    emp.emp_fname first_name,
    emp.emp_lname last_name,
    pmt.id1,
    pmt.id2,
    pmt.pay_date,
    pmt.pay_key,
    pmt.check_num,
    case.file_num
FROM

/*query to collect all valid id1s that occur more than 13 times */
    (
        SELECT
            id1
        FROM
            (
                SELECT
                    id1,
                    COUNT(*) AS cnt
                FROM
                    payment pmt
                WHERE
                        pay_key IN (
                            SELECT DISTINCT
                                pay_key
                            FROM
                                allotment
                            WHERE
                                pay_code = 'xyz'
                        )
                    AND
                        id1 <> 0
                    AND
                        id1 IS NOT NULL
                    AND
                        trunc(pmt.pay_date) BETWEEN TO_DATE('01-JUL-17') AND TO_DATE('01-OCT-17')
                    AND
                        upper(TRIM(deleted) ) = 'N'
                GROUP BY
                    id1
            )
        WHERE
            cnt > 13
    ) ptxids

    /*join these to full-payment records with matchinig id1s during this time*/
    INNER JOIN (
        SELECT
            *
        FROM
            payment
        WHERE
                upper(TRIM(deleted) ) = 'N'
            AND
                id1 <> 0
            AND
                id1 IS NOT NULL
            AND
                trunc(payment.pay_date) BETWEEN TO_DATE('01-JUL-17') AND TO_DATE('01-OCT-17')
    ) pmt ON pmt.id1 = ptxids.id1

    /*join on allotments where pay_key matches and allotment pay_code is xyz*/
    INNER JOIN allotment alt ON
        upper(TRIM(alt.deleted) ) = 'N'
    AND
        alt.pay_code = 'xyz'
    AND
        alt.pay_key = pmt.pay_key
   /*join on case to return the requested file-num*/
    INNER JOIN case ON case.event_num = alt.event_num
  /*join on emp to return payee / employee name */
    INNER JOIN  emp ON emp.event_num = case.event_num;

Body:
This join:

FROM

/*query to collect all valid id1s that occur more than 13 times */
    (
        SELECT
            id1
        FROM
            (
                SELECT
                    id1,
                    COUNT(*) AS cnt
                FROM
                    payment pmt
                WHERE
                        pay_key IN (
                            SELECT DISTINCT
                                pay_key
                            FROM
                                allotment
                            WHERE
                                pay_code = 'xyz'
                        )
                    AND
                        id1 <> 0
                    AND
                        id1 IS NOT NULL
                    AND
                        trunc(pmt.pay_date) BETWEEN TO_DATE('01-JUL-17') AND TO_DATE('01-OCT-17')
                    AND
                        upper(TRIM(deleted) ) = 'N'
                GROUP BY
                    id1
            )
        WHERE
            cnt > 13
    ) ptxids

    /*join these to full-payment records with matchinig id1s during this time*/
    INNER JOIN (
        SELECT
            *
        FROM
            payment
        WHERE
                upper(TRIM(deleted) ) = 'N'
            AND
                id1 <> 0
            AND
                id1 IS NOT NULL
            AND
                trunc(payment.pay_date) BETWEEN TO_DATE('01-JUL-17') AND TO_DATE('01-OCT-17')
    ) pmt ON pmt.id1 = ptxids.id1

can be eliminated with a help of count(*) over analytic function. Just one subquery:

 FROM
 /*query to collect all valid id1s that occur more than 13 times */
        (
            SELECT pmt.*,
                COUNT(*) Over( Partition by id1) AS cnt
            FROM
                payment pmt
            WHERE
                    pay_key IN (
                        SELECT
                            pay_key
                        FROM
                            allotment
                        WHERE
                            pay_code = 'xyz'
                    )
                AND
                    id1 <> 0
                AND
                    id1 IS NOT NULL
                AND pmt.pay_date >= TO_DATE('01-JUL-17')
                AND pmt.pay_date < TO_DATE('01-OCT-17')+1
                AND
                    upper(TRIM(deleted) ) = 'N'
        ) xx
    WHERE
        xx.cnt > 13

Some minor changes:

removed redundant DISTINCT from the subquery

removed trunc(pmt.pay_date) because it prevents RDBMS from using an index
on this column


问:
How to set environment variables in Phoenix with Distillery library?
Follow this guide to use Distillery to release a elixir/phoenix project:

https://blog.polyscribe.io/a-complete-guide-to-deploying-elixir-phoenix-applications-on-kubernetes-part-1-setting-up-d88b35b64dcd

At the set config/prod.exs step, the author wrote:

```<code>config :myapp, Myapp.Repo,
  adapter: Ecto.Adapters.Postgres,
  hostname: "${DB_HOSTNAME}",
  username: "${DB_USERNAME}",
  password: "${DB_PASSWORD}",
  database: "${DB_NAME}",
</code>```

to config database. Here using ${DB_HOSTNAME} type to get environment variables, but not System.get_env("DB_HOSTNAME").

However, when I run MIX_ENV=prod mix release --env=prod and set environment variables local:

```<code>REPLACE_OS_VARS=true PORT=4000 HOST=0.0.0.0 SECRET_KEY_BASE=highlysecretkey DB_USERNAME=postgres DB_PASSWORD=postgres DB_NAME=myapp_dev DB_HOSTNAME=localhost ./_build/prod/rel/myapp/bin/myapp foreground
</code>```

It loops:

```<code>12:05:13.671 [error] Postgrex.Protocol (#PID<0.1348.0>) failed to connect: ** (DBConnection.ConnectionError) tcp connect (${DB_HOSTNAME}:5432): non-existing domain - :nxdomain
12:05:13.671 [error] Postgrex.Protocol (#PID<0.1347.0>) failed to connect: ** (DBConnection.ConnectionError) tcp connect (${DB_HOSTNAME}:5432): non-existing domain - :nxdomain
12:05:13.672 [error] Postgrex.Protocol (#PID<0.1344.0>) failed to connect: ** (DBConnection.ConnectionError) tcp connect (${DB_HOSTNAME}:5432): non-existing domain - :nxdomain
12:05:13.672 [error] Postgrex.Protocol (#PID<0.1346.0>) failed to connect: ** (DBConnection.ConnectionError) tcp connect (${DB_HOSTNAME}:5432): non-existing domain - :nxdomain
...
</code>```

It seems ${DB_HOSTNAME} didn't been known by elixir/phoenix.

I am using Elixir 1.5.2 and Phoenix 1.3 now. The version problem?

答:
I never saw this approach and I am unsure how it is supposed to work. The common way to getting the environment variables at runtime would be:

```<code>{:system, "VAR"}
</code>```

For your case it’d be:

```<code>config :myapp, Myapp.Repo,
  adapter: Ecto.Adapters.Postgres,
  hostname: {:system, "DB_HOSTNAME"},
  username: {:system, "DB_USERNAME"},
  password: {:system, "DB_PASSWORD"},
  database: {:system, "DB_NAME"}
</code>```

Body:
Follow this guide to use Distillery to release a elixir/phoenix project:

https://blog.polyscribe.io/a-complete-guide-to-deploying-elixir-phoenix-applications-on-kubernetes-part-1-setting-up-d88b35b64dcd

At the set config/prod.exs step, the author wrote:

config :myapp, Myapp.Repo,
  adapter: Ecto.Adapters.Postgres,
  hostname: "${DB_HOSTNAME}",
  username: "${DB_USERNAME}",
  password: "${DB_PASSWORD}",
  database: "${DB_NAME}",

to config database. Here using ${DB_HOSTNAME} type to get environment variables, but not System.get_env("DB_HOSTNAME").

However, when I run MIX_ENV=prod mix release --env=prod and set environment variables local:

REPLACE_OS_VARS=true PORT=4000 HOST=0.0.0.0 SECRET_KEY_BASE=highlysecretkey DB_USERNAME=postgres DB_PASSWORD=postgres DB_NAME=myapp_dev DB_HOSTNAME=localhost ./_build/prod/rel/myapp/bin/myapp foreground

It loops:

12:05:13.671 [error] Postgrex.Protocol (#PID<0.1348.0>) failed to connect: ** (DBConnection.ConnectionError) tcp connect (${DB_HOSTNAME}:5432): non-existing domain - :nxdomain
12:05:13.671 [error] Postgrex.Protocol (#PID<0.1347.0>) failed to connect: ** (DBConnection.ConnectionError) tcp connect (${DB_HOSTNAME}:5432): non-existing domain - :nxdomain
12:05:13.672 [error] Postgrex.Protocol (#PID<0.1344.0>) failed to connect: ** (DBConnection.ConnectionError) tcp connect (${DB_HOSTNAME}:5432): non-existing domain - :nxdomain
12:05:13.672 [error] Postgrex.Protocol (#PID<0.1346.0>) failed to connect: ** (DBConnection.ConnectionError) tcp connect (${DB_HOSTNAME}:5432): non-existing domain - :nxdomain
...

It seems ${DB_HOSTNAME} didn't been known by elixir/phoenix.

I am using Elixir 1.5.2 and Phoenix 1.3 now. The version problem?

Body:
I never saw this approach and I am unsure how it is supposed to work. The common way to getting the environment variables at runtime would be:

{:system, "VAR"}

For your case it’d be:

config :myapp, Myapp.Repo,
  adapter: Ecto.Adapters.Postgres,
  hostname: {:system, "DB_HOSTNAME"},
  username: {:system, "DB_USERNAME"},
  password: {:system, "DB_PASSWORD"},
  database: {:system, "DB_NAME"}


问:
100+ "Class implemented in both MapKit and VectorKit" warnings with Xcode 9.0.1 and above
While running my project (which doesn't even use MapKit), my console gets spammed with more than a hundred class duplicate warnings:

objc[6377]: Class ___MKPlaceBusinessInfoItemAccessibility_super is implemented in both /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/AccessibilityBundles/MapKit.axbundle/MapKit (0x12f128f00) and /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/AccessibilityBundles/VectorKit.axbundle/VectorKit (0x12f2187b0). One of the two will be used. Which one is undefined.

These warnings were not present with Xcode 9.0.0, I am only experiencing this on Xcode 9.0.1 and above.

I am aware that this is a bug and I found a radar that is about this issue. Is there a way to silence these warnings without affecting the visibility of other SDK warnings?

答:
I don't give a damn about accessibility in the simulator so I just renamed one of the duplicate files so it wouldn't be found:

```<code>mv /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/AccessibilityBundles/MapKit.axbundle/MapKit /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/AccessibilityBundles/MapKit.axbundle/MapKit_
</code>```

lol

Body:
I don't give a damn about accessibility in the simulator so I just renamed one of the duplicate files so it wouldn't be found:

mv /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/AccessibilityBundles/MapKit.axbundle/MapKit /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/AccessibilityBundles/MapKit.axbundle/MapKit_

lol


问:
Size of buttons inside GridBagLayout
I have an 3 * 6 array of JButtons inside a GridBagLayout. But since the text length of each button may vary, each column of buttons has slightly different width. How do I make them have the same width?

Here is the code:

```<code>for (int i = 0; i < 3; i++)
{
    for (int j = 0; j < 6; j++)
    {
        buttonConstraints.fill = GridBagConstraints.BOTH;
        buttonConstraints.weightx = 1;
        buttonConstraints.weighty = 1;
        buttonConstraints.gridx = j;
        buttonConstraints.gridy = i;
        buttonPanel.add(buttons[i * 6 + j], buttonConstraints);
    }
}
</code>```

Thanks in advance.

答:
try this:</p>

```<code>buttonConstraints.fill = GridBagConstraints.HORIZONTAL;
</code>```

Title: Size of buttons inside GridBagLayout

Body:
I have an 3 * 6 array of JButtons inside a GridBagLayout. But since the text length of each button may vary, each column of buttons has slightly different width. How do I make them have the same width?

Here is the code:

for (int i = 0; i < 3; i++)
{
    for (int j = 0; j < 6; j++)
    {
        buttonConstraints.fill = GridBagConstraints.BOTH;
        buttonConstraints.weightx = 1;
        buttonConstraints.weighty = 1;
        buttonConstraints.gridx = j;
        buttonConstraints.gridy = i;
        buttonPanel.add(buttons[i * 6 + j], buttonConstraints);
    }
}

Thanks in advance.

Body:
try this:

buttonConstraints.fill = GridBagConstraints.HORIZONTAL;


问:
php mysql - get product thumbnail image of a product
I'm using woocommerce, I'm trying to retrieve thumbnail image of a product, I've tried to use woocommerce api but it did not have any parameters for thumbnail, I've searched in database and found it in wp_postmeta table, but the structure of meta_value is very difficult to read, for example:

```<code>a:5:{s:5:"width";i:694;s:6:"height";i:660;s:4:"file";s:69:"2017/11/روغن-ذرت-زرین-1.8-لیتری-33150-26500اصل.jpg";s:5:"sizes";a:4:{s:9:"thumbnail";a:4:{s:4:"file";s:69:"روغن-ذرت-زرین-1.8-لیتری-33150-26500اصل-150x150.jpg";s:5:"width";i:150;s:6:"height";i:150;s:9:"mime-type";s:10:"image/jpeg";}s:6:"medium";a:4:{s:4:"file";s:69:"روغن-ذرت-زرین-1.8-لیتری-33150-26500اصل-300x285.jpg";s:5:"width";i:300;s:6:"height";i:285;s:9:"mime-type";s:10:"image/jpeg";}s:14:"shop_thumbnail";a:4:{s:4:"file";s:69:"روغن-ذرت-زرین-1.8-لیتری-33150-26500اصل-150x143.jpg";s:5:"width";i:150;s:6:"height";i:143;s:9:"mime-type";s:10:"image/jpeg";}s:12:"shop_catalog";a:4:{s:4:"file";s:69:"روغن-ذرت-زرین-1.8-لیتری-33150-26500اصل-300x285.jpg";s:5:"width";i:300;s:6:"height";i:285;s:9:"mime-type";s:10:"image/jpeg";}}s:10:"image_meta";a:12:{s:8:"aperture";s:1:"0";s:6:"credit";s:0:"";s:6:"camera";s:0:"";s:7:"caption";s:0:"";s:17:"created_timestamp";s:1:"0";s:9:"copyright";s:0:"";s:12:"focal_length";s:1:"0";s:3:"iso";s:1:"0";s:13:"shutter_speed";s:1:"0";s:5:"title";s:0:"";s:11:"orientation";s:1:"1";s:8:"keywords";a:0:{}}}
</code>```

it has all images of a product with different sizes, the question is, how can I read this in php and get the image src I want from this?

答:
That format is serialize array, you can unserialize it using WordPress function maybe_unserialize

maybe_unserialize( $your_meta_value );

ContentLicense: CC BY-SA 4.0

Body:
I'm using woocommerce, I'm trying to retrieve thumbnail image of a product, I've tried to use woocommerce api but it did not have any parameters for thumbnail, I've searched in database and found it in wp_postmeta table, but the structure of meta_value is very difficult to read, for example:

a:5:{s:5:"width";i:694;s:6:"height";i:660;s:4:"file";s:69:"2017/11/روغن-ذرت-زرین-1.8-لیتری-33150-26500اصل.jpg";s:5:"sizes";a:4:{s:9:"thumbnail";a:4:{s:4:"file";s:69:"روغن-ذرت-زرین-1.8-لیتری-33150-26500اصل-150x150.jpg";s:5:"width";i:150;s:6:"height";i:150;s:9:"mime-type";s:10:"image/jpeg";}s:6:"medium";a:4:{s:4:"file";s:69:"روغن-ذرت-زرین-1.8-لیتری-33150-26500اصل-300x285.jpg";s:5:"width";i:300;s:6:"height";i:285;s:9:"mime-type";s:10:"image/jpeg";}s:14:"shop_thumbnail";a:4:{s:4:"file";s:69:"روغن-ذرت-زرین-1.8-لیتری-33150-26500اصل-150x143.jpg";s:5:"width";i:150;s:6:"height";i:143;s:9:"mime-type";s:10:"image/jpeg";}s:12:"shop_catalog";a:4:{s:4:"file";s:69:"روغن-ذرت-زرین-1.8-لیتری-33150-26500اصل-300x285.jpg";s:5:"width";i:300;s:6:"height";i:285;s:9:"mime-type";s:10:"image/jpeg";}}s:10:"image_meta";a:12:{s:8:"aperture";s:1:"0";s:6:"credit";s:0:"";s:6:"camera";s:0:"";s:7:"caption";s:0:"";s:17:"created_timestamp";s:1:"0";s:9:"copyright";s:0:"";s:12:"focal_length";s:1:"0";s:3:"iso";s:1:"0";s:13:"shutter_speed";s:1:"0";s:5:"title";s:0:"";s:11:"orientation";s:1:"1";s:8:"keywords";a:0:{}}}

it has all images of a product with different sizes, the question is, how can I read this in php and get the image src I want from this?


问:
C++ how to format a pointer to an array of classes?
I want to read information from a file and put that information in an pointer to an array of classes. it keeps throwing an exception at us->setUserName(name); but if I change it to us[i]->setUserName(name); it says "expression must have pointer type". How can I fix this?

```<code>    const int SIZE = 100;
    User *us = new User[SIZE];

    input.open("Account.txt", ios::in);

    if (input)
    {
       input >> size;

       for (int i = 0; i < size; i++)
       {
          us = new User[i];
          getline(input, uName);
          us->setUserName(uName);

          getline(input, password);
          us->setPassword(password);

          getline(input, name);
          us->setName(name);
       }
    else
       cout << "Error opening file" << endl;
</code>```

here is the user class:

```<code>    class User
    {
    public:
      User();
      ~User();

      void setName(string);
      string getName();

      void setUserName(string);
      string getUserName();

      void setPassword(string);
      string getPassword();

      void setFollower(vector<User*>*);
      vector<User*>* getFollower();

      void setFollowing(vector<User*>*);
      vector<User*>* getFollowing();

    protected:
      string name;
      string userName;
      string password;

      vector <User*>* followers;
      vector <User*>* following;

  };
</code>```

答:
```<code>us = new User[i];
</code>```

Your problem here. This code will create an array has i element, every element is a new object User, and then pointer us will point to this.
I suggest you use vector, it's dynamic array, it's better than a static array with SIZE = 100 in case you are not sure about input file (Account.txt could be contain more than 100 user information)

```<code>std::vector<User> v;  // create a vector of User

input.open("Account.txt", ios::in);

if (input)
{
    input >> size;
    User user;  // a temporary user
    for (int i = 0; i < size; i++)
    {
        getline(input, uName);
        user->setUserName(uName);

        getline(input, password);
        user->setPassword(password);

        getline(input, name);
        user->setName(name);
        v.push_back(user); // push to vector
    }
}
else
    cout << "Error opening file" << endl;
</code>```

Body:
I want to read information from a file and put that information in an pointer to an array of classes. it keeps throwing an exception at us->setUserName(name); but if I change it to us[i]->setUserName(name); it says "expression must have pointer type". How can I fix this?

    const int SIZE = 100;
    User *us = new User[SIZE];

    input.open("Account.txt", ios::in);

    if (input)
    {
       input >> size;

       for (int i = 0; i < size; i++)
       {
          us = new User[i];
          getline(input, uName);
          us->setUserName(uName);

          getline(input, password);
          us->setPassword(password);

          getline(input, name);
          us->setName(name);
       }
    else
       cout << "Error opening file" << endl;

here is the user class:

    class User
    {
    public:
      User();
      ~User();

      void setName(string);
      string getName();

      void setUserName(string);
      string getUserName();

      void setPassword(string);
      string getPassword();

      void setFollower(vector<User*>*);
      vector<User*>* getFollower();

      void setFollowing(vector<User*>*);
      vector<User*>* getFollowing();

    protected:
      string name;
      string userName;
      string password;

      vector <User*>* followers;
      vector <User*>* following;

  };

Body:
us = new User[i];

Your problem here. This code will create an array has i element, every element is a new object User, and then pointer us will point to this.
I suggest you use vector, it's dynamic array, it's better than a static array with SIZE = 100 in case you are not sure about input file (Account.txt could be contain more than 100 user information)

std::vector<User> v;  // create a vector of User

input.open("Account.txt", ios::in);

if (input)
{
    input >> size;
    User user;  // a temporary user
    for (int i = 0; i < size; i++)
    {
        getline(input, uName);
        user->setUserName(uName);

        getline(input, password);
        user->setPassword(password);

        getline(input, name);
        user->setName(name);
        v.push_back(user); // push to vector
    }
}
else
    cout << "Error opening file" << endl;


问:
find instances of a form in vb 2008
```<code>Dim f as new frmNameHere
f.show()
</code>```

How do I find all instances of frmNameHere created using the above code?

答:
For example:

```<code>For i As Int32 = 1 To 10
   Dim frm As New frmNameHere()
   frm.Show()
Next
Dim openForms = Application.OpenForms.OfType(Of frmNameHere)()
While openForms.Any()
   openForms.First.Close()
End While
</code>```

Works also without linq, but then you have to iterate through all OpenForms:

```<code>Dim forms As FormCollection = Application.OpenForms
For Each form As Form In forms
   If TypeOf form Is frmNameHere Then
      'do something with your frmNameHere-Form'
   End If
Next
</code>```

Title: find instances of a form in vb 2008

Body:
Dim f as new frmNameHere
f.show()

How do I find all instances of frmNameHere created using the above code?

Body:
For example:

For i As Int32 = 1 To 10
   Dim frm As New frmNameHere()
   frm.Show()
Next
Dim openForms = Application.OpenForms.OfType(Of frmNameHere)()
While openForms.Any()
   openForms.First.Close()
End While

Works also without linq, but then you have to iterate through all OpenForms:

Dim forms As FormCollection = Application.OpenForms
For Each form As Form In forms
   If TypeOf form Is frmNameHere Then
      'do something with your frmNameHere-Form'
   End If
Next


问:
Getting Commit ID in CodePipeline
I am using CodePipeline with CodeCommit. Builds are triggered automatically with push to master branch. In CodePipeline console it is clearly visible that i am receiving commit id but i need to get it in the build environment so i can add them as a tag to the ECS image when i build it. Is there a way to get in in build environment.

答: You can use the CODEBUILD_RESOLVED_SOURCE_VERSION environment variable to retrieve the commit hash displayed in CodePipeline at build time.

Title: Getting Commit ID in CodePipeline


问:
Xcode 6: Keyboard does not show up in simulator
The keyboard does not show up when I run the simulator and click in the UITextView. How do I re-enable the keyboard?

It used to work but now it doesn't - I don't know what I might have clicked by accident.

答:
If keyboard do not shown up automatically in simulator, just press [Command+K]

or Hardware -> Keyboard -> Toggle Software Keyboard


问:
How to add additional jar file to spring-boot application at runtime?
I built a spring-boot application and make the jar file exectuable. There is a compileOnly dependency on my project which need to be provided at runtime. When I run java -jar myApp.jar I will get ClassNotFound exeception which is expected. But I don't know how to add the additional jar file on java command. I have tried below command:

```<code>java -Dloader.path=/libs/third.jar -jar myApp.jar
</code>```

but it doesn't work. How can I add /libs/third.jar on my application?

答:
On Unix:
java -cp MyApp.jar:./libs/third.jar com.packagename.MainClass

On Windows: use ; instead of : and also \ instead of /

Body:
I built a spring-boot application and make the jar file exectuable. There is a compileOnly dependency on my project which need to be provided at runtime. When I run java -jar myApp.jar I will get ClassNotFound exeception which is expected. But I don't know how to add the additional jar file on java command. I have tried below command:

java -Dloader.path=/libs/third.jar -jar myApp.jar

but it doesn't work. How can I add /libs/third.jar on my application?


问:
How to get the result of the confirm popup in to a variable in spring MVC?
This is my jsp page

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
function getChoice(){
    var k=confirm("Do you want me to overwrite the existing file ?");
    return k;
}
</script>
</head>
<body style="background-color:powderblue;color:Tomato">
<center><form method="POST" action="saveagain">
<h3>${message} </h3>
            <br> <br>
<input type="hidden" name="fname" value="${filename}">
<input type="hidden" name="fcontent" value="${filecontent}"> <br><br>
 <input type="button" value="Overwrite ?" onclick="choice=getChoice()"/>
<input type="submit" value="Submit ?"></form></center>
<br>
<br>
<center><b>${m}</b></center>
<br><br>
<center><a href="toupload">Click me to upload a file</a>  <br><br>
</center>
</body>
</html>
</code>```

In the above code, i want to get the result of confirm popup in to a variable "choice". How to do that ?

Modified code :

bean class :

```<code>package com.fss;

public class Choice {
 private String choice;
private String fname;
private String fcontent;

public String getChoice() {
    return choice;
}

public void setChoice(String choice) {
    this.choice = choice;
}

public String getFname() {
    return fname;
}

public void setFname(String fname) {
    this.fname = fname;
}

public String getFcontent() {
    return fcontent;
}

public void setFcontent(String fcontent) {
    this.fcontent = fcontent;
}

}
</code>```

this is my jsp page :

```<code><html>
<head>
<script>
function getUserChoice(){
    var k=confirm("Do you want me to overwrite the existing file ?");
    $('#choice').val(k);
    return k;
}
</script>
</head>
<body>
<center><h3>${message} </h3></center>
            <br>
  <center><form method="POST" action="saveagain">
    <input type="hidden" name="fname" value="${filename}">
    <input type="hidden" name="fcontent" value="${filecontent}">
    <input type="hidden" name="choice" id="choice"> <br><br>
    <input type="submit" value="Overwrite ?" onclick="getUserChoice()"/></form></center>
<center><a href="toupload">Click me to upload a file</a>  </center>
</body>
</html>
</code>```

This is my Controller class:

```<code> @RequestMapping(value="/saveagain",method = RequestMethod.POST)
 public ModelAndView fileUploading2(@ModelAttribute("ch") Choice ch) throws IOException{

     String ch1;
     String message="";
     ch1=ch.getChoice();
     System.out.println("popup result "+ch1);
     return new ModelAndView("fileUpload","message",message);
 }
</code>```

fname and fcontent values are reflecting in controller. why is choice value not reflecting in "ch1" ?

答:
With your approach, you can use javascript in the getChoice() function to put the return value(true/false) as an hidden element value and retrieve on the server side

```<code>function getChoice() {
    var k=confirm("Do you want me to overwrite the existing file ?");
    $('#hidden_choice').val(k);
}

<!-- HTML element -->
<input type="hidden" name="choice" id="hidden_choice" />
<input id="button_id" type="button" value="Overwrite ?" onclick="getChoice()"/>
</code>```

On the server side, you can use @RequestParam to retrieve the value. Following is the Example code:

```<code> @RequestMapping(value="/saveagain",method = RequestMethod.POST)
 public ModelAndView fileUploading2(@RequestParam("choice") Boolean ch) throws IOException {
      // do your thing with choice variable here
      System.out.println("Choice is: " + ch);
}
</code>```

If the boolean value does not work, try with String and convert it to Boolean value manually.

Body:
This is my jsp page

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

<form method="POST" action="saveagain">

${message}

<input type="hidden" name="fname" value="${filename}">
<input type="hidden" name="fcontent" value="${filecontent}">

 <input type="button" value="Overwrite ?" onclick="choice=getChoice()"/>
<input type="submit" value="Submit ?"></form>

${m}

Click me to upload a file

In the above code, i want to get the result of confirm popup in to a variable "choice". How to do that ?

Modified code :

bean class :

package com.fss;

public class Choice {
 private String choice;
private String fname;
private String fcontent;

public String getChoice() {
    return choice;
}

public void setChoice(String choice) {
    this.choice = choice;
}

public String getFname() {
    return fname;
}

public void setFname(String fname) {
    this.fname = fname;
}

public String getFcontent() {
    return fcontent;
}

public void setFcontent(String fcontent) {
    this.fcontent = fcontent;
}

}

this is my jsp page :

${message}

  <form method="POST" action="saveagain">
    <input type="hidden" name="fname" value="${filename}">
    <input type="hidden" name="fcontent" value="${filecontent}">
    <input type="hidden" name="choice" id="choice">

    <input type="submit" value="Overwrite ?" onclick="getUserChoice()"/></form>
Click me to upload a file

This is my Controller class:

 @RequestMapping(value="/saveagain",method = RequestMethod.POST)
 public ModelAndView fileUploading2(@ModelAttribute("ch") Choice ch) throws IOException{

     String ch1;
     String message="";
     ch1=ch.getChoice();
     System.out.println("popup result "+ch1);
     return new ModelAndView("fileUpload","message",message);
 }

fname and fcontent values are reflecting in controller. why is choice value not reflecting in "ch1" ?

Body:
With your approach, you can use javascript in the getChoice() function to put the return value(true/false) as an hidden element value and retrieve on the server side

function getChoice() {
    var k=confirm("Do you want me to overwrite the existing file ?");
    $('#hidden_choice').val(k);
}

<!-- HTML element -->
<input type="hidden" name="choice" id="hidden_choice" />
<input id="button_id" type="button" value="Overwrite ?" onclick="getChoice()"/>

On the server side, you can use @RequestParam to retrieve the value. Following is the Example code:

 @RequestMapping(value="/saveagain",method = RequestMethod.POST)
 public ModelAndView fileUploading2(@RequestParam("choice") Boolean ch) throws IOException {
      // do your thing with choice variable here
      System.out.println("Choice is: " + ch);
}

If the boolean value does not work, try with String and convert it to Boolean value manually.


问:
Angularjs delay append new data and display old data 1s
It delays append new data and display old data 1s when I click: https://youtu.be/KeqRdGueekg

In controller:

```<code>   myApp.controller('Notebook', function($scope, $http){
    //Display Note click NoteBook
    $scope.xl_note = function(id){
        $http.get("/thunder_note/notebooks/show_note?id=" + id)
            .then(function(response) {
                $scope.dataNote = response.data;
            });
    };
});
</code>```

In view:

```<code><div class="modal-body">
    <div class="list_body list_body_note_of_notebook">
        <div class="list_content show_noteaas" ng-repeat="data in dataNote.Note">
            <a href="/thunder_note/notes/note_detail/{{data.id}}" style="text-decoration: none;">
                <p class="title">{{data.title}}</p>
            </a>
        </div>
    </div>
</div>
</code>```

答:
when you call /thunder_note/notes/note_detail/<br>
you do 2 things calling api and redirecting page
the page ridects immidiate so there is allready old data
but api response takes some time  for getting response
so clear  $scope.dataNote ="";  before your calling api  </p>

Body:
It delays append new data and display old data 1s when I click: https://youtu.be/KeqRdGueekg

In controller:

   myApp.controller('Notebook', function($scope, $http){
    //Display Note click NoteBook
    $scope.xl_note = function(id){
        $http.get("/thunder_note/notebooks/show_note?id=" + id)
            .then(function(response) {
                $scope.dataNote = response.data;
            });
    };
});

In view:

{{data.title}}

Body:
when you call /thunder_note/notes/note_detail/

you do 2 things calling api and redirecting page
the page ridects immidiate so there is allready old data
but api response takes some time  for getting response
so clear  $scope.dataNote ="";  before your calling api


问:
Uploading image by using Retrofit
I've been trying to upload an image from my application through API. But I keep getting this as response:

```<code>{"error":"<p>You did not select a file to upload.<\/p>"}
</code>```

This is my code:

APIService.java

```<code>@Multipart
@POST("/media/upload.html")
Call<UploadImg> uploadimage (@Part MultipartBody.Part file);
</code>```

UploadImageActivity.java

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){
        Uri uri = data.getData();
        Picasso.with(this).load(uri).fit().into(btn_img_picker);

        String imagePath;

        if (data.toString().contains("content:")) {
            imagePath = getRealPathFromURI(uri);
        } else if (data.toString().contains("file:")) {
            imagePath = uri.getPath();
        } else {
            imagePath = null;
        }

        File file = new File(imagePath);

        System.out.println(imagePath);

        RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);

        MultipartBody.Part body = MultipartBody.Part.createFormData("userfile", file.getName(), requestFile);

        System.out.println(file.getName());

        Call<UploadImg> call = mAPIService.uploadimage(body);
        call.enqueue(new Callback<UploadImg>() {
            @Override
            public void onResponse(Call<UploadImg> call, Response<UploadImg> response) {
                System.out.println(response.raw());
            }

            @Override
            public void onFailure(Call<UploadImg> call, Throwable t) {
                System.out.println(t);
            }
        });
    }
}

public String getRealPathFromURI(Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        cursor = getContentResolver().query(contentUri, proj, null, null,
                null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}
</code>```

I have tested sending image in Postman's form-data. I can send a picture from my desktop and received intended response. But I can't do the same with my code in android.

Am I sending the incorrect path format of the image? Currently, variable imagePath has an output like this:

```<code>/storage/emulated/0/Download/download.jpg
</code>```

If this is the incorrect path to send, please tell the correct one. Thanks in advance.

答:
You can use below code for uploading image

First you write code for calling request

```<code>//profile pic is image path
    RequestBody imagePath = Utility.imageToBody(profilePic);

 TestApiInterface service = WebServiceCaller.getClient();
 Call<SuccessResponse> call = service.mediaUpload(imagePath);

 call.enqueue(new Callback<SuccessResponse>() {
                @Override
                public void onResponse(Call<SuccessResponse> call,
 Response<SuccessResponse> response) {
                    SuccessResponse result;
                    if (response.isSuccessful()) {
                        result = response.body();

                     }
                }

                @Override
                public void onFailure(Call<SuccessResponse> call, Throwable t) {

                }
            });
</code>```

Then you write code for API

```<code>@Multipart
@POST("user/mediaupload")
Call<SuccessResponse> mediaUpload(@Part("media_file\"; filename=\"test_media.png\" ") RequestBody media_file);
</code>```

Then code for Imagetobody covert is below

```<code>public static RequestBody imageToBody(String text) {
    RequestBody requestBody;
    if (text != null && text.length() > 0) {
        MediaType MEDIA_TYPE = MediaType.parse("image/*");
        File file = new File(text);
        requestBody = RequestBody.create(MEDIA_TYPE, file);
    } else {
        requestBody = null;
    }
    return requestBody;
}
</code>```

Title: Uploading image by using Retrofit

Body:
I've been trying to upload an image from my application through API. But I keep getting this as response:

{"error":"
You did not select a file to upload.<\/p>"}

This is my code:

APIService.java

@Multipart
@POST("/media/upload.html")
Call<UploadImg> uploadimage (@Part MultipartBody.Part file);

UploadImageActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){
        Uri uri = data.getData();
        Picasso.with(this).load(uri).fit().into(btn_img_picker);

        String imagePath;

        if (data.toString().contains("content:")) {
            imagePath = getRealPathFromURI(uri);
        } else if (data.toString().contains("file:")) {
            imagePath = uri.getPath();
        } else {
            imagePath = null;
        }

        File file = new File(imagePath);

        System.out.println(imagePath);

        RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);

        MultipartBody.Part body = MultipartBody.Part.createFormData("userfile", file.getName(), requestFile);

        System.out.println(file.getName());

        Call<UploadImg> call = mAPIService.uploadimage(body);
        call.enqueue(new Callback<UploadImg>() {
            @Override
            public void onResponse(Call<UploadImg> call, Response<UploadImg> response) {
                System.out.println(response.raw());
            }

            @Override
            public void onFailure(Call<UploadImg> call, Throwable t) {
                System.out.println(t);
            }
        });
    }
}

public String getRealPathFromURI(Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        cursor = getContentResolver().query(contentUri, proj, null, null,
                null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

I have tested sending image in Postman's form-data. I can send a picture from my desktop and received intended response. But I can't do the same with my code in android.

Am I sending the incorrect path format of the image? Currently, variable imagePath has an output like this:

/storage/emulated/0/Download/download.jpg

If this is the incorrect path to send, please tell the correct one. Thanks in advance.

Body:
You can use below code for uploading image

First you write code for calling request

//profile pic is image path
    RequestBody imagePath = Utility.imageToBody(profilePic);

 TestApiInterface service = WebServiceCaller.getClient();
 Call<SuccessResponse> call = service.mediaUpload(imagePath);

 call.enqueue(new Callback<SuccessResponse>() {
                @Override
                public void onResponse(Call<SuccessResponse> call,
 Response<SuccessResponse> response) {
                    SuccessResponse result;
                    if (response.isSuccessful()) {
                        result = response.body();

                     }
                }

                @Override
                public void onFailure(Call<SuccessResponse> call, Throwable t) {

                }
            });

Then you write code for API

@Multipart
@POST("user/mediaupload")
Call<SuccessResponse> mediaUpload(@Part("media_file\"; filename=\"test_media.png\" ") RequestBody media_file);

Then code for Imagetobody covert is below

public static RequestBody imageToBody(String text) {
    RequestBody requestBody;
    if (text != null && text.length() > 0) {
        MediaType MEDIA_TYPE = MediaType.parse("image/*");
        File file = new File(text);
        requestBody = RequestBody.create(MEDIA_TYPE, file);
    } else {
        requestBody = null;
    }
    return requestBody;
}


问:
Why doesn't this crash?
I'm attempting to narrow down a bug to a minimum reproducible case and found something odd.

Consider this code:

```<code>static NSString *staticString = nil;
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    if (staticString == nil) {
        staticString = [[NSArray arrayWithObjects:@"1", @"2", @"3", nil] componentsJoinedByString:@","];
    }

    [pool drain];

    NSLog(@"static: %@", staticString);
    return 0;
}
</code>```

I'm expecting this code to crash.  Instead, it logs:

```<code>2011-01-18 14:41:06.311 EmptyFoundation[61419:a0f] static: static:
</code>```

However, if I change the NSLog() to:

```<code>NSLog(@"static: %s", [staticString UTF8String]);
</code>```

Then it does crash.

edit a bit more info:

After draining the pool:

```<code>NSLog(@"static: %@", staticString);  //this logs "static: static: "
NSLog(@"static: %@", [staticString description]); //this crashes
</code>```

So apparently invoking a method on the string is good enough to get it to crash.  In that case, why doesn't logging the string directly cause it to crash?  Shouldn't NSLog() be invoking the -description method?

Where is the second "static: " coming from?  Why isn't this crashing?

Results:

Both Kevin Ballard and Graham Lee are correct.  Graham's correct in realizing that NSLog() is not invoking -description (as I was erroneously assuming), and Kevin is almost definitely correct that this is a weird stack-related issue with copying a format string and a va_list around.

NSLogging and NSString does not invoke -description.  Graham elegantly showed this, and if you trace through the Core Foundation sources that do the logging, you'll see that this is the case.  Any backtrace originating inside NSLog shows that it invokes NSLogv => _CFLogvEx => _CFStringCreateWithFormatAndArgumentsAux => _CFStringAppendFormatAndArgumentsAux.  _CFStringAppendFormatAndArgumentsAux() (line 5365) is where all of the magic is going on.  You can see that it's manually going through to find all the % substitutions.  It only ends up invoking the description copy function if the type of the substitution is a CFFormatObjectType, the description function is non-nil, and the substitution hasn't already been handled by another type.  Since we've shown that the description is not getting copied, it's reasonable to assume that an NSString gets handled earlier (in which case it's probably going to be doing a raw byte copy), which leads us to believe...

There's a stack error going on here, as Kevin surmises.  Somehow the pointer that was pointing to the autoreleased string is getting substituted to a different object, which happens to be an NSString.  So, it doesn't crash.  Weird.  However, if we change the type of the static variable to something else, like an NSArray, then the -description method does get called, and the program does crash as expected.

How truly and utterly strange.  Points go to Kevin for being the most correct about the root cause of the behavior, and kudos to Graham for correcting my fallacious thinking.  I wish I could accept two answers...

答: Maybe it has something to do with the @"static:" being stored in the same memory location as staticString. staticString will be deallocated and it stores the @"static: %@" in that recycled mem location, so then the staticString pointer is on "static: %@" so it ends up static: static:.</p>

ContentLicense: CC BY-SA 2.5

Title: Why doesn't this crash?

Body:
I'm attempting to narrow down a bug to a minimum reproducible case and found something odd.

Consider this code:

static NSString *staticString = nil;
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    if (staticString == nil) {
        staticString = [[NSArray arrayWithObjects:@"1", @"2", @"3", nil] componentsJoinedByString:@","];
    }

    [pool drain];

    NSLog(@"static: %@", staticString);
    return 0;
}

I'm expecting this code to crash.  Instead, it logs:

2011-01-18 14:41:06.311 EmptyFoundation[61419:a0f] static: static:

However, if I change the NSLog() to:

NSLog(@"static: %s", [staticString UTF8String]);

Then it does crash.

edit a bit more info:

After draining the pool:

NSLog(@"static: %@", staticString);  //this logs "static: static: "
NSLog(@"static: %@", [staticString description]); //this crashes

So apparently invoking a method on the string is good enough to get it to crash.  In that case, why doesn't logging the string directly cause it to crash?  Shouldn't NSLog() be invoking the -description method?

Where is the second "static: " coming from?  Why isn't this crashing?

Results:

Both Kevin Ballard and Graham Lee are correct.  Graham's correct in realizing that NSLog() is not invoking -description (as I was erroneously assuming), and Kevin is almost definitely correct that this is a weird stack-related issue with copying a format string and a va_list around.

NSLogging and NSString does not invoke -description.  Graham elegantly showed this, and if you trace through the Core Foundation sources that do the logging, you'll see that this is the case.  Any backtrace originating inside NSLog shows that it invokes NSLogv => _CFLogvEx => _CFStringCreateWithFormatAndArgumentsAux => _CFStringAppendFormatAndArgumentsAux.  _CFStringAppendFormatAndArgumentsAux() (line 5365) is where all of the magic is going on.  You can see that it's manually going through to find all the % substitutions.  It only ends up invoking the description copy function if the type of the substitution is a CFFormatObjectType, the description function is non-nil, and the substitution hasn't already been handled by another type.  Since we've shown that the description is not getting copied, it's reasonable to assume that an NSString gets handled earlier (in which case it's probably going to be doing a raw byte copy), which leads us to believe...

There's a stack error going on here, as Kevin surmises.  Somehow the pointer that was pointing to the autoreleased string is getting substituted to a different object, which happens to be an NSString.  So, it doesn't crash.  Weird.  However, if we change the type of the static variable to something else, like an NSArray, then the -description method does get called, and the program does crash as expected.

How truly and utterly strange.  Points go to Kevin for being the most correct about the root cause of the behavior, and kudos to Graham for correcting my fallacious thinking.  I wish I could accept two answers...


问:
Webview In Ionic 3
I have my one blog which i want to convert into ionic app.
I use InAppBrowser plugin but the problem is when i press the back button it will come to my default ionic home page.

i follow the below steps :

ionic start myblog

ionic platform add android

ionic cordova plugin add cordova-plugin-inappbrowser

npm install --save @ionic-native/in-app-browser

and then added provider in app.module and in home.ts write the following.

```<code>import { InAppBrowser } from '@ionic-native/in-app-browser';

constructor(private iab: InAppBrowser) { }

...

const browser = this.iab.create('https://ionicframework.com/','_self','location=no');
browser.show();
</code>```

Also location=no is not working.
Like android ionic provide the webview ??
can anyone help me out ?
any help is appreciated. :)

答:
In simpleway without installing any plugin u can use  tag inside which define url of your's blog.
e.g In home.ts :

```<code>    import { DomSanitizer } from '@angular/platform-browser';
    url: any;
    constructor(private sanitize: DomSanitizer){
    this.url = sanitize.bypassSecurityTrustResourceUrl("YOUR_URL");
    }
</code>```

and in home.html :

```<code><iframe  height="100%" width="100%" [src]="url" name="iframe_a"></iframe>
</code>```

Try this.

Title: Webview In Ionic 3

Body:
I have my one blog which i want to convert into ionic app.
I use InAppBrowser plugin but the problem is when i press the back button it will come to my default ionic home page.

i follow the below steps :

ionic start myblog

ionic platform add android

ionic cordova plugin add cordova-plugin-inappbrowser

npm install --save @ionic-native/in-app-browser

and then added provider in app.module and in home.ts write the following.

import { InAppBrowser } from '@ionic-native/in-app-browser';

constructor(private iab: InAppBrowser) { }

...

const browser = this.iab.create('https://ionicframework.com/','_self','location=no');
browser.show();

Also location=no is not working.
Like android ionic provide the webview ??
can anyone help me out ?
any help is appreciated. :)

Body:
In simpleway without installing any plugin u can use  tag inside which define url of your's blog.
e.g In home.ts :

    import { DomSanitizer } from '@angular/platform-browser';
    url: any;
    constructor(private sanitize: DomSanitizer){
    this.url = sanitize.bypassSecurityTrustResourceUrl("YOUR_URL");
    }

and in home.html :

<iframe  height="100%" width="100%" [src]="url" name="iframe_a"></iframe>

Try this.


问:
Instance member 'showSettings' cannot be used on type 'SettingsLauncher'
I'm trying to move a whole pile of code in my button to a single file.
Here's the button in my original VC

```<code>    let blackView = UIView()
    let settingsLuancher = SettingsLauncher()

    @IBAction func refreshBtnAction(_ sender: UIButton) {

      SettingsLauncher.showSettings()

    }
</code>```

And here is the SettingsLauncher.swift,

```<code>import Foundation
import UIKit

class SettingsLauncher:NSObject {

let blackView = UIView()

func showSettings() {
    if let window = UIApplication.shared.keyWindow{
        blackView.backgroundColor = UIColor(white: 0, alpha: 0.5)
        window.addSubview(blackView)
        blackView.frame = window.frame
        blackView.alpha = 0

        blackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleDismiss)))

        UIView.animate(withDuration: 0.2, animations: {
            self.blackView.alpha = 1
        })
    }

}

func handleDismiss(){
    UIView.animate(withDuration: 0.2, animations: {
        self.blackView.alpha = 0
        // dismisses blackView
    })
}
</code>```

The compile keeps failing and it's showing:
Instance member 'showSettings' cannot be used on type 'SettingsLauncher'; did you mean to use a value of this type instead?

Not sure why this happened, any help appreciated.

答:
You are using class name SettingsLauncher, instead on object settingsLuancher:

```<code>SettingsLauncher.showSettings()
</code>```

should be

```<code>settingsLuancher.showSettings()
</code>```

Body:
I'm trying to move a whole pile of code in my button to a single file.
Here's the button in my original VC

    let blackView = UIView()
    let settingsLuancher = SettingsLauncher()

    @IBAction func refreshBtnAction(_ sender: UIButton) {

      SettingsLauncher.showSettings()

    }

And here is the SettingsLauncher.swift,

import Foundation
import UIKit

class SettingsLauncher:NSObject {

let blackView = UIView()

func showSettings() {
    if let window = UIApplication.shared.keyWindow{
        blackView.backgroundColor = UIColor(white: 0, alpha: 0.5)
        window.addSubview(blackView)
        blackView.frame = window.frame
        blackView.alpha = 0

        blackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleDismiss)))

        UIView.animate(withDuration: 0.2, animations: {
            self.blackView.alpha = 1
        })
    }

}

func handleDismiss(){
    UIView.animate(withDuration: 0.2, animations: {
        self.blackView.alpha = 0
        // dismisses blackView
    })
}

The compile keeps failing and it's showing:
Instance member 'showSettings' cannot be used on type 'SettingsLauncher'; did you mean to use a value of this type instead?

Not sure why this happened, any help appreciated.

Body:
You are using class name SettingsLauncher, instead on object settingsLuancher:

SettingsLauncher.showSettings()

should be

settingsLuancher.showSettings()


答:
Look at SettingsLauncher.showSettings() it's not class method it instance method so It will be called by instance of class not class itself.

like below

```<code>settingsLuancher.showSettings()
</code>```

Title: Instance member 'showSettings' cannot be used on type 'SettingsLauncher'

Body:
Look at SettingsLauncher.showSettings() it's not class method it instance method so It will be called by instance of class not class itself.

like below

settingsLuancher.showSettings()


问:
How to read country_code from JSON data using jQuery or JavaScript?
```<code>{
  "status": "success",
  "description": "Data successfully received.",
  "data": {
    "geo": {
      "host": "2405:204:3213:5500:b012:b9d5:e4db:47b6",
      "ip": "2405:204:3213:5500:b012:b9d5:e4db:47b6",
      "rdns": "2405:204:3213:5500:b012:b9d5:e4db:47b6",
      "asn": "AS55836",
      "isp": "Reliance Jio Infocomm Limited ",
      "country_name": "India",
      "country_code": "IN",
      "region": "",
      "city": "",
      "postal_code": "",
      "continent_code": "AS",
      "latitude": "20",
      "longitude": "77",
      "dma_code": "",
      "area_code": "",
      "timezone": "Asia/Kolkata",
      "datetime": "2017-11-15 10:12:15"
    }
  }
}
</code>```

How to read country_code using jQuery or JavaScript?

答:
JSON.parse is what you are looking for.

```<code>let someJSObject = JSON.parse(someJSONString);
</code>```

After that you can use the member access operator to access the fields you require.

Body:
{
  "status": "success",
  "description": "Data successfully received.",
  "data": {
    "geo": {
      "host": "2405:204:3213:5500:b012:b9d5:e4db:47b6",
      "ip": "2405:204:3213:5500:b012:b9d5:e4db:47b6",
      "rdns": "2405:204:3213:5500:b012:b9d5:e4db:47b6",
      "asn": "AS55836",
      "isp": "Reliance Jio Infocomm Limited ",
      "country_name": "India",
      "country_code": "IN",
      "region": "",
      "city": "",
      "postal_code": "",
      "continent_code": "AS",
      "latitude": "20",
      "longitude": "77",
      "dma_code": "",
      "area_code": "",
      "timezone": "Asia/Kolkata",
      "datetime": "2017-11-15 10:12:15"
    }
  }
}

How to read country_code using jQuery or JavaScript?

Body:
JSON.parse is what you are looking for.

let someJSObject = JSON.parse(someJSONString);

After that you can use the member access operator to access the fields you require.


问:
How to set an image into an NSCollectionView?
Below is my code:

```<code>var  arrCategory:[NSString] =
         ["Australia","Austria","Belgium","Brazil","Cameroon","Canada","Chile","China","Denmark","Argentina"]
</code>```

The strings given in above array are the name of images.

答:
My Question Of Answer i find out and is Here:</p>

```<code>cell.imgView.image = NSImage(named:self.arrCategory[indexPath.item])
cell.lbl.stringValue =  arrlbl[indexPath.item] as String
</code>```

Body:
Below is my code:

var  arrCategory:[NSString] =
         ["Australia","Austria","Belgium","Brazil","Cameroon","Canada","Chile","China","Denmark","Argentina"]

The strings given in above array are the name of images.

Body:
My Question Of Answer i find out and is Here:

cell.imgView.image = NSImage(named:self.arrCategory[indexPath.item])
cell.lbl.stringValue =  arrlbl[indexPath.item] as String


问:
How to allow space on android:digits
I am restricting on Android Edittext as below </p>

<p>android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
but can't enter spaces.  How can I make it allow spaces?  Is this possible to get only via .xml?. </p>

答:
Edittext digit accept white space only if give space end of characters, have look:

```<code>android:digits="abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ"
</code>```

Happy coding!!

Title: How to allow space on android:digits

Body:
I am restricting on Android Edittext as below

android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
but can't enter spaces.  How can I make it allow spaces?  Is this possible to get only via .xml?.

Body:
Edittext digit accept white space only if give space end of characters, have look:

android:digits="abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ"

Happy coding!!


问:
ionic ios all view blank after keyboard hide
in ionic login page , every time when i hide keyboard it will cause a full screen blank (element still there can be click and response) , and after editing input all recover normal. (Only iOS,android is fine,other page's input is fine so it should not be the keyboard plugin's problem)</p>

答:
Maybe this link help you. But it's temporary.

replace <ion-content> with <ion-scroll>

<ion-scroll direction="y" style="right: 0;bottom: 0;left: 0;position: absolute;" class="has-header has-subheader">

keyboard issue


问:
Homegrown consumption of web services
I've been writing a few web services for a .net app, now I'm ready to consume them. I've seen numerous examples where there is homegrown code for consuming the service as opposed to using the auto generated methods that Visual Studio creates when adding the web reference.

Is there some advantages to this?

答:
No, what you're doing is fine. Don't let those people confuse you.

If you've written the web services with .net then the reference proxies generated by .net are going to be quite suitable. The situation you describe (where you are both producer and consumer) is the ideal situation.

If you need to connect to a web services that is unknown at compile time, then you would want a more dynamic approach, where you deduce the 'shape' of the web service.

But start by using the auto generated proxy class, and don't worry about it until you hit a limitation. And when you do -- come back to stack overflow ;-)

Title: Homegrown consumption of web services


问:
Why should I learn Lisp?
I really feel that I should learn Lisp and there are plenty of good resources out there to help me do it.

I'm not put off by the complicated syntax, but where in "traditional commercial programming" would I find places it would make sense to use it instead of a procedural language.

Is there a commercial killer-app out there that's been written in Lisp ?

答:
I agree that Lisp is one of those languages that you may never use in a commercial setting.  But even if you don't get to, learning it will definitely expand your understanding of programming as a whole.  For example, I learned Prolog in college and while I never used it after, I gave me a greater understanding of many programming concepts and (at times) a greater appreciation for the languages I do use.

But if you are going to learn it...by all means, read On Lisp

Title: Why should I learn Lisp?

LastEditorDisplayName: Mark Biek


问:
Why doesn't inheritance work the way I think it should work?
I'm having some inheritance issues as I've got a group of inter-related abstract classes that need to all be overridden together to create a client implementation.  Ideally I would like to do something like the following:

```<code>abstract class Animal
{
  public Leg GetLeg() {...}
}

abstract class Leg { }

class Dog : Animal
{
  public override DogLeg Leg() {...}
}

class DogLeg : Leg { }
</code>```

This would allow anyone using the Dog class to automatically get DogLegs and anyone using the Animal class to get Legs.  The problem is that the overridden function has to have the same type as the base class so this will not compile. I don't see why it shouldn't though, since DogLeg is implicitly castable to Leg.  I know there are plenty of ways around this, but I'm more curious why this isn't possible/implemented in C#.

EDIT: I modified this somewhat, since I'm actually using properties instead of functions in my code.

EDIT: I changed it back to functions, because the answer only applies to that situation (covariance on the value parameter of a property's set function shouldn't work).  Sorry for the fluctuations!  I realize it makes a lot of the answers seem irrelevant.

答:
It is a perfectly valid desire to have the signature an overriding method have a return type that is a subtype of the return type in the overridden method (phew). After all, they are run-time type compatible.

But C# does not yet support "covariant return types" in overridden methods (unlike C++ [1998] & Java [2004]).

You'll need to work around and make do for the foreseeable future, as Eric Lippert stated in his blog
[June 19, 2008]:

That kind of variance is called "return type covariance".

we have no plans to implement that kind of variance in C#.

OwnerDisplayName: Luke

Body:
I'm having some inheritance issues as I've got a group of inter-related abstract classes that need to all be overridden together to create a client implementation.  Ideally I would like to do something like the following:

abstract class Animal
{
  public Leg GetLeg() {...}
}

abstract class Leg { }

class Dog : Animal
{
  public override DogLeg Leg() {...}
}

class DogLeg : Leg { }

This would allow anyone using the Dog class to automatically get DogLegs and anyone using the Animal class to get Legs.  The problem is that the overridden function has to have the same type as the base class so this will not compile. I don't see why it shouldn't though, since DogLeg is implicitly castable to Leg.  I know there are plenty of ways around this, but I'm more curious why this isn't possible/implemented in C#.

EDIT: I modified this somewhat, since I'm actually using properties instead of functions in my code.

EDIT: I changed it back to functions, because the answer only applies to that situation (covariance on the value parameter of a property's set function shouldn't work).  Sorry for the fluctuations!  I realize it makes a lot of the answers seem irrelevant.

LastEditorDisplayName: Constantin

OwnerDisplayName: Ivan Hamilton

LastEditorDisplayName: Ivan Hamilton


问:
Div ID fade code
I'm a newbie on jQuery. Can somebody help me with my 2days problem.
I just in need of a sample code for a fading effect, slideshow.

Here's the style.

This will be 3 Divs with same class

The first div, will show for 6secs then fades out for 2secs

before the first fades out the second div will fade in for 2secs

this again will show for 6secs then fades out for 2secs.

Then the third div will fades in same way for 2secs.

Will show for 6secs then fades out for 2secs. Then they will rotate or loop.

Thank you for helping me out.

EDIT - Relevant code from comment

```<code>$(document).ready(function(){
    function looptour(){
        $("#health").hide();
        $("#billing").hide();
        $("#pension").delay(6000).fadeOut(2000);
        $("#health").delay(6000).fadeIn(2000).delay(6000).fadeOut(2000);
        $("#billing").delay(14000).fadeIn(2000).delay(6000).fadeOut(2000);
        $("#pension").delay(14000).fadeIn(2000,looptour);
   }
   looptour();
});
</code>```

答:
$(document).ready(function() {
    function looptour() {
        $(".quote4").hide();
        $(".quote3").hide();
        $(".quote2").hide();
        $(".quote1").delay(1000).fadeIn(3000).delay().fadeOut(1000);
        $(".quote2").delay(7000).fadeIn(3000).delay().fadeOut(1000);
        $(".quote3").delay(11000).fadeIn(3000).delay().fadeOut(1000);
        $(".quote4").delay(16000).fadeIn(6000).delay().fadeOut(1000, looptour);
    }

    looptour();
});
```

This is how i did it, you just need to take care of the delay.

Title: Div ID fade code

Body:
I'm a newbie on jQuery. Can somebody help me with my 2days problem.
I just in need of a sample code for a fading effect, slideshow.

Here's the style.

This will be 3 Divs with same class

The first div, will show for 6secs then fades out for 2secs

before the first fades out the second div will fade in for 2secs

this again will show for 6secs then fades out for 2secs.

Then the third div will fades in same way for 2secs.

Will show for 6secs then fades out for 2secs. Then they will rotate or loop.

Thank you for helping me out.

EDIT - Relevant code from comment

$(document).ready(function(){
    function looptour(){
        $("#health").hide();
        $("#billing").hide();
        $("#pension").delay(6000).fadeOut(2000);
        $("#health").delay(6000).fadeIn(2000).delay(6000).fadeOut(2000);
        $("#billing").delay(14000).fadeIn(2000).delay(6000).fadeOut(2000);
        $("#pension").delay(14000).fadeIn(2000,looptour);
   }
   looptour();
});

Body:
$(document).ready(function() {
    function looptour() {
        $(".quote4").hide();
        $(".quote3").hide();
        $(".quote2").hide();
        $(".quote1").delay(1000).fadeIn(3000).delay().fadeOut(1000);
        $(".quote2").delay(7000).fadeIn(3000).delay().fadeOut(1000);
        $(".quote3").delay(11000).fadeIn(3000).delay().fadeOut(1000);
        $(".quote4").delay(16000).fadeIn(6000).delay().fadeOut(1000, looptour);
    }

    looptour();
});

This is how i did it, you just need to take care of the delay.


问:
How to iterate a list within a list into columns?
Suppose I have a list of numbers divided into 3 lists:

```<code>numbers = [[0,1,2], [3,4,5], [6,7,8]]
</code>```

And I want to iterate through each 3 lists and divide them into columns:

```<code>0  1  2
3  4  5
6  7  8
</code>```

How would I go about doing this?
So far, I can only print out 1 column:

```<code>for column in numbers[0:3]:
    column1 = column[0]
    print( column1 )
</code>```

答:
You should use two loops, one for the rows, the other for the columns. In Python 3 it looks like this:</p>

```<code>for i in range(3):
    for j in range(3):
        print(numbers[i][j], end=' ') # print a single value in same line
    print()                           # print line break after each row
</code>```

Body:
Suppose I have a list of numbers divided into 3 lists:

numbers = [[0,1,2], [3,4,5], [6,7,8]]

And I want to iterate through each 3 lists and divide them into columns:

0  1  2
3  4  5
6  7  8

How would I go about doing this?
So far, I can only print out 1 column:

for column in numbers[0:3]:
    column1 = column[0]
    print( column1 )

Body:
You should use two loops, one for the rows, the other for the columns. In Python 3 it looks like this:

for i in range(3):
    for j in range(3):
        print(numbers[i][j], end=' ') # print a single value in same line
    print()                           # print line break after each row


问:
PdfViewr proplem save page
I am using PdfViewr.

I want to open pdf on the last page, which is not working. I have tried many times but its not working.

I used this code

```<code>    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newpdf);
        pdfView = (PDFView) findViewById(R.id.pdfView);
        displayFromAsset(SAMPLE_FILE);
    }

    private void displayFromAsset(String assetFileName) {
        pdfFileName = assetFileName;

        pdfView.fromAsset(SAMPLE_FILE)
                .defaultPage(pageNumber)
                .enableSwipe(true)
                .swipeHorizontal(false)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .scrollHandle(new DefaultScrollHandle(this))
                .spacing(10)
                .load();
    }

    @Override
    public void onPageChanged(int page, int pageCount) {
        pageNumber = page;
        setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
    }

    @Override
    public void loadComplete(int nbPages) {
        PdfDocument.Meta meta = pdfView.getDocumentMeta();
        printBookmarksTree(pdfView.getTableOfContents(), "-");

    }

    public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
        for (PdfDocument.Bookmark b : tree) {

            Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));

            if (b.hasChildren()) {
                printBookmarksTree(b.getChildren(), sep + "-");
            }
        }
    }
}
</code>```

How can I save pdf's last page, and I need to implement this for my app. Any help?

Thank you.

答:
Use preference to store page number so it can be globally access and not change with class instance.</p>

```<code>    public static final String MY_PREFS_NAME = "MyPrefsFile";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newpdf);
        pdfView = (PDFView) findViewById(R.id.pdfView);
        displayFromAsset(SAMPLE_FILE);
    }

    private void displayFromAsset(String assetFileName) {

    if(!getFileName().equals(assetFileName)){
           setPageNumber(0);
           setFileName(assetFileName);
     }
        pdfView.fromAsset(assetFileName)
                .defaultPage(getPageNumber())
                .enableSwipe(true)
                .swipeHorizontal(false)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .scrollHandle(new DefaultScrollHandle(this))
                .spacing(10)
                .load();
    }

    @Override
    public void onPageChanged(int page, int pageCount) {

        setPageNumber(page)
        setTitle(String.format("%s %s / %s", pdfFileName, (getPageNumber() + 1), pageCount));
    }

    @Override
    public void loadComplete(int nbPages) {
        PdfDocument.Meta meta = pdfView.getDocumentMeta();
        printBookmarksTree(pdfView.getTableOfContents(), "-");

    }

     public void setPageNumber(int pageNumber) {
            SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
            editor.putInt("page_number", pageNumber);
            editor.apply();
        }

        public int getPageNumber() {
            SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
            return prefs.getInt("page_number", 0);
        }
    public void setFileName(String fileName) {
            SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
            editor.putString("file_name", fileName);
            editor.apply();
        }

        public String getFileName() {
            SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
            return prefs.getString("file_name", "");
        }
    public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
        for (PdfDocument.Bookmark b : tree) {

            Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));

            if (b.hasChildren()) {
                printBookmarksTree(b.getChildren(), sep + "-");
            }
        }
    }
</code>```

Title: PdfViewr proplem save page

Body:
I am using PdfViewr.

I want to open pdf on the last page, which is not working. I have tried many times but its not working.

I used this code

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newpdf);
        pdfView = (PDFView) findViewById(R.id.pdfView);
        displayFromAsset(SAMPLE_FILE);
    }

    private void displayFromAsset(String assetFileName) {
        pdfFileName = assetFileName;

        pdfView.fromAsset(SAMPLE_FILE)
                .defaultPage(pageNumber)
                .enableSwipe(true)
                .swipeHorizontal(false)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .scrollHandle(new DefaultScrollHandle(this))
                .spacing(10)
                .load();
    }

    @Override
    public void onPageChanged(int page, int pageCount) {
        pageNumber = page;
        setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
    }

    @Override
    public void loadComplete(int nbPages) {
        PdfDocument.Meta meta = pdfView.getDocumentMeta();
        printBookmarksTree(pdfView.getTableOfContents(), "-");

    }

    public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
        for (PdfDocument.Bookmark b : tree) {

            Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));

            if (b.hasChildren()) {
                printBookmarksTree(b.getChildren(), sep + "-");
            }
        }
    }
}

How can I save pdf's last page, and I need to implement this for my app. Any help?

Thank you.

Body:
Use preference to store page number so it can be globally access and not change with class instance.

    public static final String MY_PREFS_NAME = "MyPrefsFile";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newpdf);
        pdfView = (PDFView) findViewById(R.id.pdfView);
        displayFromAsset(SAMPLE_FILE);
    }

    private void displayFromAsset(String assetFileName) {

    if(!getFileName().equals(assetFileName)){
           setPageNumber(0);
           setFileName(assetFileName);
     }
        pdfView.fromAsset(assetFileName)
                .defaultPage(getPageNumber())
                .enableSwipe(true)
                .swipeHorizontal(false)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .scrollHandle(new DefaultScrollHandle(this))
                .spacing(10)
                .load();
    }

    @Override
    public void onPageChanged(int page, int pageCount) {

        setPageNumber(page)
        setTitle(String.format("%s %s / %s", pdfFileName, (getPageNumber() + 1), pageCount));
    }

    @Override
    public void loadComplete(int nbPages) {
        PdfDocument.Meta meta = pdfView.getDocumentMeta();
        printBookmarksTree(pdfView.getTableOfContents(), "-");

    }

     public void setPageNumber(int pageNumber) {
            SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
            editor.putInt("page_number", pageNumber);
            editor.apply();
        }

        public int getPageNumber() {
            SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
            return prefs.getInt("page_number", 0);
        }
    public void setFileName(String fileName) {
            SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
            editor.putString("file_name", fileName);
            editor.apply();
        }

        public String getFileName() {
            SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
            return prefs.getString("file_name", "");
        }
    public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
        for (PdfDocument.Bookmark b : tree) {

            Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));

            if (b.hasChildren()) {
                printBookmarksTree(b.getChildren(), sep + "-");
            }
        }
    }


问:
ValueError at /image/ Tensor Tensor("activation_5/Softmax:0", shape=(?, 4), dtype=float32) is not an element of this graph
I am building an image processing classifier and this code is an API to predict the image class of the image the whole code is running except this line (pred = model.predict_classes(test_image)) this API is made in Django framework and am using python 2.7

here is a point if I am running this code like normally ( without making an API) it's running perfectly

```<code>def classify_image(request):
if request.method == 'POST' and request.FILES['test_image']:

    fs = FileSystemStorage()
    fs.save(request.FILES['test_image'].name, request.FILES['test_image'])

    test_image = cv2.imread('media/'+request.FILES['test_image'].name)

    if test_image is not None:
        test_image = cv2.resize(test_image, (128, 128))
        test_image = np.array(test_image)
        test_image = test_image.astype('float32')
        test_image /= 255
        print(test_image.shape)
    else:
        print('image didnt load')

    test_image = np.expand_dims(test_image, axis=0)
    print(test_image)
    print(test_image.shape)

    pred = model.predict_classes(test_image)
    print(pred)

return JsonResponse(pred, safe=False)
</code>```

答:
Your test_image and input of tensorflow model is not match.

```<code># Your image shape is (, , 3)
test_image = cv2.imread('media/'+request.FILES['test_image'].name)

if test_image is not None:
    test_image = cv2.resize(test_image, (128, 128))
    test_image = np.array(test_image)
    test_image = test_image.astype('float32')
    test_image /= 255
    print(test_image.shape)
else:
    print('image didnt load')

# Your image shape is (, , 4)
test_image = np.expand_dims(test_image, axis=0)
print(test_image)
print(test_image.shape)

pred = model.predict_classes(test_image)
</code>```

The above is just assumption. If you want to debug, i guess you should print your image size and compare with first layout of your model definition. And check whe the size (width, height, depth) is match

Body:
I am building an image processing classifier and this code is an API to predict the image class of the image the whole code is running except this line (pred = model.predict_classes(test_image)) this API is made in Django framework and am using python 2.7

here is a point if I am running this code like normally ( without making an API) it's running perfectly

def classify_image(request):
if request.method == 'POST' and request.FILES['test_image']:

    fs = FileSystemStorage()
    fs.save(request.FILES['test_image'].name, request.FILES['test_image'])

    test_image = cv2.imread('media/'+request.FILES['test_image'].name)

    if test_image is not None:
        test_image = cv2.resize(test_image, (128, 128))
        test_image = np.array(test_image)
        test_image = test_image.astype('float32')
        test_image /= 255
        print(test_image.shape)
    else:
        print('image didnt load')

    test_image = np.expand_dims(test_image, axis=0)
    print(test_image)
    print(test_image.shape)

    pred = model.predict_classes(test_image)
    print(pred)

return JsonResponse(pred, safe=False)

Body:
Your test_image and input of tensorflow model is not match.

# Your image shape is (, , 3)
test_image = cv2.imread('media/'+request.FILES['test_image'].name)

if test_image is not None:
    test_image = cv2.resize(test_image, (128, 128))
    test_image = np.array(test_image)
    test_image = test_image.astype('float32')
    test_image /= 255
    print(test_image.shape)
else:
    print('image didnt load')

# Your image shape is (, , 4)
test_image = np.expand_dims(test_image, axis=0)
print(test_image)
print(test_image.shape)

pred = model.predict_classes(test_image)

The above is just assumption. If you want to debug, i guess you should print your image size and compare with first layout of your model definition. And check whe the size (width, height, depth) is match