问:
C# - OpenOfficeXML Date Format
I am having an issue when passing some data to an Excel spreadsheet, using OOX. Thing is, everything works great, except the dates, which are shown in a numeric value instead of the datetime format. Here's my code:

```<code>private object ProcessXLSFile(PayeesWorkingHoursFullDataDTO payeesWorkingHoursFullDataDTO)
    {
        DataTable dt = Functions.ObjectToDataTable(payeesWorkingHoursFullDataDTO.ListWorkingHours);

        ExcelPackage pck = new ExcelPackage();

        //Create the worksheet
        ExcelWorksheet ws = pck.Workbook.Worksheets.Add("WorkSheet1");

        //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
        ws.Cells["A1"].LoadFromDataTable(dt, true);

        string _range = "G2:G" + (dt.Rows.Count + 1).ToString();
        using (ExcelRange col = ws.Cells[_range])
        {
            col.Style.Numberformat.Format = "#,##0.00";
            col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
        }

        _range = "J2:J" + (dt.Rows.Count + 1).ToString();
        using (ExcelRange col = ws.Cells[_range])
        {
            col.Style.Numberformat.Format = "dd/MM/yyyy";
            col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
        }

        _range = "T2:T" + (dt.Rows.Count + 1).ToString();
        using (ExcelRange col = ws.Cells[_range])
        {
            col.Style.Numberformat.Format = "dd-MM-yyyy";
            col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
        }

        //Write it back to the client
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment; filename=Payee-Grid.xlsx");
        Response.BinaryWrite(pck.GetAsByteArray());
        Response.End();

        throw new NotImplementedException();
    }
</code>```

These lines are the ones where the columns should be converted to datetime:

```<code>_range = "J2:J" + (dt.Rows.Count + 1).ToString();
        using (ExcelRange col = ws.Cells[_range])
        {
            col.Style.Numberformat.Format = "dd/MM/yyyy";
            col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
        }
</code>```

But that's definitely not working.

This is the code where I create the DataTable:

```<code>public static DataTable ObjectToDataTable<T>(this IList<T> data)
    {
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            table.Rows.Add(row);
        }
        return table;
    }
</code>```

Debugging the columns I have been able to see that, up to the lines where I format the columns to "dd-MM-yyyy", the date information is still in datetime format. I have tried everything, but I really don't seem to be able to get this to work properly. Do you guys have any idea on how to make it work?

答:
Have you tried:

```<code>_range = "J2:J" + (dt.Rows.Count + 1).ToString();
        using (ExcelRange col = ws.Cells[_range])
        {
            col.Style.Numberformat.Format = "dd\\/MM\\/yyyy";
            col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
        }
</code>```

Sometimes, for reasons unknown, you have to escape things :-)

Title: C# - OpenOfficeXML Date Format

Body:
I am having an issue when passing some data to an Excel spreadsheet, using OOX. Thing is, everything works great, except the dates, which are shown in a numeric value instead of the datetime format. Here's my code:

private object ProcessXLSFile(PayeesWorkingHoursFullDataDTO payeesWorkingHoursFullDataDTO)
    {
        DataTable dt = Functions.ObjectToDataTable(payeesWorkingHoursFullDataDTO.ListWorkingHours);

        ExcelPackage pck = new ExcelPackage();

        //Create the worksheet
        ExcelWorksheet ws = pck.Workbook.Worksheets.Add("WorkSheet1");

        //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
        ws.Cells["A1"].LoadFromDataTable(dt, true);

        string _range = "G2:G" + (dt.Rows.Count + 1).ToString();
        using (ExcelRange col = ws.Cells[_range])
        {
            col.Style.Numberformat.Format = "#,##0.00";
            col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
        }

        _range = "J2:J" + (dt.Rows.Count + 1).ToString();
        using (ExcelRange col = ws.Cells[_range])
        {
            col.Style.Numberformat.Format = "dd/MM/yyyy";
            col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
        }

        _range = "T2:T" + (dt.Rows.Count + 1).ToString();
        using (ExcelRange col = ws.Cells[_range])
        {
            col.Style.Numberformat.Format = "dd-MM-yyyy";
            col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
        }

        //Write it back to the client
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment; filename=Payee-Grid.xlsx");
        Response.BinaryWrite(pck.GetAsByteArray());
        Response.End();

        throw new NotImplementedException();
    }

These lines are the ones where the columns should be converted to datetime:

_range = "J2:J" + (dt.Rows.Count + 1).ToString();
        using (ExcelRange col = ws.Cells[_range])
        {
            col.Style.Numberformat.Format = "dd/MM/yyyy";
            col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
        }

But that's definitely not working.

This is the code where I create the DataTable:

public static DataTable ObjectToDataTable<T>(this IList<T> data)
    {
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            table.Rows.Add(row);
        }
        return table;
    }

Debugging the columns I have been able to see that, up to the lines where I format the columns to "dd-MM-yyyy", the date information is still in datetime format. I have tried everything, but I really don't seem to be able to get this to work properly. Do you guys have any idea on how to make it work?

Body:
Have you tried:

_range = "J2:J" + (dt.Rows.Count + 1).ToString();
        using (ExcelRange col = ws.Cells[_range])
        {
            col.Style.Numberformat.Format = "dd\\/MM\\/yyyy";
            col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
        }

Sometimes, for reasons unknown, you have to escape things :-)


来源: stackexchange

问:
Should I process a JSON in the frontend or Backend, which is faster?
I am getting a response from an API as a json response.
I am coding in python for backend.

The frontend team needs information from the raw json response for populating a UI so we have to order the json and make it more easier for them to fetch information.

Now I can order the json in a specific format and push to the frontend team or I can pass the raw json response*to the frontend team and let them handle ordering the json and further use for their UI.

Remember my json file size is 15MB.

Which is faster and a better design principle?

Process in the backend then push to frontend or process in the frontend?

答:
I would suggest to perform this on the backend, some key reasons I would suggest this is:

Processing on mobile devices leads to massive battery drain

If your frontend is web, javascript will block while the processing is occurring (which could lead to bad experiences)

Server response can be cached to speed up response times and lower duplicate processing

Your backend language may be able to perform the task more optimally then the frontend device can

ContentLicense: CC BY-SA 4.0


问:
The Expo SDK requires Expo to run. i am beginner in react-native?
I am an experienced android developer and started learning react native. I am using ubuntu to make a project. I used code like this one react-native init myprojectand am using visual studio code for code editor.

To run a project on my physical device I run adb devices on the terminal, change directory to project directory then I start localhost like react-native start then I start my project on android by this code react-native run-android. The project works fine on my physical device.

But I am getting an error when I use Expo (** I do not know what is expo is**). I am following the net ninja tutorial series. When I use expo-icons I get no icons. This is the tutorial link : icons

When today I was learning about how to use custom fonts in the react-native I got similar errors like this one shown in this link.

I do not know why does expo is not working on my project. Before following this series, I looked at the book to learn react-native which was saying that now we do not use expo. So how can I get out of this problem?

although i get few answer that clears what is expo and one have also answered the problem of icons in react-native . currently i am not able to use custom fonts in react-native .

答:
Expo and react-native both are different CLI to create an applications.
Instead of using any components from expo in react-native application, you should use other packages. Since expo dependencies is not supported directly by react-native. (Correct me if I am wrong.)
Like, Instead of expo-icons you can use react-native-vector-icons
It will solve your current error.</p>


问:
SwiftUI iOS 13.3 Missing Navigation Bar title when nested inside TabView
The Navigation Bar title is missing when I put the view within a TabView. Anyone know what's the problem?

```<code>struct ContentView: View {
    var body: some View {
        NavigationView {
            TabView {
                Text("Tab 1")
                    .tabItem {
                        Text("Tab 1")
                    }
                    .navigationBarTitle("Tab 1")
                    .navigationBarHidden(false)

                Text("Tab 2")
                    .tabItem {
                        Text("Tab 2")
                    }
                    .navigationBarTitle("Tab 2")
                    .navigationBarHidden(false)
            }
        }
    }
}
</code>```

This is what I'm getting:

This is what I wish to achieve:

答:
Update: Xcode 13.4 / iOS 15.5

A possible approach is to join navigation view title with tab view selection dynamically, like

```<code>struct ContentView: View {
    let tabs = ["Tab 1", "Tab 2"]   // can be in model

    @State private var selection: String

    init() {
        _selection = State(initialValue: tabs[0]) // initial tab
    }

    var body: some View {
        NavigationView {
            TabView(selection: $selection) {   // << here !!
                Text("Tab 1")
                    .tabItem {
                        Text("Tab 1")
                    }.tag(tabs[0])

                Text("Tab 2")
                    .tabItem {
                        Text("Tab 2")
                    }.tag(tabs[1])
            }
            .navigationBarTitle(selection)    // << here !!
        }
    }
}
</code>```

Original

TabBar is designed to be a root view, so to achieve your needs the following approach can be used instead

```<code>struct ContentView: View {
    var body: some View {
        TabView {
            NavigationView {
                Text("Tab 1")
                    .navigationBarTitle("Tab 1")
                    .navigationBarHidden(false)
            }
            .tabItem {
                Text("Tab 1")
            }

            NavigationView {
                Text("Tab 2")
                    .navigationBarTitle("Tab 2")
                    .navigationBarHidden(false)
            }
            .tabItem {
                Text("Tab 2")
            }
            .navigationBarTitle("Tab 2")
            .navigationBarHidden(false)
        }
    }
}
</code>```

Body:
The Navigation Bar title is missing when I put the view within a TabView. Anyone know what's the problem?

struct ContentView: View {
    var body: some View {
        NavigationView {
            TabView {
                Text("Tab 1")
                    .tabItem {
                        Text("Tab 1")
                    }
                    .navigationBarTitle("Tab 1")
                    .navigationBarHidden(false)

                Text("Tab 2")
                    .tabItem {
                        Text("Tab 2")
                    }
                    .navigationBarTitle("Tab 2")
                    .navigationBarHidden(false)
            }
        }
    }
}

This is what I'm getting:

This is what I wish to achieve:

Body:
Update: Xcode 13.4 / iOS 15.5

A possible approach is to join navigation view title with tab view selection dynamically, like

struct ContentView: View {
    let tabs = ["Tab 1", "Tab 2"]   // can be in model

    @State private var selection: String

    init() {
        _selection = State(initialValue: tabs[0]) // initial tab
    }

    var body: some View {
        NavigationView {
            TabView(selection: $selection) {   // << here !!
                Text("Tab 1")
                    .tabItem {
                        Text("Tab 1")
                    }.tag(tabs[0])

                Text("Tab 2")
                    .tabItem {
                        Text("Tab 2")
                    }.tag(tabs[1])
            }
            .navigationBarTitle(selection)    // << here !!
        }
    }
}

Original

TabBar is designed to be a root view, so to achieve your needs the following approach can be used instead

struct ContentView: View {
    var body: some View {
        TabView {
            NavigationView {
                Text("Tab 1")
                    .navigationBarTitle("Tab 1")
                    .navigationBarHidden(false)
            }
            .tabItem {
                Text("Tab 1")
            }

            NavigationView {
                Text("Tab 2")
                    .navigationBarTitle("Tab 2")
                    .navigationBarHidden(false)
            }
            .tabItem {
                Text("Tab 2")
            }
            .navigationBarTitle("Tab 2")
            .navigationBarHidden(false)
        }
    }
}


问:
ITMS-90035 Error After Changing Build System to "New Build System" in Xcode
After I change build system from "Legacy Build System" to "New Build System" I started to get below error when trying to upload IPA to Appstore. For both options, I can get success build. What can be the problem?

P.S: My export options plist file is for Distrubition. Therefore, there is no problem with the certificate etc.. (As I mentioned, I can successfully UPLOAD it when build with legacy build system.

What I want to learn is that what can be the reasons for the problem. I'll check all of the reasons of it (e.g naming in files).

ERROR ITMS-90035: "Invalid Signature. A sealed resource is missing or invalid. The file at path [Şans.app/Şans] is not properly signed. Make sure you have signed your application with a distribution certificate, not an ad hoc certificate or a development certificate. Verify that the code signing settings in Xcode are correct at the target level (which override any values at the project level). Additionally, make sure the bundle you are uploading was built using a Release target in Xcode, not a Simulator target. If you are certain your code signing settings are correct, choose "Clean All" in Xcode, delete the "build" directory in the Finder, and rebuild your release target. For more information, please consult https://developer.apple.com/library/ios/documentation/Security/Conceptual/CodeSigningGuide/Introduction/Introduction.html

答:
There are may two possibilities in your case.

First: you are generating build using production/distribution certificate it's fine, but you must use App Store distribution provisioning profile instead of Ad Hoc.

Second thing you need to check, Is there any file exists with the special characters on it. For exemple: "IconFileName (Cópia).png" or "Atalar sözləri oyunu.app" etc. application archive does not support non-ASCII characters so rename file name if any exist.


问:
HTTP 1.0 vs 1.1
Could somebody give me a brief overview of the differences between HTTP 1.0 and HTTP 1.1?  I've spent some time with both of the RFCs, but haven't been able to pull out a lot of difference between them.  Wikipedia says this:

HTTP/1.1 (1997-1999)

Current version; persistent connections enabled by default and works well with proxies. Also supports request pipelining, allowing multiple requests to be sent at the same time, allowing the server to prepare for the workload and potentially transfer the requested resources more quickly to the client.

But that doesn't mean a lot to me.  I realize this is a somewhat complicated subject, so I'm not expecting a full answer, but can someone give me a brief overview of the differences at a bit lower level?

By this I mean that I'm looking for the info I would need to know to implement either an HTTP server or application. I'm mostly looking for a nudge in the right direction so that I can figure it out on my own.

答:
HTTP 1.1 comes with the host header in its specification while the HTTP 1.0 doesn't officially have a host header, but it doesn't refuse to add one.

The host header is useful because it allows the client to route a  message throughout the proxy server, and the major difference between 1.0 and 1.1 versions HTTP are:

HTTP 1.1 comes with persistent connections which define that we can have more than one request or response on the same HTTP connection.

while in HTTP 1.0 you have to open a new connection for each request and response

In HTTP 1.0 it has a pragma while in HTTP 1.1 it has Cache-Control
this is similar to pragma

OwnerDisplayName: Jason Baker

ContentLicense: CC BY-SA 3.0

Title: HTTP 1.0 vs 1.1


问:
Do I need to run the command npm install every time I want to compile my project?
I am currently working on a project at a large company, and according to the project I am working on, every time I want to quickstart the app, I would need to first run the command npm install and then run all the additional compiling instructions, but the problem is that running npm install can take a long time, and that is why I am wondering if it is necessary to run this command every time I make a change to the code, and then want to compile and run it.

What exactly does npm install do? If you could explain to me in terms of how we compile and run java code i.e. javac bob.java && java bob and try to make analogies on that basis, that would greatly help me understand the concept. The way I am currently thinking about it right now is that npm install kind of runs like how javac runs, but I am not sure if that is correct. Thanks in advance!

答:
NPM basically is the package manager for node. It helps with installing various packages and resolving their various dependencies. It greatly helps with your Node development. NPM helps you install the various modules you need for your web development and not just given you a whole bunch of features you might never need.
When you start an app, it comes with a package.json file. That package contains the list of node_modules you are gonna need. Whenever you enter npm install, what you are doing is to download that list of node_modules. So yeah, you have to download the modules all over again.
#NOTE: In your project, you have a file called package.json. this file is responsible for holding track of your project's dependencies. That's why you have to install it every time#.


问:
Shoud I store user-identifier in keychain using sign in with apple?
I'm implementing sign in with Apple referencing Apple's sample apple (Juice).

in Sample app, after authorize completed, save user identifier in keychain.

// For the purpose of this demo app, store the `userIdentifier` in the keychain.
self.saveUserInKeychain(userIdentifier)
```

I think, it is good solution for saving and restoring userIdentifier.

but description in code block, said it is purpose of demo app.
It's OK if i store useridentifier in keychain?

答: Yes, it's fine. Store "userIdentifier" on your server because if a user resets the device || root a device, then you will lose this info. So it's always better to store it on the server. </p>

Body:
I'm implementing sign in with Apple referencing Apple's sample apple (Juice).

in Sample app, after authorize completed, save user identifier in keychain.

// For the purpose of this demo app, store the `userIdentifier` in the keychain.
self.saveUserInKeychain(userIdentifier)

I think, it is good solution for saving and restoring userIdentifier.

but description in code block, said it is purpose of demo app.
It's OK if i store useridentifier in keychain?


问:
socket.io emit doesn't work inside socket.on
I'm new to socket.io so I'm following the steps of this tutorial here

I'm trying to send a value from client to server, then make some calculations and send the new value to another view of the client. This is my code so far:

server.js

```<code>var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);

io.on('connection', function(socket){

  socket.on('fromClient', function(data){
    console.log(data);
    //calculations will be here, not relevant
    socket.emit('fromServer', data);
  });

//  socket.send(req.query.gid);

  socket.on('disconnect', function () {
  });

});
</code>```

client.js (the part that should receive the 'fromServer' emit, this is an angular controller)

```<code>    var socket = io();
    socket.on('fromServer', function(data){
        console.log(data);
    });
</code>```

I know the 'fromClient' side is working cause it does print the value of data, but it doesn't print the 'fromServer' value. I'm not sure if the problem here is that the socket.emit inside socket.on is never called (server) or maybe the socket.on('fromServer') is not working(client).

For the record, I did another test and it did work, but it was only with express. On the other hand, I tried to use socket.send and socket.emit outside of the socket.on in my project and it worked, so I'm not sure if it has something to do with angular, it's the io.on('connection') event, or it's just the nesting.

答:
When you use socket event inside the same socket, always call the event by io.
I had used this in my project and it was working

Answer is io.emit(...)

var io = require('socket.io')(strapi.server);
io.on('connection', async function(socket) {
    socket.on('getQuestionNext', (data)=>{
        io.emit('question', {message : 1})
    })
}
```

Body:
I'm new to socket.io so I'm following the steps of this tutorial here

I'm trying to send a value from client to server, then make some calculations and send the new value to another view of the client. This is my code so far:

server.js

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);

io.on('connection', function(socket){

  socket.on('fromClient', function(data){
    console.log(data);
    //calculations will be here, not relevant
    socket.emit('fromServer', data);
  });

//  socket.send(req.query.gid);

  socket.on('disconnect', function () {
  });

});

client.js (the part that should receive the 'fromServer' emit, this is an angular controller)

    var socket = io();
    socket.on('fromServer', function(data){
        console.log(data);
    });

I know the 'fromClient' side is working cause it does print the value of data, but it doesn't print the 'fromServer' value. I'm not sure if the problem here is that the socket.emit inside socket.on is never called (server) or maybe the socket.on('fromServer') is not working(client).

For the record, I did another test and it did work, but it was only with express. On the other hand, I tried to use socket.send and socket.emit outside of the socket.on in my project and it worked, so I'm not sure if it has something to do with angular, it's the io.on('connection') event, or it's just the nesting.


问:
Differents size of files between writing in Python and writing in C
I'm wondering why when I'm writing the file in C its size is 131696B and when I'm writing the file in Python is divided by 2 (65848B) ? And so how to get the same size in C.

```<code>int str2bin(char *str) {

char *ptr = str;
int i;
char str1[] = "1";
char str0[] = "0";
FILE *fp = fopen("output_file.txt", "a");

for(; *ptr != 0; ++ptr)
{

    /* perform bitwise AND for every bit of the character */
    for(i = 7; i >= 0; --i) {
        if (*ptr & 1 << i){
             fwrite(str1, 1, sizeof(str1), fp);
         } else{
             fwrite(str0, 1, sizeof(str0), fp);
         }
    }
}

fclose(fp);
return 0;
</code>```

And the code to open the file I want to transform in binary:

```<code>FILE *fp = fopen(argv[1], "r");
fseek(fp, 0, SEEK_END);
long fsize = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *buffer = malloc(fsize + 1);

fread(buffer, 1, fsize, fp);

fclose(fp);
// printf("%s\n", buffer);
str2bin(buffer);
</code>```

Thanks

答:
```<code> for(i = 7; i >= 0; --i) {
</code>```

by doing --i instead of i-- you are writing only [0-6] of the byte.

You also are not writing in binary, you are writing in chars of 0 and 1, you would want

```<code>char str1[] = "1";
char str0[] = "0";
</code>```

to be

```<code> char str1 = 1;
 char str0 = 0;
</code>```

Body:
I'm wondering why when I'm writing the file in C its size is 131696B and when I'm writing the file in Python is divided by 2 (65848B) ? And so how to get the same size in C.

int str2bin(char *str) {

char *ptr = str;
int i;
char str1[] = "1";
char str0[] = "0";
FILE *fp = fopen("output_file.txt", "a");

for(; *ptr != 0; ++ptr)
{

    /* perform bitwise AND for every bit of the character */
    for(i = 7; i >= 0; --i) {
        if (*ptr & 1 << i){
             fwrite(str1, 1, sizeof(str1), fp);
         } else{
             fwrite(str0, 1, sizeof(str0), fp);
         }
    }
}

fclose(fp);
return 0;

And the code to open the file I want to transform in binary:

FILE *fp = fopen(argv[1], "r");
fseek(fp, 0, SEEK_END);
long fsize = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *buffer = malloc(fsize + 1);

fread(buffer, 1, fsize, fp);

fclose(fp);
// printf("%s\n", buffer);
str2bin(buffer);

Thanks

Body:
 for(i = 7; i >= 0; --i) {

by doing --i instead of i-- you are writing only [0-6] of the byte.

You also are not writing in binary, you are writing in chars of 0 and 1, you would want

char str1[] = "1";
char str0[] = "0";

to be

 char str1 = 1;
 char str0 = 0;


问:
How to create a list in Python that will yield the following result []
This a question on coursera practices excess.

Create a new list using the 9th through 12th elements (four items in all) of new_lst and assign it to the variable sub_lst.

link to the question: https://runestone.academy/runestone/books/published/fopp/Sequences/TheSliceOperator.html
The last question on the list.

How is my code

```<code>new_lst = ["computer", "luxurious", "basket", "crime", 0, 2.49, "institution", "slice", "sun",
["water", "air", "fire", "earth"], "games", 2.7, "code", "java", ["birthday", "celebration", 1817,
"party", "cake", 5], "rain", "thunderstorm", "top down"]
new_lst = new_lst[9:12]
sub_lst = new_lst
print(sub_lst)
</code>```

My output:

```<code>[['water', 'air', 'fire', 'earth'], 'games', 2.7]
</code>```

But here is the expected output:

```<code>['sun', ['water', 'air', 'fire', 'earth'], 'games', 2.7]
</code>```

Please why am I not getting the expected output?

答:
I think you are  assigning  more than the question asked and here is the solution

```<code>new_lst = ["computer", "luxurious", "basket", "crime", 0, 2.49, "institution", "slice", "sun", ["water", "air", "fire", "earth"], "games", 2.7, "code", "java", ["birthday", "celebration", 1817, "party", "cake", 5], "rain", "thunderstorm", "top down"]
sub_lst = new_lst[8:12]
</code>```

just   do "sub_lst = new_lst[8:12]" assign just sliced list in sub_lst.

Body:
This a question on coursera practices excess.

Create a new list using the 9th through 12th elements (four items in all) of new_lst and assign it to the variable sub_lst.

link to the question: https://runestone.academy/runestone/books/published/fopp/Sequences/TheSliceOperator.html
The last question on the list.

How is my code

new_lst = ["computer", "luxurious", "basket", "crime", 0, 2.49, "institution", "slice", "sun",
["water", "air", "fire", "earth"], "games", 2.7, "code", "java", ["birthday", "celebration", 1817,
"party", "cake", 5], "rain", "thunderstorm", "top down"]
new_lst = new_lst[9:12]
sub_lst = new_lst
print(sub_lst)

My output:

[['water', 'air', 'fire', 'earth'], 'games', 2.7]

But here is the expected output:

['sun', ['water', 'air', 'fire', 'earth'], 'games', 2.7]

Please why am I not getting the expected output?

Body:
I think you are  assigning  more than the question asked and here is the solution

new_lst = ["computer", "luxurious", "basket", "crime", 0, 2.49, "institution", "slice", "sun", ["water", "air", "fire", "earth"], "games", 2.7, "code", "java", ["birthday", "celebration", 1817, "party", "cake", 5], "rain", "thunderstorm", "top down"]
sub_lst = new_lst[8:12]

just   do "sub_lst = new_lst[8:12]" assign just sliced list in sub_lst.


问:
Absolute panel in R shiny gets hidden behind the leaflet output
I am trying to make a leaflet map full screen and also add filter controls on top of the map. However, when I try to do this my filter control(absolute panel) gets hidden behind the leaflet output during runtime.

Absolute panel is present when I give width manually

I want the map to be full-screen , when I do it, it gets hidden behind the map.

How can I make the map go behind the absolute panel?
Any help is appreciated.

Thanks

Below is the UI code:

```<code>fluidPage(style="padding-top: 10px;",
      h1("Locations"),
      absolutePanel(
        top = 60, left = "auto", right = 20, bottom = "auto",
        width = 330, height = "auto",draggable = TRUE,
        wellPanel(
          selectInput("Suburb", "Select one Suburb:",choices = c("Select one Suburb" = "All", as.character(mydata$SuburbTown))),
          uiOutput("secondselection")
          ),
        style = "opacity: 0.65"
          ),

      leafletOutput("leafl", height = "800px")
          )
</code>```

答:
just rewrite it,
     send it top of absolutePanel     leafletOutput("leafl", height = "800px")</p>

```<code>fluidPage(style="padding-top: 10px;",
  h1("Locations"),
  leafletOutput("leafl", height = "800px"),
  absolutePanel(
    top = 60, left = "auto", right = 20, bottom = "auto",
        width = 330, height = "auto",draggable = TRUE,
        wellPanel(
          selectInput("Suburb", "Select one Suburb:",choices = c("Select one Suburb" =
"All", as.character(mydata$SuburbTown))),
          uiOutput("secondselection")
          ),`enter code here`
        style = "opacity: 0.65"
              )
      )
</code>```

Body:
I am trying to make a leaflet map full screen and also add filter controls on top of the map. However, when I try to do this my filter control(absolute panel) gets hidden behind the leaflet output during runtime.

Absolute panel is present when I give width manually

I want the map to be full-screen , when I do it, it gets hidden behind the map.

How can I make the map go behind the absolute panel?
Any help is appreciated.

Thanks

Below is the UI code:

fluidPage(style="padding-top: 10px;",
      h1("Locations"),
      absolutePanel(
        top = 60, left = "auto", right = 20, bottom = "auto",
        width = 330, height = "auto",draggable = TRUE,
        wellPanel(
          selectInput("Suburb", "Select one Suburb:",choices = c("Select one Suburb" = "All", as.character(mydata$SuburbTown))),
          uiOutput("secondselection")
          ),
        style = "opacity: 0.65"
          ),

      leafletOutput("leafl", height = "800px")
          )

Body:
just rewrite it,
     send it top of absolutePanel     leafletOutput("leafl", height = "800px")

fluidPage(style="padding-top: 10px;",
  h1("Locations"),
  leafletOutput("leafl", height = "800px"),
  absolutePanel(
    top = 60, left = "auto", right = 20, bottom = "auto",
        width = 330, height = "auto",draggable = TRUE,
        wellPanel(
          selectInput("Suburb", "Select one Suburb:",choices = c("Select one Suburb" =
"All", as.character(mydata$SuburbTown))),
          uiOutput("secondselection")
          ),`enter code here`
        style = "opacity: 0.65"
              )
      )


问:
Yocto Warrior Bitbake Recipe for PyTorch for NVIDIA Jetson Nano
I am trying to create a simple Yocto Python Recipe for Python 3 PyTorch. The target is an SD Card Image for the NVIDIA Jetson Nano produced by Yocto from the meta-tegra layer. I can successfully compile and boot an image from meta-tegra without these recipes.

NVIDIA themselves have compiled and released the ".whl" Python packages and they are found here: https://devtalk.nvidia.com/default/topic/1048776/official-tensorflow-for-jetson-nano-/

Using their build instructions, I tried to write a Bitbake recipe to install PyTorch as follows:

```<code>SUMMARY = "Facebook PyTorch AI"
DESCRIPTION = "Facebook PyTorch AI"
HOMEPAGE = "https://pytorch.org/"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://LICENSE;md5=acf4d595f99e159bf31797aa872aef57"

inherit pypi
inherit setuptools3

#BBCLASSEXTEND = "native nativesdk"

DEPENDS += "python3-pytest-runner-native python3-pyyaml-native cmake-native"

do_configure_prepend() {
  USE_NCCL=0
  USE_DISTRIBUTED=0
  TORCH_CUDA_ARCH_LIST="5.3;6.2;7.2"
}

do_compile_prepend() {
  USE_NCCL=0
  USE_DISTRIBUTED=0
  TORCH_CUDA_ARCH_LIST="5.3;6.2;7.2"
}

SRC_URI = "gitsm://github.com/pytorch/pytorch.git;protocol=https"
SRCREV = "a3346e100e7f4e7ec90f18b7befcccc47d5a1c82"

S = "${WORKDIR}/git"
</code>```

The problem is that I hit the following error. I think it has to do with my environment variables not being picked up becuase the error includes "-DUSE_CUDA=False", however when I look at the bitbake environment ( bitbake -e ), it seems to be there.

Here is the error:

```<code>**NOTE: Executing SetScene Tasks
NOTE: Executing RunQueue Tasks
ERROR: python3-torch-1.1.0-r0 do_compile: 'python3 setup.py build ' execution failed.
ERROR: python3-torch-1.1.0-r0 do_compile: Function failed: do_compile (log file is located at /home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/temp/log.do_compile.27625)
ERROR: Logfile of failure stored in: /home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/temp/log.do_compile.27625
Log data follows:
| DEBUG: Executing shell function do_compile
| -- The CXX compiler identification is GNU 7.2.1
| -- The C compiler identification is GNU 7.2.1
| -- Check for working CXX compiler: /home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/bin/aarch64-poky-linux/aarch64-poky-linux-g++
| -- Check for working CXX compiler: /home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/bin/aarch64-poky-linux/aarch64-poky-linux-g++ -- works
| -- Detecting CXX compiler ABI info
| -- Detecting CXX compiler ABI info - done
| -- Detecting CXX compile features
| -- Detecting CXX compile features - done
| -- Check for working C compiler: /home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/bin/aarch64-poky-linux/aarch64-poky-linux-gcc
| -- Check for working C compiler: /home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/bin/aarch64-poky-linux/aarch64-poky-linux-gcc -- works
| -- Detecting C compiler ABI info
| -- Detecting C compiler ABI info - done
| -- Detecting C compile features
| -- Detecting C compile features - done
| -- Not forcing any particular BLAS to be found
| -- Performing Test COMPILER_WORKS
| -- Performing Test COMPILER_WORKS - Failed
| CMake Error at cmake/MiscCheck.cmake:52 (message):
|   Could not run a simple program built with your compiler.  If you are trying
|   to use -fsanitize=address, make sure libasan is properly installed on your
|   system (you can confirm if the problem is this by attempting to build and
|   run a small program.)
| Call Stack (most recent call first):
|   CMakeLists.txt:271 (include)
|
|
| -- Configuring incomplete, errors occurred!
| See also "/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/git/build/CMakeFiles/CMakeOutput.log".
| See also "/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/git/build/CMakeFiles/CMakeError.log".
| Building wheel torch-1.2.0a0+a3346e1
| -- Building version 1.2.0a0+a3346e1
| cmake -DBUILD_AR=ar -DBUILD_AS=as  -DBUILD_CC=gcc  -DBUILD_CCLD=gcc  -DBUILD_CFLAGS=-isystem/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/include -O2 -pipe -DBUILD_CPP=gcc  -E -DBUILD_CPPFLAGS=-isystem/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/include -DBUILD_CXX=g++  -DBUILD_CXXFLAGS=-isystem/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/include -O2 -pipe -DBUILD_FC=gfortran  -DBUILD_LD=ld  -DBUILD_LDFLAGS=-L/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/lib                         -L/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/lib                         -Wl,--enable-new-dtags                         -Wl,-rpath-link,/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/lib                         -Wl,-rpath-link,/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/lib                         -Wl,-rpath,/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/lib                         -Wl,-rpath,/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/lib                         -Wl,-O1 -Wl,--allow-shlib-undefined -Wl,--dynamic-linker=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/sysroots-uninative/x86_64-linux/lib/ld-linux-x86-64.so.2 -DBUILD_NM=nm -DBUILD_PYTHON=True -DBUILD_RANLIB=ranlib -DBUILD_STRIP=strip -DBUILD_TEST=True -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS= -O2 -pipe -g -feliminate-unused-debug-types -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0=/usr/src/debug/python3-torch/1.1.0-r0                      -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot=                      -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native=   -DCMAKE_C_FLAGS= -O2 -pipe -g -feliminate-unused-debug-types -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0=/usr/src/debug/python3-torch/1.1.0-r0                      -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot=                      -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native=   -DCMAKE_EXE_LINKER_FLAGS=-Wl,-O1 -Wl,--hash-style=gnu -Wl,--as-needed -fstack-protector-strong -Wl,-z,relro,-z,now -DCMAKE_INSTALL_PREFIX=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/git/torch -DCMAKE_PREFIX_PATH=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot/usr/lib/python3.7/site-packages -DCMAKE_SHARED_LINKER_FLAGS=-Wl,-O1 -Wl,--hash-style=gnu -Wl,--as-needed -fstack-protector-strong -Wl,-z,relro,-z,now -DINSTALL_TEST=True -DPYTHON_EXECUTABLE=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/bin/python3-native/python3 -DPYTHON_INCLUDE_DIR=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot/usr/include/python3.7m -DPYTHON_LIBRARY=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot/usr/lib/libpython3.7m.so.1.0 -DTORCH_BUILD_VERSION=1.2.0a0+a3346e1 -DUSE_CUDA=False -DUSE_DISTRIBUTED=True -DUSE_FBGEMM=True -DUSE_NCCL=False -DUSE_NUMPY=True -DUSE_QNNPACK=True -DUSE_SYSTEM_EIGEN_INSTALL=OFF -DUSE_SYSTEM_NCCL=False /home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/git
| Traceback (most recent call last):
|   File "setup.py", line 749, in <module>
|     build_deps()
|   File "setup.py", line 323, in build_deps
|     cmake=cmake)
|   File "/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/git/tools/build_pytorch_libs.py", line 61, in build_caffe2
|     rerun_cmake)
|   File "/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/git/tools/setup_helpers/cmake.py", line 318, in generate
|     self.run(args, env=my_env)
|   File "/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/git/tools/setup_helpers/cmake.py", line 93, in run
|     check_call(command, cwd=self.build_dir, env=env)
|   File "/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/lib/python3.7/subprocess.py", line 347, in check_call
|     raise CalledProcessError(retcode, cmd)
| subprocess.CalledProcessError: Command '['cmake', '-DBUILD_AR=ar', '-DBUILD_AS=as ', '-DBUILD_CC=gcc ', '-DBUILD_CCLD=gcc ', '-DBUILD_CFLAGS=-isystem/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/include -O2 -pipe', '-DBUILD_CPP=gcc  -E', '-DBUILD_CPPFLAGS=-isystem/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/include', '-DBUILD_CXX=g++ ', '-DBUILD_CXXFLAGS=-isystem/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/include -O2 -pipe', '-DBUILD_FC=gfortran ', '-DBUILD_LD=ld ', '-DBUILD_LDFLAGS=-L/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/lib                         -L/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/lib                         -Wl,--enable-new-dtags                         -Wl,-rpath-link,/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/lib                         -Wl,-rpath-link,/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/lib                         -Wl,-rpath,/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/lib                         -Wl,-rpath,/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/lib                         -Wl,-O1 -Wl,--allow-shlib-undefined -Wl,--dynamic-linker=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/sysroots-uninative/x86_64-linux/lib/ld-linux-x86-64.so.2', '-DBUILD_NM=nm', '-DBUILD_PYTHON=True', '-DBUILD_RANLIB=ranlib', '-DBUILD_STRIP=strip', '-DBUILD_TEST=True', '-DCMAKE_BUILD_TYPE=Release', '-DCMAKE_CXX_FLAGS= -O2 -pipe -g -feliminate-unused-debug-types -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0=/usr/src/debug/python3-torch/1.1.0-r0                      -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot=                      -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native=  ', '-DCMAKE_C_FLAGS= -O2 -pipe -g -feliminate-unused-debug-types -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0=/usr/src/debug/python3-torch/1.1.0-r0                      -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot=                      -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native=  ', '-DCMAKE_EXE_LINKER_FLAGS=-Wl,-O1 -Wl,--hash-style=gnu -Wl,--as-needed -fstack-protector-strong -Wl,-z,relro,-z,now', '-DCMAKE_INSTALL_PREFIX=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/git/torch', '-DCMAKE_PREFIX_PATH=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot/usr/lib/python3.7/site-packages', '-DCMAKE_SHARED_LINKER_FLAGS=-Wl,-O1 -Wl,--hash-style=gnu -Wl,--as-needed -fstack-protector-strong -Wl,-z,relro,-z,now', '-DINSTALL_TEST=True', '-DPYTHON_EXECUTABLE=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/bin/python3-native/python3', '-DPYTHON_INCLUDE_DIR=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot/usr/include/python3.7m', '-DPYTHON_LIBRARY=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot/usr/lib/libpython3.7m.so.1.0', '-DTORCH_BUILD_VERSION=1.2.0a0+a3346e1', '-DUSE_CUDA=False', '-DUSE_DISTRIBUTED=True', '-DUSE_FBGEMM=True', '-DUSE_NCCL=False', '-DUSE_NUMPY=True', '-DUSE_QNNPACK=True', '-DUSE_SYSTEM_EIGEN_INSTALL=OFF', '-DUSE_SYSTEM_NCCL=False', '/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/git']' returned non-zero exit status 1.
| ERROR: 'python3 setup.py build ' execution failed.
| WARNING: exit code 1 from a shell command.
| ERROR: Function failed: do_compile (log file is located at /home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/temp/log.do_compile.27625)
ERROR: Task (/home/ubuntu/Desktop/comp-jetson-yocto/layers/meta-comp/recipes-python/python3-torch/python3-torch_1.1.0.bb:do_compile) failed with exit code '1'
NOTE: Tasks Summary: Attempted 1770 tasks of which 1763 didn't need to be rerun and 1 failed.

Summary: 1 task failed:
  /home/ubuntu/Desktop/comp-jetson-yocto/layers/meta-comp/recipes-python/python3-torch/python3-torch_1.1.0.bb:do_compile
Summary: There was 1 WARNING message shown.
Summary: There were 2 ERROR messages shown, returning a non-zero exit code.**
</code>```

答:
root-cause of the problem is

```<code>if (NOT INTERN_BUILD_MOBILE)
  # ---[ Check that our programs run.  This is different from the native CMake
  # compiler check, which just tests if the program compiles and links.  This is
  # important because with ASAN you might need to help the compiled library find
  # some dynamic libraries.
  cmake_push_check_state(RESET)
  CHECK_C_SOURCE_RUNS("
  int main() { return 0; }
  " COMPILER_WORKS)
  if (NOT COMPILER_WORKS)
    # Force cmake to retest next time around
    unset(COMPILER_WORKS CACHE)
    message(FATAL_ERROR
        "Could not run a simple program built with your compiler. "
        "If you are trying to use -fsanitize=address, make sure "
        "libasan is properly installed on your system (you can confirm "
        "if the problem is this by attempting to build and run a "
        "small program.)")
  endif()
  cmake_pop_check_state()
endif()
</code>```

this is running program compiled.
but we are cross compiling here.
can you try setting INTERN_BUILD_MOBILE

```<code>set(INTERN_BUILD_MOBILE ON)
</code>```

I don't have direct source which will build on jetson-nano
but following is close may help progressing.
you can refer to this pull request for cross-compiling for android.

Happy to answer anything else you may need.

Body:
I am trying to create a simple Yocto Python Recipe for Python 3 PyTorch. The target is an SD Card Image for the NVIDIA Jetson Nano produced by Yocto from the meta-tegra layer. I can successfully compile and boot an image from meta-tegra without these recipes.

NVIDIA themselves have compiled and released the ".whl" Python packages and they are found here: https://devtalk.nvidia.com/default/topic/1048776/official-tensorflow-for-jetson-nano-/

Using their build instructions, I tried to write a Bitbake recipe to install PyTorch as follows:

SUMMARY = "Facebook PyTorch AI"
DESCRIPTION = "Facebook PyTorch AI"
HOMEPAGE = "https://pytorch.org/"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://LICENSE;md5=acf4d595f99e159bf31797aa872aef57"

inherit pypi
inherit setuptools3

#BBCLASSEXTEND = "native nativesdk"

DEPENDS += "python3-pytest-runner-native python3-pyyaml-native cmake-native"

do_configure_prepend() {
  USE_NCCL=0
  USE_DISTRIBUTED=0
  TORCH_CUDA_ARCH_LIST="5.3;6.2;7.2"
}

do_compile_prepend() {
  USE_NCCL=0
  USE_DISTRIBUTED=0
  TORCH_CUDA_ARCH_LIST="5.3;6.2;7.2"
}

SRC_URI = "gitsm://github.com/pytorch/pytorch.git;protocol=https"
SRCREV = "a3346e100e7f4e7ec90f18b7befcccc47d5a1c82"

S = "${WORKDIR}/git"

The problem is that I hit the following error. I think it has to do with my environment variables not being picked up becuase the error includes "-DUSE_CUDA=False", however when I look at the bitbake environment ( bitbake -e ), it seems to be there.

Here is the error:

**NOTE: Executing SetScene Tasks
NOTE: Executing RunQueue Tasks
ERROR: python3-torch-1.1.0-r0 do_compile: 'python3 setup.py build ' execution failed.
ERROR: python3-torch-1.1.0-r0 do_compile: Function failed: do_compile (log file is located at /home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/temp/log.do_compile.27625)
ERROR: Logfile of failure stored in: /home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/temp/log.do_compile.27625
Log data follows:
| DEBUG: Executing shell function do_compile
| -- The CXX compiler identification is GNU 7.2.1
| -- The C compiler identification is GNU 7.2.1
| -- Check for working CXX compiler: /home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/bin/aarch64-poky-linux/aarch64-poky-linux-g++
| -- Check for working CXX compiler: /home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/bin/aarch64-poky-linux/aarch64-poky-linux-g++ -- works
| -- Detecting CXX compiler ABI info
| -- Detecting CXX compiler ABI info - done
| -- Detecting CXX compile features
| -- Detecting CXX compile features - done
| -- Check for working C compiler: /home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/bin/aarch64-poky-linux/aarch64-poky-linux-gcc
| -- Check for working C compiler: /home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/bin/aarch64-poky-linux/aarch64-poky-linux-gcc -- works
| -- Detecting C compiler ABI info
| -- Detecting C compiler ABI info - done
| -- Detecting C compile features
| -- Detecting C compile features - done
| -- Not forcing any particular BLAS to be found
| -- Performing Test COMPILER_WORKS
| -- Performing Test COMPILER_WORKS - Failed
| CMake Error at cmake/MiscCheck.cmake:52 (message):
|   Could not run a simple program built with your compiler.  If you are trying
|   to use -fsanitize=address, make sure libasan is properly installed on your
|   system (you can confirm if the problem is this by attempting to build and
|   run a small program.)
| Call Stack (most recent call first):
|   CMakeLists.txt:271 (include)
|
|
| -- Configuring incomplete, errors occurred!
| See also "/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/git/build/CMakeFiles/CMakeOutput.log".
| See also "/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/git/build/CMakeFiles/CMakeError.log".
| Building wheel torch-1.2.0a0+a3346e1
| -- Building version 1.2.0a0+a3346e1
| cmake -DBUILD_AR=ar -DBUILD_AS=as  -DBUILD_CC=gcc  -DBUILD_CCLD=gcc  -DBUILD_CFLAGS=-isystem/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/include -O2 -pipe -DBUILD_CPP=gcc  -E -DBUILD_CPPFLAGS=-isystem/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/include -DBUILD_CXX=g++  -DBUILD_CXXFLAGS=-isystem/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/include -O2 -pipe -DBUILD_FC=gfortran  -DBUILD_LD=ld  -DBUILD_LDFLAGS=-L/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/lib                         -L/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/lib                         -Wl,--enable-new-dtags                         -Wl,-rpath-link,/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/lib                         -Wl,-rpath-link,/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/lib                         -Wl,-rpath,/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/lib                         -Wl,-rpath,/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/lib                         -Wl,-O1 -Wl,--allow-shlib-undefined -Wl,--dynamic-linker=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/sysroots-uninative/x86_64-linux/lib/ld-linux-x86-64.so.2 -DBUILD_NM=nm -DBUILD_PYTHON=True -DBUILD_RANLIB=ranlib -DBUILD_STRIP=strip -DBUILD_TEST=True -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS= -O2 -pipe -g -feliminate-unused-debug-types -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0=/usr/src/debug/python3-torch/1.1.0-r0                      -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot=                      -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native=   -DCMAKE_C_FLAGS= -O2 -pipe -g -feliminate-unused-debug-types -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0=/usr/src/debug/python3-torch/1.1.0-r0                      -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot=                      -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native=   -DCMAKE_EXE_LINKER_FLAGS=-Wl,-O1 -Wl,--hash-style=gnu -Wl,--as-needed -fstack-protector-strong -Wl,-z,relro,-z,now -DCMAKE_INSTALL_PREFIX=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/git/torch -DCMAKE_PREFIX_PATH=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot/usr/lib/python3.7/site-packages -DCMAKE_SHARED_LINKER_FLAGS=-Wl,-O1 -Wl,--hash-style=gnu -Wl,--as-needed -fstack-protector-strong -Wl,-z,relro,-z,now -DINSTALL_TEST=True -DPYTHON_EXECUTABLE=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/bin/python3-native/python3 -DPYTHON_INCLUDE_DIR=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot/usr/include/python3.7m -DPYTHON_LIBRARY=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot/usr/lib/libpython3.7m.so.1.0 -DTORCH_BUILD_VERSION=1.2.0a0+a3346e1 -DUSE_CUDA=False -DUSE_DISTRIBUTED=True -DUSE_FBGEMM=True -DUSE_NCCL=False -DUSE_NUMPY=True -DUSE_QNNPACK=True -DUSE_SYSTEM_EIGEN_INSTALL=OFF -DUSE_SYSTEM_NCCL=False /home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/git
| Traceback (most recent call last):
|   File "setup.py", line 749, in <module>
|     build_deps()
|   File "setup.py", line 323, in build_deps
|     cmake=cmake)
|   File "/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/git/tools/build_pytorch_libs.py", line 61, in build_caffe2
|     rerun_cmake)
|   File "/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/git/tools/setup_helpers/cmake.py", line 318, in generate
|     self.run(args, env=my_env)
|   File "/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/git/tools/setup_helpers/cmake.py", line 93, in run
|     check_call(command, cwd=self.build_dir, env=env)
|   File "/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/lib/python3.7/subprocess.py", line 347, in check_call
|     raise CalledProcessError(retcode, cmd)
| subprocess.CalledProcessError: Command '['cmake', '-DBUILD_AR=ar', '-DBUILD_AS=as ', '-DBUILD_CC=gcc ', '-DBUILD_CCLD=gcc ', '-DBUILD_CFLAGS=-isystem/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/include -O2 -pipe', '-DBUILD_CPP=gcc  -E', '-DBUILD_CPPFLAGS=-isystem/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/include', '-DBUILD_CXX=g++ ', '-DBUILD_CXXFLAGS=-isystem/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/include -O2 -pipe', '-DBUILD_FC=gfortran ', '-DBUILD_LD=ld ', '-DBUILD_LDFLAGS=-L/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/lib                         -L/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/lib                         -Wl,--enable-new-dtags                         -Wl,-rpath-link,/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/lib                         -Wl,-rpath-link,/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/lib                         -Wl,-rpath,/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/lib                         -Wl,-rpath,/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/lib                         -Wl,-O1 -Wl,--allow-shlib-undefined -Wl,--dynamic-linker=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/sysroots-uninative/x86_64-linux/lib/ld-linux-x86-64.so.2', '-DBUILD_NM=nm', '-DBUILD_PYTHON=True', '-DBUILD_RANLIB=ranlib', '-DBUILD_STRIP=strip', '-DBUILD_TEST=True', '-DCMAKE_BUILD_TYPE=Release', '-DCMAKE_CXX_FLAGS= -O2 -pipe -g -feliminate-unused-debug-types -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0=/usr/src/debug/python3-torch/1.1.0-r0                      -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot=                      -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native=  ', '-DCMAKE_C_FLAGS= -O2 -pipe -g -feliminate-unused-debug-types -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0=/usr/src/debug/python3-torch/1.1.0-r0                      -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot=                      -fdebug-prefix-map=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native=  ', '-DCMAKE_EXE_LINKER_FLAGS=-Wl,-O1 -Wl,--hash-style=gnu -Wl,--as-needed -fstack-protector-strong -Wl,-z,relro,-z,now', '-DCMAKE_INSTALL_PREFIX=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/git/torch', '-DCMAKE_PREFIX_PATH=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot/usr/lib/python3.7/site-packages', '-DCMAKE_SHARED_LINKER_FLAGS=-Wl,-O1 -Wl,--hash-style=gnu -Wl,--as-needed -fstack-protector-strong -Wl,-z,relro,-z,now', '-DINSTALL_TEST=True', '-DPYTHON_EXECUTABLE=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot-native/usr/bin/python3-native/python3', '-DPYTHON_INCLUDE_DIR=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot/usr/include/python3.7m', '-DPYTHON_LIBRARY=/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/recipe-sysroot/usr/lib/libpython3.7m.so.1.0', '-DTORCH_BUILD_VERSION=1.2.0a0+a3346e1', '-DUSE_CUDA=False', '-DUSE_DISTRIBUTED=True', '-DUSE_FBGEMM=True', '-DUSE_NCCL=False', '-DUSE_NUMPY=True', '-DUSE_QNNPACK=True', '-DUSE_SYSTEM_EIGEN_INSTALL=OFF', '-DUSE_SYSTEM_NCCL=False', '/home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/git']' returned non-zero exit status 1.
| ERROR: 'python3 setup.py build ' execution failed.
| WARNING: exit code 1 from a shell command.
| ERROR: Function failed: do_compile (log file is located at /home/ubuntu/Desktop/comp-jetson-yocto/build/tmp/work/aarch64-poky-linux/python3-torch/1.1.0-r0/temp/log.do_compile.27625)
ERROR: Task (/home/ubuntu/Desktop/comp-jetson-yocto/layers/meta-comp/recipes-python/python3-torch/python3-torch_1.1.0.bb:do_compile) failed with exit code '1'
NOTE: Tasks Summary: Attempted 1770 tasks of which 1763 didn't need to be rerun and 1 failed.

Summary: 1 task failed:
  /home/ubuntu/Desktop/comp-jetson-yocto/layers/meta-comp/recipes-python/python3-torch/python3-torch_1.1.0.bb:do_compile
Summary: There was 1 WARNING message shown.
Summary: There were 2 ERROR messages shown, returning a non-zero exit code.**

Body:
root-cause of the problem is

if (NOT INTERN_BUILD_MOBILE)
  # ---[ Check that our programs run.  This is different from the native CMake
  # compiler check, which just tests if the program compiles and links.  This is
  # important because with ASAN you might need to help the compiled library find
  # some dynamic libraries.
  cmake_push_check_state(RESET)
  CHECK_C_SOURCE_RUNS("
  int main() { return 0; }
  " COMPILER_WORKS)
  if (NOT COMPILER_WORKS)
    # Force cmake to retest next time around
    unset(COMPILER_WORKS CACHE)
    message(FATAL_ERROR
        "Could not run a simple program built with your compiler. "
        "If you are trying to use -fsanitize=address, make sure "
        "libasan is properly installed on your system (you can confirm "
        "if the problem is this by attempting to build and run a "
        "small program.)")
  endif()
  cmake_pop_check_state()
endif()

this is running program compiled.
but we are cross compiling here.
can you try setting INTERN_BUILD_MOBILE

set(INTERN_BUILD_MOBILE ON)

I don't have direct source which will build on jetson-nano
but following is close may help progressing.
you can refer to this pull request for cross-compiling for android.

Happy to answer anything else you may need.


问:
java: TimeZone in rest api
In my jersey rest api when a user sends a POST request

```<code>{
   "user":"john",
   "question":"what was temperature an hour ago"
}
</code>```

a QuestionProcessor transforms the String an hour ago into LocalDateTime.now(ZoneId.of(UTC)).minusHours(5).format(dateformatter);

I want to replace the UTC default by the users timezone. How can I do that?

Thanks for the help

答:
You asked:

replace the UTC default by the users timezone

Easy:

```<code>ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ;
ZonedDateTime then = now.minusHours( 1 ) ;
</code>```

The catch: You must know the user’s time zone name such as Africa/Tunis, Europe/Paris, Asia/Kolkata, Pacific/Auckland, or America/Montreal.

You need to reformulate your REST API to also pass a field for time zone name.

Specify a proper time zone name in the format of Continent/Region, such as examples seen above. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

By the way, I cannot imagine when calling LocalDateTime.now is the right thing to do. That class cannot represent a moment as it purposely lacks the context of an offset-from-UTC or time zone. Use Instant, OffsetDateTime, or ZonedDateTime instead.

Title: java: TimeZone in rest api

Body:
In my jersey rest api when a user sends a POST request

{
   "user":"john",
   "question":"what was temperature an hour ago"
}

a QuestionProcessor transforms the String an hour ago into LocalDateTime.now(ZoneId.of(UTC)).minusHours(5).format(dateformatter);

I want to replace the UTC default by the users timezone. How can I do that?

Thanks for the help

Body:
You asked:

replace the UTC default by the users timezone

Easy:

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ;
ZonedDateTime then = now.minusHours( 1 ) ;

The catch: You must know the user’s time zone name such as Africa/Tunis, Europe/Paris, Asia/Kolkata, Pacific/Auckland, or America/Montreal.

You need to reformulate your REST API to also pass a field for time zone name.

Specify a proper time zone name in the format of Continent/Region, such as examples seen above. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

By the way, I cannot imagine when calling LocalDateTime.now is the right thing to do. That class cannot represent a moment as it purposely lacks the context of an offset-from-UTC or time zone. Use Instant, OffsetDateTime, or ZonedDateTime instead.


问:
Problem with SqlConnection, ASP.net C#
I have the following C# code:

```<code>public string TargetDate()
{
    SqlConnection con =
        new SqlConnection("Server=localhost;Database=Timer;Trusted_Connectopn=True");
    SqlCommand cmd = new SqlCommand("select * from Timer");
    con.Open();

    DataSet ds = new DataSet(cmd,con);
    SqlDataAdapter da = new SqlDataAdapter();
    da.Fill(ds);
    con.Close();
}
</code>```

but I get error at the: new DataSet(cmd,con); ...

the error: CS1502: The best overloaded
  method match for

```<code>'System.Data.DataSet.DataSet(System.Runtime.Serialization.SerializationInfo,
</code>```

System.Runtime.Serialization.StreamingContext)'
  has some invalid arguments

What is could be the problem?

答:
You've got the wrong constructor for the DataSet. Try this</p>

```<code>DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(con);
</code>```

Title: Problem with SqlConnection, ASP.net C#

Body:
I have the following C# code:

public string TargetDate()
{
    SqlConnection con =
        new SqlConnection("Server=localhost;Database=Timer;Trusted_Connectopn=True");
    SqlCommand cmd = new SqlCommand("select * from Timer");
    con.Open();

    DataSet ds = new DataSet(cmd,con);
    SqlDataAdapter da = new SqlDataAdapter();
    da.Fill(ds);
    con.Close();
}

but I get error at the: new DataSet(cmd,con); ...

the error: CS1502: The best overloaded
  method match for

'System.Data.DataSet.DataSet(System.Runtime.Serialization.SerializationInfo,

System.Runtime.Serialization.StreamingContext)'
  has some invalid arguments

What is could be the problem?

Body:
You've got the wrong constructor for the DataSet. Try this

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(con);


问:
Correct way to deploy WAR files in docker image
What is the docker way to deploy java projects in a docker container?

Do I copy the war into webapps:

```<code>FROM jetty:9.2.10
MAINTAINER Me "me@me.com"
ADD ./target/*.war /var/lib/jetty/webapps/ROOT.war
</code>```

or do I take the exploded war file:

```<code>FROM jetty:9.2.10
MAINTAINER Me "me@me.com"
ADD ./target/app-0.1.0.BUILD-SNAPSHOT /var/lib/jetty/webapps/ROOT
</code>```

Normally one would deploy the sealed war file if it was a normal container, but with docker, that means pushing a 10-20MB file every time you make a small change whereas adding the exploded war would only push the difference - the .class file that has changed.

Are there any downsides to deploying the exploded war instead of the war file?

答:
If you stumbled here, like I did, looking for how to simply get a WAR deployed in a container (using Apache Tomcat), and didn't care whether or not you have a Dockerfile.

A simple, elegant solution.

```<code>docker run \
-d \ # Detached mode, swap for -it if we want interactive.
-p 8080:8080  \
-v ${absolute_path_your_project_dir}/${MY_WAR}.war:/usr/local/tomcat/webapps/app.war \
tomcat:latest
</code>```

Then navigate to http://localhost:8080/app/.

If that link doesn't work for you, be sure to change ...8080/app/ in the URL to whatever matches the .war name you gave in /usr/local/tomcat/webapps/app.war.

I also found that, while working through IntelliJ's Docker Plugin, it's easy to adapt this to Docker Plugins. Just be sure to put in your full path.

Body:
What is the docker way to deploy java projects in a docker container?

Do I copy the war into webapps:

FROM jetty:9.2.10
MAINTAINER Me "me@me.com"
ADD ./target/*.war /var/lib/jetty/webapps/ROOT.war

or do I take the exploded war file:

FROM jetty:9.2.10
MAINTAINER Me "me@me.com"
ADD ./target/app-0.1.0.BUILD-SNAPSHOT /var/lib/jetty/webapps/ROOT

Normally one would deploy the sealed war file if it was a normal container, but with docker, that means pushing a 10-20MB file every time you make a small change whereas adding the exploded war would only push the difference - the .class file that has changed.

Are there any downsides to deploying the exploded war instead of the war file?

Body:
If you stumbled here, like I did, looking for how to simply get a WAR deployed in a container (using Apache Tomcat), and didn't care whether or not you have a Dockerfile.

A simple, elegant solution.

docker run \
-d \ # Detached mode, swap for -it if we want interactive.
-p 8080:8080  \
-v ${absolute_path_your_project_dir}/${MY_WAR}.war:/usr/local/tomcat/webapps/app.war \
tomcat:latest

Then navigate to http://localhost:8080/app/.

If that link doesn't work for you, be sure to change ...8080/app/ in the URL to whatever matches the .war name you gave in /usr/local/tomcat/webapps/app.war.

I also found that, while working through IntelliJ's Docker Plugin, it's easy to adapt this to Docker Plugins. Just be sure to put in your full path.


问:
In Next.js, how to create a bg image that covers the entire browser window
In the following picture, we have to apply height 100% to both html and body tags. But how to do that in a next.js component??

Refer [1]: https://i.stack.imgur.com/K1r9l.png

[2] https://www.w3schools.com/howto/howto_css_full_page.asp

"mainImage.jsx"

```<code>import React from 'react';
import './mainImage.css'

export default ()=>(
    <div>
        <div className="bg"></div>
    </div>
)
</code>```

"mainImage.css"

```<code>.bg {
    /* The image used */
    background-image: url("/public/jeep3.jpg");

    /* Full height */
    height: 100vh;

    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}
</code>```

after applying height:100vh; i just show the empty div with length not the image.

答:
You need to change height value to :</p>

```<code>.bg {

height:100vh;

}
</code>```

Body:
In the following picture, we have to apply height 100% to both html and body tags. But how to do that in a next.js component??

Refer [1]: https://i.stack.imgur.com/K1r9l.png

[2] https://www.w3schools.com/howto/howto_css_full_page.asp

"mainImage.jsx"

import React from 'react';
import './mainImage.css'

export default ()=>(

)

"mainImage.css"

.bg {
    /* The image used */
    background-image: url("/public/jeep3.jpg");

    /* Full height */
    height: 100vh;

    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}

after applying height:100vh; i just show the empty div with length not the image.

Body:
You need to change height value to :

.bg {

height:100vh;

}


问:
Delete AWS Log Groups that haven't been touched in X days
Is there a way to delete all AWS Log Groups that haven't had any writes to them in the past 30 days?

Or conversely, get the list of log groups that haven't had anything written to them in the past 30 days?

答:
Here is some quick script I wrote:</p>

```<code>#!/usr/bin/python3

# describe log groups
# describe log streams
# get log groups with the lastEventTimestamp after some time
# delete those log groups
# have a dry run option
# support profile

# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/logs.html#CloudWatchLogs.Client.describe_log_streams
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/logs.html#CloudWatchLogs.Client.describe_log_groups
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/logs.html#CloudWatchLogs.Client.delete_log_group

import boto3
import time
millis = int(round(time.time() * 1000))

delete = False
debug = False
log_group_prefix='/' # NEED TO CHANGE THESE

days = 30
# Create CloudWatchLogs client
cloudwatch_logs = boto3.client('logs')

log_groups=[]
# List log groups through the pagination interface
paginator = cloudwatch_logs.get_paginator('describe_log_groups')
for response in paginator.paginate(logGroupNamePrefix=log_group_prefix):
    for log_group in response['logGroups']:
        log_groups.append(log_group['logGroupName'])

if debug:
    print(log_groups)

old_log_groups=[]
empty_log_groups=[]
for log_group in log_groups:
    response = cloudwatch_logs.describe_log_streams(
        logGroupName=log_group, #logStreamNamePrefix='',
        orderBy='LastEventTime',
        descending=True,
        limit=1
    )
    # The time of the most recent log event in the log stream in CloudWatch Logs. This number is expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
    if len(response['logStreams']) > 0:
        if debug:
            print("full response is:")
            print(response)
            print("Last event is:")
            print(response['logStreams'][0]['lastEventTimestamp'])
            print("current millis is:")
            print(millis)
        if response['logStreams'][0]['lastEventTimestamp'] < millis - (days * 24 * 60 * 60 * 1000):
            old_log_groups.append(log_group)
    else:
        empty_log_groups.append(log_group)

# delete log group
if delete:
    for log_group in old_log_groups:
        response = cloudwatch_logs.delete_log_group(logGroupName=log_group)
    #for log_group in empty_log_groups:
    #    response = cloudwatch_logs.delete_log_group(logGroupName=log_group)
else:
    print("old log groups are:")
    print(old_log_groups)
    print("Number of log groups:")
    print(len(old_log_groups))
    print("empty log groups are:")
    print(empty_log_groups)
</code>```

Body:
Here is some quick script I wrote:

#!/usr/bin/python3

# describe log groups
# describe log streams
# get log groups with the lastEventTimestamp after some time
# delete those log groups
# have a dry run option
# support profile

# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/logs.html#CloudWatchLogs.Client.describe_log_streams
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/logs.html#CloudWatchLogs.Client.describe_log_groups
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/logs.html#CloudWatchLogs.Client.delete_log_group

import boto3
import time
millis = int(round(time.time() * 1000))

delete = False
debug = False
log_group_prefix='/' # NEED TO CHANGE THESE

days = 30
# Create CloudWatchLogs client
cloudwatch_logs = boto3.client('logs')

log_groups=[]
# List log groups through the pagination interface
paginator = cloudwatch_logs.get_paginator('describe_log_groups')
for response in paginator.paginate(logGroupNamePrefix=log_group_prefix):
    for log_group in response['logGroups']:
        log_groups.append(log_group['logGroupName'])

if debug:
    print(log_groups)

old_log_groups=[]
empty_log_groups=[]
for log_group in log_groups:
    response = cloudwatch_logs.describe_log_streams(
        logGroupName=log_group, #logStreamNamePrefix='',
        orderBy='LastEventTime',
        descending=True,
        limit=1
    )
    # The time of the most recent log event in the log stream in CloudWatch Logs. This number is expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
    if len(response['logStreams']) > 0:
        if debug:
            print("full response is:")
            print(response)
            print("Last event is:")
            print(response['logStreams'][0]['lastEventTimestamp'])
            print("current millis is:")
            print(millis)
        if response['logStreams'][0]['lastEventTimestamp'] < millis - (days * 24 * 60 * 60 * 1000):
            old_log_groups.append(log_group)
    else:
        empty_log_groups.append(log_group)

# delete log group
if delete:
    for log_group in old_log_groups:
        response = cloudwatch_logs.delete_log_group(logGroupName=log_group)
    #for log_group in empty_log_groups:
    #    response = cloudwatch_logs.delete_log_group(logGroupName=log_group)
else:
    print("old log groups are:")
    print(old_log_groups)
    print("Number of log groups:")
    print(len(old_log_groups))
    print("empty log groups are:")
    print(empty_log_groups)


问:
Python - How to update a value in a json file?
I hate json files. They are unwieldy and hard to handle :( Please tell me why the following doesn't work:

```<code>with open('data.json', 'r+') as file_object:
        data = json.load(file_object)[user_1]['balance']
        am_nt = 5
        data += int(am_nt['amount'])
        print(data)
        file_object[user_1]['balance'] = data
</code>```

Through trial and error (and many print statements), I have discovered that it opens the file, goes to the correct place, and then actually adds the am_nt, but I can't make the original json file update. Please help me :( :( . I get:

```<code>2000
TypeError: '_io.TextIOWrapper' object is not subscriptable
</code>```

答:
json is fun to work with as it is similar to python data structures.

The error is: object is not subscriptable
This error is for this line:
    file_object[user_1]['balance'] = data

file_object is not  json/dictionary data that can be updated like above. Hence the error.

Try to read the json data:
    data=json.load(file_object)

Then manipulate the data as python dictionary. And save the file.

Body:
I hate json files. They are unwieldy and hard to handle :( Please tell me why the following doesn't work:

with open('data.json', 'r+') as file_object:
        data = json.load(file_object)[user_1]['balance']
        am_nt = 5
        data += int(am_nt['amount'])
        print(data)
        file_object[user_1]['balance'] = data

Through trial and error (and many print statements), I have discovered that it opens the file, goes to the correct place, and then actually adds the am_nt, but I can't make the original json file update. Please help me :( :( . I get:

2000
TypeError: '_io.TextIOWrapper' object is not subscriptable


问:
React Router: How to render element on all routes, except one?
I have HTML structure like this:

```

<p>And routing defined like this:</p>

<pre class="lang-js prettyprint-override"><code><Router>
  <Fragment>
    <Navbar />
    <Route exact path="/" component={Landing} />
    <div className="container">
       <Alert />
       <Switch>
           <Route exact path="/register" component={Register} />
           <Route exact path="/login" component={Login} />
           <Route exact path="/profiles" component={Profiles} />
       </Switch>
    </div>
  </Fragment>
</Router>
</code>```

The "container" element is present on all routes however I do not want it to be rendered on the "/" route.

How can I stop
 from being rendered on the "/" route? I want it to be rendered on all other routes except of "/".

A solution I found, but don't want to use is to explicitly insert the element with class="container" in each component that is rendered in my <Switch>. Is there a better way?

答:
If you don't want to create a separate component, you can just do this. You need to keep the inner switch as well, if you want to keep the original functionality.

```<code>// parent switch
<Switch>
  <Route exact path="/" component={Landing} />
  // start route wrap!!!
  <Route>
    <div className="container">
      <Switch>
        <Route exact path="/register" component={Register} />
        <Route exact path="/login" component={Login} />
        <Route exact path="/profiles" component={Profiles} />
      </Switch>
    </div>
  </Route>
 // end route wrap!!!
</Switch>
</code>```

You should think of Routes as of any other UI components. You can nest them arbitrarily.

Body:
I have HTML structure like this:

And routing defined like this:

<Router>
  <Fragment>
    <Navbar />
    <Route exact path="/" component={Landing} />

       <Alert />
       <Switch>
           <Route exact path="/register" component={Register} />
           <Route exact path="/login" component={Login} />
           <Route exact path="/profiles" component={Profiles} />
       </Switch>

  </Fragment>
</Router>

The "container" element is present on all routes however I do not want it to be rendered on the "/" route.

How can I stop
 from being rendered on the "/" route? I want it to be rendered on all other routes except of "/".

A solution I found, but don't want to use is to explicitly insert the element with class="container" in each component that is rendered in my <Switch>. Is there a better way?

Body:
If you don't want to create a separate component, you can just do this. You need to keep the inner switch as well, if you want to keep the original functionality.

// parent switch
<Switch>
  <Route exact path="/" component={Landing} />
  // start route wrap!!!
  <Route>
    <div className="container">
      <Switch>
        <Route exact path="/register" component={Register} />
        <Route exact path="/login" component={Login} />
        <Route exact path="/profiles" component={Profiles} />
      </Switch>
    </div>
  </Route>
 // end route wrap!!!
</Switch>

You should think of Routes as of any other UI components. You can nest them arbitrarily.


问:
Corrupted PDF from direct url in SSRS
I am trying to generate a direct url to my report so it can be downloaded as PDF instead of redirect to the report UI.
If I paste the url on the browser it just redirects me to the report's page.
I found 2 solutions to my problem but both generate a corrupted pdf.</p>

```<code>        public ActionResult GetReportingData()
        {
            var theURL = "http://servername/Reports_DomainName/Pages/Report.aspx?ItemPath=%2fMQMS2_TST%2fReportTest&year=2019&rs:Format=PDF";

            WebClient Client = new WebClient();
            Client.Credentials = new NetworkCredential(@"username", "password");

            byte[] myDataBuffer = Client.DownloadData(theURL);

            var filename = "Test.pdf";
            var path = "C:\\Test";

            var fileLocation = path + "\\" + filename;

            System.IO.File.WriteAllBytes(fileLocation, myDataBuffer);
            return RedirectToAction("Index", "Case");
        }
</code>```

```<code>        public ActionResult GetReportingData()
        {
            var url = "http://servername/Reports_DomainName/Pages/Report.aspx?ItemPath=%2fMQMS2_TST%2fReportTest&year=2019&rs:Format=PDF";
            try
            {
                url = url.Replace("\n", "");
                WebRequest request = WebRequest.Create(url);

                NetworkCredential credentials = new NetworkCredential(@"username", "password");
                request.Credentials = credentials;

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream stream = response.GetResponseStream();

                return new FileStreamResult(stream, "application/pdf");
            }
            catch (Exception ex)
            {
                return RedirectToAction("Index", "Case");
            }
        }
</code>```

答:
I found the error.

This is the link for the asnwer: SSRS Report Render report in PDF Via URL

Basically I was using the web portal url (wrong) instead of the web service url (correct):

Original (wrong url): http://servername/Reports_DomainName/Pages/Report.aspx?ItemPath=%2fMQMS2_TST%2fReportTest&year=2019&rs:Format=PDF

Correct url: http://servername/ReportServer_DomainName/Pages/Report.aspx?ItemPath=%2fMQMS2_TST%2fReportTest&year=2019&rs:Format=PDF

Title: Corrupted PDF from direct url in SSRS

Body:
I am trying to generate a direct url to my report so it can be downloaded as PDF instead of redirect to the report UI.
If I paste the url on the browser it just redirects me to the report's page.
I found 2 solutions to my problem but both generate a corrupted pdf.

        public ActionResult GetReportingData()
        {
            var theURL = "http://servername/Reports_DomainName/Pages/Report.aspx?ItemPath=%2fMQMS2_TST%2fReportTest&year=2019&rs:Format=PDF";

            WebClient Client = new WebClient();
            Client.Credentials = new NetworkCredential(@"username", "password");

            byte[] myDataBuffer = Client.DownloadData(theURL);

            var filename = "Test.pdf";
            var path = "C:\\Test";

            var fileLocation = path + "\\" + filename;

            System.IO.File.WriteAllBytes(fileLocation, myDataBuffer);
            return RedirectToAction("Index", "Case");
        }

        public ActionResult GetReportingData()
        {
            var url = "http://servername/Reports_DomainName/Pages/Report.aspx?ItemPath=%2fMQMS2_TST%2fReportTest&year=2019&rs:Format=PDF";
            try
            {
                url = url.Replace("\n", "");
                WebRequest request = WebRequest.Create(url);

                NetworkCredential credentials = new NetworkCredential(@"username", "password");
                request.Credentials = credentials;

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream stream = response.GetResponseStream();

                return new FileStreamResult(stream, "application/pdf");
            }
            catch (Exception ex)
            {
                return RedirectToAction("Index", "Case");
            }
        }


问:
Best practice to design a ViewModel containing display data and binding data for HttpGet and HttpPost
I've been reading StackOverflow for quite a while now and it's time for my first post:

I'm currently using C# / ASP.NET Core 3.1. What's the best practice to design a ViewModel containing display data and binding data for HttpGet and HttpPost. I found some discussions on keeping display and binding data separated or not separated but without any examples. The problem with using the same ViewModel on HttpPost (without binding attributes) is that Display Data references get an invalid modelstate because they are of course null in the incoming model.

I usually tend to use the following stripped-down code. Is inheritance the way to go or any other sort of pattern? Or is it better to put everything in the view model with binding attributes for non-binding data?

Thanks all!

```<code>public class CMyBindModel
{
  public int ProductQuantity ( get; set; }    // Binding Data

  // Other Binding properties ...
}

public class CMyViewModel : CMyBindModel
{
  public string ProductName ( get; set; }    // Display Data

  // Other Display properties ...
}
</code>```

```<code>public IActionResult Cart ()
{
  CMyViewModel viewModel = BuildViewModel () ;
  return View (viewModel) ;
}

[HttpPost]
public IActionResult Cart (CMyBindModel bindModel)
{
  if (ModelState.IsValid)
  {
    SetProductQuantity (bindModel.ProductQuantity) ;
    return RedirectToAction ("Cart") ;
  }

  CMyViewModel viewModel = BuildViewModel () ;
  return View (viewModel) ;
}
</code>```

```<code>Cart.cshtml

@model CMyViewModel

<div>@Model.ProductName</div>

<form method="post" asp-area="" asp-controller="CartController" asp-action="Cart">
  <input asp-for="ProductQuantity" />
  <button type="submit">Update</button>
</form>
</code>```

答:
The problem on using the same ViewModel on HttpPost (without binding attributes) is that Display Data references get an invalid modelstate because they are of course null in the incoming model.

By using the same ViewModel(here is CMyViewModel),you could overcome the validation error by removing the field from ModelState prior to judging ModelState.IsValid.

Refer to my simple demo:

Model:

```<code>public class CMyViewModel
{
    [Required]
    public int ProductQuantity { get; set; }  // Binding Data

    // Other Binding properties ...

    [Required]
    public string ProductName{get; set; }    // Display Data

    // Other Displaying properties ...
}
</code>```

Actions:

```<code>public void RemoveDisplayingDataValidation()
{
    ModelState.Remove("ProductName");
    //remove other Displaying properties' validation
}

[HttpPost]
public IActionResult Cart(CMyViewModel viewModel)
{
    RemoveDisplayingDataValidation();
    if (ModelState.IsValid)
    {
        SetProductQuantity (viewModel.ProductQuantity) ;
        return RedirectToAction("Cart");
    }

    CMyViewModel viewModel = BuildViewModel () ;
    return View(viewModel);
}
</code>```

Refer to ModelState.IsValid does not exclude required property

Besides, Christoph Lütjen's suggestion of using two models separately also will work.

Body:
I've been reading StackOverflow for quite a while now and it's time for my first post:

I'm currently using C# / ASP.NET Core 3.1. What's the best practice to design a ViewModel containing display data and binding data for HttpGet and HttpPost. I found some discussions on keeping display and binding data separated or not separated but without any examples. The problem with using the same ViewModel on HttpPost (without binding attributes) is that Display Data references get an invalid modelstate because they are of course null in the incoming model.

I usually tend to use the following stripped-down code. Is inheritance the way to go or any other sort of pattern? Or is it better to put everything in the view model with binding attributes for non-binding data?

Thanks all!

public class CMyBindModel
{
  public int ProductQuantity ( get; set; }    // Binding Data

  // Other Binding properties ...
}

public class CMyViewModel : CMyBindModel
{
  public string ProductName ( get; set; }    // Display Data

  // Other Display properties ...
}

public IActionResult Cart ()
{
  CMyViewModel viewModel = BuildViewModel () ;
  return View (viewModel) ;
}

[HttpPost]
public IActionResult Cart (CMyBindModel bindModel)
{
  if (ModelState.IsValid)
  {
    SetProductQuantity (bindModel.ProductQuantity) ;
    return RedirectToAction ("Cart") ;
  }

  CMyViewModel viewModel = BuildViewModel () ;
  return View (viewModel) ;
}

Cart.cshtml

@model CMyViewModel

@Model.ProductName

<form method="post" asp-area="" asp-controller="CartController" asp-action="Cart">
  <input asp-for="ProductQuantity" />
  <button type="submit">Update</button>
</form>

Body:
The problem on using the same ViewModel on HttpPost (without binding attributes) is that Display Data references get an invalid modelstate because they are of course null in the incoming model.

By using the same ViewModel(here is CMyViewModel),you could overcome the validation error by removing the field from ModelState prior to judging ModelState.IsValid.

Refer to my simple demo:

Model:

public class CMyViewModel
{
    [Required]
    public int ProductQuantity { get; set; }  // Binding Data

    // Other Binding properties ...

    [Required]
    public string ProductName{get; set; }    // Display Data

    // Other Displaying properties ...
}

Actions:

public void RemoveDisplayingDataValidation()
{
    ModelState.Remove("ProductName");
    //remove other Displaying properties' validation
}

[HttpPost]
public IActionResult Cart(CMyViewModel viewModel)
{
    RemoveDisplayingDataValidation();
    if (ModelState.IsValid)
    {
        SetProductQuantity (viewModel.ProductQuantity) ;
        return RedirectToAction("Cart");
    }

    CMyViewModel viewModel = BuildViewModel () ;
    return View(viewModel);
}

Refer to ModelState.IsValid does not exclude required property

Besides, Christoph Lütjen's suggestion of using two models separately also will work.