问:
TCPDF Laravel Email Attachments
TCPDF doesn't seem to be working well with either $dest option ("E" or "S") for sending PDF attachments in Laravel 5.1. Files are always corrupt with an error upon launching Acrobat Reader (error message: ... for example, it was sent as an email attachment and wasn't correctly decoded). Decoding seems ok when I try another PDF generator like DOMPDF.

```<code>$pdf = new \TCPDF('P', 'in', 'LETTER', true, 'UTF-8', false);
$pdf->WriteHTML(view('emails.receipt_pdf', $receipt_data));
$attachment = $pdf->Output('Receipt - '.date("M-d-Y").'.pdf','E');

Mail::queue('emails.receipt_email', $receipt_data, function($message) use ($email, $attachment)
{
  $message->from('no-reply@website.com')
    ->to($email)
    ->subject('Receipt')
    ->attachData($attachment, 'Receipt.pdf');
});
</code>```

答:
Just use "S" option while generating pdf. Email-related things will be done by Laravel.

Update

```<code>$attachment = $pdf->Output('Receipt - '.date("M-d-Y").'.pdf','E');
</code>```

to

```<code>$attachment = $pdf->Output('Receipt - '.date("M-d-Y").'.pdf','S');
</code>```

Additionally, if you are using queue() instead of send(), it will fail because of the attachment. To queue, write a job and send with the job queue.

Title: TCPDF Laravel Email Attachments

Body:
TCPDF doesn't seem to be working well with either $dest option ("E" or "S") for sending PDF attachments in Laravel 5.1. Files are always corrupt with an error upon launching Acrobat Reader (error message: ... for example, it was sent as an email attachment and wasn't correctly decoded). Decoding seems ok when I try another PDF generator like DOMPDF.

$pdf = new \TCPDF('P', 'in', 'LETTER', true, 'UTF-8', false);
$pdf->WriteHTML(view('emails.receipt_pdf', $receipt_data));
$attachment = $pdf->Output('Receipt - '.date("M-d-Y").'.pdf','E');

Mail::queue('emails.receipt_email', $receipt_data, function($message) use ($email, $attachment)
{
  $message->from('no-reply@website.com')
    ->to($email)
    ->subject('Receipt')
    ->attachData($attachment, 'Receipt.pdf');
});

Body:
Just use "S" option while generating pdf. Email-related things will be done by Laravel.

Update

$attachment = $pdf->Output('Receipt - '.date("M-d-Y").'.pdf','E');

to

$attachment = $pdf->Output('Receipt - '.date("M-d-Y").'.pdf','S');

Additionally, if you are using queue() instead of send(), it will fail because of the attachment. To queue, write a job and send with the job queue.


来源: stackexchange

问:
How to create expiration date logic for a link shared via email
I am sending a transaction ID as a link via email, using this link anyone can search for the details of transaction happened in my system. I would like to enforce expiry time for the link, say for 1 month link should work and post 1 month, link should expire.

I am using nodejs for implementing my software. I would like to send only transaction ID as the parameter for creating the link.

I planned to combine Transaction ID and expiry_timestamp and encode/encrypt and send the encoded/encrypted data as the parameter in the URL. Later when link is clicked and request is received to server, I should be able to retrieve the expiry_timestamp and compare it with current data and decide to proceed or no. Here if Iam sending timestamp in plaintext, user may change the timestamp and request, so I am planning to encode or encrypt it.

Please suggest some cryptographic techniques for implementing this.
Thanks in advance.

答:
You can do this by following way.

Create another column name something like token

Store expiry date and time on another column as you are already doing this.

Pass token as a query string that has been stored in DB rather than the timestamp.

when user click on the link you can check either validate or not using token (query string)

You can use this( https://www.npmjs.com/package/rand-token)  package to generate tokens.

ContentLicense: CC BY-SA 4.0


问:
Error overriding get method in Django Rest
I am new to Django Rest Framework. In my work I was suggested to work in an existing project and learn the Rest Framework on the fly. So I was writing an api to display the vehicle-list with both the get_queryset method and the get method. I could make the get_queryset() method work, but the get() method isn't working (I'm assuming some kind of syntax error).

The working code :

```<code>class VehicleList(ListAPIView):
    permission_classes = (AllowAny,)
    serializer_class = FleetVehicleSerializer

    def get_queryset(self):
        domain = self.request.META.get('HTTP_DOMAIN', None)
        if domain is None:
            raise Exception("Domain is missing in request header")
        qs = FleetVehicle.objects.using(domain).all()
        return qs
</code>```

Not working code:

```<code>class VehicleList(ListAPIView):
    permission_classes = (AllowAny,)
    serializer_class = FleetVehicleSerializer

  def get(self, request):
        domain = self.request.META.get('HTTP_DOMAIN', None)
        if domain is None:
            raise Exception("Domain is missing in request header")
        vehicles = FleetVehicle.objects.using(domain).all()
        return Response({'a': vehicles},status=status.HTTP_200_OK, content_type = 'application/json' )
</code>```

The output is supposed to be a json, I am testing the api in postman. Can anyone help me with the possible syntax error?

答:
```<code>def get(self, request):
        domain = self.request.META.get('HTTP_DOMAIN', None)
        if domain is None:
            raise Exception("Domain is missing in request header")
        vehicles = FleetVehicle.objects.using(domain).all()
        data = FleetVehicleSerializer(vehicles,many=True)
        return Response({'a': data.data},status=status.HTTP_200_OK, content_type = 'application/json' )
</code>```

well according to the error you were getting in the get method I have given the solution.

Body:
I am new to Django Rest Framework. In my work I was suggested to work in an existing project and learn the Rest Framework on the fly. So I was writing an api to display the vehicle-list with both the get_queryset method and the get method. I could make the get_queryset() method work, but the get() method isn't working (I'm assuming some kind of syntax error).

The working code :

class VehicleList(ListAPIView):
    permission_classes = (AllowAny,)
    serializer_class = FleetVehicleSerializer

    def get_queryset(self):
        domain = self.request.META.get('HTTP_DOMAIN', None)
        if domain is None:
            raise Exception("Domain is missing in request header")
        qs = FleetVehicle.objects.using(domain).all()
        return qs

Not working code:

class VehicleList(ListAPIView):
    permission_classes = (AllowAny,)
    serializer_class = FleetVehicleSerializer

  def get(self, request):
        domain = self.request.META.get('HTTP_DOMAIN', None)
        if domain is None:
            raise Exception("Domain is missing in request header")
        vehicles = FleetVehicle.objects.using(domain).all()
        return Response({'a': vehicles},status=status.HTTP_200_OK, content_type = 'application/json' )

The output is supposed to be a json, I am testing the api in postman. Can anyone help me with the possible syntax error?

Body:
def get(self, request):
        domain = self.request.META.get('HTTP_DOMAIN', None)
        if domain is None:
            raise Exception("Domain is missing in request header")
        vehicles = FleetVehicle.objects.using(domain).all()
        data = FleetVehicleSerializer(vehicles,many=True)
        return Response({'a': data.data},status=status.HTTP_200_OK, content_type = 'application/json' )

well according to the error you were getting in the get method I have given the solution.


问:
Scrapy Item not return unicode when append to dataframe?
I'm using Scrapy Pipeline to get all the items to a dataframe.

The code runs well but the unicode text is not showing correctly on the output of the dataframe.

However the result in csv file exported by feed_exporter is still fine. Could you guys please advise?

Here are the code

#In pipelines.py
class CrawlerPipeline(object):
    def open_spider(self, spider):
        settings = get_project_settings()
        self.df = pd.DataFrame(columns=settings.get('FEED_EXPORT_FIELDS'))
        print('SUCCESS CREATE DATAFRAME', self.df.columns)

    def process_item(self, item, spider):
        self.df = self.df.append([dict(item)]) #I think it has problem in this line of code
        print('SUCCESS APPEND RECORD TO DATAFRAME, DF LEN:', len(self.df))
        return item

#In spider.py
def parse_detail_page(self, response):
    ads = CrawlerItem()
    ads['body'] = (response.css('#sgg > div > div>  div.car_des > div::text').extract_first() or "").encode('utf-8').strip()
    yield(ads)
```

This is the incorrect output of the scraped text:

b'Salon \xc3\xb4 t\xc3\xb4 \xc3\x81nh L\xc3\xbd b\xc3\xa1n xe Kia Carens s\xe1\xba\xa3n xu\xe1\xba\xa5t 2015 m\xc3\xa0u c\xc3\xa1t'

答:
The incorrect output you mention is the UTF-8-encoded bytes string corresponding to the desired text string.

You have two options:

Remove .encode('utf-8') from your code.

Add .decode('utf-8') when reading the string from the dataframe.

Body:
I'm using Scrapy Pipeline to get all the items to a dataframe.

The code runs well but the unicode text is not showing correctly on the output of the dataframe.

However the result in csv file exported by feed_exporter is still fine. Could you guys please advise?

Here are the code

#In pipelines.py
class CrawlerPipeline(object):
    def open_spider(self, spider):
        settings = get_project_settings()
        self.df = pd.DataFrame(columns=settings.get('FEED_EXPORT_FIELDS'))
        print('SUCCESS CREATE DATAFRAME', self.df.columns)

    def process_item(self, item, spider):
        self.df = self.df.append([dict(item)]) #I think it has problem in this line of code
        print('SUCCESS APPEND RECORD TO DATAFRAME, DF LEN:', len(self.df))
        return item

#In spider.py
def parse_detail_page(self, response):
    ads = CrawlerItem()
    ads['body'] = (response.css('#sgg > div > div>  div.car_des > div::text').extract_first() or "").encode('utf-8').strip()
    yield(ads)

This is the incorrect output of the scraped text:

b'Salon \xc3\xb4 t\xc3\xb4 \xc3\x81nh L\xc3\xbd b\xc3\xa1n xe Kia Carens s\xe1\xba\xa3n xu\xe1\xba\xa5t 2015 m\xc3\xa0u c\xc3\xa1t'


问:
How to fail dependent tests if one test is failed in XCUITest?
I want to force fail my test if one of my dependent test fails in XCUITest

Ex: func testA() {
}

func testB()

if my func testA() fails then func testB() should also fail

答:
XCUITest does not support dependencies between test cases. We can use the below workaround to overcome that.</p>

```<code>class TestClass: XCTestCase {
    static var isTestAPassed = true

    override func setUp() {
    }

    override func tearDown() {
        if testRun?.test.name == "testA" {
            TestClass.isTestAPassed = testRun?.hasSucceeded
        }
    }

    func testA() {
    }

    func testB() {
        XCTAssertTrue(TestClass.isTestAPassed)
    }
}
</code>```

Body:
XCUITest does not support dependencies between test cases. We can use the below workaround to overcome that.

class TestClass: XCTestCase {
    static var isTestAPassed = true

    override func setUp() {
    }

    override func tearDown() {
        if testRun?.test.name == "testA" {
            TestClass.isTestAPassed = testRun?.hasSucceeded
        }
    }

    func testA() {
    }

    func testB() {
        XCTAssertTrue(TestClass.isTestAPassed)
    }
}


问:
How to determine the URL that a local Git repository was originally cloned from
I pulled a project with several forks on GitHub, but forgot which fork it was. How do I determine which fork I pulled?</p>

答:
```<code>git config --list
</code>```

This command will give all information related to your repository.

Body:
git config --list

This command will give all information related to your repository.


问:
How to find a number in a string using JavaScript?
Suppose I have a string like - "you can enter maximum 500 choices".
I need to extract 500 from the string.

The main problem is the String may vary like "you can enter maximum 12500 choices".
So how to get the integer part?

答:
You can also try this :

var string = "border-radius:10px 20px 30px 40px";
var numbers = string.match(/\d+/g).map(Number);
console.log(numbers)```

ContentLicense: CC BY-SA 3.0


问:
jQuery - black & white image to color image (hover)
I have black and white image contained in a css:

http://cl.ly/3G0E0g1e2G2h3k3U3F2O

In the same file I put in color image:

http://cl.ly/1l2A2F0o1j3E1z2s223V

Now I wants to when you hover the mouse on this image has changed from black and white to color...

I put the function in jQuery:

```<code>    $("ul li").mouseover(function() {

        $(this).find("span.thumb").hover().css({
            'background-position': 'center bottom'
        }).stop().fadeTo(400, 0).show();

    });

    $("ul li").mouseout(function() {

        $(this).find("span.thumb").hover().css({
            'background-position': 'center top'
        }).stop().fadeTo(400, 1).show();

    });
</code>```

HTML:

```<code><span class="thumb"></span>
</code>```

CSS:

```<code>ul li span.thumb {background:url(image.png) no-repeat}
</code>```

Q: How I can do it differently? (that when you hover the mouse on the image did not disappear).

答:
Hi looks to me that you've over complicated it slightly, try this:

HTML

```<code><div>
  <img src="http://ajthomas.co.uk/flower-col.png" alt="" />
</div>
</code>```

JQUERY

```<code>$(document).ready(function() {
    $('div').mouseover(function(){
        $('img').fadeIn('slow');
    });
    $('img').mouseout(function(){
        $('img').fadeOut('slow');
    });
});
</code>```

CSS

```<code>div{width:300px;
    height:300px;
    background-image:url(http://ajthomas.co.uk/flower-gs.png)}

img{display:none;}
</code>```

I've coded it up for you too on JSFiddle

Body:
I have black and white image contained in a css:

http://cl.ly/3G0E0g1e2G2h3k3U3F2O

In the same file I put in color image:

http://cl.ly/1l2A2F0o1j3E1z2s223V

Now I wants to when you hover the mouse on this image has changed from black and white to color...

I put the function in jQuery:

    $("ul li").mouseover(function() {

        $(this).find("span.thumb").hover().css({
            'background-position': 'center bottom'
        }).stop().fadeTo(400, 0).show();

    });

    $("ul li").mouseout(function() {

        $(this).find("span.thumb").hover().css({
            'background-position': 'center top'
        }).stop().fadeTo(400, 1).show();

    });

HTML:

CSS:

ul li span.thumb {background:url(image.png) no-repeat}

Q: How I can do it differently? (that when you hover the mouse on the image did not disappear).

Body:
Hi looks to me that you've over complicated it slightly, try this:

HTML

<div>
  <img src="http://ajthomas.co.uk/flower-col.png" alt="" />
</div>

JQUERY

$(document).ready(function() {
    $('div').mouseover(function(){
        $('img').fadeIn('slow');
    });
    $('img').mouseout(function(){
        $('img').fadeOut('slow');
    });
});

CSS

div{width:300px;
    height:300px;
    background-image:url(http://ajthomas.co.uk/flower-gs.png)}

img{display:none;}

I've coded it up for you too on JSFiddle


问:
How to create a list corresponding to each number from 2 to 100 that will contain numbers from an array that are its multiples?
Recently i came across this question and could not figure out an optimal solution for it.

Suppose we have an array of numbers of any range like 9,-3,0,4,11,2,-8,.....
We need to print numbers from 2 to 100 and corresponding to each of them we need to print a list of numbers from the array such that the number in the array is divisible by it.
Example:
Using the existing array in example,
2 -> 4,2,-8,...
3 -> -3,9,...
4 -> 4,-8,...
and like this upto 100.

I tried working out the solution by dividing each number of the array by numbers from 2 to 100 and subsequently creating the list corresponding to each of them. But that didn't seem to me an optimal solution.

I even tried grouping numbers like a number which is divisible by 8 will be divisible by 2 and 4 so we don't need to divide it again. This would reduce some operations and complexity but would in turn, require creating such groups.

Please can anyone help finding an optimal solution for this problem by reducing the need to divide each number by 2 to 100.

答:
If you keep each sublist as you go, you can use previous results to limit the length of the list:

```<code>    List<List<Integer>> lists = new ArrayList<>();
    lists.add(list); // at 0: never used
    lists.add(list);
    for (int i = 2; i <= 100; ++i) {
        for (int j = i/2; j > 0; --j) {
            if (i%j == 0) {
                lists.add(extractMultiples(lists.get(j), i));
                break;
            }
        }
    }
    for (int i = 2; i <= 100; ++i) {
        System.out.println(i + ": " + lists.get(i));
    }
</code>```

with method extractMultiples:

```<code>public static List<Integer> extractMultiples(List<Integer> list, int n) {
    List<Integer> result = new ArrayList<>();
    for (int x: list) {
        if (x%n == 0) {
            result.add(x);
        }
    }
    return result;
}
</code>```

Body:
If you keep each sublist as you go, you can use previous results to limit the length of the list:

    List<List<Integer>> lists = new ArrayList<>();
    lists.add(list); // at 0: never used
    lists.add(list);
    for (int i = 2; i <= 100; ++i) {
        for (int j = i/2; j > 0; --j) {
            if (i%j == 0) {
                lists.add(extractMultiples(lists.get(j), i));
                break;
            }
        }
    }
    for (int i = 2; i <= 100; ++i) {
        System.out.println(i + ": " + lists.get(i));
    }

with method extractMultiples:

public static List<Integer> extractMultiples(List<Integer> list, int n) {
    List<Integer> result = new ArrayList<>();
    for (int x: list) {
        if (x%n == 0) {
            result.add(x);
        }
    }
    return result;
}


问:
How to do conditional processing in a bulk collect loop?
we have Oracle 11G and i'm trying to move data from one table to another using bulk collect. Problem is when I tried to evaluate if one field from origin is empty my package got invalidated. What I have:

Declaration:

```<code>CREATE OR REPLACE PACKAGE MYSCHEMA.MYPKG AS
CURSOR CUR_MYDATA IS
        SELECT
            o.name,
            o.last_name,
            o.id,
            o.socnum
        FROM
            origin o
        WHERE
            1=1
            AND o.name like upper ('a%');

        TYPE t_name IS TABLE OF origin.name%TYPE;
        TYPE t_lastname IS TABLE OF origin.last_name%TYPE;
        TYPE t_id IS TABLE OF origin.id%TYPE;
        TYPE t_socnum IS TABLE OF origin.socnum%TYPE;

        l_name t_name;
        l_lastname t_lastname;
        l_id t_id;
        l_socnum t_socnum;

PROCEDURE MYPROCEDURE;

END MYPKG;
</code>```

Body:

```<code>CREATE OR REPLACE PACKAGE BODY MYSCHEMA.MYPKG AS

    PROCEDURE MYPROCEDURE IS

    BEGIN
        OPEN CUR_MYDATA;
        LOOP
        FETCH CUR_MYDATA BULK COLLECT INTO l_name,l_lastname,l_id,l_socnum;
            forall i IN 1 .. l_name.COUNT
            IF ( l_socnum(i) IS NULL)
                THEN (select oo.socnum from other_origin where oo.id=l_id(i))
            END IF;
                INSERT INTO destiny (
                    d_name,
                    d_lastname,
                    d_id,
                    d_socnum)
                VALUES (
                    l_name(i),
                    l_lastname(i),
                    l_id(i),
                    l_socnum(i),
            EXIT WHEN l_name.count = 0;
        END LOOP;
    END MYPROCEDURE;

END MYPKG;
</code>```

but when I check body status it is INVALID

any thoughs?

答:
FORALL is not a loop construct: it cannot be split from its DML statement.

when I tried to evaluate if one field from origin is empty

You need to loop round the populated collection and fix that before executing the FORALL ... INSERT.

```<code>CREATE OR REPLACE PACKAGE BODY MYSCHEMA.MYPKG AS

    PROCEDURE MYPROCEDURE IS

    BEGIN
        OPEN CUR_MYDATA;
        LOOP
            FETCH CUR_MYDATA BULK COLLECT INTO l_name,l_lastname,l_id,l_socnum;
            EXIT WHEN l_name.count = 0;

            for idx in 1 .. l_socnum.count() loop
                IF l_socnum(idx) IS NULL THEN
                      select oo.socnum
                      into l_socnum(idx)
                      from other_origin
                      where oo.id = l_id(idx);
                END IF;

            end loop;

            forall i IN 1 .. l_name.COUNT
                INSERT INTO destiny (
                    d_name,
                    d_lastname,
                    d_id,
                    d_socnum)
                VALUES (
                    l_name(i),
                    l_lastname(i),
                    l_id(i),
                    l_socnum(i));
        END LOOP;
    END MYPROCEDURE;

END MYPKG;
</code>```

Other notes.

Check whether the fetch returns any records immediately after executing the fetch. Otherwise your code will attempt to execute code over an empty collection, which will fail.

You should define a collection based on the target table %rowtype: this is simpler than defining and handling multiple collections based on columns.

Also, your real code may be way more complicated than what you posted here, but if you have a large amount of data to shift there is a lot of performance gain in using pure SQL rather than a procedure:

```<code>INSERT INTO DESTINY (
            D_NAME,
            D_LASTNAME,
            D_ID,
            D_SOCNUM
        )
SELECT
        o.name,
        o.last_name,
        o.id,
        coalesce(o.socnum, oo.socnum)
FROM
    origin o
left outer join other_origin oo
   on oo.id = o.id
WHERE
    1=1
    AND o.name like upper ('a%');
</code>```

Body:
we have Oracle 11G and i'm trying to move data from one table to another using bulk collect. Problem is when I tried to evaluate if one field from origin is empty my package got invalidated. What I have:

Declaration:

CREATE OR REPLACE PACKAGE MYSCHEMA.MYPKG AS
CURSOR CUR_MYDATA IS
        SELECT
            o.name,
            o.last_name,
            o.id,
            o.socnum
        FROM
            origin o
        WHERE
            1=1
            AND o.name like upper ('a%');

        TYPE t_name IS TABLE OF origin.name%TYPE;
        TYPE t_lastname IS TABLE OF origin.last_name%TYPE;
        TYPE t_id IS TABLE OF origin.id%TYPE;
        TYPE t_socnum IS TABLE OF origin.socnum%TYPE;

        l_name t_name;
        l_lastname t_lastname;
        l_id t_id;
        l_socnum t_socnum;

PROCEDURE MYPROCEDURE;

END MYPKG;

Body:

CREATE OR REPLACE PACKAGE BODY MYSCHEMA.MYPKG AS

    PROCEDURE MYPROCEDURE IS

    BEGIN
        OPEN CUR_MYDATA;
        LOOP
        FETCH CUR_MYDATA BULK COLLECT INTO l_name,l_lastname,l_id,l_socnum;
            forall i IN 1 .. l_name.COUNT
            IF ( l_socnum(i) IS NULL)
                THEN (select oo.socnum from other_origin where oo.id=l_id(i))
            END IF;
                INSERT INTO destiny (
                    d_name,
                    d_lastname,
                    d_id,
                    d_socnum)
                VALUES (
                    l_name(i),
                    l_lastname(i),
                    l_id(i),
                    l_socnum(i),
            EXIT WHEN l_name.count = 0;
        END LOOP;
    END MYPROCEDURE;

END MYPKG;

but when I check body status it is INVALID

any thoughs?

Body:
FORALL is not a loop construct: it cannot be split from its DML statement.

when I tried to evaluate if one field from origin is empty

You need to loop round the populated collection and fix that before executing the FORALL ... INSERT.

CREATE OR REPLACE PACKAGE BODY MYSCHEMA.MYPKG AS

    PROCEDURE MYPROCEDURE IS

    BEGIN
        OPEN CUR_MYDATA;
        LOOP
            FETCH CUR_MYDATA BULK COLLECT INTO l_name,l_lastname,l_id,l_socnum;
            EXIT WHEN l_name.count = 0;

            for idx in 1 .. l_socnum.count() loop
                IF l_socnum(idx) IS NULL THEN
                      select oo.socnum
                      into l_socnum(idx)
                      from other_origin
                      where oo.id = l_id(idx);
                END IF;

            end loop;

            forall i IN 1 .. l_name.COUNT
                INSERT INTO destiny (
                    d_name,
                    d_lastname,
                    d_id,
                    d_socnum)
                VALUES (
                    l_name(i),
                    l_lastname(i),
                    l_id(i),
                    l_socnum(i));
        END LOOP;
    END MYPROCEDURE;

END MYPKG;

Other notes.

Check whether the fetch returns any records immediately after executing the fetch. Otherwise your code will attempt to execute code over an empty collection, which will fail.

You should define a collection based on the target table %rowtype: this is simpler than defining and handling multiple collections based on columns.

Also, your real code may be way more complicated than what you posted here, but if you have a large amount of data to shift there is a lot of performance gain in using pure SQL rather than a procedure:

INSERT INTO DESTINY (
            D_NAME,
            D_LASTNAME,
            D_ID,
            D_SOCNUM
        )
SELECT
        o.name,
        o.last_name,
        o.id,
        coalesce(o.socnum, oo.socnum)
FROM
    origin o
left outer join other_origin oo
   on oo.id = o.id
WHERE
    1=1
    AND o.name like upper ('a%');


问:
Install and export INTERFACE only library, CMake
new CMake user here.

I've made a simple header only library, with the following CMake file:

```<code>cmake_minimum_required(VERSION 3.7)

project(mylib VERSION 0.1 LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 14)
#add_compile_options(-Wa -aslh)

# Define the library target
add_library(mylib INTERFACE)
target_include_directories(mylib INTERFACE include/)

add_executable(mytest test/basic_checks.cpp)
target_link_libraries(mytest mylib)
</code>```

From http://foonathan.net/blog/2016/03/03/cmake-install.html

I've learned there are several steps to getting a library installed and to have it useable from another CMake project. First it must be "installed" and then it must be "exported". Then there's find_package, but I'll cross that bridge after I've gotten over the first two steps.

So following the example, I figure that I could add the following to the bottom of my CMake file:

```<code># Install the header file.
install(FILES include/mylib.hpp DESTINATION "include/mylib-${PROJECT_VERSION}")
</code>```

But the guide talks about also using install on TARGETS, and then adding EXPORT to the target install commands.

How much of this applies to a header only library in which I have no other compiled code of files other than the header?

How do I apply the steps described in : http://foonathan.net/blog/2016/03/03/cmake-install.html
To an INTERFACE only library? The lack of .cpp files in my project is leading me to question which instructions apply and don't apply.

答:
Just a small addition to https://stackoverflow.com/a/49143782/2119944

Probably cmake/mylibConfig.cmake.in should look like this:

```<code>@PACKAGE_INIT@

include("${CMAKE_INSTALL_PREFIX}/lib/cmake/mylib/mylibTargets.cmake")
check_required_components("@PROJECT_NAME@")
</code>```

Otherwise it will point to local project dir.

Body:
new CMake user here.

I've made a simple header only library, with the following CMake file:

cmake_minimum_required(VERSION 3.7)

project(mylib VERSION 0.1 LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 14)
#add_compile_options(-Wa -aslh)

# Define the library target
add_library(mylib INTERFACE)
target_include_directories(mylib INTERFACE include/)

add_executable(mytest test/basic_checks.cpp)
target_link_libraries(mytest mylib)

From http://foonathan.net/blog/2016/03/03/cmake-install.html

I've learned there are several steps to getting a library installed and to have it useable from another CMake project. First it must be "installed" and then it must be "exported". Then there's find_package, but I'll cross that bridge after I've gotten over the first two steps.

So following the example, I figure that I could add the following to the bottom of my CMake file:

# Install the header file.
install(FILES include/mylib.hpp DESTINATION "include/mylib-${PROJECT_VERSION}")

But the guide talks about also using install on TARGETS, and then adding EXPORT to the target install commands.

How much of this applies to a header only library in which I have no other compiled code of files other than the header?

How do I apply the steps described in : http://foonathan.net/blog/2016/03/03/cmake-install.html
To an INTERFACE only library? The lack of .cpp files in my project is leading me to question which instructions apply and don't apply.

Body:
Just a small addition to https://stackoverflow.com/a/49143782/2119944

Probably cmake/mylibConfig.cmake.in should look like this:

@PACKAGE_INIT@

include("${CMAKE_INSTALL_PREFIX}/lib/cmake/mylib/mylibTargets.cmake")
check_required_components("@PROJECT_NAME@")

Otherwise it will point to local project dir.


问:
Autofac registration with multiple assembies and differing EntityConnections
We have two Assemblies that contain their own Entity-Framework EDMX & repositoriy objects. These are registered using Autofac in an ASP.NET webapplication.

These Assemblies are very similar of architecture (but differing EDMX) we have found that the last EntityConnection being registered is the EntityConnection that is being used in both Assemblies. We need to limit the usage of an EntityConnection to only be used by Types of an assembly or namespace.

```<code>var assembly = typeof(Activity).Assembly;
builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces();
builder.Register(reg => new EntityConnection(ConnectionString));

var assembly = typeof(User).Assembly;
builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces();
builder.Register(reg => new EntityConnection(ConnectionString));
</code>```

Is there a way to register the EntityConnection and limit the depth of EntityConnection? Limit each EntityConnection to the assembly it belong to?

Here's a pseudocode example of how we want to register EntityConnection for use in only an assembly or namespace.

```<code>builder.Register(reg => new EntityConnection(ConnectionString)).ForNamespace("x");
</code>```

答:
try to solve the problem at an higher level of abstraction. Since you have two separate domains (one containing the Activity entity, and one containing the User entity), it would be convenient to have this explicitly in your application design. For instance, define a factory of some kind per domain:

```<code>public interface IActivityDomainContextFactory
{
    ObjectContext CreateNew();
}

public interface IPeopleDomainContextFactory
{
    ObjectContext CreateNew();
}
</code>```

You can now easily create an implementation for each interface, register them in the Autofac ContainerBuilder and let your services depend on one of those interfaces, instead of depending them on a EntityConnection.

In this case you of course still have a dependency on the Entity Framework itself (see here for how to abstract that away), but this makes your configuration much easier, less fragile, better performing, and your application code more maintainable.

I hope this helps.

Body:
We have two Assemblies that contain their own Entity-Framework EDMX & repositoriy objects. These are registered using Autofac in an ASP.NET webapplication.

These Assemblies are very similar of architecture (but differing EDMX) we have found that the last EntityConnection being registered is the EntityConnection that is being used in both Assemblies. We need to limit the usage of an EntityConnection to only be used by Types of an assembly or namespace.

var assembly = typeof(Activity).Assembly;
builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces();
builder.Register(reg => new EntityConnection(ConnectionString));

var assembly = typeof(User).Assembly;
builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces();
builder.Register(reg => new EntityConnection(ConnectionString));

Is there a way to register the EntityConnection and limit the depth of EntityConnection? Limit each EntityConnection to the assembly it belong to?

Here's a pseudocode example of how we want to register EntityConnection for use in only an assembly or namespace.

builder.Register(reg => new EntityConnection(ConnectionString)).ForNamespace("x");

Body:
try to solve the problem at an higher level of abstraction. Since you have two separate domains (one containing the Activity entity, and one containing the User entity), it would be convenient to have this explicitly in your application design. For instance, define a factory of some kind per domain:

public interface IActivityDomainContextFactory
{
    ObjectContext CreateNew();
}

public interface IPeopleDomainContextFactory
{
    ObjectContext CreateNew();
}

You can now easily create an implementation for each interface, register them in the Autofac ContainerBuilder and let your services depend on one of those interfaces, instead of depending them on a EntityConnection.

In this case you of course still have a dependency on the Entity Framework itself (see here for how to abstract that away), but this makes your configuration much easier, less fragile, better performing, and your application code more maintainable.

I hope this helps.


问:
Create a stored procedure to insert new data into a table
I want to create a stored procedure to insert a new row in a table 'dbo.Terms'

```<code>CREATE PROCEDURE dbo.terms
       @Term_en                      NVARCHAR(50)  = NULL   ,
       @Createdate                   DATETIME      = NULL   ,
       @Writer                       NVARCHAR(50)  = NULL   ,
       @Term_Subdomain               NVARCHAR(50)  = NULL
AS
BEGIN
     SET NOCOUNT ON

     INSERT INTO dbo.terms
          (
            Term_en                     ,
            Createdate                  ,
            Writer                      ,
            Term_Subdomain
          )
     VALUES
          (
            @Term_en    = 'Cat'               ,
            @Createdate   = '2013-12-12'      ,
            @Writer         = 'Fadi'          ,
            @Term_Subdomain = 'English'
          )

END

GO
</code>```

But is shows me an error here ( @Term_en    = 'Cat') incorrect syntax
Any help?

答:
```<code>-- =============================================
-- Author:      xxxx
-- Create date: xx-xx-xxxx
-- Description: Procedure for Inserting Data in table
-- =============================================

CREATE PROCEDURE [dbo].[SP_Emp_Insert]
(
@Empname nvarchar(250)=null,
@Status int=null,
@LoginUserId nvarchar(50)=null,
@Msg nvarchar(MAX)=null OUTPUT
)
AS
BEGIN TRY

    INSERT INTO tbl_Employee
    VALUES
    (
    @Empname ,
    @Status,
    GETDATE(),
    GETDATE(),
    @LoginUserId
    )

    SET @Msg='Table Detail Saved Successfully.'

END TRY
BEGIN CATCH

    SET @Msg=ERROR_MESSAGE()

END CATCH

GO
</code>```

Body:
I want to create a stored procedure to insert a new row in a table 'dbo.Terms'

CREATE PROCEDURE dbo.terms
       @Term_en                      NVARCHAR(50)  = NULL   ,
       @Createdate                   DATETIME      = NULL   ,
       @Writer                       NVARCHAR(50)  = NULL   ,
       @Term_Subdomain               NVARCHAR(50)  = NULL
AS
BEGIN
     SET NOCOUNT ON

     INSERT INTO dbo.terms
          (
            Term_en                     ,
            Createdate                  ,
            Writer                      ,
            Term_Subdomain
          )
     VALUES
          (
            @Term_en    = 'Cat'               ,
            @Createdate   = '2013-12-12'      ,
            @Writer         = 'Fadi'          ,
            @Term_Subdomain = 'English'
          )

END

GO

But is shows me an error here ( @Term_en    = 'Cat') incorrect syntax
Any help?


问:
Display data from observable list in tableview javafx
i have this code

```<code>ObservableList data = FXCollections.observableArrayList();
data.addAll(itemNumber, "Not Verified", "");

mItemNoColumn.setCellValueFactory (value -> SimpleObjectProperty<>(data.get(0)));
mStatusColumn.setCellValueFactory (value -> SimpleObjectProperty<>(data.get(1)));

mTableView.getItems().add(data);

</code>```

Assume that all variables are already declared and initialized.

The output given by that code in the tableview is it is only getting the last value of the ObservableList and not all the data needed.

But when i print the observable list in the console, all the data needed is printed correctly.

The expected output in the tableview should be all the items inside the observable list

答:
The cell value factory is used for each cell in a TableColumn. This means when you explicitly use data (which is just one row of your table) in the factories you have inadvertently tied every cell (i.e. every row) to that one data object. The CellDataFeatures object passed to the factory gives you access to the row's item its trying to grab the value for. Your code should look more like:

```<code>mItemNoColumn.setCellValueFactory(features -> Bindings.valueAt(features.getValue(), 0));
mStatusColumn.setCellValueFactory(features -> Bindings.valueAt(features.getValue(), 1));
</code>```

I used Bindings.valueAt(ObservableList,int) because it will update if you change the value at that index of the ObservableList. However, if you don't need that you can continue wrapping the value in an ObjectProperty.

You don't provide much context so I can't be sure where this code is called, but remember you only need to set the cellValueFactory once.

Body:
i have this code

ObservableList data = FXCollections.observableArrayList();
data.addAll(itemNumber, "Not Verified", "");

mItemNoColumn.setCellValueFactory (value -> SimpleObjectProperty<>(data.get(0)));
mStatusColumn.setCellValueFactory (value -> SimpleObjectProperty<>(data.get(1)));

mTableView.getItems().add(data);

Assume that all variables are already declared and initialized.

The output given by that code in the tableview is it is only getting the last value of the ObservableList and not all the data needed.

But when i print the observable list in the console, all the data needed is printed correctly.

The expected output in the tableview should be all the items inside the observable list

Body:
The cell value factory is used for each cell in a TableColumn. This means when you explicitly use data (which is just one row of your table) in the factories you have inadvertently tied every cell (i.e. every row) to that one data object. The CellDataFeatures object passed to the factory gives you access to the row's item its trying to grab the value for. Your code should look more like:

mItemNoColumn.setCellValueFactory(features -> Bindings.valueAt(features.getValue(), 0));
mStatusColumn.setCellValueFactory(features -> Bindings.valueAt(features.getValue(), 1));

I used Bindings.valueAt(ObservableList,int) because it will update if you change the value at that index of the ObservableList. However, if you don't need that you can continue wrapping the value in an ObjectProperty.

You don't provide much context so I can't be sure where this code is called, but remember you only need to set the cellValueFactory once.


问:
IShellLinkW::GetPath( SLGP_RAWPATH ) does not return the 'raw' target of a lnk file
I noticed that the method IShellLinkW::GetPath returns an empty string if the target of a shortcut points to a special folder, like 'My PC', or a Control Panel applet.

Sample code

```<code>' CLSID_ShellLink from ShlGuid.h
Dim cShellLink As New CShellLink()

' https://msdn.microsoft.com/en-us/library/windows/desktop/ms687223%28v=vs.85%29.aspx
Dim persistFile As IPersistFile = DirectCast(cShellLink, IPersistFile)
persistFile.Load(lnkFilePath, 0)

Dim target As New StringBuilder(260)

' https://learn.microsoft.com/en-us/windows/desktop/api/shobjidl_core/nn-shobjidl_core-ishelllinkw
Dim lnkW As IShellLinkW = DirectCast(cShellLink, IShellLinkW)
lnkW.GetPath(target, target.Capacity, Nothing, IShellLinkGetPathFlags.RawPath)
</code>```

( Sorry, are too many P/Invokes to share here, but you can find them in this repository. )

The code above works correctly to retrieve the target of any .lnk file that points to a file or directory. It can't retrieve a target that points to special item / virtual folders.

My questions are:

Is this by design?. If not, what I'm missing or doing wrong? (maybe are my definitions wrong?). And what I have to do in order to retrieve the special target?. Note that I would like to retrieve the target to display it in a PropertyGrid, and also to create a new target with a clone of the special target.

Please note that the programming language on which I developed this code does not matter, because I'm firstly asking for orientation, and also I accept any solution written in C#.

答:
As mentioned in the comments box of the main post, in order to retrieve the raw target of a shell link that points to a special, non-file system path (eg. 'My PC'), first we need to retrieve the PIDL by calling IShellLinkW::GetIDList().

Next, we pass that (absolute)PIDL to SHGetNameFromIDList with the flag SIGDN_DESKTOPABSOLUTEPARSING, and finally this will return a CLSID string that we can specify for the target of a .lnk file with IShellLinkW::SetPath(). It works as expected.

Note that I'm not sure if there could exist special scenarios (rare targets of a lnk file) on which this could not work as expected. I didn't found that error case.

And if needed, the normal display name can be obtained with the flag SIGDN_NORMALDISPLAY, or also by calling the SHGetFileInfo function as mentioned too in the comments box of the main post.

Credits for the users that suggested me the PIDL retrieval and its usage, because I was not sure about what to investigate in order to solve this problem.

I also will give credits to Vanara open-source library, that helped me to find the right P/Invokes of every SH* function in their source-code, specially the signature for SHGetNameFromIDList.

Body:
I noticed that the method IShellLinkW::GetPath returns an empty string if the target of a shortcut points to a special folder, like 'My PC', or a Control Panel applet.

Sample code

' CLSID_ShellLink from ShlGuid.h
Dim cShellLink As New CShellLink()

' https://msdn.microsoft.com/en-us/library/windows/desktop/ms687223%28v=vs.85%29.aspx
Dim persistFile As IPersistFile = DirectCast(cShellLink, IPersistFile)
persistFile.Load(lnkFilePath, 0)

Dim target As New StringBuilder(260)

' https://learn.microsoft.com/en-us/windows/desktop/api/shobjidl_core/nn-shobjidl_core-ishelllinkw
Dim lnkW As IShellLinkW = DirectCast(cShellLink, IShellLinkW)
lnkW.GetPath(target, target.Capacity, Nothing, IShellLinkGetPathFlags.RawPath)

( Sorry, are too many P/Invokes to share here, but you can find them in this repository. )

The code above works correctly to retrieve the target of any .lnk file that points to a file or directory. It can't retrieve a target that points to special item / virtual folders.

My questions are:

Is this by design?. If not, what I'm missing or doing wrong? (maybe are my definitions wrong?). And what I have to do in order to retrieve the special target?. Note that I would like to retrieve the target to display it in a PropertyGrid, and also to create a new target with a clone of the special target.

Please note that the programming language on which I developed this code does not matter, because I'm firstly asking for orientation, and also I accept any solution written in C#.


问:
Can't load image with path from FromFile in UWP
I'm developing an App for Android and UWP. In one screen I need to load an image from the device-filesystem and display it. Strangely it works perfectly on Android, but not on UWP. The Paths seem to be returned correctly by the FilePicker...

My XAML

<Image Grid.Row="0" Grid.Column="0"
Source="{Binding NewImage}" Margin="10,10,10,10" Aspect="AspectFit"
VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" />
```

<p>The source i use for the image</p>

<pre class="lang-cs prettyprint-override"><code>private FileImageSource _newImage;
public FileImageSource NewImage
        {
            get { return _newImage; }
            set
            {
                _newImage = value;
                OnPropertyChanged(nameof(NewImage));
            }
        }
</code>```

The function which is supposed to load the image and set the path.

private async void OnAddImage()
        {
            string[] types = { ".jpg", ".png" };
            FileData temp = await CrossFilePicker.Current.PickFile(types);
            if (temp == null)
            {
                return;
            }
            Debug.WriteLine($"ImagePath: {temp.FilePath}");
            Debug.WriteLine($"ImageName: {temp.FileName}");
            NewEntry.ImagePath = temp.FilePath;
            NewImage = (FileImageSource)ImageSource.FromFile(temp.FilePath);
        }
```

答:
When you used file picker to pick images on UWP, these images may be stored on the external disk. We can only use a path to load files embedded in the project or stored in the local storage on UWP: https://blogs.msdn.microsoft.com/wsdevsol/2012/12/04/skip-the-path-stick-to-the-storagefile/

So adjust your loading event like:

```<code>string[] types = { ".jpg", ".png" };
FileData temp = await CrossFilePicker.Current.PickFile(types);
if (temp == null)
{
    return;
}
Debug.WriteLine($"ImagePath: {temp.FilePath}");
Debug.WriteLine($"ImageName: {temp.FileName}");
//NewEntry.ImagePath = temp.FilePath;
NewImage = (StreamImageSource)ImageSource.FromStream(() => temp.GetStream());

// Property
private StreamImageSource _newImage;
public StreamImageSource NewImage
{
    get { return _newImage; }
    set
    {
        _newImage = value;
        OnPropertyChanged(nameof(NewImage));
    }
}
</code>```

This is also adapted on Android.

Body:
I'm developing an App for Android and UWP. In one screen I need to load an image from the device-filesystem and display it. Strangely it works perfectly on Android, but not on UWP. The Paths seem to be returned correctly by the FilePicker...

My XAML

<Image Grid.Row="0" Grid.Column="0"
Source="{Binding NewImage}" Margin="10,10,10,10" Aspect="AspectFit"
VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" />

The source i use for the image

private FileImageSource _newImage;
public FileImageSource NewImage
        {
            get { return _newImage; }
            set
            {
                _newImage = value;
                OnPropertyChanged(nameof(NewImage));
            }
        }

The function which is supposed to load the image and set the path.

private async void OnAddImage()
        {
            string[] types = { ".jpg", ".png" };
            FileData temp = await CrossFilePicker.Current.PickFile(types);
            if (temp == null)
            {
                return;
            }
            Debug.WriteLine($"ImagePath: {temp.FilePath}");
            Debug.WriteLine($"ImageName: {temp.FileName}");
            NewEntry.ImagePath = temp.FilePath;
            NewImage = (FileImageSource)ImageSource.FromFile(temp.FilePath);
        }

Body:
When you used file picker to pick images on UWP, these images may be stored on the external disk. We can only use a path to load files embedded in the project or stored in the local storage on UWP: https://blogs.msdn.microsoft.com/wsdevsol/2012/12/04/skip-the-path-stick-to-the-storagefile/

So adjust your loading event like:

string[] types = { ".jpg", ".png" };
FileData temp = await CrossFilePicker.Current.PickFile(types);
if (temp == null)
{
    return;
}
Debug.WriteLine($"ImagePath: {temp.FilePath}");
Debug.WriteLine($"ImageName: {temp.FileName}");
//NewEntry.ImagePath = temp.FilePath;
NewImage = (StreamImageSource)ImageSource.FromStream(() => temp.GetStream());

// Property
private StreamImageSource _newImage;
public StreamImageSource NewImage
{
    get { return _newImage; }
    set
    {
        _newImage = value;
        OnPropertyChanged(nameof(NewImage));
    }
}

This is also adapted on Android.


问:
RestTemplate throwing generic 400 Bad Request, but custom server sent message is not is lost
We have a rest controller API with POST mapping which takes an object as request param and creates the same on DB. We have got few validations on the input object, and if there is any error, then we are throwing exception with a custom message.

If we invoke this API from post man, we see the appropriate error.

Whereas when we invoke this in the caller method of other application with Spring's RestTemplate, all we see is a 400 Bad request with empty body. No error message is seen.

What could be the issue here. How can we get the custom message thrown from the API.

Here is how we are calling the API with rest template.

```<code>    String url = "https://localhost:8895/servuceUrl";
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    HttpEntity<AddRequest> entity = new HttpEntity<AddRequest>(obj, headers);
    ResponseEntity<String> data = null;
    adddata = restTemplate.exchange(syncurl, HttpMethod.POST, entity, String.class);
</code>```

And one server side we have an exception written as

```<code>@ResponseStatus(value=HttpStatus.BAD_REQUEST)
public class InvalidDataException extends Exception {

    public InvalidDataException(String msg) {
        super(msg);
    }
}
</code>```

The controller looks like

```<code>@PostMapping(RestUriMappings.POST_MAPPING)
public ResponseDto add(@Valid @RequestBody AddRequest data) throws InvalidDataException
{

    logger.debug("Incoming data for add: {}", data.toString());

    // validate the payload
    if(data.getName()==null)
       throw new InvalidDataException("Name shouldnt be null");
}
</code>```

答:
Spring's RestTemplate implementation has kind of a weird functionality. Whenever, the response is a 4XX, it throws a HttpClientErrorException instead of returning the response. Similarly, when the response is a 5XX response, it throws a HttpServerErrorException.

When you go inside the library, you will come across the piece of code which is responsible for such functionality inside DefaultResponseErrorHandler.java#handleError(ClientHttpResponse response).

So, if you want to fetch the original 4XX or 5XX response, you would have to write a wrapper over the RestTemplate.java#exchange() method. Something like this-

```<code>private ResponseEntity<String> exchange(String url, HttpMethod method, HttpEntity<?> httpEntity,
                                           Class<?> class1, Map<String, String> paramMap) {
        ResponseEntity<String> responseEntity = null;
        try {
            responseEntity = restTemplate.exchange(url, method, httpEntity, String.class, paramMap);
        }catch(HttpClientErrorException e) {
            responseEntity = new ResponseEntity<>(e.getResponseBodyAsString(), HttpStatus.BAD_REQUEST);
        }catch(HttpServerErrorException e) {
            responseEntity = new ResponseEntity<>(e.getResponseBodyAsString(), HttpStatus.INTERNAL_SERVER_ERROR);
            throw e;
        }catch(Exception e) {
            responseEntity = new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
            throw e;
        }
        return responseEntity;
    }
</code>```

Body:
We have a rest controller API with POST mapping which takes an object as request param and creates the same on DB. We have got few validations on the input object, and if there is any error, then we are throwing exception with a custom message.

If we invoke this API from post man, we see the appropriate error.

Whereas when we invoke this in the caller method of other application with Spring's RestTemplate, all we see is a 400 Bad request with empty body. No error message is seen.

What could be the issue here. How can we get the custom message thrown from the API.

Here is how we are calling the API with rest template.

    String url = "https://localhost:8895/servuceUrl";
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    HttpEntity<AddRequest> entity = new HttpEntity<AddRequest>(obj, headers);
    ResponseEntity<String> data = null;
    adddata = restTemplate.exchange(syncurl, HttpMethod.POST, entity, String.class);

And one server side we have an exception written as

@ResponseStatus(value=HttpStatus.BAD_REQUEST)
public class InvalidDataException extends Exception {

    public InvalidDataException(String msg) {
        super(msg);
    }
}

The controller looks like

@PostMapping(RestUriMappings.POST_MAPPING)
public ResponseDto add(@Valid @RequestBody AddRequest data) throws InvalidDataException
{

    logger.debug("Incoming data for add: {}", data.toString());

    // validate the payload
    if(data.getName()==null)
       throw new InvalidDataException("Name shouldnt be null");
}

Body:
Spring's RestTemplate implementation has kind of a weird functionality. Whenever, the response is a 4XX, it throws a HttpClientErrorException instead of returning the response. Similarly, when the response is a 5XX response, it throws a HttpServerErrorException.

When you go inside the library, you will come across the piece of code which is responsible for such functionality inside DefaultResponseErrorHandler.java#handleError(ClientHttpResponse response).

So, if you want to fetch the original 4XX or 5XX response, you would have to write a wrapper over the RestTemplate.java#exchange() method. Something like this-

private ResponseEntity<String> exchange(String url, HttpMethod method, HttpEntity<?> httpEntity,
                                           Class<?> class1, Map<String, String> paramMap) {
        ResponseEntity<String> responseEntity = null;
        try {
            responseEntity = restTemplate.exchange(url, method, httpEntity, String.class, paramMap);
        }catch(HttpClientErrorException e) {
            responseEntity = new ResponseEntity<>(e.getResponseBodyAsString(), HttpStatus.BAD_REQUEST);
        }catch(HttpServerErrorException e) {
            responseEntity = new ResponseEntity<>(e.getResponseBodyAsString(), HttpStatus.INTERNAL_SERVER_ERROR);
            throw e;
        }catch(Exception e) {
            responseEntity = new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
            throw e;
        }
        return responseEntity;
    }


问:
Exact number of nested ranked data exact in SQL procedure
I have a procedure like this:

```<code>SELECT Name, Date, Par3, Date_rank
FROM
   (SELECT Name, ROW_NUMBER() OVER (PARTITION BY Date ORDER BY Par3 ASC)
   AS Date_rank
   FROM Table
   WHERE (..conditions..)) ranked
WHERE Par2_rank <= 3
ORDER BY Par2 ASC, Par3 ASC
</code>```

The result gives me if number of rows is less or equal 3 is:

```<code>Name,    Date,     Par3,    Date_rank
AB   2010-01-01    1.5          1
CD   2010-02-16    0.9          1
EF   2010-02-16    1.1          2
GH   2010-02-16    1.7          3
</code>```

But I need only results, where we have exact number of rows for date, equal 3.
So the result should be:

```<code>Name,    Date,     Par3,    Date_rank
CD   2010-02-16    0.9          1
EF   2010-02-16    1.1          2
GH   2010-02-16    1.7          3
</code>```

I tried to put WHERE Par2_rank = 3.

Then I get only one row:

```<code>Name,    Date,     Par3,    Date_rank
GH   2010-02-16    1.7          3
</code>```

Also I tried to use HAVING COUNT, but it gives me no rows.

Thanks in advance.

UPDATE:
Thanks to all you guys for quick answers. COUNT (*) OVER PARTITION did the trick. It's so simple.. I hope, I will code better in SQL thanks to you in the future.

答:
You can do it using EXISTS:</p>

```<code>WITH ranked AS
(
    SELECT Name, date, ROW_NUMBER() OVER (PARTITION BY Date ORDER BY Par3 ASC)
       AS Date_rank
       FROM Table
       WHERE (..conditions..)
)
SELECT
    *
FROM ranked AS R
    WHERE EXISTS (SELECT 1
                    FROM ranked
                    where r.Date = Date
                    and Date_rank = 3
                    and Date_rank <> 4
                  )
</code>```

Body:
I have a procedure like this:

SELECT Name, Date, Par3, Date_rank
FROM
   (SELECT Name, ROW_NUMBER() OVER (PARTITION BY Date ORDER BY Par3 ASC)
   AS Date_rank
   FROM Table
   WHERE (..conditions..)) ranked
WHERE Par2_rank <= 3
ORDER BY Par2 ASC, Par3 ASC

The result gives me if number of rows is less or equal 3 is:

Name,    Date,     Par3,    Date_rank
AB   2010-01-01    1.5          1
CD   2010-02-16    0.9          1
EF   2010-02-16    1.1          2
GH   2010-02-16    1.7          3

But I need only results, where we have exact number of rows for date, equal 3.
So the result should be:

Name,    Date,     Par3,    Date_rank
CD   2010-02-16    0.9          1
EF   2010-02-16    1.1          2
GH   2010-02-16    1.7          3

I tried to put WHERE Par2_rank = 3.

Then I get only one row:

Name,    Date,     Par3,    Date_rank
GH   2010-02-16    1.7          3

Also I tried to use HAVING COUNT, but it gives me no rows.

Thanks in advance.

UPDATE:
Thanks to all you guys for quick answers. COUNT (*) OVER PARTITION did the trick. It's so simple.. I hope, I will code better in SQL thanks to you in the future.

Body:
You can do it using EXISTS:

WITH ranked AS
(
    SELECT Name, date, ROW_NUMBER() OVER (PARTITION BY Date ORDER BY Par3 ASC)
       AS Date_rank
       FROM Table
       WHERE (..conditions..)
)
SELECT
    *
FROM ranked AS R
    WHERE EXISTS (SELECT 1
                    FROM ranked
                    where r.Date = Date
                    and Date_rank = 3
                    and Date_rank <> 4
                  )


问:
Asking user to input two numbers, store them in memory, doing addition and substraction and display both result
I'm new to MIPS, and I'm working on this question, my code wold assemble, but after I hit the run buttom and entered the first number, it would show a runtime exception: Runtime exception at 0x00400018: address out of range 0x00000000

I don't understand what's happening to my code, can anyone help me?

```<code>    .data
str1:   .asciiz "Enter number 1: "

str2:   .asciiz "Enter number 2: "

str3:   .asciiz "The sum of the two number is: "

str4:   .asciiz "The difference of the two number is: "

num1:   .word 4

num2:   .word 4

    .text
    .globl main
main:

la  $t0, str1

li  $v0, 4      #syscall code for print_str

la  $a0, ($t0)  #address of string to print

syscall         #print str1

la  $s0, num1

li  $v0, 5      #syscall code for read int

syscall         #read int

sw  $s0, ($v0)  #store the enterd value in num1

    la  $t1, str2
    li  $v0, 4      #syscall for print_str
    la  $a0, ($t1)      #address of string to print
    syscall         #print str2
    la  $s1, num2
    li  $v0, 5      #syscall code for read int
    syscall         #read int
    sw  $s1, ($v0)  #store the entered value in num2

    add $s2, $s0, $s1   #add num1 and num2

    la  $t2, str3
    li  $v0, 4      #syscall for print_str
    la  $a0, ($t2)      #address of str3
    la  $a1, ($s2)      #address of the sum
    syscall         #print str3 and the sum

    sub $s3, $s0, $s1   #substract num1 and num2    ERROR COULD BE HERE

    la  $t3, str4
    li  $v0, 4      #syscall for print_str
    la  $a0, ($t3)      #address of str4
    la  $a1, ($s3)      #address of the difference
    syscall         #print str4 and the difference
    li  $v0, 10     #exit
    syscall
</code>```

Error in C:\Users\Desktop\exercise2.s line 18: Runtime exception at 0x00400018: address out of range 0x00000000

Go: execution terminated with errors.

答:
Many problems in your code.

la  $a0, ($t0) is incorrect. The assembler should warn you. la is a two instructions macro  that` loads an address from a label, while $t0 is a register (that already holds the value of str1).

It should be replaced by la $a0, str1 or (much better because it is a   a unique instruction) mov $a0, $t1 as you already did this computation for $t1. You have the same problem for str2, str3 and str4.
But there is no need to use a temporary register and you could directly do the computation in $a0.

There is another problem. According to documentation after syscall 5 "$v0 contains integer read". So the sw  $s0, ($v0) after reading the ints are incorrect. What should be stored is $v0 and the store address is num1 and has already been loaded in $s0.

add $s2, $s1, $s0 is also incorrect, as $s0 and $s1 values are integer addresses, not integer values.

Last, you cannot print at once a string and an integer. It must be done in two syscalls : syscall 4 to print a string and syscall 1 to print the integer.

```<code>   .data
str1:   .asciiz "Enter number 1: "
str2:   .asciiz "Enter number 2: "
str3:   .asciiz "The sum of the two number is: "
str4:   .asciiz "The difference of the two number is: "
num1:   .word 4
num2:   .word 4

    .text
    .globl main
main:
    la  $a0, str1
    li  $v0, 4      #syscall code for print_str
    syscall         #print str1

    li  $v0, 5      #syscall code for read int
    syscall         #read int
    mov $s0, $v0    ## keep the value of int in a register
    la  $t1, num2
    sw  $v0, ($t1)  #store the entered value in num2

    li  $v0, 4      #syscall for print_str
    la  $a0, str2      #address of string to print
    syscall         #print str2

    li  $v0, 5      #syscall code for read int
    syscall         #read int
    mov $s1, $v0    ## keep the value of int in a register
    la  $t1, num2
    sw  $v0, ($t1)  #store the entered value in num2

    add $s2, $s0, $s1   #add num1 and num2

    la  $a0, str3
    li  $v0, 4      #syscall for print_str
    syscall         #print str3
    li  $v0, 1      #syscall for print integer
    mov $a0, $s2    #value of the sum
    syscall         #print sum

    sub $s3, $t0, $t1   #substract num1 and num2

    la  $a0, str4
    li  $v0, 4      #syscall for print_str
    syscall         #print str4
    li  $v0, 1      #syscall for print integer
    mov $a0, $s3    #value of the diff
    syscall         #print diff value
</code>```

BTW, storing the integers is useless. I kept them because it is in the title of the question, but it you just need the sum and diff, the sw instructions and corresponding la can be suppressed.

Body:
I'm new to MIPS, and I'm working on this question, my code wold assemble, but after I hit the run buttom and entered the first number, it would show a runtime exception: Runtime exception at 0x00400018: address out of range 0x00000000

I don't understand what's happening to my code, can anyone help me?

    .data
str1:   .asciiz "Enter number 1: "

str2:   .asciiz "Enter number 2: "

str3:   .asciiz "The sum of the two number is: "

str4:   .asciiz "The difference of the two number is: "

num1:   .word 4

num2:   .word 4

    .text
    .globl main
main:

la  $t0, str1

li  $v0, 4      #syscall code for print_str

la  $a0, ($t0)  #address of string to print

syscall         #print str1

la  $s0, num1

li  $v0, 5      #syscall code for read int

syscall         #read int

sw  $s0, ($v0)  #store the enterd value in num1

    la  $t1, str2
    li  $v0, 4      #syscall for print_str
    la  $a0, ($t1)      #address of string to print
    syscall         #print str2
    la  $s1, num2
    li  $v0, 5      #syscall code for read int
    syscall         #read int
    sw  $s1, ($v0)  #store the entered value in num2

    add $s2, $s0, $s1   #add num1 and num2

    la  $t2, str3
    li  $v0, 4      #syscall for print_str
    la  $a0, ($t2)      #address of str3
    la  $a1, ($s2)      #address of the sum
    syscall         #print str3 and the sum

    sub $s3, $s0, $s1   #substract num1 and num2    ERROR COULD BE HERE

    la  $t3, str4
    li  $v0, 4      #syscall for print_str
    la  $a0, ($t3)      #address of str4
    la  $a1, ($s3)      #address of the difference
    syscall         #print str4 and the difference
    li  $v0, 10     #exit
    syscall

Error in C:\Users\Desktop\exercise2.s line 18: Runtime exception at 0x00400018: address out of range 0x00000000

Go: execution terminated with errors.

Body:
Many problems in your code.

la  $a0, ($t0) is incorrect. The assembler should warn you. la is a two instructions macro  that` loads an address from a label, while $t0 is a register (that already holds the value of str1).

It should be replaced by la $a0, str1 or (much better because it is a   a unique instruction) mov $a0, $t1 as you already did this computation for $t1. You have the same problem for str2, str3 and str4.
But there is no need to use a temporary register and you could directly do the computation in $a0.

There is another problem. According to documentation after syscall 5 "$v0 contains integer read". So the sw  $s0, ($v0) after reading the ints are incorrect. What should be stored is $v0 and the store address is num1 and has already been loaded in $s0.

add $s2, $s1, $s0 is also incorrect, as $s0 and $s1 values are integer addresses, not integer values.

Last, you cannot print at once a string and an integer. It must be done in two syscalls : syscall 4 to print a string and syscall 1 to print the integer.

   .data
str1:   .asciiz "Enter number 1: "
str2:   .asciiz "Enter number 2: "
str3:   .asciiz "The sum of the two number is: "
str4:   .asciiz "The difference of the two number is: "
num1:   .word 4
num2:   .word 4

    .text
    .globl main
main:
    la  $a0, str1
    li  $v0, 4      #syscall code for print_str
    syscall         #print str1

    li  $v0, 5      #syscall code for read int
    syscall         #read int
    mov $s0, $v0    ## keep the value of int in a register
    la  $t1, num2
    sw  $v0, ($t1)  #store the entered value in num2

    li  $v0, 4      #syscall for print_str
    la  $a0, str2      #address of string to print
    syscall         #print str2

    li  $v0, 5      #syscall code for read int
    syscall         #read int
    mov $s1, $v0    ## keep the value of int in a register
    la  $t1, num2
    sw  $v0, ($t1)  #store the entered value in num2

    add $s2, $s0, $s1   #add num1 and num2

    la  $a0, str3
    li  $v0, 4      #syscall for print_str
    syscall         #print str3
    li  $v0, 1      #syscall for print integer
    mov $a0, $s2    #value of the sum
    syscall         #print sum

    sub $s3, $t0, $t1   #substract num1 and num2

    la  $a0, str4
    li  $v0, 4      #syscall for print_str
    syscall         #print str4
    li  $v0, 1      #syscall for print integer
    mov $a0, $s3    #value of the diff
    syscall         #print diff value

BTW, storing the integers is useless. I kept them because it is in the title of the question, but it you just need the sum and diff, the sw instructions and corresponding la can be suppressed.


问:
"Length cannot be less than zero." on a blank line
I keep getting the above error message, even if I comment out the line that the error is occurring on.  Any idea what could be causing this?  I've tried re-writing the lines with test values, but I still get the same error.

This works perfectly in debug mode, it's only in the deployment that this came up.

Original code:

```<code>Line 21:             string domain, username;
Line 22:             string text = Page.User.Identity.Name;
Line 23:
Line 24:             domain = text.Substring(0, text.IndexOf("\\"));
Line 25:             username = text.Substring(text.IndexOf("\\") + 1, text.Length - text.IndexOf("\\") - 1);

Source File: F:\<file path>\Default.aspx.cs    Line: 23
</code>```

Test code (same error):

```<code>Line 21:             string domain, username;
Line 22:             //string text = "TEST"; // Page.User.Identity.Name;
Line 23:             // this line is blank
Line 24:             domain = "TEST"; //text.Substring(0, text.IndexOf("\\"));
Line 25:             username = "TEST"; // text.Substring(text.IndexOf("\\") + 1,

Source File: F:\<file path>\Default.aspx.cs    Line: 23
</code>```

Here's the stack trace if it helps at all:

```<code>[ArgumentOutOfRangeException: Length cannot be less than zero.
Parameter name: length]
System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy) +12681546
Insufficiencies._Default.Page_Load(Object sender, EventArgs e) in F:\<file path>\Default.aspx.cs:23
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3048
</code>```

答:
text.IndexOf("\\") will be returning -1 if it cannot find "\" in the string.

You are passing -1 through to the Substring() method, which is invalid.

The Page.User.Identity.Name will return an empty string if the site is not run with windows integrated authentication exclusively enabled in IIS for that site.

Users will likely be accessing the site under anonymous authentication.

From http://msdn.microsoft.com/en-us/library/ff647405.aspx:

To configure Windows authentication

Start Internet Information Services (IIS).

Right-click your application's virtual directory, and then click Properties.

Click the Directory Security tab.

Under Anonymous access and authentication control, click Edit.

Make sure the Anonymous access check box is not selected and that Integrated Windows authentication is the only selected check box.

In your application's Web.config file or in the machine-level Web.config file, ensure that the authentication mode is set to Windows as shown here.

```<code><system.web>
 ...
   <authentication mode="Windows"/>
 ...
 </system.web>
</code>```

Body:
I keep getting the above error message, even if I comment out the line that the error is occurring on.  Any idea what could be causing this?  I've tried re-writing the lines with test values, but I still get the same error.

This works perfectly in debug mode, it's only in the deployment that this came up.

Original code:

Line 21:             string domain, username;
Line 22:             string text = Page.User.Identity.Name;
Line 23:
Line 24:             domain = text.Substring(0, text.IndexOf("\\"));
Line 25:             username = text.Substring(text.IndexOf("\\") + 1, text.Length - text.IndexOf("\\") - 1);

Source File: F:\<file path>\Default.aspx.cs    Line: 23

Test code (same error):

Line 21:             string domain, username;
Line 22:             //string text = "TEST"; // Page.User.Identity.Name;
Line 23:             // this line is blank
Line 24:             domain = "TEST"; //text.Substring(0, text.IndexOf("\\"));
Line 25:             username = "TEST"; // text.Substring(text.IndexOf("\\") + 1,

Source File: F:\<file path>\Default.aspx.cs    Line: 23

Here's the stack trace if it helps at all:

[ArgumentOutOfRangeException: Length cannot be less than zero.
Parameter name: length]
System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy) +12681546
Insufficiencies._Default.Page_Load(Object sender, EventArgs e) in F:\<file path>\Default.aspx.cs:23
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3048

Body:
text.IndexOf("\\") will be returning -1 if it cannot find "\" in the string.

You are passing -1 through to the Substring() method, which is invalid.

The Page.User.Identity.Name will return an empty string if the site is not run with windows integrated authentication exclusively enabled in IIS for that site.

Users will likely be accessing the site under anonymous authentication.

From http://msdn.microsoft.com/en-us/library/ff647405.aspx:

To configure Windows authentication

Start Internet Information Services (IIS).

Right-click your application's virtual directory, and then click Properties.

Click the Directory Security tab.

Under Anonymous access and authentication control, click Edit.

Make sure the Anonymous access check box is not selected and that Integrated Windows authentication is the only selected check box.

In your application's Web.config file or in the machine-level Web.config file, ensure that the authentication mode is set to Windows as shown here.

<system.web>
 ...
   <authentication mode="Windows"/>
 ...
 </system.web>


问:
How to import js file from src file into index.html?
I am creating one system using React and I am still new to React. I need to add js file in my index.html where that js file is located in the src folder. I need to import this js file in order to make my system works. Does anyone know how to solve my problem? Thanks in advance.

This is how I import my js file. I think there is something wrong with my path. Does anyone know the correct path to import my js file?

```<code>      //index.html
      <!DOCTYPE html>
       <html lang="en">
        <head>
         <meta charset="utf-8" />
         <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
         <meta name="viewport" content="width=device-width, initial-scale=1" />
         <meta name="theme-color" content="#000000" />
         <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
         <title>React App</title>
         </head>
         <body>
           <noscript>You need to enable JavaScript to run this app.</noscript>
           <div id="root"></div>
           <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
           <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
           <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
           <script src="https://unpkg.com/@coreui/coreui/dist/js/coreui.min.js"></script>
           <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js" crossorigin></script>
           <script type="text/javascript" src='../src/js/index.js'></script>
         </body>
        </html>
</code>```

As you can see from the picture above, my index.js is located under the src folder.

答:
Path should be

```<code><script src='../src/js/index.js'></script>
</code>```

You need to go up one folder ('../') to be at the same spot as public and src then go into src/js/index.js

Body:
I am creating one system using React and I am still new to React. I need to add js file in my index.html where that js file is located in the src folder. I need to import this js file in order to make my system works. Does anyone know how to solve my problem? Thanks in advance.

This is how I import my js file. I think there is something wrong with my path. Does anyone know the correct path to import my js file?

      //index.html
      <!DOCTYPE html>

         <meta charset="utf-8" />
         <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
         <meta name="viewport" content="width=device-width, initial-scale=1" />
         <meta name="theme-color" content="#000000" />
         <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
         <title>React App</title>

           You need to enable JavaScript to run this app.

As you can see from the picture above, my index.js is located under the src folder.

Body:
Path should be

<script src='../src/js/index.js'></script>

You need to go up one folder ('../') to be at the same spot as public and src then go into src/js/index.js


问:
How to get next all element of a specific class?
I am triggering an event and the element has the class .pvtd. I have more elements with the same class name after that so I want to perform some functionality on all those elements which have the same class name after that element.

On selecting any option which is has no value I want the next .pvtd get disabled. The previous .pvtd class before the selected element should not be disabled, only the next ones. Any idea how I can do this?

$('.pvtd').on('change', function(event) {
  let value = $(`${this} option:selected`).val();
  if (!value) {
    $('.pvtd').nextAll().attr("disabled", "disabled");
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-md-2">
  <label for="inputCity"><strong>Produce</strong></label>
  <select name="first" id="produce_rprt" class="pvtd">
    <option value="" selected="selected">Select Produce</option>
    <option value="1">Potato</option>
  </select>
</div>

<div class="form-group col-md-2">
  <label for="inputState"><strong>Variety</strong></label>
  <select name="variety" id="variety_rprt" class="pvtd">
    <option value="" selected="selected">Select Variety</option>
    <option value="1">Default</option>
  </select>
</div>

<div class="form-group col-md-2">
  <label for="inputState"><strong>Type</strong></label>
  <select name="type" id="type_rprt" class="pvtd">
    <option value="" selected="selected">Select Type</option>
    <option value="1">Default</option>
  </select>
</div>

<div class="form-group col-md-2">
  <label for="inputState"><strong>Defect</strong></label>
  <select name="defect" id="defect_rprt" class="pvtd">
    <option value="" selected="selected">Select Defect</option>
    <option value="1">Default</option>
  </select>
</div></code>```

答:
There's two issues here. Firstly, this is a reference to the element which raised the event. As such you cannot concatenate it to a jQuery selector string. Aside from this you don't need to, as the value of the selected option can be read simply by doing $(this).val().

Secondly, nextAll() won't work in this situation as the .pvtd are not siblings. To fix this you could select all of them, then when required, you can find all those elements with a higher index that the current one.

However, given your below comment:

I want only type and defect to get disabled if I am selecting 'Select Variety'.

You do not need nextAll() in this case, as you only want the single following .pvtd element. To achieve that you can use eq(), like this:

var $pvtd = $('.pvtd').on('change', function(event) {
  let value = $(this).val();
  if (!value) {
    $('.pvtd').eq($(this).index('.pvtd') + 1).prop("disabled", true);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-md-2">
  <label for="inputCity"><strong>Produce</strong></label>
  <select name="first" id="produce_rprt" class="pvtd">
    <option value="" selected="selected">Select Produce</option>
    <option value="1">Potato</option>
  </select>
</div>
<div class="form-group col-md-2">
  <label for="inputState"><strong>Variety</strong></label>
  <select name="variety" id="variety_rprt" class="pvtd">
    <option value="" selected="selected">Select Variety</option>
    <option value="1">Default</option>
  </select>
</div>
<div class="form-group col-md-2">
  <label for="inputState"><strong>Type</strong></label>
  <select name="type" id="type_rprt" class="pvtd">
    <option value="" selected="selected">Select Type</option>
    <option value="1">Default</option>
  </select>
</div>
<div class="form-group col-md-2">
  <label for="inputState"><strong>Defect</strong></label>
  <select name="defect" id="defect_rprt" class="pvtd">
    <option value="" selected="selected">Select Defect</option>
    <option value="1">Default</option>
  </select>
</div></code>```

Body:
I am triggering an event and the element has the class .pvtd. I have more elements with the same class name after that so I want to perform some functionality on all those elements which have the same class name after that element.

On selecting any option which is has no value I want the next .pvtd get disabled. The previous .pvtd class before the selected element should not be disabled, only the next ones. Any idea how I can do this?

$('.pvtd').on('change', function(event) {
  let value = $(`${this} option:selected`).val();
  if (!value) {
    $('.pvtd').nextAll().attr("disabled", "disabled");
  }
});

  Produce
  <select name="first" id="produce_rprt" class="pvtd">
    <option value="" selected="selected">Select Produce</option>
    <option value="1">Potato</option>
  </select>

  Variety
  <select name="variety" id="variety_rprt" class="pvtd">
    <option value="" selected="selected">Select Variety</option>
    <option value="1">Default</option>
  </select>

  Type
  <select name="type" id="type_rprt" class="pvtd">
    <option value="" selected="selected">Select Type</option>
    <option value="1">Default</option>
  </select>

  Defect
  <select name="defect" id="defect_rprt" class="pvtd">
    <option value="" selected="selected">Select Defect</option>
    <option value="1">Default</option>
  </select>

Body:
There's two issues here. Firstly, this is a reference to the element which raised the event. As such you cannot concatenate it to a jQuery selector string. Aside from this you don't need to, as the value of the selected option can be read simply by doing $(this).val().

Secondly, nextAll() won't work in this situation as the .pvtd are not siblings. To fix this you could select all of them, then when required, you can find all those elements with a higher index that the current one.

However, given your below comment:

I want only type and defect to get disabled if I am selecting 'Select Variety'.

You do not need nextAll() in this case, as you only want the single following .pvtd element. To achieve that you can use eq(), like this:

var $pvtd = $('.pvtd').on('change', function(event) {
  let value = $(this).val();
  if (!value) {
    $('.pvtd').eq($(this).index('.pvtd') + 1).prop("disabled", true);
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-md-2">
  <label for="inputCity"><strong>Produce</strong></label>
  <select name="first" id="produce_rprt" class="pvtd">
    <option value="" selected="selected">Select Produce</option>
    <option value="1">Potato</option>
  </select>
</div>
<div class="form-group col-md-2">
  <label for="inputState"><strong>Variety</strong></label>
  <select name="variety" id="variety_rprt" class="pvtd">
    <option value="" selected="selected">Select Variety</option>
    <option value="1">Default</option>
  </select>
</div>
<div class="form-group col-md-2">
  <label for="inputState"><strong>Type</strong></label>
  <select name="type" id="type_rprt" class="pvtd">
    <option value="" selected="selected">Select Type</option>
    <option value="1">Default</option>
  </select>
</div>
<div class="form-group col-md-2">
  <label for="inputState"><strong>Defect</strong></label>
  <select name="defect" id="defect_rprt" class="pvtd">
    <option value="" selected="selected">Select Defect</option>
    <option value="1">Default</option>
  </select>
</div>


问:
How to pass async data retrieved in splashscreen to App.js?
This article explains how to use splash screen to load data before initial screen. Basically it defines:

```<code>const InitialNavigator = createSwitchNavigator({
  Splash: SplashScreen,
  App: AppNavigator
});

export default createAppContainer(InitialNavigator);
</code>```

Here is the AppNavigator:

```<code>const AppNavigator = createBottomTabNavigator(
  {
    Home: {
      screen: HomeNavigator
    },
    HighScores: {
      screen: HighScoresScreen
    },
    {
     initialRouteName: initialScreen,
   }
  }
);
</code>```

The initialScreen will be based on the data loaded during initialization.

Here is component SplashScreen which call 2 async functions to load variable result and user:

```<code>class SplashScreen extends React.Component {
  performTimeConsumingTask = async() => {
    var result, user;
    try {
    result = await helper.getJwtToken();
    console.log("App.js token result is : ", result);
    if (result) {
      console.log("App.js result is true. Retrieve user");
      user = await helper._getUser(result.password, result.username);
      console.log("User is : ", user.name);

    } else {
      console.log("App.js result is false");

    };
    console.log("I am out of App.js async without error");
  } catch (err) {
    console.log("Error in retrieving token : ", err);
    return "";

  };
  }

  async componentDidMount() {
    // Preload data from an external API
    // Preload data using AsyncStorage
    const data = await this.performTimeConsumingTask();

    if (data !== null) {
      this.props.navigation.navigate('App');
    }
  }
.......
</code>```

But how can I pass the value of result and user to App?

答:
you can pass a parameter named "params" to pass value to the next screen

take a look at the document

Body:
This article explains how to use splash screen to load data before initial screen. Basically it defines:

const InitialNavigator = createSwitchNavigator({
  Splash: SplashScreen,
  App: AppNavigator
});

export default createAppContainer(InitialNavigator);

Here is the AppNavigator:

const AppNavigator = createBottomTabNavigator(
  {
    Home: {
      screen: HomeNavigator
    },
    HighScores: {
      screen: HighScoresScreen
    },
    {
     initialRouteName: initialScreen,
   }
  }
);

The initialScreen will be based on the data loaded during initialization.

Here is component SplashScreen which call 2 async functions to load variable result and user:

class SplashScreen extends React.Component {
  performTimeConsumingTask = async() => {
    var result, user;
    try {
    result = await helper.getJwtToken();
    console.log("App.js token result is : ", result);
    if (result) {
      console.log("App.js result is true. Retrieve user");
      user = await helper._getUser(result.password, result.username);
      console.log("User is : ", user.name);

    } else {
      console.log("App.js result is false");

    };
    console.log("I am out of App.js async without error");
  } catch (err) {
    console.log("Error in retrieving token : ", err);
    return "";

  };
  }

  async componentDidMount() {
    // Preload data from an external API
    // Preload data using AsyncStorage
    const data = await this.performTimeConsumingTask();

    if (data !== null) {
      this.props.navigation.navigate('App');
    }
  }
.......

But how can I pass the value of result and user to App?


问:
Different results for factorial calculation in C, Python and JavaScript
I wrote some simple code in Python, JavaScript and C.  I found that the Python and JavaScript results are the same, but C gives me another -wrong- result and I can't understand what is the error.

C code:

```<code>int fact(int n){
    if(n==1){
        return 1;
    }else{
        return (n*fact(n-1));
    }
}

int main(void){
    printf("%i \n",fact(13));
}
</code>```

JS code:

function fact(n){
    if (n==1){
        return (1);
    }else{
        return (n*fact(n-1));
    }
}

console.log(fact(13));```
</div>
</div>
</p>

<p>Python code:</p>

```def fact(n):
    if(n == 0):
        return 1
    else:
        return n * fact(n - 1)

print(fact(13))
```

Can you explain?

答:
Being interpreted languages, they (probably) automatically choose the data type for variables according to the size of the data.

However, in C you specified that "int" has to be used - and it is way too small to hold 13!

If you switch "int" for "unsigned long long int" (yes, use "long" twice), then your program will return proper results for a longer time, until it fails again - exceeding the size of 64-bits.

Body:
I wrote some simple code in Python, JavaScript and C.  I found that the Python and JavaScript results are the same, but C gives me another -wrong- result and I can't understand what is the error.

C code:

int fact(int n){
    if(n==1){
        return 1;
    }else{
        return (n*fact(n-1));
    }
}

int main(void){
    printf("%i \n",fact(13));
}

JS code:

function fact(n){
    if (n==1){
        return (1);
    }else{
        return (n*fact(n-1));
    }
}

console.log(fact(13));

Python code:

def fact(n):
    if(n == 0):
        return 1
    else:
        return n * fact(n - 1)

print(fact(13))

Can you explain?


问:
Retrofit and SimpleXmlConverterFactory
I have a problem with retrofit and XML, I use SimpleXmlConverterFactory, and I have this error : Caused by: "java.lang.IllegalArgumentException: Could not locate ResponseBody converter for java.util.List.
Tried:

* retrofit2.BuiltInConverters                                                        * retrofit2.converter.simplexml.SimpleXmlConverterFactory"

gradle:

```<code>compile 'com.google.code.gson:gson:2.8.1'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.8.0'
compile ('com.squareup.retrofit2:converter-simplexml:2.3.0') {
    exclude group: 'xpp3', module: 'xpp3'
    exclude group: 'stax', module: 'stax-api'
    exclude group: 'stax', module: 'stax'
}
</code>```

service :

```<code>        Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(URL)
            .client(buildHttpClient())
            .addConverterFactory(SimpleXmlConverterFactory.create())
            .build();

private OkHttpClient buildHttpClient() {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    return (new OkHttpClient.Builder())
            .addInterceptor(buildDefaultHeadersInterceptor())
            .addNetworkInterceptor(buildLogInterceptor())
            .build();
}
</code>```

model :

```<code>    @Root(name = "item")
    public class Item {

    @Element(name = "link")
    private String link;

    @Element(name = "title")
    private String title;

    @Element(name = "description")
    private String description;

    public Item() {}
}
</code>```

xml :

```<code><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" version="2.0">
   <channel xml:lang="fr">
       <title>...</title>
       <link>http://www.jouars-pontchartrain.fr/</link>
       <description>...</description>
       <language>fr</language>
       <generator>SPIP - www.spip.net</generator>
       <image>...</image>
       <item xml:lang="fr">
           <title>
              title here
           </title>
           <link>
              link here
           </link>
           <description>
              description here
           </description>
       </item>
       <item xml:lang="fr">...</item>
       <item xml:lang="fr">...</item>
       <item xml:lang="fr">...</item>
       <item xml:lang="fr">...</item>
   </channel>
</rss>
</code>```

答:
Faced with the same problem. The solution is to make the internal class static (or just create a new separate java class). Also add the "Root" annotation for the "channel" node.

```<code>    @Root(name = "rss", strict = false)
public class ArticleResponse {

@Element(name = "channel")
private Channel channel;

@Root(name = "channel", strict = false)
static class Channel {

    @ElementList(inline = true, name="item")
    private List<Article> articles;
  }

}
</code>```

The same with the "enclosure" and "source" nodes - create new files or create static internal classes.

```<code>public class Enclosure {

    @Attribute(name = "url")
    private String url;

    @Attribute(name = "length")
    private long length;

    @Attribute(name = "type")
    private String type;
}
</code>```

Title: Retrofit and SimpleXmlConverterFactory

Body:
I have a problem with retrofit and XML, I use SimpleXmlConverterFactory, and I have this error : Caused by: "java.lang.IllegalArgumentException: Could not locate ResponseBody converter for java.util.List.
Tried:

* retrofit2.BuiltInConverters                                                        * retrofit2.converter.simplexml.SimpleXmlConverterFactory"

gradle:

compile 'com.google.code.gson:gson:2.8.1'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.8.0'
compile ('com.squareup.retrofit2:converter-simplexml:2.3.0') {
    exclude group: 'xpp3', module: 'xpp3'
    exclude group: 'stax', module: 'stax-api'
    exclude group: 'stax', module: 'stax'
}

service :

        Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(URL)
            .client(buildHttpClient())
            .addConverterFactory(SimpleXmlConverterFactory.create())
            .build();

private OkHttpClient buildHttpClient() {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    return (new OkHttpClient.Builder())
            .addInterceptor(buildDefaultHeadersInterceptor())
            .addNetworkInterceptor(buildLogInterceptor())
            .build();
}

model :

    @Root(name = "item")
    public class Item {

    @Element(name = "link")
    private String link;

    @Element(name = "title")
    private String title;

    @Element(name = "description")
    private String description;

    public Item() {}
}

xml :

<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" version="2.0">
   <channel xml:lang="fr">
       <title>...</title>
       <link>http://www.jouars-pontchartrain.fr/</link>
       <description>...</description>
       <language>fr</language>
       <generator>SPIP - www.spip.net</generator>
       <image>...</image>
       <item xml:lang="fr">
           <title>
              title here
           </title>
           <link>
              link here
           </link>
           <description>
              description here
           </description>
       </item>
       <item xml:lang="fr">...</item>
       <item xml:lang="fr">...</item>
       <item xml:lang="fr">...</item>
       <item xml:lang="fr">...</item>
   </channel>
</rss>

Body:
Faced with the same problem. The solution is to make the internal class static (or just create a new separate java class). Also add the "Root" annotation for the "channel" node.

    @Root(name = "rss", strict = false)
public class ArticleResponse {

@Element(name = "channel")
private Channel channel;

@Root(name = "channel", strict = false)
static class Channel {

    @ElementList(inline = true, name="item")
    private List<Article> articles;
  }

}

The same with the "enclosure" and "source" nodes - create new files or create static internal classes.

public class Enclosure {

    @Attribute(name = "url")
    private String url;

    @Attribute(name = "length")
    private long length;

    @Attribute(name = "type")
    private String type;
}


问:
Why use Tornado and Flask together?
As far as I can tell Tornado is a server and a framework in one. It seems to me that using Flask and Tornado together is like adding another abstraction layer (more overhead). Why do people use Flask and Tornado together, what are the advantages?</p>

答:
Use each one for what is better at, but take into account that the mix don't always get the performance gains you are looking for.

This benchmark, https://gist.github.com/andreif/6088558, for example, question what combination of frameworks is faster, you must adapt the example to your main use case. On this example, flask+tornado don't deliver the expected performance gains.

Title: Why use Tornado and Flask together?


问:
Failed to load resource: the server responded with a status of 404 (Not Found) EnterpriseMaster/BindNatureofAssignment: not working after publish
code is working good in localhost but when i publish this code error get and not loading table

EnterpriseMaster/BindNatureofAssignment:1 Failed to load resource: the server responded with a status of 404 (Not Found)

```<code>              var post = $http({
              method: "POST",
              url: "/EnterpriseMaster/BindNatureofAssignment",
              dataType: 'json',
              headers: { "Content-Type": "application/json" } });
              post.success(function (data, status) {
                  //The received response is saved in Customers array.
                  $scope.NAO = data;
              });
</code>```

答:
404 error occurs means,Please check the action BindNatureofAssignment is occur in controller or not, if its present Please assign  a base url for javascript variable and give that javascript variable to</p>

```<code> var ApplicationPath = 'Path of your Application';

var post = $http({
          method: "POST",
         url:  ApplicationPath+"/EnterpriseMaster/BindNatureofAssignment",
          dataType: 'json',
          headers: { "Content-Type": "application/json" } });
          post.success(function (data, status) {
              //The received response is saved in Customers array.
              $scope.NAO = data;
          });
</code>```

Body:
code is working good in localhost but when i publish this code error get and not loading table

EnterpriseMaster/BindNatureofAssignment:1 Failed to load resource: the server responded with a status of 404 (Not Found)

              var post = $http({
              method: "POST",
              url: "/EnterpriseMaster/BindNatureofAssignment",
              dataType: 'json',
              headers: { "Content-Type": "application/json" } });
              post.success(function (data, status) {
                  //The received response is saved in Customers array.
                  $scope.NAO = data;
              });

Body:
404 error occurs means,Please check the action BindNatureofAssignment is occur in controller or not, if its present Please assign  a base url for javascript variable and give that javascript variable to

 var ApplicationPath = 'Path of your Application';

var post = $http({
          method: "POST",
         url:  ApplicationPath+"/EnterpriseMaster/BindNatureofAssignment",
          dataType: 'json',
          headers: { "Content-Type": "application/json" } });
          post.success(function (data, status) {
              //The received response is saved in Customers array.
              $scope.NAO = data;
          });