问:
Assemble multiple lists into a single list through a loop
As part of an application reading Csv files made using tkinder and the tksheet library, I would have liked to ensure that each of the lines retrieved from my spreadsheet and individually transformed into a list could be grouped into a single and unique comma separated list.

I currently have the following code:

with open('my_csv_file.csv') as csvfile:
     reader = csv.reader(csvfile, delimiter=';')

     for row in reader:
         if row != '' and row[0].isdigit():
            liste = [row[0], row[1], row[2], row[3], row[4]]
            print(liste)
```
<p>Output :</p>
```['AAA', 'AAA', 'AAA', 'AAA', 'AAA']
['BBB', 'BBB', 'BBB', 'BBB', 'BBB']
['CCC', 'CCC', 'CCC', 'CCC', 'CCC']
```
<p>What I want:</p>
```[['AAA', 'AAA', 'AAA', 'AAA', 'AAA'],
['BBB', 'BBB', 'BBB', 'BBB', 'BBB'],
['CCC', 'CCC', 'CCC', 'CCC', 'CCC']]
```

答:
you can add list and append list in the list with  list +=

```<code>with open('my_csv_file.csv') as csvfile:
     res = []
     reader = csv.reader(csvfile, delimiter=';')

     for row in reader:
         if row != '' and row[0].isdigit():
            res += [[row[0], row[1], row[2], row[3], row[4]]]

</code>```

or you can use append

```<code>with open('my_csv_file.csv') as csvfile:
     res = []
     reader = csv.reader(csvfile, delimiter=';')

     for row in reader:
         if row != '' and row[0].isdigit():
            res.append([row[0], row[1], row[2], row[3], row[4]])

</code>```

Body:
As part of an application reading Csv files made using tkinder and the tksheet library, I would have liked to ensure that each of the lines retrieved from my spreadsheet and individually transformed into a list could be grouped into a single and unique comma separated list.

I currently have the following code:

with open('my_csv_file.csv') as csvfile:
     reader = csv.reader(csvfile, delimiter=';')

     for row in reader:
         if row != '' and row[0].isdigit():
            liste = [row[0], row[1], row[2], row[3], row[4]]
            print(liste)

Output :

['AAA', 'AAA', 'AAA', 'AAA', 'AAA']
['BBB', 'BBB', 'BBB', 'BBB', 'BBB']
['CCC', 'CCC', 'CCC', 'CCC', 'CCC']

What I want:

[['AAA', 'AAA', 'AAA', 'AAA', 'AAA'],
['BBB', 'BBB', 'BBB', 'BBB', 'BBB'],
['CCC', 'CCC', 'CCC', 'CCC', 'CCC']]

Body:
you can add list and append list in the list with  list +=

with open('my_csv_file.csv') as csvfile:
     res = []
     reader = csv.reader(csvfile, delimiter=';')

     for row in reader:
         if row != '' and row[0].isdigit():
            res += [[row[0], row[1], row[2], row[3], row[4]]]

or you can use append

with open('my_csv_file.csv') as csvfile:
     res = []
     reader = csv.reader(csvfile, delimiter=';')

     for row in reader:
         if row != '' and row[0].isdigit():
            res.append([row[0], row[1], row[2], row[3], row[4]])


来源: stackexchange

问:
juiceshop heroku forge unsigned token challenge not solved
I recently deployed Juiceshop on Heroku and am trying to solve the challenge of forging an unsigned JWT token using Burpsuite. I followed the hints provided in the ebook starting from using burpsuite to get a valid JWT token from the request header using the proxy tab on the /rest/user/whoami URL and sent it to the repeater. In the repeater tab, I changed the alg property in the token to "none" and the email to "jwtn3d@juice-sh.op". I then encoded them in base64 and put a period after the header and payload respectively in the token value. When I send the request, I get a HTTP 200 OK status and the jwtn3d@juice-sh.op email is reflected as well, but the juiceshop challenge doesn't seem to be solved. When I reload the website, I'm not logged in as jwtn3d@juice-sh.op either.

```<code>Server: Cowboy
Connection: close
Access-Control-Allow-Origin: *
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Feature-Policy: payment 'self'
Set-Cookie: token=ewogICJ0eXAiOiAiSldUIiwKICAiYWxnIjogIm5vbmUiCn0.ewogICJzdGF0dXMiOiAic3VjY2VzcyIsCiAgImRhdGEiOiB7CiAgICAiaWQiOiAxLAogICAgInVzZXJuYW1lIjogIiIsCiAgICAiZW1haWwiOiAiand0bjNkQGp1aWNlLXNoLm9wIiwKICAgICJwYXNzd29yZCI6ICIwMTkyMDIzYTdiYmQ3MzI1MDUxNmYwNjlkZjE4YjUwMCIsCiAgICAicm9sZSI6ICJhZG1pbiIsCiAgICAiZGVsdXhlVG9rZW4iOiAiIiwKICAgICJsYXN0TG9naW5JcCI6ICIwLjAuMC4wIiwKICAgICJwcm9maWxlSW1hZ2UiOiAiYXNzZXRzL3B1YmxpYy9pbWFnZXMvdXBsb2Fkcy9kZWZhdWx0QWRtaW4ucG5nIiwKICAgICJ0b3RwU2VjcmV0IjogIiIsCiAgICAiaXNBY3RpdmUiOiB0cnVlLAogICAgImNyZWF0ZWRBdCI6ICIyMDIyLTAyLTA2IDExOjUyOjAxLjQwOSArMDA6MDAiLAogICAgInVwZGF0ZWRBdCI6ICIyMDIyLTAyLTA2IDExOjUyOjAxLjQwOSArMDA6MDAiLAogICAgImRlbGV0ZWRBdCI6IG51bGwKICB9LAogICJpYXQiOiAxNjQ0MTQ4NDcxLAogICJleHAiOiAxNjQ0MTY2NDcxCn0.; Path=/
Content-Type: application/json; charset=utf-8
Content-Length: 133
Etag: W/"85-PWOL8M3mYJv9caLvST18mm7K+2g"
Vary: Accept-Encoding
Date: Sun, 06 Feb 2022 11:57:25 GMT
Via: 1.1 vegur

{"user":{"id":1,"email":"jwtn3d@juice-sh.op","lastLoginIp":"0.0.0.0","profileImage":"assets/public/images/uploads/defaultAdmin.png"}}
</code>```

I tried opening DevTools on the website and manually changing the cookie value to the forged token, and when I reloaded the website it reflected the jwtn3d@juice-sh.op email on the profile. But it still didn't solve the challenge. I've looked for tutorials everywhere and the challenges all seem to have just been solved once they sent the forged token over using the repeater, I'm at a loss as to why it isn't working in my case.

答: I found an alternative to using repeater, I used proxy intercept instead and changed the token value to the forged token on the /rest/user/whoami requests. That seemed to do the trick, though the notif pop up for the solved challenge didn't appear but it did show as solved in the scoreboard.</p>

ContentLicense: CC BY-SA 4.0

Body:
I recently deployed Juiceshop on Heroku and am trying to solve the challenge of forging an unsigned JWT token using Burpsuite. I followed the hints provided in the ebook starting from using burpsuite to get a valid JWT token from the request header using the proxy tab on the /rest/user/whoami URL and sent it to the repeater. In the repeater tab, I changed the alg property in the token to "none" and the email to "jwtn3d@juice-sh.op". I then encoded them in base64 and put a period after the header and payload respectively in the token value. When I send the request, I get a HTTP 200 OK status and the jwtn3d@juice-sh.op email is reflected as well, but the juiceshop challenge doesn't seem to be solved. When I reload the website, I'm not logged in as jwtn3d@juice-sh.op either.

Server: Cowboy
Connection: close
Access-Control-Allow-Origin: *
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Feature-Policy: payment 'self'
Set-Cookie: token=ewogICJ0eXAiOiAiSldUIiwKICAiYWxnIjogIm5vbmUiCn0.ewogICJzdGF0dXMiOiAic3VjY2VzcyIsCiAgImRhdGEiOiB7CiAgICAiaWQiOiAxLAogICAgInVzZXJuYW1lIjogIiIsCiAgICAiZW1haWwiOiAiand0bjNkQGp1aWNlLXNoLm9wIiwKICAgICJwYXNzd29yZCI6ICIwMTkyMDIzYTdiYmQ3MzI1MDUxNmYwNjlkZjE4YjUwMCIsCiAgICAicm9sZSI6ICJhZG1pbiIsCiAgICAiZGVsdXhlVG9rZW4iOiAiIiwKICAgICJsYXN0TG9naW5JcCI6ICIwLjAuMC4wIiwKICAgICJwcm9maWxlSW1hZ2UiOiAiYXNzZXRzL3B1YmxpYy9pbWFnZXMvdXBsb2Fkcy9kZWZhdWx0QWRtaW4ucG5nIiwKICAgICJ0b3RwU2VjcmV0IjogIiIsCiAgICAiaXNBY3RpdmUiOiB0cnVlLAogICAgImNyZWF0ZWRBdCI6ICIyMDIyLTAyLTA2IDExOjUyOjAxLjQwOSArMDA6MDAiLAogICAgInVwZGF0ZWRBdCI6ICIyMDIyLTAyLTA2IDExOjUyOjAxLjQwOSArMDA6MDAiLAogICAgImRlbGV0ZWRBdCI6IG51bGwKICB9LAogICJpYXQiOiAxNjQ0MTQ4NDcxLAogICJleHAiOiAxNjQ0MTY2NDcxCn0.; Path=/
Content-Type: application/json; charset=utf-8
Content-Length: 133
Etag: W/"85-PWOL8M3mYJv9caLvST18mm7K+2g"
Vary: Accept-Encoding
Date: Sun, 06 Feb 2022 11:57:25 GMT
Via: 1.1 vegur

{"user":{"id":1,"email":"jwtn3d@juice-sh.op","lastLoginIp":"0.0.0.0","profileImage":"assets/public/images/uploads/defaultAdmin.png"}}

I tried opening DevTools on the website and manually changing the cookie value to the forged token, and when I reloaded the website it reflected the jwtn3d@juice-sh.op email on the profile. But it still didn't solve the challenge. I've looked for tutorials everywhere and the challenges all seem to have just been solved once they sent the forged token over using the repeater, I'm at a loss as to why it isn't working in my case.


问:
How to make multi-dementional arrays with array lists wiht axios and vue js
I am quite new to the axios and javascript and I am so confused with making multi-dimentional array.

1. I want my data to look like :

```<code>userList: [
                    {
                        user_no: 1,
                        user_nickname: "hailey",
                    },
                    {
                        user_no: 2,
                        user_nickname: "mandi",
                    },
                    {
                        user_no: 3,
                        user_nickname: "loren",
                    },
                    {
                        user_no: 4,
                        user_nickname: "james",
                    },
],

</code>```

2. But from axios response, I am getting result like this :

```<code>{user_no : 1, user_nickname : "hailey"}
{user_no : 2 , user_nickname : "mandi"}
{user_no : 3 , user_nickname : "loren"}
{user_no : 4 , user_nickname : "james"}
</code>```

How can I wrap those individual lists into multi dimentional array so I can make #2 -> #1 ?
I saw some functions like flat which does the opposite of what I want. So I was wondering if there's any way like those to wrap all arrays with outer array.

答:
I did not see any issues with the axios response you are getting. As v-data-table need an array to iterate and you are getting the same from the API response.

Working Demo :

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: () => ({
    dataList: [{
            "user_no": 1,
            "user_nickname": "hailey"
    },
    {
      "user_no": 2,
      "user_nickname": "mandi"
    },
    {
      "user_no": 3,
      "user_nickname": "loren"
    },
    {
      "user_no": 4,
      "user_nickname": "james"
    }]
  }),
  computed: {
    gridHeaders() {
      return [
        { text: "User Number", value: "user_no" },
        { text: "User Nickname", value: "user_nickname" }
      ];
    },
  },
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.5.0/dist/vuetify.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css" rel="stylesheet">

<div id="app">
    <v-data-table :headers="gridHeaders" :items="dataList" item-key="user_no">
    </v-data-table>
</div></code>```

Body:
I am quite new to the axios and javascript and I am so confused with making multi-dimentional array.

1. I want my data to look like :

userList: [
                    {
                        user_no: 1,
                        user_nickname: "hailey",
                    },
                    {
                        user_no: 2,
                        user_nickname: "mandi",
                    },
                    {
                        user_no: 3,
                        user_nickname: "loren",
                    },
                    {
                        user_no: 4,
                        user_nickname: "james",
                    },
],

2. But from axios response, I am getting result like this :

{user_no : 1, user_nickname : "hailey"}
{user_no : 2 , user_nickname : "mandi"}
{user_no : 3 , user_nickname : "loren"}
{user_no : 4 , user_nickname : "james"}

How can I wrap those individual lists into multi dimentional array so I can make #2 -> #1 ?
I saw some functions like flat which does the opposite of what I want. So I was wondering if there's any way like those to wrap all arrays with outer array.

Body:
I did not see any issues with the axios response you are getting. As v-data-table need an array to iterate and you are getting the same from the API response.

Working Demo :

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: () => ({
    dataList: [{
            "user_no": 1,
            "user_nickname": "hailey"
    },
    {
      "user_no": 2,
      "user_nickname": "mandi"
    },
    {
      "user_no": 3,
      "user_nickname": "loren"
    },
    {
      "user_no": 4,
      "user_nickname": "james"
    }]
  }),
  computed: {
    gridHeaders() {
      return [
        { text: "User Number", value: "user_no" },
        { text: "User Nickname", value: "user_nickname" }
      ];
    },
  },
})

<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.5.0/dist/vuetify.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css" rel="stylesheet">

<div id="app">
    <v-data-table :headers="gridHeaders" :items="dataList" item-key="user_no">
    </v-data-table>
</div>


问:
Slow SQL Query / Displaying (PHP / jQuery)
I have a request to get data in my mySQL database (36,848 entries).
Then I format and append them with jQuery on my web page.

These two operations take 2 minutes and 30 seconds.
During this time, no other operation is possible on the page.

Is there a way to optimize this to speed up the process?
Like this, it's unusable.

My PHP function

```<code><?php
function get_my_customers() {
    $req = $bdd->prepare("SELECT * FROM clients ORDER BY raison_sociale");
    $req->execute();
    $customers = $req->fetchAll(PDO::FETCH_ASSOC);

    return $customers;
}

if(isset($_POST['ajax'])){
    $result = get_my_customers();
    echo json_encode($result);
}
?>
</code>```

Data retrieval in jQuery (Ajax)

```<code>function get_my_customers(){
    var customers;
    $.ajax({
        url: "model/application/*******/customers/get_my_customers.php",
        async: false,
        type: "POST",
        dataType: 'json',
        data: {ajax: 'true'},
        success: function(data)
        {
            customers = data;
        }
    });
    return customers;
}

var my_customers = get_my_customers();

$('#customers_list').append('<div class="list_card" card="customers_list"></div>');

$.each(my_customers, function(key, val){
    if(val.enseigne == null){
        var enseigne = '';
    }else{
        var enseigne = ',' + val.enseigne;
    }

    $('.list_card[card="customers_list"]').append(''+
        '<div class="list_card_element">'+
            '<div><b>'+ val.numero_client +'</b></div>'+
            '<div>'+
                '<b>'+ val.raison_sociale +'</b>' + enseigne +
                '<br>'+
                val.cp_livraison + ', ' + val.adresse_livraison +
            '</div>'+
        '</div>'
    );
});
</code>```

Do you know what I can do to speed up processing time?
I've tried limiting the SELECT query to only the fields I need but that doesn't improve processing time.

I wonder if it's not rather the jQuery layout that takes time rather than the SQL query.

Thank you !

答:
try to use indexes see that

MySQL can use an index on the columns in the ORDER BY (under certain conditions). However, MySQL cannot use an index for mixed ASC,DESC order by (SELECT * FROM foo ORDER BY bar ASC, pants DESC). Sharing your query and CREATE TABLE statement would help us answer your question more specifically.

Body:
I have a request to get data in my mySQL database (36,848 entries).
Then I format and append them with jQuery on my web page.

These two operations take 2 minutes and 30 seconds.
During this time, no other operation is possible on the page.

Is there a way to optimize this to speed up the process?
Like this, it's unusable.

My PHP function

<?php
function get_my_customers() {
    $req = $bdd->prepare("SELECT * FROM clients ORDER BY raison_sociale");
    $req->execute();
    $customers = $req->fetchAll(PDO::FETCH_ASSOC);

    return $customers;
}

if(isset($_POST['ajax'])){
    $result = get_my_customers();
    echo json_encode($result);
}
?>

Data retrieval in jQuery (Ajax)

function get_my_customers(){
    var customers;
    $.ajax({
        url: "model/application/*******/customers/get_my_customers.php",
        async: false,
        type: "POST",
        dataType: 'json',
        data: {ajax: 'true'},
        success: function(data)
        {
            customers = data;
        }
    });
    return customers;
}

var my_customers = get_my_customers();

$('#customers_list').append('

');

$.each(my_customers, function(key, val){
    if(val.enseigne == null){
        var enseigne = '';
    }else{
        var enseigne = ',' + val.enseigne;
    }

    $('.list_card[card="customers_list"]').append(''+
        '
'+
            '
'+ val.numero_client +'
'+
            '
'+
                ''+ val.raison_sociale +'' + enseigne +
                '
'+
                val.cp_livraison + ', ' + val.adresse_livraison +
            '
'+
        '
'
    );
});

Do you know what I can do to speed up processing time?
I've tried limiting the SELECT query to only the fields I need but that doesn't improve processing time.

I wonder if it's not rather the jQuery layout that takes time rather than the SQL query.

Thank you !


问:
No module named myapp
I have this project directory structure:

```<code>.
.pylintrc
|--myproj   .
            |--myapp
            |--myproj (settings.py is here)
            __init__.py
            manage.py
            .
</code>```

In settings.py, INSTALLED_APPS I have the first entry 'myapp'.

From the root folder (containing .pylintrc), I call

```<code>$ DJANGO_SETTINGS_MODULE=myproj.myproj.settings pylint myproj --load-plugins pylint_django
</code>```

However, I get error no module named 'myapp'. If I change the INSTALLED_APPS entry to 'myproj.myapp', then it is able to continue, but now I'm unable to start the project normally with manage.py runserver.

pastebin myproj.settings

What am I doing wrong, and what can I do to proceed?

答:
The same problem happened to me and I find my solution.

In My Case, I missed my urls.py file.

```<code>re_path(r"^chaining/", include("smart_selects.urls")),
</code>```

to

```<code>re_path(r"^chaining/", include("packages.smart_selects.urls")),
</code>```

Title: No module named myapp

Body:
I have this project directory structure:

.
.pylintrc
|--myproj   .
            |--myapp
            |--myproj (settings.py is here)
            __init__.py
            manage.py
            .

In settings.py, INSTALLED_APPS I have the first entry 'myapp'.

From the root folder (containing .pylintrc), I call

$ DJANGO_SETTINGS_MODULE=myproj.myproj.settings pylint myproj --load-plugins pylint_django

However, I get error no module named 'myapp'. If I change the INSTALLED_APPS entry to 'myproj.myapp', then it is able to continue, but now I'm unable to start the project normally with manage.py runserver.

pastebin myproj.settings

What am I doing wrong, and what can I do to proceed?

Body:
The same problem happened to me and I find my solution.

In My Case, I missed my urls.py file.

re_path(r"^chaining/", include("smart_selects.urls")),

to

re_path(r"^chaining/", include("packages.smart_selects.urls")),


问:
I'm trying to expand the Datagrid when adding another value. Using Xamarin.Forms.Datagrid
I'm using Xamarin.Forms.Datagrid. What I'm struggling with is displaying the second row. I suspect it is in the adding value part that I'm not specifying to add a new row to the Datagrid. But for the life of me I can't see it.

Now if I scanned a different barcode. It adds the new value to the collection but does not expand the datagrid.

My ObservableCollection:

```<code>public ObservableCollection<dgvProductionReceiptSource> ProductionReceiptSource { get; } = new ObservableCollection<dgvProductionReceiptSource>();
</code>```

Where I get my data from:

```<code>private void FillDataGrid()
    {
        try
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();

                using (SqlCommand command = new SqlCommand("SELECT DocNum, OWOR.ItemCode, ItemName, PlannedQty, CAST(OWOR.DueDate AS DATE) FROM OWOR " +
                    "INNER JOIN OITM ON OWOR.ItemCode = OITM.ItemCode WHERE Status = 'R' AND OWOR.DocNum = '" + ScanBarcodeText + "' ORDER BY DueDate ASC", connection))
                {
                    using (SqlDataReader reader = command.ExecuteReader())
                    {

                        if (reader != null)
                        {
                            while (reader.Read())
                            {

                                ItemNum = reader.GetString(1);
                                Desc = reader.GetString(2);
                                PlannedQty = reader.GetDecimal(3);
                                DueDate = reader.GetDateTime(4);
                                ScanQty = 0;

                                if (DueDate == DateTime.Today)
                                {
                                    if (DocNum.ToString() == ScanBarcodeText)
                                    {
                                        AddQty();
                                    }

                                    if (DocNum.ToString() != ScanBarcodeText)
                                    {
                                        DocNum = reader.GetInt32(0);
                                        ProductionReceiptSource.Add(new dgvProductionReceiptSource()
                                        {
                                            DocNumProductionReceipt = DocNum,
                                            ItemNumberProductionReceipt = reader.GetString(1),
                                            DescriptionProductionReceipt = reader.GetString(2),
                                            PlannedQuantityProductionReceipt = reader.GetDecimal(3),
                                            ScannedQuantityProductionReceipt = 0
                                        });
                                        AddQty();
                                    }
                                }
                            }
                        }
                    }
                }
                connection.Close();
            }
            ScanBarcodeText = string.Empty;
        }
        catch(Exception ex)
        {
            Application.Current.MainPage.DisplayAlert("Alert", ex.Message, "OK");
        }
    }
</code>```

Any help would be appreciated

答:
Like Jason suggested, I need to increase the height of the control

```<code>            <ContentView HeightRequest="380">
                <ScrollView Orientation="Horizontal">
                    <dg:DataGrid x:Name="dgvProductionReceiptSource"
                                 ItemsSource="{Binding ProductionReceiptSource}"
                                 IsRefreshing="{Binding ProductionReceiptRefresh}"
                                 PullToRefreshCommand="{Binding ProductionReceiptRefreshCommand}"
                                 IsVisible="False"
                                 RowHeight="60"
                                 HeaderHeight="50"
                                 HeaderBackground="#e0e6f8"
                                 HeaderFontSize="15"
                                 ActiveRowColor="#8899AA">
                        <x:Arguments>
                            <ListViewCachingStrategy>RetainElement</ListViewCachingStrategy>
                        </x:Arguments>
                        <dg:DataGrid.Columns>
                            <dg:DataGridColumn Title="Order Number" PropertyName="DocNumProductionReceipt" Width="150"
                                           HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
                            <dg:DataGridColumn Title="Item Number" PropertyName="ItemNumberProductionReceipt" Width="150"
                                           HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
                            <dg:DataGridColumn Title="Item Description" PropertyName="DescriptionProductionReceipt" Width="150"
                                           HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
                            <dg:DataGridColumn Title="Planned Quantity" PropertyName="PlannedQuantityProductionReceipt" Width="150"
                                           HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
                            <dg:DataGridColumn Title="Scanned Bin" PropertyName="ScannedBinsProductionReceipt" Width="150"
                                               HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
                            <dg:DataGridColumn Title="Remaining Bins" PropertyName="RemainingBinsProductionReceipt" Width="150"
                                               HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
                        </dg:DataGrid.Columns>
                        <dg:DataGrid.RowsBackgroundColorPalette>
                            <dg:PaletteCollection>
                                <Color>#E0E6f8</Color>
                            </dg:PaletteCollection>
                        </dg:DataGrid.RowsBackgroundColorPalette>
                    </dg:DataGrid>
                </ScrollView>
            </ContentView>
</code>```

I changed the ContentView HeightRequest

Body:
I'm using Xamarin.Forms.Datagrid. What I'm struggling with is displaying the second row. I suspect it is in the adding value part that I'm not specifying to add a new row to the Datagrid. But for the life of me I can't see it.

Now if I scanned a different barcode. It adds the new value to the collection but does not expand the datagrid.

My ObservableCollection:

public ObservableCollection<dgvProductionReceiptSource> ProductionReceiptSource { get; } = new ObservableCollection<dgvProductionReceiptSource>();

Where I get my data from:

private void FillDataGrid()
    {
        try
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();

                using (SqlCommand command = new SqlCommand("SELECT DocNum, OWOR.ItemCode, ItemName, PlannedQty, CAST(OWOR.DueDate AS DATE) FROM OWOR " +
                    "INNER JOIN OITM ON OWOR.ItemCode = OITM.ItemCode WHERE Status = 'R' AND OWOR.DocNum = '" + ScanBarcodeText + "' ORDER BY DueDate ASC", connection))
                {
                    using (SqlDataReader reader = command.ExecuteReader())
                    {

                        if (reader != null)
                        {
                            while (reader.Read())
                            {

                                ItemNum = reader.GetString(1);
                                Desc = reader.GetString(2);
                                PlannedQty = reader.GetDecimal(3);
                                DueDate = reader.GetDateTime(4);
                                ScanQty = 0;

                                if (DueDate == DateTime.Today)
                                {
                                    if (DocNum.ToString() == ScanBarcodeText)
                                    {
                                        AddQty();
                                    }

                                    if (DocNum.ToString() != ScanBarcodeText)
                                    {
                                        DocNum = reader.GetInt32(0);
                                        ProductionReceiptSource.Add(new dgvProductionReceiptSource()
                                        {
                                            DocNumProductionReceipt = DocNum,
                                            ItemNumberProductionReceipt = reader.GetString(1),
                                            DescriptionProductionReceipt = reader.GetString(2),
                                            PlannedQuantityProductionReceipt = reader.GetDecimal(3),
                                            ScannedQuantityProductionReceipt = 0
                                        });
                                        AddQty();
                                    }
                                }
                            }
                        }
                    }
                }
                connection.Close();
            }
            ScanBarcodeText = string.Empty;
        }
        catch(Exception ex)
        {
            Application.Current.MainPage.DisplayAlert("Alert", ex.Message, "OK");
        }
    }

Any help would be appreciated

Body:
Like Jason suggested, I need to increase the height of the control

            <ContentView HeightRequest="380">
                <ScrollView Orientation="Horizontal">
                    <dg:DataGrid x:Name="dgvProductionReceiptSource"
                                 ItemsSource="{Binding ProductionReceiptSource}"
                                 IsRefreshing="{Binding ProductionReceiptRefresh}"
                                 PullToRefreshCommand="{Binding ProductionReceiptRefreshCommand}"
                                 IsVisible="False"
                                 RowHeight="60"
                                 HeaderHeight="50"
                                 HeaderBackground="#e0e6f8"
                                 HeaderFontSize="15"
                                 ActiveRowColor="#8899AA">
                        <x:Arguments>
                            <ListViewCachingStrategy>RetainElement</ListViewCachingStrategy>
                        </x:Arguments>
                        <dg:DataGrid.Columns>
                            <dg:DataGridColumn Title="Order Number" PropertyName="DocNumProductionReceipt" Width="150"
                                           HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
                            <dg:DataGridColumn Title="Item Number" PropertyName="ItemNumberProductionReceipt" Width="150"
                                           HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
                            <dg:DataGridColumn Title="Item Description" PropertyName="DescriptionProductionReceipt" Width="150"
                                           HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
                            <dg:DataGridColumn Title="Planned Quantity" PropertyName="PlannedQuantityProductionReceipt" Width="150"
                                           HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
                            <dg:DataGridColumn Title="Scanned Bin" PropertyName="ScannedBinsProductionReceipt" Width="150"
                                               HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
                            <dg:DataGridColumn Title="Remaining Bins" PropertyName="RemainingBinsProductionReceipt" Width="150"
                                               HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
                        </dg:DataGrid.Columns>
                        <dg:DataGrid.RowsBackgroundColorPalette>
                            <dg:PaletteCollection>
                                <Color>#E0E6f8</Color>
                            </dg:PaletteCollection>
                        </dg:DataGrid.RowsBackgroundColorPalette>
                    </dg:DataGrid>
                </ScrollView>
            </ContentView>

I changed the ContentView HeightRequest


问:
Manually moving a state file to a different backend
I recreated a state file for an existing infrastructure using a third party tool i.e. terraformer. Now I want o move the .tfstate to another azurerm back-end and manage from there.

If I just copy the file i.e. mystate.tfstate from local to inside storage account container with the same file name/key as in the backend configurations will it work or do I need to do something else to achieve it?

I don't want to risk the state file or infrastructure by trying to do something that isn't sure to work as I expect.

答:
I don't want to risk the state file or infrastructure by trying to do
something that isnt sure to work as I expect.

Make a backup of the state file first, and then you won't be risking the state file.

As long as you aren't running an apply command, you won't be risking the infrastructure. And even if you are running an apply command, you will be able to review the plan before proceeding.

So just (always) backup your state file, and always review a plan before applying it, and there is no risk.


问:
Fetch file to multer returns undefined
I want to fetch a file via JS to multer but it always returns undefined. I made a postman request and works perfectly and the file saves in '/uploads'. Tried to look into my JS code but don't know whats wrong.

HTML:

<form action="/" class="form" id="form" accept-charset="utf-8" onsubmit="return(validate())">

        Send an image (optional)
        <input type="file" name="image" id="image">

    <button class="form__submit" type="submit">Submit</button>
</form>
```
<p>JS:</p>
<pre class="lang-js prettyprint-override"><code>const validate = () => {
    const formData = new FormData(document.querySelector('#form'));

    fetch('/send_file', {
        method: 'POST',
        body: formData.get('image')
    })
    .then(data => console.log(data))
    .catch(err => console.log(err))
    return false;
}
</code>```

Node:

const express = require('express');
const multer = require('multer');

const app = express();
app.use(express.static('./public'));
app.use(express.json());

const storage = multer.diskStorage({
    destination: './uploads',
    filename: function(req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now())
    }
})

const upload = multer({ storage: storage });

app.listen(3000);

app.post('/send_file', upload.single('image'), (req, res) => {
    console.log(req.body.image);
    res.end();
})
```

答:
if you are trying to send data using multer, you must put this in your form tag</p>
```<code>enctype="multipart/form-data"
</code>```

Title: Fetch file to multer returns undefined

Body:
I want to fetch a file via JS to multer but it always returns undefined. I made a postman request and works perfectly and the file saves in '/uploads'. Tried to look into my JS code but don't know whats wrong.

HTML:

<form action="/" class="form" id="form" accept-charset="utf-8" onsubmit="return(validate())">

        Send an image (optional)
        <input type="file" name="image" id="image">

    <button class="form__submit" type="submit">Submit</button>
</form>

JS:

const validate = () => {
    const formData = new FormData(document.querySelector('#form'));

    fetch('/send_file', {
        method: 'POST',
        body: formData.get('image')
    })
    .then(data => console.log(data))
    .catch(err => console.log(err))
    return false;
}

Node:

const express = require('express');
const multer = require('multer');

const app = express();
app.use(express.static('./public'));
app.use(express.json());

const storage = multer.diskStorage({
    destination: './uploads',
    filename: function(req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now())
    }
})

const upload = multer({ storage: storage });

app.listen(3000);

app.post('/send_file', upload.single('image'), (req, res) => {
    console.log(req.body.image);
    res.end();
})

Body:
if you are trying to send data using multer, you must put this in your form tag

enctype="multipart/form-data"


问:
Locating Work items which have comments addressed to me?
In Azure DevOps is possible to @Tag a user in the comments of a work item.  Is it possible to query the items to find the work items which have comments which I am tagged in?  </p>

答: You can make a custom query just setting the ID in @RecentMentions like this:


问:
DAX PERCENTILE.INC by category in calculated column
I would like to calculate a quartile (ntile) by category using PERCENTILE.INC in a calculated column. My question is a variation to this question:
Equal bins in DAX equivalent of NTILE function

How to modify the accepted solution to the problem if we want to calculate the result by a category?

```<code>Bucket =
VAR N = 4
VAR Percentiles =
    ADDCOLUMNS (
        GENERATESERIES ( 1, N ),
        "Percentile", PERCENTILE.INC ( Table1[Col1], [Value] / N )
    )
RETURN
    MINX ( FILTER ( Percentiles, Table1[Col1] <= [Percentile] ), [Value] )
</code>```

I tried this but the results are not desired values:

```<code>VAR N = 4
VAR Percentiles =
    ADDCOLUMNS(
        CROSSJOIN( VALUES( Tab[Category] ), GENERATESERIES( 1, N ) ),
        "Percentile",
            PERCENTILEX.INC(
                VAR Category = 'Tab'[Category] RETURN FILTER( Tab, 'Tab'[Category] = Category ),
                Tab[Quantity] * 1.0,
                [Value] / N
            )
    )
RETURN
    MINX(
        FILTER(
            Percentiles,
            Tab[Quantity] <= [Percentile]
                && 'Tab'[Category] = [Category]
        ),
        [Value]
    )
</code>```

Edit.

Sample data:

```<code>Table =
DATATABLE (
    "No", INTEGER,
    "Category", STRING,
    "Quantity", DOUBLE,
    {
        {  1 , "apple"  , 1 },
        {  2 , "apple"  , 5 },
        {  3 , "apple"  , 1 },
        {  4 , "apple"  , 4 },
        {  5 , "apple"  , 1 },
        {  6 , "apple"  , 2 },
        {  7 , "apple"  , 5 },
        {  8 , "apple"  , 4 },
        {  9 , "banana" , 9 },
        { 10 , "banana" , 7 },
        { 11 , "banana" , 6 },
        { 12 , "banana" , 4 },
        { 13 , "banana" , 5 },
        { 14 , "banana" , 7 },
        { 15 , "banana" , 8 },
        { 16 , "banana" , 9 }
    }
)
</code>```

答:
This is the solution I was suggesting in the comments from the prior thread.</p>
```<code>Bucket =
VAR N = 4
VAR Percentiles =
    ADDCOLUMNS (
        GENERATESERIES ( 1, N ),
        "Percentile",
            VAR K = [Value] / N
            RETURN
                CALCULATE (
                    PERCENTILE.INC ( Table1[Col1], K ),
                    ALLEXCEPT ( Table1, Table1[Category] )
                )
    )
RETURN
    MINX ( FILTER ( Percentiles, Table1[Col1] <= [Percentile] ), [Value] )
</code>```

Body:
I would like to calculate a quartile (ntile) by category using PERCENTILE.INC in a calculated column. My question is a variation to this question:
Equal bins in DAX equivalent of NTILE function

How to modify the accepted solution to the problem if we want to calculate the result by a category?

Bucket =
VAR N = 4
VAR Percentiles =
    ADDCOLUMNS (
        GENERATESERIES ( 1, N ),
        "Percentile", PERCENTILE.INC ( Table1[Col1], [Value] / N )
    )
RETURN
    MINX ( FILTER ( Percentiles, Table1[Col1] <= [Percentile] ), [Value] )

I tried this but the results are not desired values:

VAR N = 4
VAR Percentiles =
    ADDCOLUMNS(
        CROSSJOIN( VALUES( Tab[Category] ), GENERATESERIES( 1, N ) ),
        "Percentile",
            PERCENTILEX.INC(
                VAR Category = 'Tab'[Category] RETURN FILTER( Tab, 'Tab'[Category] = Category ),
                Tab[Quantity] * 1.0,
                [Value] / N
            )
    )
RETURN
    MINX(
        FILTER(
            Percentiles,
            Tab[Quantity] <= [Percentile]
                && 'Tab'[Category] = [Category]
        ),
        [Value]
    )

Edit.

Sample data:

Table =
DATATABLE (
    "No", INTEGER,
    "Category", STRING,
    "Quantity", DOUBLE,
    {
        {  1 , "apple"  , 1 },
        {  2 , "apple"  , 5 },
        {  3 , "apple"  , 1 },
        {  4 , "apple"  , 4 },
        {  5 , "apple"  , 1 },
        {  6 , "apple"  , 2 },
        {  7 , "apple"  , 5 },
        {  8 , "apple"  , 4 },
        {  9 , "banana" , 9 },
        { 10 , "banana" , 7 },
        { 11 , "banana" , 6 },
        { 12 , "banana" , 4 },
        { 13 , "banana" , 5 },
        { 14 , "banana" , 7 },
        { 15 , "banana" , 8 },
        { 16 , "banana" , 9 }
    }
)

Body:
This is the solution I was suggesting in the comments from the prior thread.

Bucket =
VAR N = 4
VAR Percentiles =
    ADDCOLUMNS (
        GENERATESERIES ( 1, N ),
        "Percentile",
            VAR K = [Value] / N
            RETURN
                CALCULATE (
                    PERCENTILE.INC ( Table1[Col1], K ),
                    ALLEXCEPT ( Table1, Table1[Category] )
                )
    )
RETURN
    MINX ( FILTER ( Percentiles, Table1[Col1] <= [Percentile] ), [Value] )


问:
why "if" condition is ignored?
when I run this server on postman, I'm getting "error login" but it should return "success".
but when i do add console.log(body.req) then on terminal I'm gettting "name, email,password", which i passed in body.
and also when I do console.log(req.body.name===database.users[0].name && req.body.email===database.users[0].email, req.body, database);
then in terminal I'm getting all data from database but for "If" it is returning false.

```<code> const bodyParser=require('body-parser');
 const app=express();
  app.use(bodyParser.json());
  app.use(express.urlencoded({ extended: true }));
  app.use(express.urlencoded({ extended: false}));

 const database= {
     users : [
         {
          id: '123',
          name: 'amit',
          email :'amitrk@gmail.com',
          password:'123',
          entries:'0',
           joined: new Date()
         },
         /*{
            id: '124',
          name:'Rahul',
          email :'amit@gmail.com',
          password:'54858',
          entries:'0',
           joined: new Date()
         },*/
     ]

 }
   /*const app=express();
   app.get('/',(req,res)=>{
        res.send("this is working");
   })*/
    app.post('/signin',(req,res)=>{
         //console.log(req.body);
      if(req.body.name===database.users[0].name && req.body.email===database.users[0].email) {
           console.log("sucess");
      }
       else {
           res.status(400).json("error login");
       }
    })
   app.listen(3000,()=>{
        console.log("app is running on port");
   })
</code>```

答:
First of all you don't appear to be sending a response in the if condition. What this will do, if the control went to your if condition, is print 'success' on console, but not send any response (i.e. hang the request).

Secondly, is this exactly the code you ran? Did you have password check in the if condition as well? Do note that when using ===, '123' is not equal to 123.

These are the only clues, I can provide from what was shared. You can share the postman request body, which might have more clues.

Title: why "if" condition is ignored?

Body:
when I run this server on postman, I'm getting "error login" but it should return "success".
but when i do add console.log(body.req) then on terminal I'm gettting "name, email,password", which i passed in body.
and also when I do console.log(req.body.name===database.users[0].name && req.body.email===database.users[0].email, req.body, database);
then in terminal I'm getting all data from database but for "If" it is returning false.

 const bodyParser=require('body-parser');
 const app=express();
  app.use(bodyParser.json());
  app.use(express.urlencoded({ extended: true }));
  app.use(express.urlencoded({ extended: false}));

 const database= {
     users : [
         {
          id: '123',
          name: 'amit',
          email :'amitrk@gmail.com',
          password:'123',
          entries:'0',
           joined: new Date()
         },
         /*{
            id: '124',
          name:'Rahul',
          email :'amit@gmail.com',
          password:'54858',
          entries:'0',
           joined: new Date()
         },*/
     ]

 }
   /*const app=express();
   app.get('/',(req,res)=>{
        res.send("this is working");
   })*/
    app.post('/signin',(req,res)=>{
         //console.log(req.body);
      if(req.body.name===database.users[0].name && req.body.email===database.users[0].email) {
           console.log("sucess");
      }
       else {
           res.status(400).json("error login");
       }
    })
   app.listen(3000,()=>{
        console.log("app is running on port");
   })


问:
'super' object has no attribute '__getattr__' error in kivy?
What I am attempting to do is to make it so that when I enter into a text input and then press "submit" the text will be printed. However this is not working and I instead recieve the error "'super' object has no attribute 'getattr'". I have attempted to place they python code in different classes however this also does not work. Attached bellow is the relevant code as well as the full code along with the error message tht I recieved.
The error message

Any help with this issue would be appreciated as I am new to kivy so I don't fully understand all of it's quirks.

The offending part of code in python is:

```<code>class MainApp(MDApp):
    def build(self):
        Window.size = [300, 600]
        return Builder.load_file("screen.kv")
    def returnusername(self):
        text = self.root.ids.input.text
        print(text)
    def returnpassword(self):
        text = self.root.ids.input.text
        print(text)
</code>```

The offending part of code in kivy is:

```<code>        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Submit"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.45}
            size_hint: 0.25, 0.05
            on_release:
                app.returnusername()
                app.returnpassword()
</code>```

Full Python Code:

```<code>import kivy
from kivymd.app import MDApp
from kivymd.uix.label import MDLabel
from kivymd.uix.button import MDRectangleFlatButton
from kivy.core.window import Window
from kivy.app import Builder
from kivymd.uix.screen import MDScreen
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.textinput import TextInput

class FirstPageScreen(MDScreen):
    pass

class LoginPageScreen(MDScreen):
    pass

class NewAccountScreen(MDScreen):
    pass

class WindowManager(ScreenManager):
    pass

class MainApp(MDApp):
    def build(self):
        Window.size = [300, 600]
        return Builder.load_file("screen.kv")
    def returnusername(self):
        text = self.root.ids.input.text
        print(text)
    def returnpassword(self):
        text = self.root.ids.input.text
        print(text)

MainApp().run()
</code>```

Full Kivy Code:

```<code>#:kivy  2.0.0

WindowManager:
    FirstPageScreen:
    LoginPageScreen:
    NewAccountScreen:

<FirstPageScreen>:
    name: "FirstPage"
    MDFloatLayout:
        MDLabel:
            text: "Time Saving App"
            halign: "center"
            valign: "center"
            font_size: 25
            pos_hint: {'center_x': 0.5, 'center_y': 0.85}

        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Login"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.75}
            on_release:
                app.root.current = "LoginPage"

        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Create new account"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.65}
            on_release:
                app.root.current = "NewAccount"

<LoginPageScreen>:
    name: "LoginPage"
    MDFloatLayout:
        MDLabel:
            text: "Login"
            halign: "center"
            valign: "center"
            font_size: 25
            pos: (0,220)
        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Back"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.3}
            on_release:
                app.root.current = "FirstPage"
        TextInput:
            id: usernameinput
            hint_text:'Enter your Username'
            pos_hint: {'center_x': 0.5, 'center_y': 0.705}
            size_hint: 0.8, 0.05
            multiline: False
        TextInput:
            id: passwordinput
            hint_text:'Enter your Password'
            pos_hint: {'center_x': 0.5, 'center_y': 0.6}
            size_hint: 0.8, 0.05
            multiline: False
        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Submit"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.45}
            size_hint: 0.25, 0.05
            on_release:
                app.returnusername()
                app.returnpassword()

<NewAccountScreen>:
    name: "NewAccount"
    MDFloatLayout:
        MDLabel:
            text: "Create New account"
            halign: "center"
            valign: "center"
            font_size: 25
            pos: (0,220)
        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Back"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.3}
            size_hint: 0.25, 0.05
            on_release:
                app.root.current = "FirstPage"
        TextInput:
            id: newusernameinput
            hint_text:'Enter a Username'
            pos_hint: {'center_x': 0.5, 'center_y': 0.705}
            size_hint: 0.8, 0.05
            multiline: False
        TextInput:
            id: newpasswordinput
            hint_text:'Enter a Password'
            pos_hint: {'center_x': 0.5, 'center_y': 0.6}
            size_hint: 0.8, 0.05
            multiline: False
        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Submit"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.45}
            size_hint: 0.25, 0.05
            on_release:
                pass
</code>```

答:
Your code self.root.ids.input.text is trying to reference ids in the app root. There are two problems with that. First, the root is the WindowManager, which has no ids in your code. Second, there is no input id defined in your kv. The fix is to define an input id somewhere in your kv, and then use something like

```<code>self.root.get_screen('some_screen_name').ids.input.text
</code>```

where some_screen_name is the name of the Screen that contains the input id.

Body:
What I am attempting to do is to make it so that when I enter into a text input and then press "submit" the text will be printed. However this is not working and I instead recieve the error "'super' object has no attribute 'getattr'". I have attempted to place they python code in different classes however this also does not work. Attached bellow is the relevant code as well as the full code along with the error message tht I recieved.
The error message

Any help with this issue would be appreciated as I am new to kivy so I don't fully understand all of it's quirks.

The offending part of code in python is:

class MainApp(MDApp):
    def build(self):
        Window.size = [300, 600]
        return Builder.load_file("screen.kv")
    def returnusername(self):
        text = self.root.ids.input.text
        print(text)
    def returnpassword(self):
        text = self.root.ids.input.text
        print(text)

The offending part of code in kivy is:

        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Submit"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.45}
            size_hint: 0.25, 0.05
            on_release:
                app.returnusername()
                app.returnpassword()

Full Python Code:

import kivy
from kivymd.app import MDApp
from kivymd.uix.label import MDLabel
from kivymd.uix.button import MDRectangleFlatButton
from kivy.core.window import Window
from kivy.app import Builder
from kivymd.uix.screen import MDScreen
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.textinput import TextInput

class FirstPageScreen(MDScreen):
    pass

class LoginPageScreen(MDScreen):
    pass

class NewAccountScreen(MDScreen):
    pass

class WindowManager(ScreenManager):
    pass

class MainApp(MDApp):
    def build(self):
        Window.size = [300, 600]
        return Builder.load_file("screen.kv")
    def returnusername(self):
        text = self.root.ids.input.text
        print(text)
    def returnpassword(self):
        text = self.root.ids.input.text
        print(text)

MainApp().run()

Full Kivy Code:

#:kivy  2.0.0

WindowManager:
    FirstPageScreen:
    LoginPageScreen:
    NewAccountScreen:

<FirstPageScreen>:
    name: "FirstPage"
    MDFloatLayout:
        MDLabel:
            text: "Time Saving App"
            halign: "center"
            valign: "center"
            font_size: 25
            pos_hint: {'center_x': 0.5, 'center_y': 0.85}

        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Login"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.75}
            on_release:
                app.root.current = "LoginPage"

        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Create new account"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.65}
            on_release:
                app.root.current = "NewAccount"

<LoginPageScreen>:
    name: "LoginPage"
    MDFloatLayout:
        MDLabel:
            text: "Login"
            halign: "center"
            valign: "center"
            font_size: 25
            pos: (0,220)
        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Back"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.3}
            on_release:
                app.root.current = "FirstPage"
        TextInput:
            id: usernameinput
            hint_text:'Enter your Username'
            pos_hint: {'center_x': 0.5, 'center_y': 0.705}
            size_hint: 0.8, 0.05
            multiline: False
        TextInput:
            id: passwordinput
            hint_text:'Enter your Password'
            pos_hint: {'center_x': 0.5, 'center_y': 0.6}
            size_hint: 0.8, 0.05
            multiline: False
        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Submit"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.45}
            size_hint: 0.25, 0.05
            on_release:
                app.returnusername()
                app.returnpassword()

<NewAccountScreen>:
    name: "NewAccount"
    MDFloatLayout:
        MDLabel:
            text: "Create New account"
            halign: "center"
            valign: "center"
            font_size: 25
            pos: (0,220)
        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Back"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.3}
            size_hint: 0.25, 0.05
            on_release:
                app.root.current = "FirstPage"
        TextInput:
            id: newusernameinput
            hint_text:'Enter a Username'
            pos_hint: {'center_x': 0.5, 'center_y': 0.705}
            size_hint: 0.8, 0.05
            multiline: False
        TextInput:
            id: newpasswordinput
            hint_text:'Enter a Password'
            pos_hint: {'center_x': 0.5, 'center_y': 0.6}
            size_hint: 0.8, 0.05
            multiline: False
        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Submit"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.45}
            size_hint: 0.25, 0.05
            on_release:
                pass

Body:
Your code self.root.ids.input.text is trying to reference ids in the app root. There are two problems with that. First, the root is the WindowManager, which has no ids in your code. Second, there is no input id defined in your kv. The fix is to define an input id somewhere in your kv, and then use something like

self.root.get_screen('some_screen_name').ids.input.text

where some_screen_name is the name of the Screen that contains the input id.


问:
Im trying to create a a code that count numbers divisible by 9 by putting numbers into an array and count the numbers in it
Im trying to create a a code that count numbers divisible by 9 by putting numbers into  an array and count the numbers in it but it only prints 1 instead of the number of numbers divisible by 9 please help me i want to use array to count those numbers</p>
```<code>#include <iostream>
using namespace std;
int main(){
    int a,b,i;
    int numbers[]={i};
    cin >>a>>b;
    for (i=a; i<=b; i++)
        if (i%9==0){
            cout << sizeof(numbers)/sizeof(numbers[0]);
        }
}
</code>```

答:
Nowhere in your code are you adding numbers to the array. Anyhow, it is not possible to add elements to arrays, because they are of fixed size. Your array has a single element.

Moreover, int numbers[]={i}; is undefined, because i has not been initialized.

Further, it is not clear what is the purpose of sizeof(numbers)/sizeof(numbers[0]) in your code. sizeof(numbers) is the size of a single int because the array has a single element. sizeof(numbers[0]) is the size of a single int as well. Hence the result is 1 always. (Its a compile time constant btw.)

If you want to count how many numbers fullfil some condition you best use a counter and print its value after the loop:

```<code>#include <iostream>

int main(){
    int a,b;

    cin >> a >> b;
    unsigned counter = 0;
    for (int i=a; i<=b; i++) {
        if (i%9==0){
            ++counter;
        }
    }
    std::cout << counter;
}
</code>```

i want to use array for my learning porpuses please help me

You chose the wrong example to train working with arrays, because as already mentioned, arrays have fixed size. It is an opportunity to learn about std::vector. You can add elements to a std::vector at runtime and query its size:

```<code>#include <iostream>
#include <vector>

int main(){
    int a,b;
    std::vector<int> by9divisables;
    std::cin >> a >> b;
    for (int i=a; i<=b; i++) {
        if (i%9==0) {
            by9divisables.push_back(i);
        }
    }
    std::cout << by9divisables.size();
}
</code>```

However, other than to see how std::vector is working, the vector has no place in this code. As you can see above, the result can be obtained without it.

Body:
Im trying to create a a code that count numbers divisible by 9 by putting numbers into  an array and count the numbers in it but it only prints 1 instead of the number of numbers divisible by 9 please help me i want to use array to count those numbers

#include <iostream>
using namespace std;
int main(){
    int a,b,i;
    int numbers[]={i};
    cin >>a>>b;
    for (i=a; i<=b; i++)
        if (i%9==0){
            cout << sizeof(numbers)/sizeof(numbers[0]);
        }
}

Body:
Nowhere in your code are you adding numbers to the array. Anyhow, it is not possible to add elements to arrays, because they are of fixed size. Your array has a single element.

Moreover, int numbers[]={i}; is undefined, because i has not been initialized.

Further, it is not clear what is the purpose of sizeof(numbers)/sizeof(numbers[0]) in your code. sizeof(numbers) is the size of a single int because the array has a single element. sizeof(numbers[0]) is the size of a single int as well. Hence the result is 1 always. (Its a compile time constant btw.)

If you want to count how many numbers fullfil some condition you best use a counter and print its value after the loop:

#include <iostream>

int main(){
    int a,b;

    cin >> a >> b;
    unsigned counter = 0;
    for (int i=a; i<=b; i++) {
        if (i%9==0){
            ++counter;
        }
    }
    std::cout << counter;
}

i want to use array for my learning porpuses please help me

You chose the wrong example to train working with arrays, because as already mentioned, arrays have fixed size. It is an opportunity to learn about std::vector. You can add elements to a std::vector at runtime and query its size:

#include <iostream>
#include <vector>

int main(){
    int a,b;
    std::vector<int> by9divisables;
    std::cin >> a >> b;
    for (int i=a; i<=b; i++) {
        if (i%9==0) {
            by9divisables.push_back(i);
        }
    }
    std::cout << by9divisables.size();
}

However, other than to see how std::vector is working, the vector has no place in this code. As you can see above, the result can be obtained without it.


问:
Which HSV range should I use to get rid of the light green color in this picture?
I want to pre-process this image for OCR. I want it to be able to read all the text from it, as you can see, the text has different colors. I'm using HSV ranges to detect the colors I want and I just turn everything into white so it's easier for the OCR software to translate the image into text. With my current settings it's reading all the text correctly except the one that it's surrounded by the light green background, I believe the issue is my HSV values, how could I adjust it so it reads all the text?

This is my preprocessing code:

def pre_process_img(img):
    """
    Prepares image for OCR

    :param img: PIL.Image
        Image object

    :return: output_img
    """
    open_cv_image = np.array(img)

    # Convert image to HSV in order to be able to extract what we care about using masks
    img_hsv = cv2.cvtColor(open_cv_image, cv2.COLOR_RGB2HSV)

    # Init mask
    mask = 0
    for color_name, data in ocr.COLORS.items():
        if color_name not in ['white', 'dark_red', 'yellow']:
            continue

        lower = np.array(data['lower'])
        upper = np.array(data['upper'])

        # Join masks
        mask += cv2.inRange(img_hsv, lower, upper)

    # Set my output img to zero everywhere except my mask
    # output_img = open_cv_image.copy()
    img_hsv[np.where(mask == 0)] = 0

    # Change image to white where we found the color we want
    img_hsv[mask > 0] = (255, 255, 255)

    # cv2.imshow("out", img_hsv)
    # cv2.waitKey(0)
    return img_hsv
```
<p>My HSV ranges</p>
<pre class="lang-py prettyprint-override"><code>COLORS = {
    'dark_red': {
        'lower': [0, 180, 100],
        'upper': [5, 240, 200]
    },
    'red': {
        'lower': [0, 150, 100],
        'upper': [10, 255, 255]
    },
    'white': {
        'lower': [0, 0, 168],
        'upper': [172, 111, 255]
    },
    'blue': {
        'lower': [100, 150, 0],
        'upper': [140, 255, 255]
    },
    'grey': {
        'lower': [36, 50, 70],
        'upper': [89, 255, 255]
    },
    'purple': {
        'lower': [129, 50, 70],
        'upper': [158, 255, 255]
    },
    'green': {
        'lower': [36, 50, 70],
        'upper': [89, 255, 255]
    },
    'yellow': {
        'lower': [25, 50, 70],
        'upper': [60, 255, 255]
    },
    'orange': {
        'lower': [5, 50, 50],
        'upper': [15, 180, 230]
    }
}
</code>```

I know it looks like I don't need all the colors but there are specific examples that use all the colors.

This is the image

My image to text function in case it's needed

```<code>def image_to_text(img):
    """
    :param img: PIL.Image
        Image object
    :return: text: str
        Generated text
    """
    # Tesseract path
    pytesseract.tesseract_cmd = "C:\\Program Files\\Tesseract-OCR\\tesseract.exe"

    img = pre_process_img(img)

    config = '--oem 3 --psm %d' % 6

    text = image_to_string(img, config=config, lang='eng')
    # Dirty text
    # print(text)
    return text
</code>```

My current output is

```<code>You have decided to bug § DaddyEredin's house tonight.
10 Pagond has left the game.
9 viagra has left the game.

Amember of the mafia visited 8 Blesser last night.
Amember of the mafia visited 14 jesus last night.
Amember of the mafia visited 7 Someone Especial last night.
</code>```

My desired output is

```<code>You have decided to bug § DaddyEredin's house tonight.
10 Pagond has left the game.
9 viagra has left the game.

You were attacked but someone nursed you back to health
Amember of the mafia visited 8 Blesser last night.
Amember of the mafia visited 14 jesus last night.
Amember of the mafia visited 7 Someone Especial last night.
</code>```

答:
The green bar and the green text has the same HSV values, so I'm lightening the image with the background. The bar in the resulting image is more saturated, while the text is not.

Also, 5 pixels of the image from both sides is cropped horizontally.

As a general rule, it is best to preprocess colors when there is a conflict.

def pre_process_img(img):
    # crop useless area
    img = img.crop((5, 0, img.size[0]-10, img.size[1]))
    # cut and stretch background strip
    open_cv_bg = np.array(img.crop((0, 0, 1, img.size[1])).resize(img.size)).astype(float)
    open_cv_image = np.array(img).astype(float)
    # blend lighten image with background to saturate the green bar
    diff = blend_modes.lighten_only(open_cv_image, open_cv_bg, 1).astype(np.uint8)

    # Convert image to HSV in order to be able to extract what we care about using masks
    img_hsv = cv2.cvtColor(diff, cv2.COLOR_RGB2HSV)

    # Init mask
    mask = 0
    for color_name, data in COLORS.items():
        if color_name not in ['white', 'green', 'yellow']:
            continue

        lower = np.array(data['lower'])
        upper = np.array(data['upper'])

        # Join masks
        mask += cv2.inRange(img_hsv, lower, upper)

    cv2.imshow("mask", mask)
    cv2.waitKey(0)
    return mask
```
<p>The image blended with its background to saturate the green background.
<img src="https://i.stack.imgur.com/viMUO.png" alt="saturated image" /></p>
<pre class="lang-py prettyprint-override"><code>COLORS = {
    'white': {
        'lower': [0, 0, 168],
        'upper': [172, 111, 255]
    },
    'green': {
        'lower': [55, 100, 50],
        'upper': [65, 220, 255]
    },
    'yellow': {
        'lower': [25, 100, 70],
        'upper': [50, 255, 255]
    }
}
</code>```

Output

```<code>a
You have decided to bug § DaddyEredin's house tonight.

10 Pagond has left the game.

9 viagra has left the game.

You were attacked but someone nursed you back to health!
Amember of the mafia visited 8 Blesser last night.

A member of the mafia visited 14 jesus last night.

A member of the mafia visited 7 Someone Especial last night.
</code>```

Body:
I want to pre-process this image for OCR. I want it to be able to read all the text from it, as you can see, the text has different colors. I'm using HSV ranges to detect the colors I want and I just turn everything into white so it's easier for the OCR software to translate the image into text. With my current settings it's reading all the text correctly except the one that it's surrounded by the light green background, I believe the issue is my HSV values, how could I adjust it so it reads all the text?

This is my preprocessing code:

def pre_process_img(img):
    """
    Prepares image for OCR

    :param img: PIL.Image
        Image object

    :return: output_img
    """
    open_cv_image = np.array(img)

    # Convert image to HSV in order to be able to extract what we care about using masks
    img_hsv = cv2.cvtColor(open_cv_image, cv2.COLOR_RGB2HSV)

    # Init mask
    mask = 0
    for color_name, data in ocr.COLORS.items():
        if color_name not in ['white', 'dark_red', 'yellow']:
            continue

        lower = np.array(data['lower'])
        upper = np.array(data['upper'])

        # Join masks
        mask += cv2.inRange(img_hsv, lower, upper)

    # Set my output img to zero everywhere except my mask
    # output_img = open_cv_image.copy()
    img_hsv[np.where(mask == 0)] = 0

    # Change image to white where we found the color we want
    img_hsv[mask > 0] = (255, 255, 255)

    # cv2.imshow("out", img_hsv)
    # cv2.waitKey(0)
    return img_hsv

My HSV ranges

COLORS = {
    'dark_red': {
        'lower': [0, 180, 100],
        'upper': [5, 240, 200]
    },
    'red': {
        'lower': [0, 150, 100],
        'upper': [10, 255, 255]
    },
    'white': {
        'lower': [0, 0, 168],
        'upper': [172, 111, 255]
    },
    'blue': {
        'lower': [100, 150, 0],
        'upper': [140, 255, 255]
    },
    'grey': {
        'lower': [36, 50, 70],
        'upper': [89, 255, 255]
    },
    'purple': {
        'lower': [129, 50, 70],
        'upper': [158, 255, 255]
    },
    'green': {
        'lower': [36, 50, 70],
        'upper': [89, 255, 255]
    },
    'yellow': {
        'lower': [25, 50, 70],
        'upper': [60, 255, 255]
    },
    'orange': {
        'lower': [5, 50, 50],
        'upper': [15, 180, 230]
    }
}

I know it looks like I don't need all the colors but there are specific examples that use all the colors.

This is the image

My image to text function in case it's needed

def image_to_text(img):
    """
    :param img: PIL.Image
        Image object
    :return: text: str
        Generated text
    """
    # Tesseract path
    pytesseract.tesseract_cmd = "C:\\Program Files\\Tesseract-OCR\\tesseract.exe"

    img = pre_process_img(img)

    config = '--oem 3 --psm %d' % 6

    text = image_to_string(img, config=config, lang='eng')
    # Dirty text
    # print(text)
    return text

My current output is

You have decided to bug § DaddyEredin's house tonight.
10 Pagond has left the game.
9 viagra has left the game.

Amember of the mafia visited 8 Blesser last night.
Amember of the mafia visited 14 jesus last night.
Amember of the mafia visited 7 Someone Especial last night.

My desired output is

You have decided to bug § DaddyEredin's house tonight.
10 Pagond has left the game.
9 viagra has left the game.

You were attacked but someone nursed you back to health
Amember of the mafia visited 8 Blesser last night.
Amember of the mafia visited 14 jesus last night.
Amember of the mafia visited 7 Someone Especial last night.

Body:
The green bar and the green text has the same HSV values, so I'm lightening the image with the background. The bar in the resulting image is more saturated, while the text is not.

Also, 5 pixels of the image from both sides is cropped horizontally.

As a general rule, it is best to preprocess colors when there is a conflict.

def pre_process_img(img):
    # crop useless area
    img = img.crop((5, 0, img.size[0]-10, img.size[1]))
    # cut and stretch background strip
    open_cv_bg = np.array(img.crop((0, 0, 1, img.size[1])).resize(img.size)).astype(float)
    open_cv_image = np.array(img).astype(float)
    # blend lighten image with background to saturate the green bar
    diff = blend_modes.lighten_only(open_cv_image, open_cv_bg, 1).astype(np.uint8)

    # Convert image to HSV in order to be able to extract what we care about using masks
    img_hsv = cv2.cvtColor(diff, cv2.COLOR_RGB2HSV)

    # Init mask
    mask = 0
    for color_name, data in COLORS.items():
        if color_name not in ['white', 'green', 'yellow']:
            continue

        lower = np.array(data['lower'])
        upper = np.array(data['upper'])

        # Join masks
        mask += cv2.inRange(img_hsv, lower, upper)

    cv2.imshow("mask", mask)
    cv2.waitKey(0)
    return mask

The image blended with its background to saturate the green background.

COLORS = {
    'white': {
        'lower': [0, 0, 168],
        'upper': [172, 111, 255]
    },
    'green': {
        'lower': [55, 100, 50],
        'upper': [65, 220, 255]
    },
    'yellow': {
        'lower': [25, 100, 70],
        'upper': [50, 255, 255]
    }
}

Output

a
You have decided to bug § DaddyEredin's house tonight.

10 Pagond has left the game.

9 viagra has left the game.

You were attacked but someone nursed you back to health!
Amember of the mafia visited 8 Blesser last night.

A member of the mafia visited 14 jesus last night.

A member of the mafia visited 7 Someone Especial last night.


答:
Your code is printing one's for each element found because your array only has one element in it!

Print i instead like so:

```<code>#include <iostream>
using namespace std;
int main(){
    int a,b,i;
    //int numbers[]={i};
    cin >>a>>b;
    for (i=a; i<=b; i++)
    {
        if (i%9==0)
        {
            cout << "i: " << i << endl;
        }
    }
}
</code>```

Title: Im trying to create a a code that count numbers divisible by 9 by putting numbers into an array and count the numbers in it

Body:
Your code is printing one's for each element found because your array only has one element in it!

Print i instead like so:

#include <iostream>
using namespace std;
int main(){
    int a,b,i;
    //int numbers[]={i};
    cin >>a>>b;
    for (i=a; i<=b; i++)
    {
        if (i%9==0)
        {
            cout << "i: " << i << endl;
        }
    }
}


问:
How to plot in edges and routes on the same folium in osmnx
I'm trying to plot edges and routes in an interactive map by using: ox.plot_graph_folium or ox.plot_routes_folium.

# plot the street network with folium
m1 = ox.plot_graph_folium(G, popup_attribute="name", weight=2, color="#8b0000")
```

I can plot the edges or routes separately, However, is there any way I can plot the edges and routes on the same grape?
This is my ideal output:

答:
According to the documentations: plot_graph_folium has the parameter graph_map, which is a folium.folium.Map object. As well, plot_route_folium has the parameter route_map, which is a folium.folium.Map object.
For both of these parameters the docs state:

if not None, plot on this preexisting folium map object

So you simply need to call one of these methods and take the returned folium map, e.g. your m1, and pass it to the respective parameter while calling the other method.

Body:
I'm trying to plot edges and routes in an interactive map by using: ox.plot_graph_folium or ox.plot_routes_folium.

# plot the street network with folium
m1 = ox.plot_graph_folium(G, popup_attribute="name", weight=2, color="#8b0000")

I can plot the edges or routes separately, However, is there any way I can plot the edges and routes on the same grape?
This is my ideal output:


问:
How to return values from C/++ functions correctly?
I have made some app and the method im using is this:

```<code>INT name(char *one,char *two,char buffer[]){
memcpy(buffer,"omg",4);//or using std::string::copy ... that's how I actually return value
...}
</code>```

and I call it like:

```<code>char returned[255];
name(first,second,returned);
printf/cout;
</code>```

Everything is fine. Now my question is, is this method terrible or a disaster? Also, what is going on with allocated memory for 255 chars, I mean is there a way to re-allocate it somehow to save memory a little?

This is so called pass-by-reference, in either case I have to return multiple values (from 2 to 10). If I would need only 1 I would use return buffer with static type I guess.

Thanks. Write your favourite methods please while I read similar questions to this one hehe.

答:
If you're talking C++ - That's pretty bad. Using std::strings, you can do the same thing:

```<code>void name(const string &first, const string &second, string &returned) {
    returned = first + second + "omg"; // Or something else
}
</code>```

And calling it:

```<code>string f = "one", s = "two", r;
name(f, s, r);
cout << r; // 'R' now contains "onetwoomg"
</code>```

Although 'mutating' things like this isn't very C++. In C it's used a lot, but in C++ you generally assign to a returned value rather than pass by non-const reference.

ContentLicense: CC BY-SA 3.0

Body:
I have made some app and the method im using is this:

INT name(char *one,char *two,char buffer[]){
memcpy(buffer,"omg",4);//or using std::string::copy ... that's how I actually return value
...}

and I call it like:

char returned[255];
name(first,second,returned);
printf/cout;

Everything is fine. Now my question is, is this method terrible or a disaster? Also, what is going on with allocated memory for 255 chars, I mean is there a way to re-allocate it somehow to save memory a little?

This is so called pass-by-reference, in either case I have to return multiple values (from 2 to 10). If I would need only 1 I would use return buffer with static type I guess.

Thanks. Write your favourite methods please while I read similar questions to this one hehe.

Body:
If you're talking C++ - That's pretty bad. Using std::strings, you can do the same thing:

void name(const string &first, const string &second, string &returned) {
    returned = first + second + "omg"; // Or something else
}

And calling it:

string f = "one", s = "two", r;
name(f, s, r);
cout << r; // 'R' now contains "onetwoomg"

Although 'mutating' things like this isn't very C++. In C it's used a lot, but in C++ you generally assign to a returned value rather than pass by non-const reference.


问:
How can i setup connection timeout error in websocket?
I am trying to toast a message if I don't get a response from a WebSocket connection but I am not able to figure out how to do so</p>

答:
You can display the message after some timeout:

Start a timer when you send the request, which will display the message when this timer has finished

Cancel the timer when the response comes.

You can not display a message if the response never comes, because you can not know if the response will eventually come any time later.


问:
Assemble multiple lists into a single list through a loop
As part of an application reading Csv files made using tkinder and the tksheet library, I would have liked to ensure that each of the lines retrieved from my spreadsheet and individually transformed into a list could be grouped into a single and unique comma separated list.

I currently have the following code:

with open('my_csv_file.csv') as csvfile:
     reader = csv.reader(csvfile, delimiter=';')

     for row in reader:
         if row != '' and row[0].isdigit():
            liste = [row[0], row[1], row[2], row[3], row[4]]
            print(liste)
```
<p>Output :</p>
```['AAA', 'AAA', 'AAA', 'AAA', 'AAA']
['BBB', 'BBB', 'BBB', 'BBB', 'BBB']
['CCC', 'CCC', 'CCC', 'CCC', 'CCC']
```
<p>What I want:</p>
```[['AAA', 'AAA', 'AAA', 'AAA', 'AAA'],
['BBB', 'BBB', 'BBB', 'BBB', 'BBB'],
['CCC', 'CCC', 'CCC', 'CCC', 'CCC']]
```

答:
Append to the top list to make your nested list.</p>
```<code>lst = []

with open('my_csv_file.csv') as csvfile:
     reader = csv.reader(csvfile, delimiter=';')

     for row in reader:
         if row != '' and row[0].isdigit():
            lst.append([row[0], row[1], row[2], row[3], row[4]])

print(lst)
</code>```

Body:
As part of an application reading Csv files made using tkinder and the tksheet library, I would have liked to ensure that each of the lines retrieved from my spreadsheet and individually transformed into a list could be grouped into a single and unique comma separated list.

I currently have the following code:

with open('my_csv_file.csv') as csvfile:
     reader = csv.reader(csvfile, delimiter=';')

     for row in reader:
         if row != '' and row[0].isdigit():
            liste = [row[0], row[1], row[2], row[3], row[4]]
            print(liste)

Output :

['AAA', 'AAA', 'AAA', 'AAA', 'AAA']
['BBB', 'BBB', 'BBB', 'BBB', 'BBB']
['CCC', 'CCC', 'CCC', 'CCC', 'CCC']

What I want:

[['AAA', 'AAA', 'AAA', 'AAA', 'AAA'],
['BBB', 'BBB', 'BBB', 'BBB', 'BBB'],
['CCC', 'CCC', 'CCC', 'CCC', 'CCC']]

Body:
Append to the top list to make your nested list.

lst = []

with open('my_csv_file.csv') as csvfile:
     reader = csv.reader(csvfile, delimiter=';')

     for row in reader:
         if row != '' and row[0].isdigit():
            lst.append([row[0], row[1], row[2], row[3], row[4]])

print(lst)


问:
Getting illegal character when sending GET request in JMETER. Working fine in browser
Im getting illegal character in JMETER for GET request -
https://dev1/api/v1/query/job/?filter={%22job_manager_id%22:%22553f2350-12d3-4252-8fe0-39691019c495%22}
tried replacing %22 with "" but still getting illegal character.
Any solutions ?</p>

答:
I think problematic characters are { and }, they need to be percent-encoded

The options are in:

Tick "URL-encode" box next to the filter parameter in the HTTP Request sampler :

Use __urlencode() function in "Path" field like

see Apache JMeter Functions - An Introduction article to learn more about JMeter Functions concept

Or just hard-code the percent-encoded Path part like:

```<code>https://dev1/api/v1/query/job/?filter=%7B%22job_manager_id%22%3A%22553f2350-12d3-4252-8fe0-39691019c495%22%7D
</code>```

Body:
I think problematic characters are { and }, they need to be percent-encoded

The options are in:

Tick "URL-encode" box next to the filter parameter in the HTTP Request sampler :

Use __urlencode() function in "Path" field like

see Apache JMeter Functions - An Introduction article to learn more about JMeter Functions concept

Or just hard-code the percent-encoded Path part like:

https://dev1/api/v1/query/job/?filter=%7B%22job_manager_id%22%3A%22553f2350-12d3-4252-8fe0-39691019c495%22%7D


问:
Turning date into integers in R
I have a data frame in R and I have a month column and a day column containing characters like "jan", "feb", or "mar" for months or "mon", "tue" or "wed" for days. I would like to find a way to convert both columns into integers ranging from 1 to 12 for months and 1 to 7 for days. I have tried built-in functions like month.abb but when I try using match with the column for months it just returns a list of NA. Thank you very much for your help !</p>

答:
A general method would be to define a factor with the levels you want, and then turn it into an integer. See reprex underneath.

This would also work for weekdays.

months <- c(
  "jan", "feb", "mar", "apr", "may", "jun",
  "jul", "aug", "sep", "oct", "nov", "des"
  )

x <- sample(months, 10, replace = TRUE)

x
#>  [1] "sep" "oct" "mar" "jun" "oct" "mar" "apr" "aug" "jul" "sep"

as.integer(factor(x, levels = months))
#>  [1]  9 10  3  6 10  3  4  8  7  9
```

Title: Turning date into integers in R


问:
Firebase serve error: Port 5000 is not open. Could not start functions emulator
I'm trying to serve firebase functions locally, but when I run firebase serve or firebase emulators:start the error message is: "Port 5000 is not open, could not start functions emulator."

I'm using Windows 10, so I've tried to change the port number, check if the port is blocked by Firewall and I create a new rule in Firewall to ports 5000-5010 but none of this approaches worked for me.

答:
macOS Monterey 12.2 user here. I've simply changed the port to 5005 and it worked like a charm.</p>
```<code>{
  "hosting": {
    "public": "functions/browser",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "function": "ssrapp"
      }
    ]
  },
  "emulators": {
    "hosting": {
      "port": "5005"
    }
  }
}
</code>```

Body:
macOS Monterey 12.2 user here. I've simply changed the port to 5005 and it worked like a charm.

{
  "hosting": {
    "public": "functions/browser",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "function": "ssrapp"
      }
    ]
  },
  "emulators": {
    "hosting": {
      "port": "5005"
    }
  }
}


问:
css button font size doesn't work
I can't get a input button to change its font size unless I change the background color.

this html:

```<code><input type="button" id="startStop" value="start" />
</code>```

and this css:

```<code>input#startStop{
    font-size: 3em;
}
</code>```

result in this:

which is exactly the same as with no styling at all.

Nothing I do to the css changes it: making it 60em; changing how I select it; they all result in the same, default-looking button.

I inspected it in Chrome, and the style is actually hitting the element, and not getting overridden:

But somehow the computed style isn't working:

(that's with a base font-size of 1em for the whole document. and, no, changing the base font-size has no effect)

The only thing that changes the font size it is if I give it a background-color:

```<code>input#startStop{
    font-size: 3em;
    background-color: white;
}
</code>```

results in this:

Can anybody tell me what is going on?

EDIT: @Hashem Qolami, thanks for posting it in an external editor, which I should have done. When I look at your JS bin, it looks like this:

EDIT 2: it's browser specific.

The error is only occurring on Chrome, Safari and Opera, and only on Mac.

If renders correctly on Firefox for Mac and on all browsers (IE10, Chrome, Firefox, Safari, and Opera) on windows.

答: I see that you successfully had solved the problem, but I wonder, if the only problem is to make the button bigger, why sticking to font-size method while you can also change the button size by width + height or padding.</p>

Title: css button font size doesn't work

Body:
I can't get a input button to change its font size unless I change the background color.

this html:

<input type="button" id="startStop" value="start" />

and this css:

input#startStop{
    font-size: 3em;
}

result in this:

which is exactly the same as with no styling at all.

Nothing I do to the css changes it: making it 60em; changing how I select it; they all result in the same, default-looking button.

I inspected it in Chrome, and the style is actually hitting the element, and not getting overridden:

But somehow the computed style isn't working:

(that's with a base font-size of 1em for the whole document. and, no, changing the base font-size has no effect)

The only thing that changes the font size it is if I give it a background-color:

input#startStop{
    font-size: 3em;
    background-color: white;
}

results in this:

Can anybody tell me what is going on?

EDIT: @Hashem Qolami, thanks for posting it in an external editor, which I should have done. When I look at your JS bin, it looks like this:

EDIT 2: it's browser specific.

The error is only occurring on Chrome, Safari and Opera, and only on Mac.

If renders correctly on Firefox for Mac and on all browsers (IE10, Chrome, Firefox, Safari, and Opera) on windows.


问:
Python - implement range of mysql cursor command in for loop
I am trying to extract data for many points from MySQL database via cursor() in python. So Far my code looks like:

```<code>cursor1 = db.cursor()
cursor2 = db.cursor()

sql_select_Query1 ="SELECT AVG(IWV) As AverageIWV FROM GNSS_OUT WHERE StationID=51 AND Datetime BETWEEN '2021-05-01' AND '2021-05-31' AND SourceGpsID=23 ;"
    cursor1.execute(sql_select_Query1)

sql_select_Query2 ="SELECT AVG(IWV) As AverageIWV FROM GNSS_OUT WHERE StationID=52 AND Datetime BETWEEN '2021-05-01' AND '2021-05-31' AND SourceGpsID=23 ;"

cursor2.execute(sql_select_Query2)

yaxis1 = cursor1.fetchall()
yaxis2 = cursor2.fetchall()
</code>```

And it works well, but I need more than 2 values I want to make it compact, maybe in a for loop with range(). I've tried something like this:

```<code>for m in range(1,5):
    exec(f'cursor{m} = db.cursor()')

for n in range(1,5):
    for stat in range(51,55):
        exec(f'sql_select_AVG{n} = "SELECT AVG(IWV) As AverageIWV FROM GNSS_OUT WHERE StationID={stat} AND Datetime BETWEEN '2021-05-01' AND '2021-05-31' AND SourceGpsID=23 ;"')

        exec(f'cursor{n}.executemany(sql_select_AVG{n})')

        exec(f'yaxis{n}=cursor{n}.fetchall()')
</code>```

And when I run the script I get:

```<code>exec(cursor{m} = db.cursor())
               ^
SyntaxError: invalid syntax
</code>```

答:
The best way to do this is to use lists or dictionaries to hold the queries and results, something like this:

queries = ['SELECT ...', 'SELECT ...', ...]
y_axes = []

cur = db.cursor()
for query in queries:
    cur.execute(query)
    y_axes.append(cur.fetchall())
```

Once the loop has completed, y_axes will contain the result of each query as a sublist, so you can loop over y_axes to perform further processing.

You can also use the zip built-in function to loop over lists in parallel.

Body:
I am trying to extract data for many points from MySQL database via cursor() in python. So Far my code looks like:

cursor1 = db.cursor()
cursor2 = db.cursor()

sql_select_Query1 ="SELECT AVG(IWV) As AverageIWV FROM GNSS_OUT WHERE StationID=51 AND Datetime BETWEEN '2021-05-01' AND '2021-05-31' AND SourceGpsID=23 ;"
    cursor1.execute(sql_select_Query1)

sql_select_Query2 ="SELECT AVG(IWV) As AverageIWV FROM GNSS_OUT WHERE StationID=52 AND Datetime BETWEEN '2021-05-01' AND '2021-05-31' AND SourceGpsID=23 ;"

cursor2.execute(sql_select_Query2)

yaxis1 = cursor1.fetchall()
yaxis2 = cursor2.fetchall()

And it works well, but I need more than 2 values I want to make it compact, maybe in a for loop with range(). I've tried something like this:

for m in range(1,5):
    exec(f'cursor{m} = db.cursor()')

for n in range(1,5):
    for stat in range(51,55):
        exec(f'sql_select_AVG{n} = "SELECT AVG(IWV) As AverageIWV FROM GNSS_OUT WHERE StationID={stat} AND Datetime BETWEEN '2021-05-01' AND '2021-05-31' AND SourceGpsID=23 ;"')

        exec(f'cursor{n}.executemany(sql_select_AVG{n})')

        exec(f'yaxis{n}=cursor{n}.fetchall()')

And when I run the script I get:

exec(cursor{m} = db.cursor())
               ^
SyntaxError: invalid syntax

Body:
The best way to do this is to use lists or dictionaries to hold the queries and results, something like this:

queries = ['SELECT ...', 'SELECT ...', ...]
y_axes = []

cur = db.cursor()
for query in queries:
    cur.execute(query)
    y_axes.append(cur.fetchall())

Once the loop has completed, y_axes will contain the result of each query as a sublist, so you can loop over y_axes to perform further processing.

You can also use the zip built-in function to loop over lists in parallel.


问:
Google Sheets: Query data with HH:MM format
Which query should I use to calculate Total shift time and Total task time grouped by Shift?

Google Sheets query doesn't allow me to sum Col2 or Col3 because it's formatted into HH:MM (I can't change it to number because source data is HH:MM).

答:
I feel you should change your source data so that the shift pattern is formatted to include both date and time.  Then follow this procedure to do the correct arithmetic:

https://www.ablebits.com/office-addins-blog/2017/10/19/calculating-time-google-sheets/