问:
Disabling specific test instance defined from a dataset
Let's say I have the following test code:

struct MyData
{
    MyData( int in_, double out_ )
    : m_in{ in_ }
    , m_out{ out_ }
    {}

    int    m_in;
    double m_out;
};

std::ostream& operator<<( std::ostream& os_, MyData data_ )
{
    os_ << data_.m_in << " " << data_.m_out << std::endl;
    return os_;
}

std::vector< MyData > DataSetGet()
{
    return
        {
            { 1, 1.0 },
            { 2, 2.0 }, // I would like to disable this...
            { 3, 3.0 },
        };
}

BOOST_DATA_TEST_CASE( CastIntToDouble, DataSetGet() )
{
    BOOST_TEST( static_cast< double >( sample.m_in ) == sample.m_out );
}

```
<p>I would like to disable the second test instance. I could just comment out the second case, like this:</p>
<pre class="lang-cpp prettyprint-override"><code>std::vector< MyData > DataSetGet()
{
    return
        {
            { 1, 1.0 },
            //{ 2, 2.0 }, // I would like to disable this...
            { 3, 3.0 },
        };
}
</code>```

but then this case would no longer be compiled, which is not what I am looking for. In my real scenario, test cases are more complex and I would like them compiled, but not run.

I have searched the boost documentation on this topic and I came across the disable decorator, which looks like what I need. However, I have found no way to use it in data test cases. Is this possible?

答:
You can supply a command line argument, like:

```<code>./sotest -l all -t "!*/*_1"
</code>```

Which outputs:

More Advanced/Dynamic

You could also supply your own decorator based on enable_if, which you could make to use your own custom command line options (you'll need to supply your own test_main to parse those).

For an example of such custom decorator: https://www.boost.org/doc/libs/1_78_0/libs/test/doc/html/boost_test/tests_organization/enabling.html#boost_test.tests_organization.enabling.runtime_run_status

Live Demo

Live On Coliru

```<code>#define BOOST_TEST_MODULE StackOverflow
#include <boost/test/unit_test.hpp>
#include <boost/test/data/dataset.hpp>
#include <boost/test/data/test_case.hpp>
#include <boost/test/unit_test_parameters.hpp>

namespace but = boost::unit_test;
namespace utf = boost::unit_test_framework;

struct MyData {
    MyData(int in_, double out_) : m_in{in_}, m_out{out_} {}

    int    m_in;
    double m_out;
};

std::ostream& operator<<(std::ostream& os_, MyData data_) {
    return os_ << data_.m_in << " " << data_.m_out << std::endl;
}

std::vector<MyData> DataSetGet()
{
    return {
        {1, 1.0},
        {2, 2.0}, // I would like to disable this...
        {3, 3.0},
    };
}

BOOST_DATA_TEST_CASE(CastIntToDouble, DataSetGet())
{
    BOOST_TEST( static_cast< double >( sample.m_in ) == sample.m_out );
}
</code>```

Run with

```<code>g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp -lboost_unit_test_framework
./a.out -l all -t "!*/*_1" --no_color_output
</code>```

Prints

```<code>Running 2 test cases...
Entering test module "StackOverflow"
main.cpp(30): Entering test suite "CastIntToDouble"
main.cpp(30): Entering test case "_0"
main.cpp(32): info: check static_cast< double >( sample.m_in ) == sample.m_out has passed
Assertion occurred in a following context:
    sample = 1 1
;
main.cpp(30): Leaving test case "_0"; testing time: 443us
main.cpp(30): Test case "CastIntToDouble/_1" is skipped because disabled
main.cpp(30): Entering test case "_2"
main.cpp(32): info: check static_cast< double >( sample.m_in ) == sample.m_out has passed
Assertion occurred in a following context:
    sample = 3 3
;
main.cpp(30): Leaving test case "_2"; testing time: 404us
main.cpp(30): Leaving test suite "CastIntToDouble"; testing time: 967us
Leaving test module "StackOverflow"; testing time: 1016us

*** No errors detected
</code>```

Body:
Let's say I have the following test code:

struct MyData
{
    MyData( int in_, double out_ )
    : m_in{ in_ }
    , m_out{ out_ }
    {}

    int    m_in;
    double m_out;
};

std::ostream& operator<<( std::ostream& os_, MyData data_ )
{
    os_ << data_.m_in << " " << data_.m_out << std::endl;
    return os_;
}

std::vector< MyData > DataSetGet()
{
    return
        {
            { 1, 1.0 },
            { 2, 2.0 }, // I would like to disable this...
            { 3, 3.0 },
        };
}

BOOST_DATA_TEST_CASE( CastIntToDouble, DataSetGet() )
{
    BOOST_TEST( static_cast< double >( sample.m_in ) == sample.m_out );
}

I would like to disable the second test instance. I could just comment out the second case, like this:

std::vector< MyData > DataSetGet()
{
    return
        {
            { 1, 1.0 },
            //{ 2, 2.0 }, // I would like to disable this...
            { 3, 3.0 },
        };
}

but then this case would no longer be compiled, which is not what I am looking for. In my real scenario, test cases are more complex and I would like them compiled, but not run.

I have searched the boost documentation on this topic and I came across the disable decorator, which looks like what I need. However, I have found no way to use it in data test cases. Is this possible?

Body:
You can supply a command line argument, like:

./sotest -l all -t "!*/*_1"

Which outputs:

More Advanced/Dynamic

You could also supply your own decorator based on enable_if, which you could make to use your own custom command line options (you'll need to supply your own test_main to parse those).

For an example of such custom decorator: https://www.boost.org/doc/libs/1_78_0/libs/test/doc/html/boost_test/tests_organization/enabling.html#boost_test.tests_organization.enabling.runtime_run_status

Live Demo

Live On Coliru

#define BOOST_TEST_MODULE StackOverflow
#include <boost/test/unit_test.hpp>
#include <boost/test/data/dataset.hpp>
#include <boost/test/data/test_case.hpp>
#include <boost/test/unit_test_parameters.hpp>

namespace but = boost::unit_test;
namespace utf = boost::unit_test_framework;

struct MyData {
    MyData(int in_, double out_) : m_in{in_}, m_out{out_} {}

    int    m_in;
    double m_out;
};

std::ostream& operator<<(std::ostream& os_, MyData data_) {
    return os_ << data_.m_in << " " << data_.m_out << std::endl;
}

std::vector<MyData> DataSetGet()
{
    return {
        {1, 1.0},
        {2, 2.0}, // I would like to disable this...
        {3, 3.0},
    };
}

BOOST_DATA_TEST_CASE(CastIntToDouble, DataSetGet())
{
    BOOST_TEST( static_cast< double >( sample.m_in ) == sample.m_out );
}

Run with

g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp -lboost_unit_test_framework
./a.out -l all -t "!*/*_1" --no_color_output

Prints

Running 2 test cases...
Entering test module "StackOverflow"
main.cpp(30): Entering test suite "CastIntToDouble"
main.cpp(30): Entering test case "_0"
main.cpp(32): info: check static_cast< double >( sample.m_in ) == sample.m_out has passed
Assertion occurred in a following context:
    sample = 1 1
;
main.cpp(30): Leaving test case "_0"; testing time: 443us
main.cpp(30): Test case "CastIntToDouble/_1" is skipped because disabled
main.cpp(30): Entering test case "_2"
main.cpp(32): info: check static_cast< double >( sample.m_in ) == sample.m_out has passed
Assertion occurred in a following context:
    sample = 3 3
;
main.cpp(30): Leaving test case "_2"; testing time: 404us
main.cpp(30): Leaving test suite "CastIntToDouble"; testing time: 967us
Leaving test module "StackOverflow"; testing time: 1016us

*** No errors detected


来源: stackexchange

问:
How to perform Redis client side caching of a Sorted Set, by rank
I have an application which pulls the 'top ten' from a Redis Sorted Set. That is, the members of the set with the highest ranking, e.g. ZRANGE top40 0 9 REV. I would like to cache this result on the client and be informed by the Server when the members of this subset change.

From my research so far, I have understood that Redis server-assisted client-side caching (RSACSC) is implemented such that the server keeps a record of the keys which are requested by each client and will inform that client (or another) when the keys change. This would imply that the server is not tracking their rank within a Sorted Set.

What I want to achieve is this:

I have a Sorted Set which contains the Top 40 songs, ranked by number of streams

I have a (Python) client which fetches and caches the highest ranking 10 from the Top 40

If a new song comes in at number 5, the server will send an expiration message for either

cached members 5-10, or

the entire cached subset of 10 members

<s>I would like to understand if RSACSC can accommodate this as-is.</s> If not, can it be achieved using other Redis trickery, for example somehow storing the Top 10 server-side as a new key and pulling this key into the Python app.

I would hugely appreciate an example using a Python client, although the main purpose of the question is to better understand RSACSC and its limitation regarding Sorted Sets, plus any workarounds.

Having done some more research, and using a real-world dataset (and following the positive confirmation from @guyroyse), it seems that any change to the Sorted Set results in a client invalidate notification, even if the change happened outside of the subset of members that the client requested. Redis does indeed appear to treat the entire Set's key as a single entity, rather than track the client's request for and range of members.

In this way, (3) is not possible. Therefore this becomes a question of workarounds, e.g. some server-side ability to automatically store the subset as a separate key.

答:
Having done some more research, and using a real-world dataset, I can confirm that any change to the Sorted Set results in a client invalidate notification, even if the change happened outside of the subset of members that the client requested. Redis does indeed appear to treat the entire Set's key as a single entity, rather than track the client's request for and range of members.

In this way, (3) is not possible.

ContentLicense: CC BY-SA 4.0


问:
Observable not working with async await function in Doc reader
I am trying to put await on Observable like below:

    documentXFDFRetriever: async () => {
            const rows = await this.annotationsService.getAnnotations(this.userService.getCurrentDocumentId()).toPromise();
            console.log(rows);
            return rows.map(row => row.annotationNode);
          }
```
<p><strong>My Service function:</strong></p>
<pre class="lang-js prettyprint-override"><code>    public getAnnotations(docId): Observable<Annotation[]> {
        const userId = this.userService.getCurrentUserId();
        const annotationsRef = collection(this.firestore, `annotations/${docId}/${userId}`);
        return collectionData(annotationsRef) as Observable<Annotation[]>;
    }

</code>```

But it can't return rows on documentXFDFRetriever function.

I m sure something is missing here on the return observable.

Can anyone help me with this issue?

答:
Ironically, this exact confusion is why RxJS has deprecated toPromise. If you're using a newer version of RxJS, I would recommend firstValueFrom or lastValueFrom.

If you're using an older version of RxJS, you can use take(1) or first() to ensure the observable completes and resolves the promise.

documentXFDFRetriever: () => this.annotationsService.getAnnotations(
  this.userService.getCurrentDocumentId()
).pipe(
  map(rows => rows.map(row => row.annotationNode)),
  first() // Complete Observable after first emission
).toPromise();
```

Body:
I am trying to put await on Observable like below:

    documentXFDFRetriever: async () => {
            const rows = await this.annotationsService.getAnnotations(this.userService.getCurrentDocumentId()).toPromise();
            console.log(rows);
            return rows.map(row => row.annotationNode);
          }

My Service function:

    public getAnnotations(docId): Observable<Annotation[]> {
        const userId = this.userService.getCurrentUserId();
        const annotationsRef = collection(this.firestore, `annotations/${docId}/${userId}`);
        return collectionData(annotationsRef) as Observable<Annotation[]>;
    }

But it can't return rows on documentXFDFRetriever function.

I m sure something is missing here on the return observable.

Can anyone help me with this issue?


问:
Using Regex how to extract a string until a character only if present, else till end
I am trying to extract string using Regex in python, that starts with word 'swap' till first '/' if present, or till end

For example:

str1: 'abcd/swap 12345 ijkl/mnop/tyuio'

str2: 'abcd/swap ijkl 1234'

str3: 'swap ijklm nop'

Required Output:

from str1: 'swap 12345 ijkl'

from str2: 'swap ijkl 1234'

from str3: 'swap ijklm nop'

I am new to regex and tried many combinations but cant get all 3 situations.

答:
The regex offered by Chris Charley is perfectly fine for the three examples you specified but I do not believe would correctly handle the following:

It would match 'abcd/unswap 12345 ijkl/mnop/tyuio'

It would not match 'abcd/swap'

See Regex Demo

So if the above types of strings are a possibility and if the above results are, in fact, not what you actually want, then consider:

```<code>\bswap\b[^/]*
</code>```

See Regex Demo

\bswap\b - matches 'swap' only on a word boundary.

[^/]* - matches 0 or more non '/' characters until it finds either a '/' character or the end of string.

Body:
The regex offered by Chris Charley is perfectly fine for the three examples you specified but I do not believe would correctly handle the following:

It would match 'abcd/unswap 12345 ijkl/mnop/tyuio'

It would not match 'abcd/swap'

See Regex Demo

So if the above types of strings are a possibility and if the above results are, in fact, not what you actually want, then consider:

\bswap\b[^/]*

See Regex Demo

\bswap\b - matches 'swap' only on a word boundary.

[^/]* - matches 0 or more non '/' characters until it finds either a '/' character or the end of string.


问:
How to find out S3 Bucket last accessed time?
I have a use-case where I need to find out last accessed time of the S3 bucket, but I am not able to find a way to do so. Though, we can get LastModifiedTime or LastUpdatedTime for the bucket, but I couldn't find any AWS API, which can give me the last accessed time for the AWS S3 Bucket. One way to do this is to parse through all the objects inside the buckets, but that's a very expensive operation to do, which I can't afford.
Can somebody help me in getting the LastAccessedTime for the AWS S3 Bucket? I am using Python with boto3.

答:
I don't have a code ready to post as an answer but I have an approach by using which you can achieve it.

You can utilize the Amazon S3 server access logging

S3 Server access logging provides detailed records of the requests that are made to objects in Amazon S3 buckets.

Amazon S3 periodically collects access log records, consolidates the records in log files, and then uploads log files to your target bucket as log objects.

Each log record consists of information such as bucket name, the operation in the request, and the time at which the request was received.

S3 Server Access Log Format provides more details about the format of the log file.

You need to use the target bucket to get the required answer.

Logging requests using server access logging

Enabling Amazon S3 server access logging

ContentLicense: CC BY-SA 3.0


问:
Cron job running successfully but nothing happens
I am very new to creating cron jobs and the linux environment in general, so apologies in advance if the questions sound too simple. I will try to present my problem as clearly as possible. So here it goes,

I have created a simple email (sending to myself) script using Python(3.5.2 version) and I want to schedule this script to run every 2 minutes using the cron job scheduling. I am logging into a remote linux server using SSH where my Python script is stored. The script runs perfectly fine when I run it manually using the linux terminal. When I try to schedule a cron job schedule for this script, my guess is that the script runs, because I can see runs in the  logs using

```<code>sudo grep CRON /var/log/syslog
</code>```

What I see in the logs is something like this

```<code>Dec 30 19:38:01 abc-abcStation CRON[18707]: (abc) CMD (/home/abc/anuj/TPA/Test_Cron.py)
</code>```

at an interval of 2 mins

But the run is not doing what it is supposed to do (send an email), which it does when I run it manually. My cron job looks like this

```<code>*/2 * * * * /home/abc/anuj/TPA/Test_Cron.py
</code>```

The email sending script is Test_Cron.py which looks like this

```<code>import smtplib

server = smtplib.SMTP('smtp.office365.com', 587)
server.starttls()
server.login("username@mycompany.com", "mypassword")

msg = "TEST MESSAGE!"
server.sendmail("username@mycompany.com", "myemail@mycompany.com", msg)
server.quit()
</code>```

I searched quite a lot for this kind of an issue and found similar cases to myself, tried all of the suggested solutions but I'm still missing something.

My guess is that this has something to do with setting the right path. I tried setting the path above my crontab statement, something like

```<code>PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
*/2 * * * * /home/abc/anuj/TPA/Test_Cron.py
</code>```

Also tried,

```<code>SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
*/2 * * * * /home/abc/anuj/TPA/Test_Cron.py
</code>```

and,

```<code>*/2 * * * *  cd /home/abc/anuj/TPA/ && Test_Cron.py
</code>```

but no success. Any help is greatly appreciated.

Thanks!

答:
I had the same issue. Tried EVERYTHING in this post. I only figured out the problem because of this post

I sent output to logger to redirect output to syslog, as I didn't want to deal with linux mail. Here is the command I ran in crontab -e

*/1 * * * * /home/me/backup 2>&1 | /usr/bin/logger -t CRON[backup_output]

Doing this now showed the commands output in /var/log/syslog. What I found was /bin/bash: me: command not found.

This was happening because I still had the username in my crontab file. User automation must be removed when using crontab -e. Adding a username should be added to cronjobs placed in /etc/cron.d/. So, solution? Remove the username in your cronjob. So just put the frequency it should run, and the script thats it.

Body:
I am very new to creating cron jobs and the linux environment in general, so apologies in advance if the questions sound too simple. I will try to present my problem as clearly as possible. So here it goes,

I have created a simple email (sending to myself) script using Python(3.5.2 version) and I want to schedule this script to run every 2 minutes using the cron job scheduling. I am logging into a remote linux server using SSH where my Python script is stored. The script runs perfectly fine when I run it manually using the linux terminal. When I try to schedule a cron job schedule for this script, my guess is that the script runs, because I can see runs in the  logs using

sudo grep CRON /var/log/syslog

What I see in the logs is something like this

Dec 30 19:38:01 abc-abcStation CRON[18707]: (abc) CMD (/home/abc/anuj/TPA/Test_Cron.py)

at an interval of 2 mins

But the run is not doing what it is supposed to do (send an email), which it does when I run it manually. My cron job looks like this

*/2 * * * * /home/abc/anuj/TPA/Test_Cron.py

The email sending script is Test_Cron.py which looks like this

import smtplib

server = smtplib.SMTP('smtp.office365.com', 587)
server.starttls()
server.login("username@mycompany.com", "mypassword")

msg = "TEST MESSAGE!"
server.sendmail("username@mycompany.com", "myemail@mycompany.com", msg)
server.quit()

I searched quite a lot for this kind of an issue and found similar cases to myself, tried all of the suggested solutions but I'm still missing something.

My guess is that this has something to do with setting the right path. I tried setting the path above my crontab statement, something like

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
*/2 * * * * /home/abc/anuj/TPA/Test_Cron.py

Also tried,

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
*/2 * * * * /home/abc/anuj/TPA/Test_Cron.py

and,

*/2 * * * *  cd /home/abc/anuj/TPA/ && Test_Cron.py

but no success. Any help is greatly appreciated.

Thanks!


问:
View and PartialView with jQuery UI
I divide my space screen with a table in 2 columns. The left one is for the menu the right one for the content. In the right column I use jQuery UI tab. The second tab manage a list of contact, I divide the content of this second tab in 2 columns. The left one is the form to add/update a contact, in the right column it's a grid. The problem when I post the form is on "DetailContactDetail", i tried return View, PartialView, or I get the form full screen without anything. I'd like refresh the content of the tab to see the change in the grid.

Controller :

```<code>public ActionResult DetailContact()
{
    ....
    return PartialView("DetailContact", model);
}

public ActionResult SaveContact(CustomerModel model)
{
    .....
    return PartialView("DetailContactDetail");
}
</code>```

HTML :

```<code><script id="Ready" type="text/javascript">
    $(document).ready(function () {
        var $tabs = $("#tabs").tabs({
            select: function (e, ui) {
                runMethod(ui.index);
            }
        });
    });

    function runMethod(selectedtab) {
        switch (selectedtab) {
            case 0:
                $.post('/Customer/DetailGeneral', function (data) {
                    $('#tabs-1').html(data);
                });
                break;
            case 1:
                $.post('/Customer/DetailContact', function (data) {
                    $('#tabs-2').html(data);
                });
                break;
            case 2:
                $.post('/Customer/DetailAdresse', function (data) {
                    $('#tabs-3').html(data);
                });
                break;
        }
    }
</script>

<table style="width:100%;">
<tr>
    <td style="width:20%;vertical-align:top;">
        @Html.Partial("MnuCustomer")
    </td>
    <td style="width:80%;vertical-align:top;">
        <div id="tabs">
            <ul>
                <li><a href="#tabs-1">Info</a></li>
                <li><a href="#tabs-2">Contact</a></li>
                <li><a href="#tabs-3">Adress</a></li>
            </ul>
            <div id="tabs-1">@Html.Partial("DetailGeneral", Model)</div>
            <div id="tabs-2"></div>
            <div id="tabs-3"></div>
        </div>

    </td>
</tr>
</table>
</code>```

The tab content look like this (PartialView "DetailContact.cshtml") look like :

```<code><table style="width:100%;" border="0">
<tr>
    <td style="width:50%;">@Html.Partial("DetailContactDetail",Model)</td>
    <td style="width:50%;">@Html.Partial("DetailContactGrid",Model)</td>
</tr>
</table>
</code>```

DetailContactDetail and DetailContactGrid are PartialView.

答:
It sounds to me you are not submitting the form via AJAX, which seemed like what you wanted to do. If you don't submit the form via AJAX, you should return the whole page (i.e. the page that you show code snippet), not just PartialView("DetailContactDetail").

In another note, it seems to me that your code with tab can be vastly simplified to the following:

```<code><script id="Ready" type="text/javascript">
    $(document).ready(function () {
        var $tabs = $("#tabs").tabs();
    });
</script>

...

<div id="tabs">
    <ul>
        <li><a href="/Customer/DetailGeneral">Info</a></li>
        <li><a href="/Customer/DetailContact">Contact</a></li>
        <li><a href="/Customer/DetailAdresse">Adress</a></li>
    </ul>
</div>
</code>```

Title: View and PartialView with jQuery UI

Body:
I divide my space screen with a table in 2 columns. The left one is for the menu the right one for the content. In the right column I use jQuery UI tab. The second tab manage a list of contact, I divide the content of this second tab in 2 columns. The left one is the form to add/update a contact, in the right column it's a grid. The problem when I post the form is on "DetailContactDetail", i tried return View, PartialView, or I get the form full screen without anything. I'd like refresh the content of the tab to see the change in the grid.

Controller :

public ActionResult DetailContact()
{
    ....
    return PartialView("DetailContact", model);
}

public ActionResult SaveContact(CustomerModel model)
{
    .....
    return PartialView("DetailContactDetail");
}

HTML :

        @Html.Partial("MnuCustomer")

Info

Contact

Adress

@Html.Partial("DetailGeneral", Model)

The tab content look like this (PartialView "DetailContact.cshtml") look like :

    @Html.Partial("DetailContactDetail",Model)
    @Html.Partial("DetailContactGrid",Model)

DetailContactDetail and DetailContactGrid are PartialView.

Body:
It sounds to me you are not submitting the form via AJAX, which seemed like what you wanted to do. If you don't submit the form via AJAX, you should return the whole page (i.e. the page that you show code snippet), not just PartialView("DetailContactDetail").

In another note, it seems to me that your code with tab can be vastly simplified to the following:

<script id="Ready" type="text/javascript">
    $(document).ready(function () {
        var $tabs = $("#tabs").tabs();
    });
</script>

...

<div id="tabs">
    <ul>
        <li><a href="/Customer/DetailGeneral">Info</a></li>
        <li><a href="/Customer/DetailContact">Contact</a></li>
        <li><a href="/Customer/DetailAdresse">Adress</a></li>
    </ul>
</div>


问:
Why isnt window.location.href= not forwarding to page using Safari?
My site lets users login via the Fb button, I'm using the FB / Parse.com JDK for this https://parse.com/docs/js/guide#users-facebook-users

Once the user has been identified, the below code logs the user in and forwards them onto a url. This works as expected under Chrome, but will not work using Safari, the page just stays on the fb.html page which is blank

I've seen that there were some historic issues with

window.location.href=

But, can't find a fix that works for my solution. Does anyone know a way around this?

```<code>Parse.FacebookUtils.logIn(null, {
    success: function(user) {
        if (!user.existed()) {

        } else {
            window.location.href="user_home.html";

        }
    },
    error: function(user, error) {

    }
});
</code>```

答:
I wanted to detect home page but faced same problems for iphone and safari.

I simply added a class called "home" in landing page then just check this class as

```<code>        if (document.querySelector('.home') !== null) {
             // the conditions comes here
        }
</code>```

Details in http://toihid.com/how-to-detect-home-page-in-iphone-and-safari/

Body:
My site lets users login via the Fb button, I'm using the FB / Parse.com JDK for this https://parse.com/docs/js/guide#users-facebook-users

Once the user has been identified, the below code logs the user in and forwards them onto a url. This works as expected under Chrome, but will not work using Safari, the page just stays on the fb.html page which is blank

I've seen that there were some historic issues with

window.location.href=

But, can't find a fix that works for my solution. Does anyone know a way around this?

Parse.FacebookUtils.logIn(null, {
    success: function(user) {
        if (!user.existed()) {

        } else {
            window.location.href="user_home.html";

        }
    },
    error: function(user, error) {

    }
});

Body:
I wanted to detect home page but faced same problems for iphone and safari.

I simply added a class called "home" in landing page then just check this class as

        if (document.querySelector('.home') !== null) {
             // the conditions comes here
        }

Details in http://toihid.com/how-to-detect-home-page-in-iphone-and-safari/


问:
How to log the time when a user closes a flask view?
I am developing a flask Application, now the requirement is to log the time when the user closes a specific flask view (or exits a flask URL). Simple example would be suppose a user is working on '/home' and now closes the browser tab or the browser itself. Then how to record the time for this particular event?

Please help

答:
This worked for me with similar use case as ajax calls cannot be made anymore so please use navigator.sendBeacon

https://stackoverflow.com/a/20322988/10738743


问:
error in android application class but app is working fine
enter image description here

Application class looks like this but app working fine ..
why is this showing error ?

答:
The file you've opened is Application

This is not a part of your app. You can refer to it as API documentation of how/when to use a particular class and see what it actually does.

To distinguish you can look at the top right corner of the editor showing "Reader Mode".


问:
How to use deleteById jpa repository if my id is a String?
I need to delete an entity using its ID, tried using JPA repository delete by id method

```<code> productRepository.deleteById(id);
</code>```

Where "id" is supposed to be Long- If passed string value will give an error: Long expected

```<code>Sample id= "402880f17ebd7e44017ebd7fe9ee0000"
</code>```

Hence I can't convert the String to Long

Entity class

```<code>@Entity
@Table(name = "products")
public class Product {

@Id @GeneratedValue(generator = "system-uuid")
@GenericGenerator(name="system-uuid",strategy = "uuid")
@Column(name="product_id")
private String id;

@Column(name="price")
@NotNull
private float productPrice;

@Column(name="product_name")
@NotNull
private String productName;

@Column(name="description")
private String productDesc;

@Column(name="stock_available")
private int productStock;

@ManyToOne(optional = false)
@JoinColumn(name = "shop_id")
private Shop shop;

public Product(){
}

public Product(String id, float productPrice, String productName, String productDesc, int productStock, Shop shop) {
    this.id = id;
    this.productPrice = productPrice;
    this.productName = productName;
    this.productDesc = productDesc;
    this.productStock = productStock;
    this.shop = shop;
}
}
</code>```

Repository Class:

```<code>@Repository
public interface ProductRepository extends JpaRepository<Product,Long>{
}
</code>```

答:
In your ProductRepository, when you are extending the JpaRepository<EntityName,EntityId Type>.
In your case, you are using the field id as string but extending the type as Long.
To solve your problem, either take the input in the form of Long number or convert the primary key type to String.

Body:
I need to delete an entity using its ID, tried using JPA repository delete by id method

 productRepository.deleteById(id);

Where "id" is supposed to be Long- If passed string value will give an error: Long expected

Sample id= "402880f17ebd7e44017ebd7fe9ee0000"

Hence I can't convert the String to Long

Entity class

@Entity
@Table(name = "products")
public class Product {

@Id @GeneratedValue(generator = "system-uuid")
@GenericGenerator(name="system-uuid",strategy = "uuid")
@Column(name="product_id")
private String id;

@Column(name="price")
@NotNull
private float productPrice;

@Column(name="product_name")
@NotNull
private String productName;

@Column(name="description")
private String productDesc;

@Column(name="stock_available")
private int productStock;

@ManyToOne(optional = false)
@JoinColumn(name = "shop_id")
private Shop shop;

public Product(){
}

public Product(String id, float productPrice, String productName, String productDesc, int productStock, Shop shop) {
    this.id = id;
    this.productPrice = productPrice;
    this.productName = productName;
    this.productDesc = productDesc;
    this.productStock = productStock;
    this.shop = shop;
}
}

Repository Class:

@Repository
public interface ProductRepository extends JpaRepository<Product,Long>{
}


问:
Outputting text from an url that returns JSON
I'm more of a backend guy, this javascript stuff is a bit out of my area. I could really use a point in the right direction :)

So I have an URL that, for example, returns this JSON:

```<code>[{"pk": 1, "model": "didyouknow.fact", "fields": {"fact": "Random fact 1"}},
 {"pk": 2, "model": "didyouknow.fact", "fields": {"fact": "Random fact 2"}},
 {"pk": 3, "model": "didyouknow.fact", "fields": {"fact": "Random fact 3"}},
 {"pk": 4, "model": "didyouknow.fact", "fields": {"fact": "Random fact 4"}},
 {"pk": 5, "model": "didyouknow.fact", "fields": {"fact": "Random fact 5"}}]
</code>```

I want to write a piece of javascript that I can embed in my HTML that will randomly choose and print one of the "fact"s from the JSON URL.

答:
You can do it like this:

```<code>var questionData = JSON.parse(data);
var randomIndex = Math.floor(Math.random() * questionData.length);
var randomFact = questionData[randomIndex].fields.fact;
</code>```

Then, what you want to do with the randomFact in your web page is up to you and you haven't provided any info on that for us to help with that.  You could put the fact into an existing element on the page.  You could create new elements on the page where you want them, etc...

Body:
I'm more of a backend guy, this javascript stuff is a bit out of my area. I could really use a point in the right direction :)

So I have an URL that, for example, returns this JSON:

[{"pk": 1, "model": "didyouknow.fact", "fields": {"fact": "Random fact 1"}},
 {"pk": 2, "model": "didyouknow.fact", "fields": {"fact": "Random fact 2"}},
 {"pk": 3, "model": "didyouknow.fact", "fields": {"fact": "Random fact 3"}},
 {"pk": 4, "model": "didyouknow.fact", "fields": {"fact": "Random fact 4"}},
 {"pk": 5, "model": "didyouknow.fact", "fields": {"fact": "Random fact 5"}}]

I want to write a piece of javascript that I can embed in my HTML that will randomly choose and print one of the "fact"s from the JSON URL.

Body:
You can do it like this:

var questionData = JSON.parse(data);
var randomIndex = Math.floor(Math.random() * questionData.length);
var randomFact = questionData[randomIndex].fields.fact;

Then, what you want to do with the randomFact in your web page is up to you and you haven't provided any info on that for us to help with that.  You could put the fact into an existing element on the page.  You could create new elements on the page where you want them, etc...


问:
AWS load balancer log analyzer
I'm new to AWS wolrd. My purpose is to find as soon as possible in case of problems using Elastic Load Balancer logs top ips from requests, if possible who they are or some inspection on it. I only found paid services. Does anyone know a free application or maybe a website that analyzes AWS ELB logs?</p>

答:
Completely free solution isn't available as I know. Btw, there are cheap solutions.

You can monitor your load balancer by "Access logs", "CloudWatch metrics", "Request tracing" and "CloudTrail logs".

I don't understand exactly what you want, but there are some possible solutions.

If you're afraid of being attacked and you need immediate protection (against security scans, DDoS etc), you can use AWS's own services. "AWS Shield Standard" is automatically included at no extra cost. Btw, "For added protection against DDoS attacks, AWS offers AWS Shield Advanced". https://docs.aws.amazon.com/shield/

WAF is also good against attacks. You can create rules, rule-actions etc. Sadly it's not completely free. It runs "pay-as-you-use" style. https://aws.amazon.com/waf/pricing/

you can store the access log in S3 and analyse it later, but this can be costly in the end (and it's not real time)

you can analyse your log records with Lambda function. In this case, you need to use some NoSQL or something to store states or logics. (Lambda and DynamoDB is "pay-as-you-use" style and cheap, but not for free)

Keep in mind that:

The load balancer and lambda also increments the corresponding CloudWatch metric (it's cheap, but not for free)

You will pay for the outgoing data transfer. I mean from AWS to internet 1TB/month/account is always free (through CloudFront): https://aws.amazon.com/free/

you should use AWS's own services if you want a cheap and good solution

Title: AWS load balancer log analyzer


问:
PieChart recharts not responsive
There are already other resources which seem to work for some people, but in this case it doesn't work and I cannot figure out a workaround.

Similar resources:

Stack Overflow

Github recharts

Github recharts

I created a sandbox for it here

Suggestions to solve this, were the use of ResponsiveContainer component (provided by recharts), but that doesn't work as you can see in the sandbox.

Plus, the original example provided by recharts and viewable here doesn't work either (try changing the width and height on the jsFiddle example to 100vw and 100vh and then resize the window to 320px and you will see the text getting cropped).

Referring to the Github closed issues, it seems they were pointing out the problem on cx, cy, innerRadius and outerRadius attributes being set as px instead of percentages and that's what caused the issue, but the jsFiddle provided are not working and I cannot figure out how to achieve that with percentages.

Any helping input would be highly appreciated, thank you!

答:
got same issue.. adding a div with class flex, justify-center worked for me..</p>
```<code><div className="flex justify-center items-center">
         <PieChart width={800} height={400} onMouseEnter={this.onPieEnter}>
        <Pie
          data={data}
          innerRadius={60}
          outerRadius={80}
          fill="#8884d8"
          paddingAngle={5}
          dataKey="value"
        >
          {data.map((entry, index) => (
            <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
          ))}
        </Pie>
        </PieChart>
      </div>
</code>```

Title: PieChart recharts not responsive

Body:
got same issue.. adding a div with class flex, justify-center worked for me..

<div className="flex justify-center items-center">
         <PieChart width={800} height={400} onMouseEnter={this.onPieEnter}>
        <Pie
          data={data}
          innerRadius={60}
          outerRadius={80}
          fill="#8884d8"
          paddingAngle={5}
          dataKey="value"
        >
          {data.map((entry, index) => (
            <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
          ))}
        </Pie>
        </PieChart>
      </div>


问:
An established connection was aborted by the software in your host machine tomcat jackson
Below is a stacktrace I get when my rest service tries to fetch a large data set (database and tomcat are on my local machine, so everything is local). It works on smaller ones, but in some cases user wants a lot of data. I checked similar problems posted here, but there seems to be none like mine.

My questions are

1. Why does it fail to display a response?

2. Is response size limited somehow on tomcat? Maybe there is a timeout or something like that?

3. Maybe it is Jackson that fails to do its job. If it is Jackson - can it be caused by annotations like @JsonBackReference and @JsonManagedReference?

4. What can I do to fix it?

```<code>ClientAbortException:  java.io.IOException: An established connection was aborted by the software in your host machine
    at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:413)
    at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:480)
    at org.apache.tomcat.util.buf.ByteChunk.append(ByteChunk.java:366)
    at org.apache.catalina.connector.OutputBuffer.writeBytes(OutputBuffer.java:438)
    at org.apache.catalina.connector.OutputBuffer.write(OutputBuffer.java:426)
    at org.apache.catalina.connector.CoyoteOutputStream.write(CoyoteOutputStream.java:91)
    at com.fasterxml.jackson.core.json.UTF8JsonGenerator._flushBuffer(UTF8JsonGenerator.java:1862)
    at com.fasterxml.jackson.core.json.UTF8JsonGenerator._writeBytes(UTF8JsonGenerator.java:1132)
    at com.fasterxml.jackson.core.json.UTF8JsonGenerator._writeFieldName(UTF8JsonGenerator.java:270)
    at com.fasterxml.jackson.core.json.UTF8JsonGenerator.writeFieldName(UTF8JsonGenerator.java:249)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:539)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:644)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:117)
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:23)
    at com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:183)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:541)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:644)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:117)
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:23)
    at com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:183)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:541)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:644)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:114)
    at com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:1837)
    at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.writeInternal(MappingJackson2HttpMessageConverter.java:253)
    at org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:208)
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:143)
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:89)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:193)
    at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:122)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:186)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:177)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:683)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1720)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1679)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.io.IOException: An established connection was aborted by the software in your host machine
    at sun.nio.ch.SocketDispatcher.write0(Native Method)
    at sun.nio.ch.SocketDispatcher.write(Unknown Source)
    at sun.nio.ch.IOUtil.writeFromNativeBuffer(Unknown Source)
    at sun.nio.ch.IOUtil.write(Unknown Source)
    at sun.nio.ch.SocketChannelImpl.write(Unknown Source)
    at org.apache.tomcat.util.net.NioChannel.write(NioChannel.java:123)
    at org.apache.tomcat.util.net.NioBlockingSelector.write(NioBlockingSelector.java:101)
    at org.apache.tomcat.util.net.NioSelectorPool.write(NioSelectorPool.java:174)
    at org.apache.coyote.http11.InternalNioOutputBuffer.writeToSocket(InternalNioOutputBuffer.java:163)
    at org.apache.coyote.http11.InternalNioOutputBuffer.flushBuffer(InternalNioOutputBuffer.java:242)
    at org.apache.coyote.http11.InternalNioOutputBuffer.addToBB(InternalNioOutputBuffer.java:213)
    at org.apache.coyote.http11.InternalNioOutputBuffer.access$000(InternalNioOutputBuffer.java:41)
    at org.apache.coyote.http11.InternalNioOutputBuffer$SocketOutputBuffer.doWrite(InternalNioOutputBuffer.java:268)
    at org.apache.coyote.http11.filters.ChunkedOutputFilter.doWrite(ChunkedOutputFilter.java:119)
    at org.apache.coyote.http11.AbstractOutputBuffer.doWrite(AbstractOutputBuffer.java:192)
    at org.apache.coyote.Response.doWrite(Response.java:520)
    at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:408)
    ... 69 more

2014-09-15 17:35:31 ERROR ExceptionHandlerExceptionResolver:343 - Failed to invoke @ExceptionHandler method: public void com.acxiom.listkey.metadata.exceptions.GlobalExceptionHandler.handleInternalException(java.lang.Exception)
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
    at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:450)
    at javax.servlet.http.HttpServletResponseWrapper.sendError(HttpServletResponseWrapper.java:119)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.setResponseStatus(ServletInvocableHandlerMethod.java:141)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
    at org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.doResolveHandlerMethodException(ExceptionHandlerExceptionResolver.java:340)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodExceptionResolver.doResolveException(AbstractHandlerMethodExceptionResolver.java:60)
    at org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(AbstractHandlerExceptionResolver.java:138)
    at org.springframework.web.servlet.handler.HandlerExceptionResolverComposite.resolveException(HandlerExceptionResolverComposite.java:75)
    at org.springframework.web.servlet.DispatcherServlet.processHandlerException(DispatcherServlet.java:1161)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:998)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:952)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:186)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:177)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:683)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1720)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1679)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
</code>```

below is the code (in controller) that returns the response to client:

```<code>@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public String getSelections(@RequestParam Integer systemId, @RequestParam String listCode)
        throws JsonProcessingException {
    SelectionsDTO selectionsDTO = new SelectionsDTO(systemSelectionService.findSelections(systemId, listCode));

    String retVal = objectMapper.writeValueAsString(selectionsDTO);
    return retVal;
}
</code>```

as you can see I have even tried to marshall it to string before returning, to exclude jackson as the reason of failure. It does not matter if I return collection of my DTOs or string. It fails the same way. I have debugged it and I checked the size of the message that was written to output successfully (it is around 2,15MB). In my opinion size of the message is the failure cause.

答:
If you are using ColdFusion, you can also set a page's requestTimeOut to override the server setting.

Per https://helpx.adobe.com/coldfusion/cfml-reference/coldfusion-tags/tags-r-s/cfsetting.html, "If you specify 0 as the value, timeout is disabled for the request".

```<code><cfsetting requestTimeOut="0">

cfscript: setting requestTimeOut="0";
</code>```

Body:
Below is a stacktrace I get when my rest service tries to fetch a large data set (database and tomcat are on my local machine, so everything is local). It works on smaller ones, but in some cases user wants a lot of data. I checked similar problems posted here, but there seems to be none like mine.

My questions are

1. Why does it fail to display a response?

2. Is response size limited somehow on tomcat? Maybe there is a timeout or something like that?

3. Maybe it is Jackson that fails to do its job. If it is Jackson - can it be caused by annotations like @JsonBackReference and @JsonManagedReference?

4. What can I do to fix it?

ClientAbortException:  java.io.IOException: An established connection was aborted by the software in your host machine
    at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:413)
    at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:480)
    at org.apache.tomcat.util.buf.ByteChunk.append(ByteChunk.java:366)
    at org.apache.catalina.connector.OutputBuffer.writeBytes(OutputBuffer.java:438)
    at org.apache.catalina.connector.OutputBuffer.write(OutputBuffer.java:426)
    at org.apache.catalina.connector.CoyoteOutputStream.write(CoyoteOutputStream.java:91)
    at com.fasterxml.jackson.core.json.UTF8JsonGenerator._flushBuffer(UTF8JsonGenerator.java:1862)
    at com.fasterxml.jackson.core.json.UTF8JsonGenerator._writeBytes(UTF8JsonGenerator.java:1132)
    at com.fasterxml.jackson.core.json.UTF8JsonGenerator._writeFieldName(UTF8JsonGenerator.java:270)
    at com.fasterxml.jackson.core.json.UTF8JsonGenerator.writeFieldName(UTF8JsonGenerator.java:249)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:539)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:644)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:117)
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:23)
    at com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:183)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:541)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:644)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:117)
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:23)
    at com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:183)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:541)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:644)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:114)
    at com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:1837)
    at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.writeInternal(MappingJackson2HttpMessageConverter.java:253)
    at org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:208)
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:143)
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:89)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:193)
    at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:122)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:186)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:177)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:683)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1720)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1679)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.io.IOException: An established connection was aborted by the software in your host machine
    at sun.nio.ch.SocketDispatcher.write0(Native Method)
    at sun.nio.ch.SocketDispatcher.write(Unknown Source)
    at sun.nio.ch.IOUtil.writeFromNativeBuffer(Unknown Source)
    at sun.nio.ch.IOUtil.write(Unknown Source)
    at sun.nio.ch.SocketChannelImpl.write(Unknown Source)
    at org.apache.tomcat.util.net.NioChannel.write(NioChannel.java:123)
    at org.apache.tomcat.util.net.NioBlockingSelector.write(NioBlockingSelector.java:101)
    at org.apache.tomcat.util.net.NioSelectorPool.write(NioSelectorPool.java:174)
    at org.apache.coyote.http11.InternalNioOutputBuffer.writeToSocket(InternalNioOutputBuffer.java:163)
    at org.apache.coyote.http11.InternalNioOutputBuffer.flushBuffer(InternalNioOutputBuffer.java:242)
    at org.apache.coyote.http11.InternalNioOutputBuffer.addToBB(InternalNioOutputBuffer.java:213)
    at org.apache.coyote.http11.InternalNioOutputBuffer.access$000(InternalNioOutputBuffer.java:41)
    at org.apache.coyote.http11.InternalNioOutputBuffer$SocketOutputBuffer.doWrite(InternalNioOutputBuffer.java:268)
    at org.apache.coyote.http11.filters.ChunkedOutputFilter.doWrite(ChunkedOutputFilter.java:119)
    at org.apache.coyote.http11.AbstractOutputBuffer.doWrite(AbstractOutputBuffer.java:192)
    at org.apache.coyote.Response.doWrite(Response.java:520)
    at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:408)
    ... 69 more

2014-09-15 17:35:31 ERROR ExceptionHandlerExceptionResolver:343 - Failed to invoke @ExceptionHandler method: public void com.acxiom.listkey.metadata.exceptions.GlobalExceptionHandler.handleInternalException(java.lang.Exception)
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
    at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:450)
    at javax.servlet.http.HttpServletResponseWrapper.sendError(HttpServletResponseWrapper.java:119)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.setResponseStatus(ServletInvocableHandlerMethod.java:141)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
    at org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.doResolveHandlerMethodException(ExceptionHandlerExceptionResolver.java:340)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodExceptionResolver.doResolveException(AbstractHandlerMethodExceptionResolver.java:60)
    at org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(AbstractHandlerExceptionResolver.java:138)
    at org.springframework.web.servlet.handler.HandlerExceptionResolverComposite.resolveException(HandlerExceptionResolverComposite.java:75)
    at org.springframework.web.servlet.DispatcherServlet.processHandlerException(DispatcherServlet.java:1161)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:998)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:952)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:186)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:177)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:683)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1720)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1679)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

below is the code (in controller) that returns the response to client:

@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public String getSelections(@RequestParam Integer systemId, @RequestParam String listCode)
        throws JsonProcessingException {
    SelectionsDTO selectionsDTO = new SelectionsDTO(systemSelectionService.findSelections(systemId, listCode));

    String retVal = objectMapper.writeValueAsString(selectionsDTO);
    return retVal;
}

as you can see I have even tried to marshall it to string before returning, to exclude jackson as the reason of failure. It does not matter if I return collection of my DTOs or string. It fails the same way. I have debugged it and I checked the size of the message that was written to output successfully (it is around 2,15MB). In my opinion size of the message is the failure cause.

Body:
If you are using ColdFusion, you can also set a page's requestTimeOut to override the server setting.

Per https://helpx.adobe.com/coldfusion/cfml-reference/coldfusion-tags/tags-r-s/cfsetting.html, "If you specify 0 as the value, timeout is disabled for the request".

<cfsetting requestTimeOut="0">

cfscript: setting requestTimeOut="0";


问:
Automate deployment of asp.net mvc site
Currently I build my websites on my machine, deploy them to a test machine to see if they still work there and then have to request the sysadmin to deploy them to the qa/production servers.

Time after time that what should be my moment of pride is killed by some deployment procedure that was misunderstood, forgotten or not documented.

Currently the sysadmin copies the files from the dev server to whatever server he sees fit and tries to follow my deploymentProcedures.txt.

Is there no mechanism I can use that makes this transition as frictionless as possible? Things I can think of now are

Set the connectionstring to production DB

Set CustomErrors to On

Check if the correct I/O rights are given to the running account

Make sure the needed COM objects are available

Something that can make the deployment fase easier for people who are not the programmers.

答: If your application is just being created by you or a team over which you have some control, You should gun for CI (Continuous Integration). There are many free products in out there which Cruise Control .NET is something which might help you.</p>

OwnerDisplayName: boris callens

ContentLicense: CC BY-SA 2.5

Title: Automate deployment of asp.net mvc site

OwnerDisplayName: Minhajuddin


答:
The primary key type is wrong, should be ‘String’, not ‘Long’:</p>
```<code>@Repository
public interface ProductRepository extends JpaRepository<Product,String>{
}
</code>```

Title: How to use deleteById jpa repository if my id is a String?

Body:
The primary key type is wrong, should be ‘String’, not ‘Long’:

@Repository
public interface ProductRepository extends JpaRepository<Product,String>{
}


问:
Angular Error Dialog invoked from ErrorHandler doesn't display data on TypeError
I've gotten most of this example working thanks to other posts, but I'm still having one problem.

If I throw an error, the Error Dialog works as expected. The Error Dialog also works if I throw an HTTP error (including if I catch the error in pipe and return throwError(error)). However, if a typescript error as thrown if attempting to display an undefined object, the Error Dialog doesn't display data from the component, and the dialog doesn't close.

Here's the code I'm experimenting with.

```<code>
    import { BrowserModule } from '@angular/platform-browser';
    import { Component, Inject, Injectable, OnInit, ErrorHandler, NgModule, NgZone } from '@angular/core';

    import { HttpClientModule } from '@angular/common/http';
    import { HttpClient } from '@angular/common/http';

    import { Observable } from 'rxjs';

    import { MatDialogModule } from '@angular/material/dialog';
    import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

    @Component({
      selector: 'app-root',
      template: `
    <div class="content">
    <h1>{{title}}</h1>
    <h3>{{something[0]['text']}}</h3>
    <button (click)="forceFakeError()">Force Fake Error</button>
    <br>
    <button (click)="forceHttpError()">Force HTTP Error</button>
    <br>
    <button (click)="forceTypeError()">Force Type Error</button>
    </div>
    `,
      styles: ['div.content {padding: 25px;}', 'button {margin: 10px}']
    })
    export class AppComponent {
      title = 'dialog-issue';
      something = [{ text: 'This is some test text' }];
      data: any;

      constructor(public dialog: MatDialog, private http: HttpClient) {}

      forceFakeError() {
          throw(new Error('Fake  eror...'));
      }

      forceHttpError() {
        this.http.get<any>('https://garbageinout.io').subscribe({
            next: data => {
                this.data = data;
            },
            error: error => {
                console.error('There was an error!', error);
                throw(error);
            }
        });
      }

      forceTypeError() {
        this.something.length = 0;
      }
    }

    @Injectable({
        providedIn: 'root'
    })
    export class ErrorHandlerService implements ErrorHandler {

       handling = false;

        constructor(private dialog: MatDialog, private ngZone: NgZone) {}

        handleError(error: any) {
            if (this.handling) {
                console.log('errorhandler already handling error message: ' + error.message);
                return;
            }
            this.handling = true;
            console.log('errorhandler error: ', error);
            console.log('errorhandler error name: ' + error.constructor.name);
            const errMsg = error.message ?? 'No message found!';
            console.log('errorhandler error message: ' + error.message);
            this.ngZone.run(() => {
                this.displayErrorMessage('Application Error', errMsg)
                    .subscribe((resp) => {
                        console.log('Response is: ', resp);
                        this.handling = false;
                    });
          });
        }

        displayErrorMessage(title: string, msg: string): Observable<string> {
            const dialogRef = this.dialog.open(TestDialog,
                {width: '400px', disableClose: true, data: { title: title, message: msg}
            });
            return dialogRef.afterClosed();
        }
    }

    export interface ErrorData {
       title: string;
       message: string;
    }

    @Component({
      selector: 'app-error',
      template: `
    <div>
    <h1 mat-dialog-title>{{title}}</h1>
    <div mat-dialog-content>
      <p>Click OK to continue, or click on the "Click here"
         link to restart the app.</p>
      <p>Message: {{msg}}</p>
      <p>{{dateTime()}}</p>
      <p><a href="/index">Click here</a> to restart app</p>
    </div>
    <button mat-raised-button (click)="onClick()">OK</button>
    </div>
    `,
      styles: ['button { margin: 5 }']
    })
    export class TestDialog implements OnInit {
        title: string = 'Fake Title';
        msg: string = 'Fake string';

        constructor(public dialogRef: MatDialogRef<TestDialog>,
                @Inject(MAT_DIALOG_DATA) public data: ErrorData) {
            this.title = data.title;
            this.msg = data.message ?? 'Message not provided...';
        }

        ngOnInit() {
            console.log('error dialog, title: ', this.title, ', msg: ', this.msg);
        }

        dateTime(): string {
            return new Date().toString();
        }

        onClick() {
            console.log('entering error dialog onClick event');
            this.dialogRef.close('OK!');
        }
    }

    @NgModule({
      declarations: [
        AppComponent,
        TestDialog
      ],
      imports: [
        BrowserModule,
        BrowserAnimationsModule,
        MatDialogModule
      ],
      exports: [
        HttpClientModule,
        MatDialogModule
      ],
      providers: [
          { provide: ErrorHandler, useClass: ErrorHandlerService }
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

</code>```

My environment is:

```<code>
    Angular CLI: 13.2.2
    Node: 16.13.0
    Package Manager: npm 8.4.1
    OS: darwin arm64

    Angular: 13.2.1
    ... animations, cdk, common, compiler, compiler-cli, core, forms
    ... material, platform-browser, platform-browser-dynamic, router

    Package                         Version
    ---------------------------------------------------------
    @angular-devkit/architect       0.1302.2
    @angular-devkit/build-angular   13.2.2
    @angular-devkit/core            13.2.2
    @angular-devkit/schematics      13.2.2
    @angular/cli                    13.2.2
    @schematics/angular             13.2.2
    rxjs                            7.5.2
    typescript                      4.5.5

</code>```

and I'm using the command "ng serve --ssl --configuration production" for execution.

Thank you in advance for any insight on how to solve this problem.

答:
That is because no Error was raised. Your something is an array and has a length property. Sure it should be readonly but javascript executes it no matter what - although it has no effect on the value of the length property.

You can test it directly in your browsers dev console. Just type and enter:

```<code>[].length = 0;
</code>```

No error is raised.

I suppose your handler whould correctly handle something like this:

```<code>this.something.unknownProperty.anotherProperty = 0;
</code>```

As unknownProperty will return undefined, javascript can´t execute that statement. It can´t resolve anotherProperty from undefined. That raises an error.

Body:
I've gotten most of this example working thanks to other posts, but I'm still having one problem.

If I throw an error, the Error Dialog works as expected. The Error Dialog also works if I throw an HTTP error (including if I catch the error in pipe and return throwError(error)). However, if a typescript error as thrown if attempting to display an undefined object, the Error Dialog doesn't display data from the component, and the dialog doesn't close.

Here's the code I'm experimenting with.

    import { BrowserModule } from '@angular/platform-browser';
    import { Component, Inject, Injectable, OnInit, ErrorHandler, NgModule, NgZone } from '@angular/core';

    import { HttpClientModule } from '@angular/common/http';
    import { HttpClient } from '@angular/common/http';

    import { Observable } from 'rxjs';

    import { MatDialogModule } from '@angular/material/dialog';
    import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

    @Component({
      selector: 'app-root',
      template: `

{{title}}

{{something[0]['text']}}

    <button (click)="forceFakeError()">Force Fake Error</button>

    <button (click)="forceHttpError()">Force HTTP Error</button>

    <button (click)="forceTypeError()">Force Type Error</button>

    `,
      styles: ['div.content {padding: 25px;}', 'button {margin: 10px}']
    })
    export class AppComponent {
      title = 'dialog-issue';
      something = [{ text: 'This is some test text' }];
      data: any;

      constructor(public dialog: MatDialog, private http: HttpClient) {}

      forceFakeError() {
          throw(new Error('Fake  eror...'));
      }

      forceHttpError() {
        this.http.get<any>('https://garbageinout.io').subscribe({
            next: data => {
                this.data = data;
            },
            error: error => {
                console.error('There was an error!', error);
                throw(error);
            }
        });
      }

      forceTypeError() {
        this.something.length = 0;
      }
    }

    @Injectable({
        providedIn: 'root'
    })
    export class ErrorHandlerService implements ErrorHandler {

       handling = false;

        constructor(private dialog: MatDialog, private ngZone: NgZone) {}

        handleError(error: any) {
            if (this.handling) {
                console.log('errorhandler already handling error message: ' + error.message);
                return;
            }
            this.handling = true;
            console.log('errorhandler error: ', error);
            console.log('errorhandler error name: ' + error.constructor.name);
            const errMsg = error.message ?? 'No message found!';
            console.log('errorhandler error message: ' + error.message);
            this.ngZone.run(() => {
                this.displayErrorMessage('Application Error', errMsg)
                    .subscribe((resp) => {
                        console.log('Response is: ', resp);
                        this.handling = false;
                    });
          });
        }

        displayErrorMessage(title: string, msg: string): Observable<string> {
            const dialogRef = this.dialog.open(TestDialog,
                {width: '400px', disableClose: true, data: { title: title, message: msg}
            });
            return dialogRef.afterClosed();
        }
    }

    export interface ErrorData {
       title: string;
       message: string;
    }

    @Component({
      selector: 'app-error',
      template: `

{{title}}

Click OK to continue, or click on the "Click here"
         link to restart the app.

Message: {{msg}}

{{dateTime()}}

Click here to restart app

    <button mat-raised-button (click)="onClick()">OK</button>

    `,
      styles: ['button { margin: 5 }']
    })
    export class TestDialog implements OnInit {
        title: string = 'Fake Title';
        msg: string = 'Fake string';

        constructor(public dialogRef: MatDialogRef<TestDialog>,
                @Inject(MAT_DIALOG_DATA) public data: ErrorData) {
            this.title = data.title;
            this.msg = data.message ?? 'Message not provided...';
        }

        ngOnInit() {
            console.log('error dialog, title: ', this.title, ', msg: ', this.msg);
        }

        dateTime(): string {
            return new Date().toString();
        }

        onClick() {
            console.log('entering error dialog onClick event');
            this.dialogRef.close('OK!');
        }
    }

    @NgModule({
      declarations: [
        AppComponent,
        TestDialog
      ],
      imports: [
        BrowserModule,
        BrowserAnimationsModule,
        MatDialogModule
      ],
      exports: [
        HttpClientModule,
        MatDialogModule
      ],
      providers: [
          { provide: ErrorHandler, useClass: ErrorHandlerService }
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

My environment is:

    Angular CLI: 13.2.2
    Node: 16.13.0
    Package Manager: npm 8.4.1
    OS: darwin arm64

    Angular: 13.2.1
    ... animations, cdk, common, compiler, compiler-cli, core, forms
    ... material, platform-browser, platform-browser-dynamic, router

    Package                         Version
    ---------------------------------------------------------
    @angular-devkit/architect       0.1302.2
    @angular-devkit/build-angular   13.2.2
    @angular-devkit/core            13.2.2
    @angular-devkit/schematics      13.2.2
    @angular/cli                    13.2.2
    @schematics/angular             13.2.2
    rxjs                            7.5.2
    typescript                      4.5.5

and I'm using the command "ng serve --ssl --configuration production" for execution.

Thank you in advance for any insight on how to solve this problem.

Body:
That is because no Error was raised. Your something is an array and has a length property. Sure it should be readonly but javascript executes it no matter what - although it has no effect on the value of the length property.

You can test it directly in your browsers dev console. Just type and enter:

[].length = 0;

No error is raised.

I suppose your handler whould correctly handle something like this:

this.something.unknownProperty.anotherProperty = 0;

As unknownProperty will return undefined, javascript can´t execute that statement. It can´t resolve anotherProperty from undefined. That raises an error.


问:
Python Pseudocode help needed . just copy and paste the link into google
enter image description here

hi there, i am struggling with this question and i have missed lessons because of covid therefore i am behind, it would be really appreciated if someone could answer this question in python code. Copy and paste the link onto a new tab

答:
```<code>answer <- 0 // Making "answer" 0
column <- 8 // Making "column" 8

WHILE column < 1: // While "column" is less than 1:
    OUTPUT "Enter bit value" // Prints the text
    bit <- USERINPUT // The user's reply is saved to "bit"
    answer <- answer + (column * bit) // Sum
    column <- column / 2 // Making "column" half its' value

// While "column" is NOT less than 1:

OUTPUT "Decimal Value is: ", answer // Prints the text followed by the value of "answer"
</code>```


问:
Select the next item in a validation list VBA
I'm creating a simple form in excel that will run in a touch device. In some part of the form i have created a dropdown validation list. I need to go to the next and previous item in the validation list with a button.

The only way thay i found is using Application.Sendkeys to acces to the dropdown but is not working. Any thoughts?

```<code>sub Next_item click()

ActiveSheet.Range(cell_rng.Text).Select
Application.SendKeys ("%{Down}")
Application.SendKeys ("{Down}{Enter}")

End Sub
</code>```

答:
You might consider going to the source of the data validation and grabbing the next item rather than trying to manipulate the in-cell dropdown directly.  For instance, if you data validation is a comma-separated list

you could use code like this to get the next value:

```<code>Public Sub NextItem()

    Dim dv As Validation
    Dim vaSplit As Variant
    Dim i As Long

    'Formula1 contains the comma sep list of values
    Set dv = ActiveCell.Validation
    vaSplit = Split(dv.Formula1, ",")

    For i = LBound(vaSplit) To UBound(vaSplit)
        'if you're at the currently selected one
        If vaSplit(i) = ActiveCell.Value Then
            'but not at the last one
            If i < UBound(vaSplit) Then
                'select the next one
                ActiveCell.Value = vaSplit(i + 1)
                Exit For
            End If
        End If
    Next i

End Sub
</code>```

And if your list comes from a simple range

you could use almost the same code

```<code>Public Sub NextItemRange()

    Dim dv As Validation
    Dim vaSplit As Variant
    Dim i As Long

    Set dv = ActiveCell.Validation

    vaSplit = Range(dv.Formula1).Value

    For i = LBound(vaSplit, 1) To UBound(vaSplit, 1)
        If vaSplit(i, 1) = ActiveCell.Value Then
            If i < UBound(vaSplit, 1) Then
                ActiveCell.Value = vaSplit(i + 1, 1)
                Exit For
            End If
        End If
    Next i

End Sub
</code>```

Dynamic ranges or tables might throw a wrench into it, but hopefully it's a start.

Body:
I'm creating a simple form in excel that will run in a touch device. In some part of the form i have created a dropdown validation list. I need to go to the next and previous item in the validation list with a button.

The only way thay i found is using Application.Sendkeys to acces to the dropdown but is not working. Any thoughts?

sub Next_item click()

ActiveSheet.Range(cell_rng.Text).Select
Application.SendKeys ("%{Down}")
Application.SendKeys ("{Down}{Enter}")

End Sub

Body:
You might consider going to the source of the data validation and grabbing the next item rather than trying to manipulate the in-cell dropdown directly.  For instance, if you data validation is a comma-separated list

you could use code like this to get the next value:

Public Sub NextItem()

    Dim dv As Validation
    Dim vaSplit As Variant
    Dim i As Long

    'Formula1 contains the comma sep list of values
    Set dv = ActiveCell.Validation
    vaSplit = Split(dv.Formula1, ",")

    For i = LBound(vaSplit) To UBound(vaSplit)
        'if you're at the currently selected one
        If vaSplit(i) = ActiveCell.Value Then
            'but not at the last one
            If i < UBound(vaSplit) Then
                'select the next one
                ActiveCell.Value = vaSplit(i + 1)
                Exit For
            End If
        End If
    Next i

End Sub

And if your list comes from a simple range

you could use almost the same code

Public Sub NextItemRange()

    Dim dv As Validation
    Dim vaSplit As Variant
    Dim i As Long

    Set dv = ActiveCell.Validation

    vaSplit = Range(dv.Formula1).Value

    For i = LBound(vaSplit, 1) To UBound(vaSplit, 1)
        If vaSplit(i, 1) = ActiveCell.Value Then
            If i < UBound(vaSplit, 1) Then
                ActiveCell.Value = vaSplit(i + 1, 1)
                Exit For
            End If
        End If
    Next i

End Sub

Dynamic ranges or tables might throw a wrench into it, but hopefully it's a start.


问:
Provisioning AWS Ubuntu using Ansible errors out with permission errors when gathering facts or installing apps regardless of become escalations
When provisioning an AWS instance running Ubuntu 20.04.3 LTS (GNU/Linux 5.11.0-1028-aws x86_64) provisioning stops at the following tasks:

TASK [Gathering Facts] task when become:true is set in the playbook. The following error message is displayed: Missing sudo password

apt: update_cache=yes task when become: true is set in the playbook and gather_facts: false. The following error message is displayed: Missing sudo password

apt: update_cache=yes task when become: true is not set in the playbook. The following error message is displayed: Failed to lock apt for exclusive operation: Failed to lock directory /var/lib/apt/lists/: E:Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)"

TASK [geerlingguy.pip : Ensure Pip is installed.]  task when become: true is not set in the playbook. The following error messages are displayed:
"E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)",
"E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root?"

I suspect this is happening because this is a AWS modified OS, being GNU/Linux 5.11.0-1028-aws. I can ssh into the instance and run sudo apt update and sudo apt install python3-pip and it works without a password because I have ALL=(ALL:ALL) NOPASSWD:ALL set in sudoers for my ssh user. However, when I run sudo apt update and sudo apt install python3-pip with become: true is not set in the playbook, the above error messages are displayed.

I have run all versions of these and re-ran the playbook.

sudo rm /var/lib/apt/lists/lock
sudo rm /var/cache/apt/archives/lock
sudo rm /var/lib/dpkg/lock
sudo rm /var/lib/apt/lists/lock
sudo rm /var/lib/dpkg/lock-frontend
```
<p>I found this stack overflow answer Ansible playbook fails to lock apt and added those tasks but it would fail at this step <code>raw: apt-get -y purge unattended-upgrades</code>.
<code>unattended-upgrades</code> seems to be disabled because I no longer see this message when I login to the instance.
<code>2 updates could not be installed automatically. For more details, see /var/log/unattended-upgrades/unattended-upgrades.log</code></p>
<p>This is the first time I have had an issue with running these very basic ansible tasks. Given that AWS has its own ansible modules, I am sure I am doing something wrong or missing something obvious. I've had a hard time finding a solution to this problem because Googling has been ineffective. There are too many irrelevant results due to the popularity of the AWS ansible modules. I'm not trying to create or modify any AWS instances. I'm just trying to provision one.</p>
<p>I'm hoping one of the many AWS or Ansible experts here can help me out.</p>
<p>Here's the code: https://github.com/kahunacoder/ansible-wikijs</p>
<p>Here's an example</p>
<p>playbook.yml:</p>
<pre class="lang-yaml prettyprint-override"><code>- hosts: all
  gather_facts: true
  become: true
  vars:
    ansible_python_interpreter: /usr/bin/python3
    pip_package: python3-pip
    pip_install_packages:
      - name: docker
  tasks:
    - name: Update apt
      apt: update_cache=yes
  roles:
    - geerlingguy.pip
</code>```

hosts.yml:

ansible_host: wiki.mydomain.com # dev machine
ansible_ssh_user: wiki
ansible_ssh_private_key_file: "~/.ssh/id_rsa"
ansible_connection: ssh
ansible_python_interpreter: /usr/bin/python3
```
<p>sudoers:</p>
<pre class="lang-sh prettyprint-override"><code>wiki ALL=(ALL:ALL) NOPASSWD:ALL
</code>```

答:
The fix was two lines of code to my ansible.cfg file.

```<code>[sudo_become_plugin]
flags = -H -S
</code>```

I found the answer here: Ansible: sudo without password

Body:
When provisioning an AWS instance running Ubuntu 20.04.3 LTS (GNU/Linux 5.11.0-1028-aws x86_64) provisioning stops at the following tasks:

TASK [Gathering Facts] task when become:true is set in the playbook. The following error message is displayed: Missing sudo password

apt: update_cache=yes task when become: true is set in the playbook and gather_facts: false. The following error message is displayed: Missing sudo password

apt: update_cache=yes task when become: true is not set in the playbook. The following error message is displayed: Failed to lock apt for exclusive operation: Failed to lock directory /var/lib/apt/lists/: E:Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)"

TASK [geerlingguy.pip : Ensure Pip is installed.]  task when become: true is not set in the playbook. The following error messages are displayed:
"E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)",
"E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root?"

I suspect this is happening because this is a AWS modified OS, being GNU/Linux 5.11.0-1028-aws. I can ssh into the instance and run sudo apt update and sudo apt install python3-pip and it works without a password because I have ALL=(ALL:ALL) NOPASSWD:ALL set in sudoers for my ssh user. However, when I run sudo apt update and sudo apt install python3-pip with become: true is not set in the playbook, the above error messages are displayed.

I have run all versions of these and re-ran the playbook.

sudo rm /var/lib/apt/lists/lock
sudo rm /var/cache/apt/archives/lock
sudo rm /var/lib/dpkg/lock
sudo rm /var/lib/apt/lists/lock
sudo rm /var/lib/dpkg/lock-frontend

I found this stack overflow answer Ansible playbook fails to lock apt and added those tasks but it would fail at this step raw: apt-get -y purge unattended-upgrades.
unattended-upgrades seems to be disabled because I no longer see this message when I login to the instance.
2 updates could not be installed automatically. For more details, see /var/log/unattended-upgrades/unattended-upgrades.log

This is the first time I have had an issue with running these very basic ansible tasks. Given that AWS has its own ansible modules, I am sure I am doing something wrong or missing something obvious. I've had a hard time finding a solution to this problem because Googling has been ineffective. There are too many irrelevant results due to the popularity of the AWS ansible modules. I'm not trying to create or modify any AWS instances. I'm just trying to provision one.

I'm hoping one of the many AWS or Ansible experts here can help me out.

Here's the code: https://github.com/kahunacoder/ansible-wikijs

Here's an example

playbook.yml:

- hosts: all
  gather_facts: true
  become: true
  vars:
    ansible_python_interpreter: /usr/bin/python3
    pip_package: python3-pip
    pip_install_packages:
      - name: docker
  tasks:
    - name: Update apt
      apt: update_cache=yes
  roles:
    - geerlingguy.pip

hosts.yml:

ansible_host: wiki.mydomain.com # dev machine
ansible_ssh_user: wiki
ansible_ssh_private_key_file: "~/.ssh/id_rsa"
ansible_connection: ssh
ansible_python_interpreter: /usr/bin/python3

sudoers:

wiki ALL=(ALL:ALL) NOPASSWD:ALL

Body:
The fix was two lines of code to my ansible.cfg file.

[sudo_become_plugin]
flags = -H -S

I found the answer here: Ansible: sudo without password


问:
WPF: ListBox unselecting

When the user clicks on a item in my single-select ListBox, the item is selected.

When the user clicks on a item the second time, the item is not unselected unless they are holding the control key.

What is the recommended way to change #2 to not require the control key?

答:
I found that Ctrl-CLick is a non-intuitive way to unselect a listbox item and fixed the behavior by simply adding a MouseDown and KeyDown event in my XAML (.net Core 5) and creating event handlers like this:

```<code>private void lboxScanList_MouseDown(object sender, MouseButtonEventArgs e) {
    // user clicked on a non-item - deselect all
    lboxScanList.UnselectAll();
}

private void lboxScanList_KeyDown(object sender, KeyEventArgs e) {
    if (e.Key == Key.Escape) {
        lboxScanList.UnselectAll();
    }
}
</code>```

This gives you unselection with Esc or a mouse click off of any item but on the listbox which I feel is much more intuitive.

Title: WPF: ListBox unselecting

Body:
I found that Ctrl-CLick is a non-intuitive way to unselect a listbox item and fixed the behavior by simply adding a MouseDown and KeyDown event in my XAML (.net Core 5) and creating event handlers like this:

private void lboxScanList_MouseDown(object sender, MouseButtonEventArgs e) {
    // user clicked on a non-item - deselect all
    lboxScanList.UnselectAll();
}

private void lboxScanList_KeyDown(object sender, KeyEventArgs e) {
    if (e.Key == Key.Escape) {
        lboxScanList.UnselectAll();
    }
}

This gives you unselection with Esc or a mouse click off of any item but on the listbox which I feel is much more intuitive.