问:
Execute javascript from inside update panel on every refresh
I have an aspx page which is made of 3 user controls (ascx). I have an update panel wrapping the 3 user controls like this:

```<code><asp:UpdatePanel ID="UpdatePanelWrapper" runat="server">
    <ContentTemplate>
         <uc1:UserControl1 ID="UserControl1" runat="server" />
         <uc2:UserControl2 ID="UserControl2" runat="server"/>
         <uc2:UserControl3 ID="UserControl3" runat="server"/>
    </ContentTemplate>
</asp:UpdatePanel>
</code>```

I show each user control by separate, so when "UserControl1" is displayed, the other 2 user controls are hidden.

Inside "UserControl1" I have some asp controls and some javascript functions. My problem is that these javascript functions are never called when "UpdatePanelWrapper" is refreshed.

I have tried this solution http://blog.dreamlabsolutions.com/post/2009/02/24/jQuery-document-ready-and-ASP-NET-Ajax-asynchronous-postback.aspx, by adding that javascript call inside the "UserControl1", though it's not working. I made it work only if I add that javascript call in the aspx page, but not inside the "UserControl1".

Any help would be appreciated, Thank you.

答:
Ideally, all of your JavaScript should be at the bottom of your page right before the closing  tag.

If you are using jQuery, you would need to use live() or delegate() to make sure those event handlers bubble up, even when the page gets refreshed.

Body:
I have an aspx page which is made of 3 user controls (ascx). I have an update panel wrapping the 3 user controls like this:

<asp:UpdatePanel ID="UpdatePanelWrapper" runat="server">
    <ContentTemplate>
         <uc1:UserControl1 ID="UserControl1" runat="server" />
         <uc2:UserControl2 ID="UserControl2" runat="server"/>
         <uc2:UserControl3 ID="UserControl3" runat="server"/>
    </ContentTemplate>
</asp:UpdatePanel>

I show each user control by separate, so when "UserControl1" is displayed, the other 2 user controls are hidden.

Inside "UserControl1" I have some asp controls and some javascript functions. My problem is that these javascript functions are never called when "UpdatePanelWrapper" is refreshed.

I have tried this solution http://blog.dreamlabsolutions.com/post/2009/02/24/jQuery-document-ready-and-ASP-NET-Ajax-asynchronous-postback.aspx, by adding that javascript call inside the "UserControl1", though it's not working. I made it work only if I add that javascript call in the aspx page, but not inside the "UserControl1".

Any help would be appreciated, Thank you.

Body:
Ideally, all of your JavaScript should be at the bottom of your page right before the closing </body> tag.

If you are using jQuery, you would need to use live() or delegate() to make sure those event handlers bubble up, even when the page gets refreshed.


来源: stackexchange

问:
How to nest abstract relationship in Django rest framework?
I have a model called Layer that has a one-to-one relationship with Geometry, and Geometry have the following design:

```<code>class Geometry(models.Model):
    pass

class Circle(Geometry):
    radius = models.CharField(max_length=255)

class Rectangle(Geometry):
    height = models.CharField(max_length=255)
    width = models.CharField(max_length=255)
</code>```

How should I define the Layer serializer to make the layer json contain a property called "geometry" regardless of which child model it has a relationship with? I don't want the property to be called neither circle nor rectangle.

Thanks in advance!

答:
You can use seperated serializers for each child models.You can decide with type param which serializer used for geometry key in dict.</p>

```<code>data = {'geometry': CircleSerializer(circle_model_object).data if type == 'circle' else RectangleSerializer(rectangle_model_object).data}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a model called Layer that has a one-to-one relationship with Geometry, and Geometry have the following design:

class Geometry(models.Model):
    pass

class Circle(Geometry):
    radius = models.CharField(max_length=255)

class Rectangle(Geometry):
    height = models.CharField(max_length=255)
    width = models.CharField(max_length=255)

How should I define the Layer serializer to make the layer json contain a property called "geometry" regardless of which child model it has a relationship with? I don't want the property to be called neither circle nor rectangle.

Thanks in advance!

Body:
You can use seperated serializers for each child models.You can decide with type param which serializer used for geometry key in dict.

data = {'geometry': CircleSerializer(circle_model_object).data if type == 'circle' else RectangleSerializer(rectangle_model_object).data}


问:
React Native - Get file name from android content uri

I need to get file name from android content uri, for example:

content://com.android.providers.downloads.documents/document/15

I try to used react-native-fs stat but it return error of "File does not exist".

How can I do it?

答:
I not found pure solution in react native, so I created native package in android and created module in react native from so I can use it.

This the the android code:

```<code>@ReactMethod
    public void getFileNameFromUri(String filepath, Promise promise) {
        Uri uri = Uri.parse(filepath);
        String fileName = "";

        if (uri.getScheme().equals("content")) {
            try {
                Cursor cursor = reactContext.getContentResolver().query(uri, null, null, null, null);

                if (cursor.moveToFirst()) {
                    fileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                    Log.d("FS", "Real File name: " + fileName);
                }
                cursor.close();
                promise.resolve(fileName);
            } catch (IllegalArgumentException ignored) {
                promise.reject("1", "Can not get cursor");
            }
        } else {
            promise.resolve(fileName);
        }
    }
</code>```

This is how to module in react native from android native code:
 react-native-modules-android

Body:
I not found pure solution in react native, so I created native package in android and created module in react native from so I can use it.

This the the android code:

@ReactMethod
    public void getFileNameFromUri(String filepath, Promise promise) {
        Uri uri = Uri.parse(filepath);
        String fileName = "";

        if (uri.getScheme().equals("content")) {
            try {
                Cursor cursor = reactContext.getContentResolver().query(uri, null, null, null, null);

                if (cursor.moveToFirst()) {
                    fileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                    Log.d("FS", "Real File name: " + fileName);
                }
                cursor.close();
                promise.resolve(fileName);
            } catch (IllegalArgumentException ignored) {
                promise.reject("1", "Can not get cursor");
            }
        } else {
            promise.resolve(fileName);
        }
    }

This is how to module in react native from android native code:
 react-native-modules-android


问:
Why does the While loop inside the QT loop is not blocking the QT GUI
I am using GLFW along with QT for an opengl application.

i have a while loop inside the main function.

Why the while loop is not blocking the QT GUI ?

```<code>int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    cont.SetName("RootItem");
    TreeModel* model = new TreeModel("RootElement", &cont);
    WavefrontRenderer w(model);
    w.show();
    glfwInit();
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    glfwWindowHint(GLFW_SAMPLES, 4);
    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Renderer", nullptr, nullptr);   //
    glfwMakeContextCurrent(window);
    GLenum GlewInitResult;
    glewExperimental = GL_TRUE;
    GlewInitResult = glewInit();

    w.InitData();

    while (!glfwWindowShouldClose(window))
    {
        glClearColor(0.0, 0.3, 0.3, 0.0);
        glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
        w.render();
        glfwPollEvents();
        glfwSwapBuffers(window);
    }
    // glfw: terminate, clearing all previously allocated GLFW resources.
    // ------------------------------------------------------------------
    glfwTerminate();
    //return 0;

    return a.exec();
</code>```

}

答:
It seems like glfwPollEvents acts in a similar enough way to QApplication::exec such that (some) events get properly processed.

They probably both call DispatchMessage (see) which then lets registered callback for a window handle the event.

But it might also be that both do additional bookkeeping which could make reliance on that error prone.

Body:
I am using GLFW along with QT for an opengl application.

i have a while loop inside the main function.

Why the while loop is not blocking the QT GUI ?

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    cont.SetName("RootItem");
    TreeModel* model = new TreeModel("RootElement", &cont);
    WavefrontRenderer w(model);
    w.show();
    glfwInit();
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    glfwWindowHint(GLFW_SAMPLES, 4);
    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Renderer", nullptr, nullptr);   //
    glfwMakeContextCurrent(window);
    GLenum GlewInitResult;
    glewExperimental = GL_TRUE;
    GlewInitResult = glewInit();

    w.InitData();

    while (!glfwWindowShouldClose(window))
    {
        glClearColor(0.0, 0.3, 0.3, 0.0);
        glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
        w.render();
        glfwPollEvents();
        glfwSwapBuffers(window);
    }
    // glfw: terminate, clearing all previously allocated GLFW resources.
    // ------------------------------------------------------------------
    glfwTerminate();
    //return 0;

    return a.exec();

}


问:
How can I force a TD with no content to render its border?
The TD has a DIV inside which I removed using jQuery's fadeOut function, but when it finishes the border disappears too.

I want to avoid that, is there any way other than adding a " " (which causes it to be ugly)?

EDIT: I am using Internet Explorer (6 and 7)

答:
So if you have a table like below:

```<code><table border="1">
<tr>
 <td>Breakfast</td>
 <td><div id="foo">Lunch</div></td>
 <td>Dinner</td></tr>
</table>
</code>```

And you fadeOut, with jQuery, Lunch, why not bring back a blank nothing with fadeIn?

Like below:

```<code>$("#foo").fadeOut("slow").html('').fadeIn("fast");
</code>```

OwnerDisplayName: Juan Manuel

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Graeme Perrow

Body:
So if you have a table like below:

<table border="1">
<tr>
 <td>Breakfast</td>
 <td><div id="foo">Lunch</div></td>
 <td>Dinner</td></tr>
</table>

And you fadeOut, with jQuery, Lunch, why not bring back a blank nothing with fadeIn?

Like below:

$("#foo").fadeOut("slow").html('').fadeIn("fast");

OwnerDisplayName: Random Echo


问:
SQL query join in Pandas
I would like to join two tables in Pandas.

df_types
Contains range size of type product (5000 rows)

```<code>| Table: TYPES |          |      |
|--------------|----------|------|
| size_max     | size_min | type |
| 1            | 5        | S    |
| 6            | 16       | M    |
| 16           | 24       | L    |
| 25           | 50       | XL   |
</code>```

Dataframe code in Pandas:

```<code>df_types = pd.DataFrame([[1,5,'S'],
                         [6,16,'M'],
                         [16,24,'L'],
                         [25,50,'XL']],
                        columns = ['size_min','size_max','type'])
</code>```

df_products
Contains products id and size (12000 rows)

```<code>| Table: Products |      |
|-----------------|------|
| id_product      | size |
| A               | 6    |
| B               | 25   |
| C               | 7    |
| D               | 2    |
| F               | 45   |
| E               | 10   |
| G               | 16   |
</code>```

Dataframe code in Pandas:

```<code>df_products = pd.DataFrame([['A',6,],
                            ['B',25],
                            ['C',7],
                            ['D',2],
                            ['F',45],
                            ['E',10],
                            ['G',16]],columns = ['id_product','size'])
</code>```

I´d like to make this SQL join in Pandas:

```<code>SELECT  *.df_products
        type.df_types
FROM    df_products     LEFT JOIN df_types
                        ON  df_products.size >= df_types.size_min
                            AND df_products.size <= df_types.size_max
</code>```

RESULT:

```<code>| id_product | size | type |
|------------|------|------|
| A          | 6    | M    |
| B          | 25   | XL   |
| C          | 7    | M    |
| D          | 2    | S    |
| F          | 45   | XL   |
| E          | 10   | M    |
| G          | 16   | M    |
</code>```

thank you! ;-)

答:
Method 1: outer join with pd.merge

Although this is a common operation SQL, there's no straightforward method for this with pandas.

One of the solutions here would be to do an outer join to match all rows and then use DataFrame.query filter the rows where size is between size_min & size_max.

But this result in an explosion of rows, so in your case 12000*5000 = 60 000 000 rows.

```<code>dfn = (
    df_products.assign(key=1)
      .merge(df_types.assign(key=1), on='key')
      .query('size >= size_min & size < size_max')
      .drop(columns='key')
)

   id_product  size  size_min  size_max type
1           A     6         6        16    M
7           B    25        25        50   XL
9           C     7         6        16    M
12          D     2         1         5    S
19          F    45        25        50   XL
21          E    10         6        16    M
26          G    16        16        24    L
</code>```

Method 2: pd.IntervalIndex:

If you don't have overlapping ranges, so if we change size_min 16 in dataframe df_types to 15, we can use this method. This will not result in an explosion of rows.

```<code>idx = pd.IntervalIndex.from_arrays(df_types['size_min'], df_types['size_max'], closed='both')
event = df_types.loc[idx.get_indexer(df_products['size']), 'type'].to_numpy()

df_products['type'] = event

  id_product  size type
0          A     6    M
1          B    25   XL
2          C     7    M
3          D     2    S
4          F    45   XL
5          E    10    M
6          G    16    L
</code>```

Title: SQL query join in Pandas

Body:
I would like to join two tables in Pandas.

df_types
Contains range size of type product (5000 rows)

| Table: TYPES |          |      |
|--------------|----------|------|
| size_max     | size_min | type |
| 1            | 5        | S    |
| 6            | 16       | M    |
| 16           | 24       | L    |
| 25           | 50       | XL   |

Dataframe code in Pandas:

df_types = pd.DataFrame([[1,5,'S'],
                         [6,16,'M'],
                         [16,24,'L'],
                         [25,50,'XL']],
                        columns = ['size_min','size_max','type'])

df_products
Contains products id and size (12000 rows)

| Table: Products |      |
|-----------------|------|
| id_product      | size |
| A               | 6    |
| B               | 25   |
| C               | 7    |
| D               | 2    |
| F               | 45   |
| E               | 10   |
| G               | 16   |

Dataframe code in Pandas:

df_products = pd.DataFrame([['A',6,],
                            ['B',25],
                            ['C',7],
                            ['D',2],
                            ['F',45],
                            ['E',10],
                            ['G',16]],columns = ['id_product','size'])

I´d like to make this SQL join in Pandas:

SELECT  *.df_products
        type.df_types
FROM    df_products     LEFT JOIN df_types
                        ON  df_products.size >= df_types.size_min
                            AND df_products.size <= df_types.size_max

RESULT:

| id_product | size | type |
|------------|------|------|
| A          | 6    | M    |
| B          | 25   | XL   |
| C          | 7    | M    |
| D          | 2    | S    |
| F          | 45   | XL   |
| E          | 10   | M    |
| G          | 16   | M    |

thank you! ;-)

Body:
Method 1: outer join with pd.merge

Although this is a common operation SQL, there's no straightforward method for this with pandas.

One of the solutions here would be to do an outer join to match all rows and then use DataFrame.query filter the rows where size is between size_min & size_max.

But this result in an explosion of rows, so in your case 12000*5000 = 60 000 000 rows.

dfn = (
    df_products.assign(key=1)
      .merge(df_types.assign(key=1), on='key')
      .query('size >= size_min & size < size_max')
      .drop(columns='key')
)

   id_product  size  size_min  size_max type
1           A     6         6        16    M
7           B    25        25        50   XL
9           C     7         6        16    M
12          D     2         1         5    S
19          F    45        25        50   XL
21          E    10         6        16    M
26          G    16        16        24    L

Method 2: pd.IntervalIndex:

If you don't have overlapping ranges, so if we change size_min 16 in dataframe df_types to 15, we can use this method. This will not result in an explosion of rows.

idx = pd.IntervalIndex.from_arrays(df_types['size_min'], df_types['size_max'], closed='both')
event = df_types.loc[idx.get_indexer(df_products['size']), 'type'].to_numpy()

df_products['type'] = event

  id_product  size type
0          A     6    M
1          B    25   XL
2          C     7    M
3          D     2    S
4          F    45   XL
5          E    10    M
6          G    16    L


问:
Remove duplicates from the string in CPP
I wrote the following code for removing the duplicates from a given string i.e. if ARRUN is the input then the output will be ARUN.

```<code>#include <bits/stdc++.h>
using namespace std;
char* removeDuplicates(string &s,int n){
    char arr[n];
    unordered_map<char,int> exists;
    int index = 0;
    for(int i=0;i<n;i++){
        if(exists[s[i]]==0)
        {
            arr[index++] = s[i];
            exists[s[i]]++;
        }
    }
    return arr;
}

//driver code
int main(){
    string str;
    cin >> str;
    cout<<removeDuplicates(str,str.length())<<endl;
    return 0;
}
</code>```

The code produces no output at all, however, it works fine if I use char arr[] instead of string class.

答:
If a function declaration looks the following way

```<code>char* removeDuplicates(string &s,int n);
</code>```

then it means that the passed object itself will be changed in the function.  Otherwise the parameter shall have the qualifier const.

Also it is unclear why the function has return type char *. It looks like the declaration of the function is contradictive.

The second parameter of the function shall have at least the type size_t or that is better std::string::size_type. The type int can not accomodate all values of the type std::string::size_type.

The function could be declared without the second parameter.

A straightforward approach without using intermediate containers that requires dynamic memory allocation can look the following way

```<code>#include <iostream>
#include <string>

std::string & removeDuplicate( std::string &s )
{
    const char *p = s.c_str();

    std::string::size_type pos = 0;

    for ( std::string::size_type i = 0, n = s.size(); i < n; i++ )
    {
        std::string::size_type j = 0;
        while ( j < pos && s[i] != s[j] ) j++;

        if ( j == pos )
        {
            if ( i != pos ) s[pos] = s[i];
            ++pos;
        }
    }

    return s.erase( pos );
}

int main()
{
    std::string s( "H e l l o" );

    std::cout << "\"" << s <<"\"\n";

    std::cout << "\"" << removeDuplicate( s ) <<"\"\n";

    return 0;
}
</code>```

The program output is

```<code>"H e l l o"
"H elo"
</code>```

Body:
I wrote the following code for removing the duplicates from a given string i.e. if ARRUN is the input then the output will be ARUN.

#include <bits/stdc++.h>
using namespace std;
char* removeDuplicates(string &s,int n){
    char arr[n];
    unordered_map<char,int> exists;
    int index = 0;
    for(int i=0;i<n;i++){
        if(exists[s[i]]==0)
        {
            arr[index++] = s[i];
            exists[s[i]]++;
        }
    }
    return arr;
}

//driver code
int main(){
    string str;
    cin >> str;
    cout<<removeDuplicates(str,str.length())<<endl;
    return 0;
}

The code produces no output at all, however, it works fine if I use char arr[] instead of string class.

Body:
If a function declaration looks the following way

char* removeDuplicates(string &s,int n);

then it means that the passed object itself will be changed in the function.  Otherwise the parameter shall have the qualifier const.

Also it is unclear why the function has return type char *. It looks like the declaration of the function is contradictive.

The second parameter of the function shall have at least the type size_t or that is better std::string::size_type. The type int can not accomodate all values of the type std::string::size_type.

The function could be declared without the second parameter.

A straightforward approach without using intermediate containers that requires dynamic memory allocation can look the following way

#include <iostream>
#include <string>

std::string & removeDuplicate( std::string &s )
{
    const char *p = s.c_str();

    std::string::size_type pos = 0;

    for ( std::string::size_type i = 0, n = s.size(); i < n; i++ )
    {
        std::string::size_type j = 0;
        while ( j < pos && s[i] != s[j] ) j++;

        if ( j == pos )
        {
            if ( i != pos ) s[pos] = s[i];
            ++pos;
        }
    }

    return s.erase( pos );
}

int main()
{
    std::string s( "H e l l o" );

    std::cout << "\"" << s <<"\"\n";

    std::cout << "\"" << removeDuplicate( s ) <<"\"\n";

    return 0;
}

The program output is

"H e l l o"
"H elo"


问:
How many minimum and maximum records FULL JOIN can return
This question is interested me in SQL query. How many min. and max. records FULL JOIN can return when joining two tables without any other conditions? Say, if there are 5 rows in table '1' and 10 rows in table '2'.

It seems to me that the minimum and maximum will be equal. 10/10. Is it so?

Exm:

```<code>SELECT customers.customer_id,

orders.order_id,

orders.order_date

FROM customers

FULL OUTER JOIN orders

ON customers.customer_id = orders.customer_id
</code>```

答:
The minimum number of rows is the number of rows in the largest table.  This would occur if all the join keys were unique and all the keys in the smaller table match keys in the larger table.

The maximum number of rows is the product of the rows in the two tables -- equivalent to a Cartesian join.  This would occur if all the keys in the two tables were the same.

So, if one table has 5 rows and the other 10, the minimum is 10 and the maximum 50.

Here is a db<>fiddle, illustrating these cases.

Body:
This question is interested me in SQL query. How many min. and max. records FULL JOIN can return when joining two tables without any other conditions? Say, if there are 5 rows in table '1' and 10 rows in table '2'.

It seems to me that the minimum and maximum will be equal. 10/10. Is it so?

Exm:

SELECT customers.customer_id,

orders.order_id,

orders.order_date

FROM customers

FULL OUTER JOIN orders

ON customers.customer_id = orders.customer_id


问:
Using cProfile on application with entry point
I know cProfile can be used like this

```<code>python -m cProfile script.py
</code>```

But suppose I have a packaged application (pip-installable) with an entry_point defined in setup.py, such that I can call the application from the terminal, without explicitly using any .py file. How can I use cProfile in that case?

答:
What if someone is using click for CLI ?
It seems not to be working for me.

Update:
Actually cProfile requires main, and adding standard

```<code>if __name__=="__main__":
    cli()
</code>```

to mymodule/cli.py program, solved the issue.

Body:
I know cProfile can be used like this

python -m cProfile script.py

But suppose I have a packaged application (pip-installable) with an entry_point defined in setup.py, such that I can call the application from the terminal, without explicitly using any .py file. How can I use cProfile in that case?

Body:
What if someone is using click for CLI ?
It seems not to be working for me.

Update:
Actually cProfile requires main, and adding standard

if __name__=="__main__":
    cli()

to mymodule/cli.py program, solved the issue.


问:
How to Hide PHP Undefined Error Messages with Echo?
I'm new to PHP and I'm trying to have a div where it outputs the user information after the user submits it by using echo.

This is my code right now:

  Name <input type="text" id="cust[name]" placeholder="E.g. John Doe" required>

  Email <input type="email" id="cust[email]" placeholder="E.g. john@mail.com" required>

  Mobile <input type="text" id="cust[mobile]" placeholder="E.g. (04) 6172 5705" required>

Name: <?php echo $_POST["cust-name"]; ?>

Email: <?php echo $_POST["cust-email"]; ?>

Mobile: <?php echo $_POST["cust-mobile"]; ?>
```

It doesn't give the error in the example above, but on the page it gives me an error that says "Notice: Undefined index". How do I fix/hide this? Thanks!

答:
There are two reasons this is occurring:

Firstly, you have given the name attribute to the labels and not the inputs themselves. Labels need the for attribute so that they know which input they correspond with.

  Name <input type="text" name="cust-name" id="cust[name]" placeholder="E.g. John Doe" required>

```

<p>Secondly, you are not checking to see whether the variables have been set in the first place. You need to wrap the HTML that shows the information in an <code>isset</code> statement:</p>

<pre class="lang-php prettyprint-override"><code><?php if (isset($_POST["your-submit-button-name"])) { ?>
<div class="order-info">Name: <?php echo $_POST["cust-name"]; ?></div>
<div class="order-info">Email: <?php echo $_POST["cust-email"]; ?></div>
<div class="order-info">Mobile: <?php echo $_POST["cust-mobile"]; ?></div>
<?php } ?>
</code>```

Body:
I'm new to PHP and I'm trying to have a div where it outputs the user information after the user submits it by using echo.

This is my code right now:

  Name <input type="text" id="cust[name]" placeholder="E.g. John Doe" required>

  Email <input type="email" id="cust[email]" placeholder="E.g. john@mail.com" required>

  Mobile <input type="text" id="cust[mobile]" placeholder="E.g. (04) 6172 5705" required>

Name: <?php echo $_POST["cust-name"]; ?>

Email: <?php echo $_POST["cust-email"]; ?>

Mobile: <?php echo $_POST["cust-mobile"]; ?>

It doesn't give the error in the example above, but on the page it gives me an error that says "Notice: Undefined index". How do I fix/hide this? Thanks!

Body:
There are two reasons this is occurring:

Firstly, you have given the name attribute to the labels and not the inputs themselves. Labels need the for attribute so that they know which input they correspond with.

<label class="input-fields" for="cust-name">
  Name <input type="text" name="cust-name" id="cust[name]" placeholder="E.g. John Doe" required>
</label>

Secondly, you are not checking to see whether the variables have been set in the first place. You need to wrap the HTML that shows the information in an isset statement:

<?php if (isset($_POST["your-submit-button-name"])) { ?>
<div class="order-info">Name: <?php echo $_POST["cust-name"]; ?></div>
<div class="order-info">Email: <?php echo $_POST["cust-email"]; ?></div>
<div class="order-info">Mobile: <?php echo $_POST["cust-mobile"]; ?></div>
<?php } ?>


问:
Get full queue name from dispatcher RabbitMq
I dispatch a message into queue:

```<code>using (var dispatcher = new Dispatcher<Scheduler.Queue.Contract.JobMessage>(new QueueConnectionInfo(_connectionSettings)))
{
    dispatcher.Dispatch(jobMessage.ToContract(), routingKey);
}
</code>```

In case when I create consumer, I can easy get queue name: consumer.QueueName

How can I get full name of queue (like "Queue.{someComponent}.{someRoute}"), in which message was dispatched?

答:
You cannot , since the Pub Sub pattern does warrants the publisher to know who all are the subscribers . The publisher only knows the exchange that it is publishing to and the exchange does the further bifurcation based on the queue bindings and respective routing keys.

However for troubleshooting RabbitMQ does provides you with a plugin ( which is not recommended for productions since it is resource heavy ) , the plugin is the Firehose plugin and it also comes with a UI which gives us the full trace from publish to all the queues that the message is routed it.

Body:
I dispatch a message into queue:

using (var dispatcher = new Dispatcher<Scheduler.Queue.Contract.JobMessage>(new QueueConnectionInfo(_connectionSettings)))
{
    dispatcher.Dispatch(jobMessage.ToContract(), routingKey);
}

In case when I create consumer, I can easy get queue name: consumer.QueueName

How can I get full name of queue (like "Queue.{someComponent}.{someRoute}"), in which message was dispatched?


问:
How to convert the following HOC implementation into a react hook implementation
I need convert the following HOC implemenation of react redux into a react hook implementation
I am a beginner in react hook, i find it fascination and i need to replace connect() function and map dispatch to props into dispatch and userSelector

```<code>    import React, { useEffect } from 'react'
    import { connect } from 'react-redux'
    import { fetchUsers } from '../actions/user.action'

    function UsersContainer ({ userData, fetchUsers }) {
    useEffect(() => {
        fetchUsers()
    }, [])
    return userData.loading ? (
        <h2>Loading</h2>
    ) : userData.error ? (
        <h2>{userData.error}</h2>
    ) : (
        <div>
        <h2>Users List</h2>
        <div>
            {userData &&
            userData.users &&
            userData.users.map(user => <p>{user.name}</p>)}
        </div>
        </div>
    )
    }

    const mapStateToProps = state => {
    return {
        userData: state.user
    }
    }

    const mapDispatchToProps = dispatch => {
    return {
        fetchUsers: () => dispatch(fetchUsers())
    }
    }

    export default connect(
    mapStateToProps,
    mapDispatchToProps
    )(UsersContainer)
</code>```

答:
Import useSelector and useDispatch hooks from react-redux.

and use them like so:

```<code>// useSelector hook allows you to extract data from the Redux store state
const userData = useSelector(state => state.user);

// useDispatch hook returns a reference to the dispatch function from the Redux store.
// You may use it to dispatch actions as needed.
const dispatch = useDispatch();
useEffect(() => {
  dispatch(fetchUsers());
}, []);
</code>```

Body:
I need convert the following HOC implemenation of react redux into a react hook implementation
I am a beginner in react hook, i find it fascination and i need to replace connect() function and map dispatch to props into dispatch and userSelector

    import React, { useEffect } from 'react'
    import { connect } from 'react-redux'
    import { fetchUsers } from '../actions/user.action'

    function UsersContainer ({ userData, fetchUsers }) {
    useEffect(() => {
        fetchUsers()
    }, [])
    return userData.loading ? (

Loading

    ) : userData.error ? (

{userData.error}

    ) : (

Users List

            {userData &&
            userData.users &&
            userData.users.map(user =>
{user.name}
)}

    )
    }

    const mapStateToProps = state => {
    return {
        userData: state.user
    }
    }

    const mapDispatchToProps = dispatch => {
    return {
        fetchUsers: () => dispatch(fetchUsers())
    }
    }

    export default connect(
    mapStateToProps,
    mapDispatchToProps
    )(UsersContainer)

Body:
Import useSelector and useDispatch hooks from react-redux.

and use them like so:

// useSelector hook allows you to extract data from the Redux store state
const userData = useSelector(state => state.user);

// useDispatch hook returns a reference to the dispatch function from the Redux store.
// You may use it to dispatch actions as needed.
const dispatch = useDispatch();
useEffect(() => {
  dispatch(fetchUsers());
}, []);


问:
How can I create an exception in .htaccess?
I try to solve folling problem with .htaccess.
I use it to rewrite everything to "https://" and put "www" in front of every url.
Now I want to use a SSL-certificate. To validate it, I put a html-file in a certain folder. I do not want this to be redirected to "www.". How can I create an exception only for this one file?
Thank you very much for helping me with this maybe kind of stupid question.</p>

```<code><IfModule mod_rewrite.c>

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

</IfModule>
</code>```

答:
You did not provide an example of URL that should not be redirected to https. But here is an example. This is a simplified version of your .htaccess file.
I have combined the https and www redirect in one directive.
Assume your domain name is example.com.

There is a negative condition (note the exclamation mark). If the request URI does not begin with index.html then the rule fails and is not enforced.
So http://example.com/index.html will not be converted to https, but there is one important caveat: in this case the www. will not be added either. I understand this what you want, then we can have a simplified set or rules.

```<code>RewriteEngine On

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{REQUEST_URI} !^/index.html
RewriteRule (.*) https://www.example.com/$1 [L,R=301]
</code>```

Body:
I try to solve folling problem with .htaccess.
I use it to rewrite everything to "https://" and put "www" in front of every url.
Now I want to use a SSL-certificate. To validate it, I put a html-file in a certain folder. I do not want this to be redirected to "www.". How can I create an exception only for this one file?
Thank you very much for helping me with this maybe kind of stupid question.

<IfModule mod_rewrite.c>

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

</IfModule>

Body:
You did not provide an example of URL that should not be redirected to https. But here is an example. This is a simplified version of your .htaccess file.
I have combined the https and www redirect in one directive.
Assume your domain name is example.com.

There is a negative condition (note the exclamation mark). If the request URI does not begin with index.html then the rule fails and is not enforced.
So http://example.com/index.html will not be converted to https, but there is one important caveat: in this case the www. will not be added either. I understand this what you want, then we can have a simplified set or rules.

RewriteEngine On

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{REQUEST_URI} !^/index.html
RewriteRule (.*) https://www.example.com/$1 [L,R=301]


问:
chaining lists from class attributes
I have three classes

```<code>class Animals:
    def __init__(self):
         self.dog = []
         self.cat = []

class Dog:
    def __init__(self,age,teeth):
        self.age   = age
        self.teeth = teeth

class Cat:
    def __init__(self,age,legs):
        self.age  = age
        self.legs = legs
</code>```

and the function:

```<code>def get_animals_from_attribute_value(animals_class, attribute, value):
    from itertools import chain
    animals = []
    for animal in chain( -> all attributes of animals_class, e.g. dog and cat <- ):
        x = getattr(animal, attribute, None)
        if x == value:
            animals.append(animal)
    return animals
</code>```

The script

```<code>animals = Animals()

animals.dog.append(Dog(1, 2))
animals.dog.append(Dog(3, 1))
animals.cat.append(Cat(1, 3))

certain_animals = get_animals_from_attribute_value(animals,"age",1)
</code>```

should give a list with all class instances, where the attribute age == 1. My problem right now is how to create an iterable list from all attributes of the animals-class (see 4th line in the function script).

Thank you :)

答:
You can use the __dict__ attribute, for example, to get dum1 and dum2 you can call

```<code>outer_class.__dict__.keys()
</code>```

Title: chaining lists from class attributes

Body:
I have three classes

class Animals:
    def __init__(self):
         self.dog = []
         self.cat = []

class Dog:
    def __init__(self,age,teeth):
        self.age   = age
        self.teeth = teeth

class Cat:
    def __init__(self,age,legs):
        self.age  = age
        self.legs = legs

and the function:

def get_animals_from_attribute_value(animals_class, attribute, value):
    from itertools import chain
    animals = []
    for animal in chain( -> all attributes of animals_class, e.g. dog and cat <- ):
        x = getattr(animal, attribute, None)
        if x == value:
            animals.append(animal)
    return animals

The script

animals = Animals()

animals.dog.append(Dog(1, 2))
animals.dog.append(Dog(3, 1))
animals.cat.append(Cat(1, 3))

certain_animals = get_animals_from_attribute_value(animals,"age",1)

should give a list with all class instances, where the attribute age == 1. My problem right now is how to create an iterable list from all attributes of the animals-class (see 4th line in the function script).

Thank you :)

Body:
You can use the __dict__ attribute, for example, to get dum1 and dum2 you can call

outer_class.__dict__.keys()


问:
How can I execute a python script directly (without prefixing by the python command) from bash?
I am just starting to use terminal for my programming needs. In a lot of Django tutorials I see people say, for example, I should type this in terminal:

```<code>manage.py runserver
</code>```

However when I do this it says:

```<code>bash: manage.py: command not found
</code>```

I get it to work when I do: python manage.py runserver, however I would like to understand why this works and the other method doesn't. I guess these are some very basic things but I thought I'd ask here.

答:
I've cooked together a small "script" to automate this: (just copy whole text, and paste inside your active terminal.)

```<code>tee -a ~/.profile <<EOF

if [ -d "/Library/Python/2.6/site-packages/django/bin" ] ; then
    PATH=/Library/Python/2.6/site-packages/django/bin:$PATH
fi
EOF
</code>```

Doesn't django-admin.py do the same? I think so, because I can find manage.py inside my ../bin folder. And stated at the official documentation, they do the same. So I believe ;)

Also, have you obtained Django via easy_install? My script expect that you are using Snow Leopard with the system version (Python 2.6).

ContentLicense: CC BY-SA 3.0

Body:
I am just starting to use terminal for my programming needs. In a lot of Django tutorials I see people say, for example, I should type this in terminal:

manage.py runserver

However when I do this it says:

bash: manage.py: command not found

I get it to work when I do: python manage.py runserver, however I would like to understand why this works and the other method doesn't. I guess these are some very basic things but I thought I'd ask here.

Body:
I've cooked together a small "script" to automate this: (just copy whole text, and paste inside your active terminal.)

tee -a ~/.profile <<EOF

if [ -d "/Library/Python/2.6/site-packages/django/bin" ] ; then
    PATH=/Library/Python/2.6/site-packages/django/bin:$PATH
fi
EOF

Doesn't django-admin.py do the same? I think so, because I can find manage.py inside my ../bin folder. And stated at the official documentation, they do the same. So I believe ;)

Also, have you obtained Django via easy_install? My script expect that you are using Snow Leopard with the system version (Python 2.6).


问:
Avoid nested subscription in RXJS
I have the following code:

```<code>someService.subscribeToChanges().subscribe(value => {
    const newValue = someArray.find(val => val.id === value.id)
    if (newValue) {
       if (value.status === 'someStatus') {
          someArray.findIndex((a) => a.id === value.id)
          someArray.splice(index, 1);
       } else {
          newValue.status = value.status;
       }
    } else {
        if (value.someProp === 'abc') {
          someService.doSomeAsyncStuff().subscribe(data => {
            someService.handleData(data);
          });
        }
    }
 });
</code>```

I would like to keep the same logic while avoiding the second subscribe.

This is the code that I tried

```<code>sub$ = someService.subscribeToChanges().pipe(switchMap(value => {
  const newValue = someArray.find(val => val.id === value.id)
  if (newValue) {
       if (value.status === 'someStatus') {
          someArray.findIndex((a) => a.id === value.id)
          someArray.splice(index, 1);
       } else {
          newValue.status = value.status;
       }
  } else {
    return iif(() => value.someProp === 'ABC', someService.doSomeAsyncStuff);
  }
}));

sub$.subscribe(data => someService.handleData(data))
</code>```

This works if the iif condition is true, but if it is false, it just stops the whole stream, while I want it to keep streaming.

答:
Nested subscriptions are an antipattern in rxjs. So its good that you try to avoid it. I would recommend you still using two subscriptions but not nested. Because you have to different side effects (someService.handleData and doSomeStuff)

Create your subscribeTochanges id with someArray id comparator for reuse reasons

```<code>const subscribeToChangesIdEqualsSomeArrayId$ = someService.subscribeToChanges().pipe(
  map(value => someArray.find(val => val.id === value.id)
);
</code>```

Create your doSomeStuff Observable

```<code>const doSomeStuff$ = subscribeToChangesIdEqualsSomeArrayId$.pipe(
  filter(newValue => newValue)
);
</code>```

Create your handleData Observable

```<code>const handleData$ = combineLatest([
  subscribeToChangesIdEqualsSomeArrayId$,
  someService.subscribeToChanges()
]).pipe(
  filter(([newValue, value]) => !newValue && value.someProp === 'abc'),
  switchMap(() => someService.doSomeStuff())
);
</code>```

Final usage

```<code>doSomeStuff$.subscribe(() => doSomeStuff());
handleData$.subscribe(data => someService.handleData(data));
</code>```

FYI: I used all the outer and inner (from pipe perspective) variable names you used in your question. I would maybe adjust them for the sake of reading :)

Title: Avoid nested subscription in RXJS

Body:
I have the following code:

someService.subscribeToChanges().subscribe(value => {
    const newValue = someArray.find(val => val.id === value.id)
    if (newValue) {
       if (value.status === 'someStatus') {
          someArray.findIndex((a) => a.id === value.id)
          someArray.splice(index, 1);
       } else {
          newValue.status = value.status;
       }
    } else {
        if (value.someProp === 'abc') {
          someService.doSomeAsyncStuff().subscribe(data => {
            someService.handleData(data);
          });
        }
    }
 });

I would like to keep the same logic while avoiding the second subscribe.

This is the code that I tried

sub$ = someService.subscribeToChanges().pipe(switchMap(value => {
  const newValue = someArray.find(val => val.id === value.id)
  if (newValue) {
       if (value.status === 'someStatus') {
          someArray.findIndex((a) => a.id === value.id)
          someArray.splice(index, 1);
       } else {
          newValue.status = value.status;
       }
  } else {
    return iif(() => value.someProp === 'ABC', someService.doSomeAsyncStuff);
  }
}));

sub$.subscribe(data => someService.handleData(data))

This works if the iif condition is true, but if it is false, it just stops the whole stream, while I want it to keep streaming.

Body:
Nested subscriptions are an antipattern in rxjs. So its good that you try to avoid it. I would recommend you still using two subscriptions but not nested. Because you have to different side effects (someService.handleData and doSomeStuff)

Create your subscribeTochanges id with someArray id comparator for reuse reasons

const subscribeToChangesIdEqualsSomeArrayId$ = someService.subscribeToChanges().pipe(
  map(value => someArray.find(val => val.id === value.id)
);

Create your doSomeStuff Observable

const doSomeStuff$ = subscribeToChangesIdEqualsSomeArrayId$.pipe(
  filter(newValue => newValue)
);

Create your handleData Observable

const handleData$ = combineLatest([
  subscribeToChangesIdEqualsSomeArrayId$,
  someService.subscribeToChanges()
]).pipe(
  filter(([newValue, value]) => !newValue && value.someProp === 'abc'),
  switchMap(() => someService.doSomeStuff())
);

Final usage

doSomeStuff$.subscribe(() => doSomeStuff());
handleData$.subscribe(data => someService.handleData(data));

FYI: I used all the outer and inner (from pipe perspective) variable names you used in your question. I would maybe adjust them for the sake of reading :)


问:
Why does this nginx server redirect to a wrong domain?
Why does this nginx server redirect to a wrong domain? My nginx webserver has two domains to serve, server1.eu and server2.eu, why do they interfere with each other? When I set up a new 'clean' server install, this behaviour does NOT appear, so what is wrong in this servers' setup.

The nginx webserver listening to IPv6 takes precedence over IPv4 and interferes with SNI. Testing with removing servers reveals the behaviour of nginx.

Remove all servers except server 1, with IPv4 and IPv6 enabled, reload nginx, then activate server 2, with only an IPv4 listener and reload nginx again. Browsing to server 2 will let you end up at server 1. It appears that nginx automatically listens to the first added IPv6. So interchanging the sequence of activation will switch the routing.

find /etc/nginx/{conf.d,sites-enabled} gives

```<code>/etc/nginx/sites-enabled/server1.eu
/etc/nginx/sites-enabled/server2.eu
</code>```

The zone file records:

```<code>AAAA    server1.eu    directs to IPv6 address
A   server1.eu    directs to IPv4 address
AAAA    server2.eu  directs to IPv6 address
A server2.eu directs to IPv4 address
</code>```

the nginx server configuration:

```<code>server {
    listen 80;
    listen [::]:80;
server_name server1.eu;
    return 301 https://www.server1.eu;
}
server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        ssl_certificate /etc/letsencrypt/live/server1.eu/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/server1.eu/privkey.pem;
        include snippets/ssl-params.conf;

        server_name www.server1.eu;
        root /var/www/server1.eu/webroot;
        index index.php index.html index.htm ;

        location / {
            try_files $uri $uri/ /index.php?$args;
        }

        location ~ \.php$ {
            include fastcgi.conf;
            fastcgi_pass unix:/run/php/php7.2-fpm.sock;
        }
}
</code>```

and

```<code>server {
    listen 80;
    listen [::]:80;
    server_name www.server2.eu;
    return 301 https://$server_name$request_uri;
}

server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
    ssl_certificate /etc/letsencrypt/live/server2.eu/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/server2.eu/privkey.pem;
    include snippets/ssl-params.conf;
    server_name www.server2.eu;
    root /var/www/server2.eu/webroot;
    index index.php index.html index.htm ;

        location / {
            try_files $uri $uri/ /index.php?$args;
        }

        location ~ \.php$ {
            include fastcgi.conf;
            fastcgi_pass unix:/run/php/php7.2-fpm.sock;
        }
}
</code>```

答: Exact same problem was happening to me. I couldn't follow what 'change' suggested by the chosen solution happen to solve your problem, but in my case, I happen to solve it by just adding 'www' in front of the domain2/server2.eu (in the conf file for domain2, in your case server2.eu).</p>

Body:
Why does this nginx server redirect to a wrong domain? My nginx webserver has two domains to serve, server1.eu and server2.eu, why do they interfere with each other? When I set up a new 'clean' server install, this behaviour does NOT appear, so what is wrong in this servers' setup.

The nginx webserver listening to IPv6 takes precedence over IPv4 and interferes with SNI. Testing with removing servers reveals the behaviour of nginx.

Remove all servers except server 1, with IPv4 and IPv6 enabled, reload nginx, then activate server 2, with only an IPv4 listener and reload nginx again. Browsing to server 2 will let you end up at server 1. It appears that nginx automatically listens to the first added IPv6. So interchanging the sequence of activation will switch the routing.

find /etc/nginx/{conf.d,sites-enabled} gives

/etc/nginx/sites-enabled/server1.eu
/etc/nginx/sites-enabled/server2.eu

The zone file records:

AAAA    server1.eu    directs to IPv6 address
A   server1.eu    directs to IPv4 address
AAAA    server2.eu  directs to IPv6 address
A server2.eu directs to IPv4 address

the nginx server configuration:

server {
    listen 80;
    listen [::]:80;
server_name server1.eu;
    return 301 https://www.server1.eu;
}
server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        ssl_certificate /etc/letsencrypt/live/server1.eu/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/server1.eu/privkey.pem;
        include snippets/ssl-params.conf;

        server_name www.server1.eu;
        root /var/www/server1.eu/webroot;
        index index.php index.html index.htm ;

        location / {
            try_files $uri $uri/ /index.php?$args;
        }

        location ~ \.php$ {
            include fastcgi.conf;
            fastcgi_pass unix:/run/php/php7.2-fpm.sock;
        }
}

and

server {
    listen 80;
    listen [::]:80;
    server_name www.server2.eu;
    return 301 https://$server_name$request_uri;
}

server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
    ssl_certificate /etc/letsencrypt/live/server2.eu/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/server2.eu/privkey.pem;
    include snippets/ssl-params.conf;
    server_name www.server2.eu;
    root /var/www/server2.eu/webroot;
    index index.php index.html index.htm ;

        location / {
            try_files $uri $uri/ /index.php?$args;
        }

        location ~ \.php$ {
            include fastcgi.conf;
            fastcgi_pass unix:/run/php/php7.2-fpm.sock;
        }
}


问:
How can I verify the sign of product of 3 numbers without multiplying them?
I have an exercise that sounds like this :

Calculate the sign of the product of 3 numbers:

Read 3 floating-point numbers

Print the sign of the product of the entered 3 numbers: positive,
  negative or zero

Try to do this without multiplying the 3 numbers

I tried this way :

```<code>import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

       Scanner in = new Scanner(System.in);

       double a = in.nextDouble();
       double b = in.nextDouble();
       double c = in.nextDouble();

       switch(){
          case a:
          case b:
          case c:
             if (a > 0 && b > 0 && c > 0){
                System.out.printf("positive");
             }else if ( a > 0 && b < 0 && c > 0){
                System.out.printf("negative");
             }else if ( a > 0 && b > 0 && c < 0){
                System.out.printf("negative");
             }else if ( a < 0 && b > 0 && c > 0){
                System.out.printf("negative");
             }else if ( a == 0 && b == 0 && c == 0){
                System.out.printf("zero");
             }
       }

}
</code>```

}

What condition should I put in switch's brackets in order to make this program work assuming that the if, else if conditions are correct?

And if they're not , what can I possibly to , with switch case , in order to solve this exercise succesfully?

My input to be for example :

```<code>2
3
-1
</code>```

My output:

```<code>negative
</code>```

答:
Considering all 3 numbers are non-zero

If you have 1 or 3 negative numbers, the product will be negative. Otherwise, the product will be positive.

```<code>int count = 0;
if(a < 0)
    count++;
if(b < 0)
    count++;
if(c < 0)
    count++;

if(count % 2 == 1)
    System.out.println("Negative");
else
    System.out.println("Positive");
</code>```

Body:
I have an exercise that sounds like this :

Calculate the sign of the product of 3 numbers:

Read 3 floating-point numbers

Print the sign of the product of the entered 3 numbers: positive,
  negative or zero

Try to do this without multiplying the 3 numbers

I tried this way :

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

       Scanner in = new Scanner(System.in);

       double a = in.nextDouble();
       double b = in.nextDouble();
       double c = in.nextDouble();

       switch(){
          case a:
          case b:
          case c:
             if (a > 0 && b > 0 && c > 0){
                System.out.printf("positive");
             }else if ( a > 0 && b < 0 && c > 0){
                System.out.printf("negative");
             }else if ( a > 0 && b > 0 && c < 0){
                System.out.printf("negative");
             }else if ( a < 0 && b > 0 && c > 0){
                System.out.printf("negative");
             }else if ( a == 0 && b == 0 && c == 0){
                System.out.printf("zero");
             }
       }

}

}

What condition should I put in switch's brackets in order to make this program work assuming that the if, else if conditions are correct?

And if they're not , what can I possibly to , with switch case , in order to solve this exercise succesfully?

My input to be for example :

2
3
-1

My output:

negative

Body:
Considering all 3 numbers are non-zero

If you have 1 or 3 negative numbers, the product will be negative. Otherwise, the product will be positive.

int count = 0;
if(a < 0)
    count++;
if(b < 0)
    count++;
if(c < 0)
    count++;

if(count % 2 == 1)
    System.out.println("Negative");
else
    System.out.println("Positive");


问:
How can I make my header image properly responsive?
I am trying to put a site together for a friend using a really nice premium Wordpress theme. I have paid for the theme but the designer will not help with customisation.

The site is currently at www.zerocarbonfood.co.uk/test/. Originally the theme had a small left-aligned logo but my friend favours this large full-width one, which I think works better. Problem is now that I look at it on an iPad or iPhone (portrait) the logo is too big and screws it up. In the theme options it is defined as 922px width and 168px height. I cannot put a percentage value in there. Can I override this in CSS somewhere?

Any help would be gratefully received as I am a bit out of my depth.

答:
Did you use the viewport meta tag in the header?</p>

```<code><meta name="viewport" content="width=device-width, initial-scale=1.0">
</code>```

Body:
Did you use the viewport meta tag in the header?

<meta name="viewport" content="width=device-width, initial-scale=1.0">


问:
Laravel 5.2: Unable to locate factory with name [default]
I want to seed database
when I use this

```<code> public function run()
{
    $users = factory(app\User::class, 3)->create();
}
</code>```

Add three user in database but when I use this

```<code> public function run()
{
    $Comment= factory(app\Comment::class, 3)->create();
}
</code>```

Show me error

[InvalidArgumentException]

  Unable to locate factory with name [default] [app\Comment].

答:
none of the answers worked for me
so I delete my factory and create it again (every this is same with the previous factory)  and this problem solved for me</p>

Body:
I want to seed database
when I use this

 public function run()
{
    $users = factory(app\User::class, 3)->create();
}

Add three user in database but when I use this

 public function run()
{
    $Comment= factory(app\Comment::class, 3)->create();
}

Show me error

[InvalidArgumentException]

  Unable to locate factory with name [default] [app\Comment].


问:
How can I match an exact pattern with sed -n
I have a file test.txt

```<code>---
kind: ClusterRole
metadata:
kind: ClusterRoleBinding
metadata:
subjects:
roleRef:
  kind: ClusterRole
  name: bla
</code>```

And need this output with sed (just the line that matches the exact pattern)

```<code>kind: ClusterRole
metadata:
</code>```

sed -n '/kind: ClusterRole/,/metadata/p' test.txt

```<code>kind: ClusterRole
metadata:
kind: ClusterRoleBinding
metadata:
  kind: ClusterRole
  name: bla
</code>```

is showing ClusterRole, ClusterRoleBinding and additional indented ClusterRole

```<code>sed -n '/kind: ClusterRole\b/,/metadata/p' test.txt
sed -n '/\<kind: ClusterRole\>/,/metadata/p' test.txt
</code>```

Both of the above output to nothing what am I doing wrong?
just so it's clear and I'm not getting any grep -B 2 suggestions ;-) this is an example file, the original file is a lot bigger and has hundreds of ClusterRoles so I need to figure out how to match the exact pattern.

Thank you!

lema

答:
This might work for you (GNU sed):

```<code>sed -n 'N;/^kind: ClusterRole\nmetadata:$/p;D' file
</code>```

Append the next line and print the lines if it matches. Delete the first line and repeat.

If you only want the first match, use:

```<code>sed -n 'N;/^kind: ClusterRole\nmetadata:$/{p;q};D' file
</code>```

Body:
I have a file test.txt

---
kind: ClusterRole
metadata:
kind: ClusterRoleBinding
metadata:
subjects:
roleRef:
  kind: ClusterRole
  name: bla

And need this output with sed (just the line that matches the exact pattern)

kind: ClusterRole
metadata:

sed -n '/kind: ClusterRole/,/metadata/p' test.txt

kind: ClusterRole
metadata:
kind: ClusterRoleBinding
metadata:
  kind: ClusterRole
  name: bla

is showing ClusterRole, ClusterRoleBinding and additional indented ClusterRole

sed -n '/kind: ClusterRole\b/,/metadata/p' test.txt
sed -n '/\<kind: ClusterRole\>/,/metadata/p' test.txt

Both of the above output to nothing what am I doing wrong?
just so it's clear and I'm not getting any grep -B 2 suggestions ;-) this is an example file, the original file is a lot bigger and has hundreds of ClusterRoles so I need to figure out how to match the exact pattern.

Thank you!

lema

Body:
This might work for you (GNU sed):

sed -n 'N;/^kind: ClusterRole\nmetadata:$/p;D' file

Append the next line and print the lines if it matches. Delete the first line and repeat.

If you only want the first match, use:

sed -n 'N;/^kind: ClusterRole\nmetadata:$/{p;q};D' file


问:
Is it possible to configure create-react-app express.static options without ejecting?
By default, when an empty folder exists, express.static triggers a 301 redirect adding a forward slash.

This is how I disable this redirect for custom Express servers.

server.use(
  express.static(path.join(__dirname, "build"), {
    redirect: false,
  })
)
```

<p>Is it possible to configure <code>redirect: false</code> when using create-react-app in development mode (<code>npm start</code>?</p>

<p>Having a look at the following headers, I guess Express is what <code>create-react-app</code> uses to serve the SPA in development mode.</p>

<p><strong>Request headers when loading http://localhost:3001/privacy-guides</strong></p>

```HTTP/1.1 301 Moved Permanently
X-Powered-By: Express
Content-Type: text/html; charset=UTF-8
Content-Length: 195
Content-Security-Policy: default-src 'none'
X-Content-Type-Options: nosniff
Location: /privacy-guides/
Vary: Accept-Encoding
```

答:
Short answer, no.

As @goto1 pointed out, the following isn’t good practice, but helped me understand how things work under the hood in CRA.

When running CRA in development mode using npm start, webpack-dev-server is used to serve the app. Webpack DevServer uses Express to serve files which explains why browsing to folders triggers a 301 redirect (see express.static options.redirect, default is true).

Redirect to trailing “/” when the pathname is a directory.

I confirm adding the following to node_modules/react-scripts/config/webpackDevServer.config.js disables the redirect.

staticOptions: {
  redirect: false
}
```

Editing this file manually is a bit of a hack but works. Unfortunately, the only legit way I could find of configuring staticOptions requires ejecting.

Body:
By default, when an empty folder exists, express.static triggers a 301 redirect adding a forward slash.

This is how I disable this redirect for custom Express servers.

server.use(
  express.static(path.join(__dirname, "build"), {
    redirect: false,
  })
)

Is it possible to configure redirect: false when using create-react-app in development mode (npm start?

Having a look at the following headers, I guess Express is what create-react-app uses to serve the SPA in development mode.

Request headers when loading http://localhost:3001/privacy-guides

HTTP/1.1 301 Moved Permanently
X-Powered-By: Express
Content-Type: text/html; charset=UTF-8
Content-Length: 195
Content-Security-Policy: default-src 'none'
X-Content-Type-Options: nosniff
Location: /privacy-guides/
Vary: Accept-Encoding

Body:
Short answer, no.

As @goto1 pointed out, the following isn’t good practice, but helped me understand how things work under the hood in CRA.

When running CRA in development mode using npm start, webpack-dev-server is used to serve the app. Webpack DevServer uses Express to serve files which explains why browsing to folders triggers a 301 redirect (see express.static options.redirect, default is true).

Redirect to trailing “/” when the pathname is a directory.

I confirm adding the following to node_modules/react-scripts/config/webpackDevServer.config.js disables the redirect.

staticOptions: {
  redirect: false
}

Editing this file manually is a bit of a hack but works. Unfortunately, the only legit way I could find of configuring staticOptions requires ejecting.


问:
Enable https in NodeJS using rejoice
I am having nodejs microservice built on HapiJS. For starting the server we use rejoice which uses .json file for configuration.
    "server": {
    },
    "connections": [
        {
            "port": 5000,
            "host": "0.0.0.0"
        }
    ]

Above port configuration been picked when we are staring the sever using rejoice command. Now we are try to run the nodejs service using https, i am not able to find out how can i do that. I see the hapi docs which says passing tls object as part of connections parameter will be send as it is nodejs. Refer Hapi server options . Now i tried passing tls object inside the connections array

```<code>"connections": [
    {
        "port": 5000,
        "host": "0.0.0.0"
        "tls" :{
            "cert":"./server_certificate.pem",
            "key": "./server_key.pem"
         }
    }
]
</code>```

then getting below.

```<code>Problems while parsing the config_prod.json file. Make sure the file exists and is well formatted.
Error: Unexpected string in JSON at position 116
./change_request/node_modules/glue/node_modules/joi/lib/index.js:144
throw error;
ValidationError: Invalid manifest "value" must be an object
</code>```

答:
It is not a valid json as you are missing a comma after host. It should be </p>

```<code>"connections": [
    {
        "port": 5000,
        "host": "0.0.0.0",
        "tls" :{
            "cert":"./server_certificate.pem",
            "key": "./server_key.pem"
         }
    }
]
</code>```

Title: Enable https in NodeJS using rejoice

Body:
I am having nodejs microservice built on HapiJS. For starting the server we use rejoice which uses .json file for configuration.
    "server": {
    },
    "connections": [
        {
            "port": 5000,
            "host": "0.0.0.0"
        }
    ]

Above port configuration been picked when we are staring the sever using rejoice command. Now we are try to run the nodejs service using https, i am not able to find out how can i do that. I see the hapi docs which says passing tls object as part of connections parameter will be send as it is nodejs. Refer Hapi server options . Now i tried passing tls object inside the connections array

"connections": [
    {
        "port": 5000,
        "host": "0.0.0.0"
        "tls" :{
            "cert":"./server_certificate.pem",
            "key": "./server_key.pem"
         }
    }
]

then getting below.

Problems while parsing the config_prod.json file. Make sure the file exists and is well formatted.
Error: Unexpected string in JSON at position 116
./change_request/node_modules/glue/node_modules/joi/lib/index.js:144
throw error;
ValidationError: Invalid manifest "value" must be an object

Body:
It is not a valid json as you are missing a comma after host. It should be

"connections": [
    {
        "port": 5000,
        "host": "0.0.0.0",
        "tls" :{
            "cert":"./server_certificate.pem",
            "key": "./server_key.pem"
         }
    }
]


问:
Remove duplicates from the string in CPP
I wrote the following code for removing the duplicates from a given string i.e. if ARRUN is the input then the output will be ARUN.

```<code>#include <bits/stdc++.h>
using namespace std;
char* removeDuplicates(string &s,int n){
    char arr[n];
    unordered_map<char,int> exists;
    int index = 0;
    for(int i=0;i<n;i++){
        if(exists[s[i]]==0)
        {
            arr[index++] = s[i];
            exists[s[i]]++;
        }
    }
    return arr;
}

//driver code
int main(){
    string str;
    cin >> str;
    cout<<removeDuplicates(str,str.length())<<endl;
    return 0;
}
</code>```

The code produces no output at all, however, it works fine if I use char arr[] instead of string class.

答:
std::string support removing elements.

```<code>#include <iostream>
#include <string>

std::string removeDuplicates(std::string str) {
    for (int i = 0; i < str.size(); i++) {
        while (true) {
            int j = str.find_last_of(str[i]);
            if (i < j) {
                str.erase(j, 1);
            } else {
                break;
            }
        }
    }
    return str;
}

int main() {
    std::cout << removeDuplicates("ARRUN");
    return 0;
}
</code>```

Body:
I wrote the following code for removing the duplicates from a given string i.e. if ARRUN is the input then the output will be ARUN.

#include <bits/stdc++.h>
using namespace std;
char* removeDuplicates(string &s,int n){
    char arr[n];
    unordered_map<char,int> exists;
    int index = 0;
    for(int i=0;i<n;i++){
        if(exists[s[i]]==0)
        {
            arr[index++] = s[i];
            exists[s[i]]++;
        }
    }
    return arr;
}

//driver code
int main(){
    string str;
    cin >> str;
    cout<<removeDuplicates(str,str.length())<<endl;
    return 0;
}

The code produces no output at all, however, it works fine if I use char arr[] instead of string class.

Body:
std::string support removing elements.

#include <iostream>
#include <string>

std::string removeDuplicates(std::string str) {
    for (int i = 0; i < str.size(); i++) {
        while (true) {
            int j = str.find_last_of(str[i]);
            if (i < j) {
                str.erase(j, 1);
            } else {
                break;
            }
        }
    }
    return str;
}

int main() {
    std::cout << removeDuplicates("ARRUN");
    return 0;
}


问:
Django changing custom settings at runtime
In my settings.py there are some custom settings, a few data structures that I use. These are rarely changed.
I've noticed that changing them from a view wont work.
How can I force django to reload the settings file at runtime ?
So far the only way that works is to restart the apache web server. But I want to avoid that.</p>

答:
Import in view.py

import django.conf as conf

def home(request):

```<code>conf.settings.SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
conf.settings.DATABASES['default']['NAME'] = 'testdb'
</code>```

Body:
Import in view.py

import django.conf as conf

def home(request):

conf.settings.SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
conf.settings.DATABASES['default']['NAME'] = 'testdb'


问:
MongoDB and Mongoose - id from two different collection queries not matching
I'm building an app where people are able to make potlucks and invite other users to their potlucks. I have what seems to be a simple problem but I haven't been able to make it work:

I want to make an invite route that checks the potluck.attendees to see if they have been invited before (and send different errors depending on if they're 0-pending, 1-attending or re-invite them if they have been invited before and their status is 2 declined) and if not, puts the invitee into the potluck.attendees object array and the potluck's _id into the invitee's user.potlucks object array.

Here are super-trimmed versions of those two models:

Simplified Potluck Model

```<code>const PotluckSchema = new Schema({
  attendees: [
    {
      attendeeId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
      },
      status: Number,
      enums: [
        0, //'pending',
        1, //'attending',
        2 //'declined'
      ]
    }
  ]
});
</code>```

Simplified User Model

```<code>const UserSchema = new Schema({
  potlucks: [
    {
      potluck: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Potluck'
      }
    }
  ]
});
</code>```

And what I have so far on this route is:

```<code>router.put('/attendees/invite/:potluckId/:inviteeId', async (req, res) => {
  try {
    const currPotluck = await db.Potluck.findOne({
      _id: req.params.potluckId,
      createdBy: req.user._id
    });
    // Makes sure potluck belongs to user before allowing to invite
    if (!currPotluck)
      return res.status(401).json({
        msg: 'You are not authorized to invite people to this potluck.'
      });
    const invitee = await db.User.findOne({ _id: req.params.inviteeId });

    console.log(currPotluck);
    console.log(invitee);

    for (let i = 0; i < currPotluck.attendees.length; i++) {
      //  Checks if invitee already exists in potluck.attendees
      //  and if their status is 0 or 1 (pending or attending)
      //  It will stop function
      if (
        currPotluck.attendees[i].attendeeId == invitee._id &&
        currPotluck.attendees[i].status == 0 ||
        currPotluck.attendees[i].attendeeId == invitee._id &&
        currPotluck.attendees[i].status == 1
      ) {
        return res.status(401).send({
          error: 'This member has already been invited to your potluck'
        });
      } else if (
        currPotluck.attendees[i].attendeeId == invitee._id &&
        currPotluck.attendees[i].status == 2
      ) {
        //  if their status is 2 (declined)
        //  it will edit their existing object in the attendees array to pending
        //  and re-insert potluck in invitee's user.potlucks model
        await db.Potluck.findOneAndUpdate(
          { _id: currPotluck._id },
          { $set: { 'attendees.$[el].status': 0 } },
          { arrayFilters: [{ 'el.attendeeId': invitee._id }] }
        );
        await db.User.findOneAndUpdate(
          { _id: invitee._id },
          { $push: { potlucks: { potluck: currPotluck._id } } }
        );
        res.send(`This user has been re-invited to your potluck!`);
      }
    }
    // If they don't exist already in potluck.attendees, create new object
    // in potlucks.attendees and user.potlucks for invitee
    await db.Potluck.findOneAndUpdate(
      { _id: currPotluck._id },
      { $push: { attendees: { attendeeId: invitee._id, status: 0 } } }
    );
    await db.User.findOneAndUpdate(
      { _id: invitee._id },
      { $push: { potlucks: { potluck: currPotluck._id } } }
    );
    res.send(`This user has been invited to your potluck!`);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server Error');
  }
});
</code>```

Now to the issue:

If I run this code in postman, it will run the two 'findOneAndUpdate's that come after the for-loop regardless if there is a match or not.  When trying to debug, I console.logged both invitee._id and currPotluck.attendees[i].attendeeId (for a test where I knew the invitee already existed in the array) and they both come up as the same id.

But if I try to console.log (currPootluck.attendees[i].attendeeId == invitee._id) it comes up false every time.  I did a 'type of' for both and they come up as objects, and they both appear to be the same type in console.logs - strings maybe?

I know the solution must be something super simple but I can't figure it out, any help would be much appreciated!

答:
Both currPootluck.attendees[i].attendeeId and invitee._id are ObjectIds, in order to check if they are the same, you must first convert it to strings.

This should do the job: currPootluck.attendees[i].attendeeId.toString() == invitee._id.toString()

Body:
I'm building an app where people are able to make potlucks and invite other users to their potlucks. I have what seems to be a simple problem but I haven't been able to make it work:

I want to make an invite route that checks the potluck.attendees to see if they have been invited before (and send different errors depending on if they're 0-pending, 1-attending or re-invite them if they have been invited before and their status is 2 declined) and if not, puts the invitee into the potluck.attendees object array and the potluck's _id into the invitee's user.potlucks object array.

Here are super-trimmed versions of those two models:

Simplified Potluck Model

const PotluckSchema = new Schema({
  attendees: [
    {
      attendeeId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
      },
      status: Number,
      enums: [
        0, //'pending',
        1, //'attending',
        2 //'declined'
      ]
    }
  ]
});

Simplified User Model

const UserSchema = new Schema({
  potlucks: [
    {
      potluck: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Potluck'
      }
    }
  ]
});

And what I have so far on this route is:

router.put('/attendees/invite/:potluckId/:inviteeId', async (req, res) => {
  try {
    const currPotluck = await db.Potluck.findOne({
      _id: req.params.potluckId,
      createdBy: req.user._id
    });
    // Makes sure potluck belongs to user before allowing to invite
    if (!currPotluck)
      return res.status(401).json({
        msg: 'You are not authorized to invite people to this potluck.'
      });
    const invitee = await db.User.findOne({ _id: req.params.inviteeId });

    console.log(currPotluck);
    console.log(invitee);

    for (let i = 0; i < currPotluck.attendees.length; i++) {
      //  Checks if invitee already exists in potluck.attendees
      //  and if their status is 0 or 1 (pending or attending)
      //  It will stop function
      if (
        currPotluck.attendees[i].attendeeId == invitee._id &&
        currPotluck.attendees[i].status == 0 ||
        currPotluck.attendees[i].attendeeId == invitee._id &&
        currPotluck.attendees[i].status == 1
      ) {
        return res.status(401).send({
          error: 'This member has already been invited to your potluck'
        });
      } else if (
        currPotluck.attendees[i].attendeeId == invitee._id &&
        currPotluck.attendees[i].status == 2
      ) {
        //  if their status is 2 (declined)
        //  it will edit their existing object in the attendees array to pending
        //  and re-insert potluck in invitee's user.potlucks model
        await db.Potluck.findOneAndUpdate(
          { _id: currPotluck._id },
          { $set: { 'attendees.$[el].status': 0 } },
          { arrayFilters: [{ 'el.attendeeId': invitee._id }] }
        );
        await db.User.findOneAndUpdate(
          { _id: invitee._id },
          { $push: { potlucks: { potluck: currPotluck._id } } }
        );
        res.send(`This user has been re-invited to your potluck!`);
      }
    }
    // If they don't exist already in potluck.attendees, create new object
    // in potlucks.attendees and user.potlucks for invitee
    await db.Potluck.findOneAndUpdate(
      { _id: currPotluck._id },
      { $push: { attendees: { attendeeId: invitee._id, status: 0 } } }
    );
    await db.User.findOneAndUpdate(
      { _id: invitee._id },
      { $push: { potlucks: { potluck: currPotluck._id } } }
    );
    res.send(`This user has been invited to your potluck!`);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server Error');
  }
});

Now to the issue:

If I run this code in postman, it will run the two 'findOneAndUpdate's that come after the for-loop regardless if there is a match or not.  When trying to debug, I console.logged both invitee._id and currPotluck.attendees[i].attendeeId (for a test where I knew the invitee already existed in the array) and they both come up as the same id.

But if I try to console.log (currPootluck.attendees[i].attendeeId == invitee._id) it comes up false every time.  I did a 'type of' for both and they come up as objects, and they both appear to be the same type in console.logs - strings maybe?

I know the solution must be something super simple but I can't figure it out, any help would be much appreciated!


问:
storing time in PHP
data stored in table1 is with time stamp. syntax used to store time stamp is NOW(). stored time format is in 2011-05-17 00:46:19. my question is how do I access latest data by time and how do I display time say "the data stored 10 minutes ago" or 5 seconds ago or 1 day etc. I am using MySQL and PHP.

答:
When you get the result from mysql_result(), use the following:

```<code>$t = strtotime($value_from_db); // now you have a Unix epoch time.
$minutediff = (mktime()-$t)/60; // $minutediff minutes ago.
</code>```

Title: storing time in PHP

Body:
When you get the result from mysql_result(), use the following:

$t = strtotime($value_from_db); // now you have a Unix epoch time.
$minutediff = (mktime()-$t)/60; // $minutediff minutes ago.


问:
Joining sheets from different excel files into one workbook python
I'm trying to understand a code that was published a while ago. I couldn't find a proper explanation so I made this post. I'm new to python and If someone could explain me how it works I would really appreciate that. I have marked parts which I don't understand.

Link to the original thread

Code itself:

```<code>    from pandas import ExcelWriter
import glob
import os
import pandas as pd

writer = ExcelWriter("output.xlsx")

for filename in glob.glob("*.xlsx"):
    excel_file = pd.ExcelFile(filename)
    (_, f_name) = os.path.split(filename) <---
    (f_short_name, _) = os.path.splitext(f_name)
    for sheet_name in excel_file.sheet_names:
        df_excel = pd.read_excel(filename, sheet_name=sheet_name)
        df_excel.to_excel(writer, f_short_name+'_'+sheet_name, index=False) <---

writer.save()

</code>```

答:
What you mark is just the creator try to name the sheet in a new excel file.

```<code>(_, f_name) = os.path.split(filename)

# _: 'C:\\Desktop'
#f_name: 'file.xlsx'
</code>```

It returns head and tail of the directory. In this case the tail is file name.

```<code>df_excel.to_excel(writer, f_short_name+'_'+sheet_name, index=False)
</code>```

This one is to save a dataframe to excel file.
First argument:

ExcelWriter if you want to create an excel file with multiple sheet inside.

If not, use file path (Where do you want to save it).

Second argument : Sheet name for each dataframe.

last argument : index or the row name

True : write

False : skip

for further information:

os.path.split : https://www.geeksforgeeks.org/python-os-path-split-method/

.to_excel : https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html

Body:
I'm trying to understand a code that was published a while ago. I couldn't find a proper explanation so I made this post. I'm new to python and If someone could explain me how it works I would really appreciate that. I have marked parts which I don't understand.

Link to the original thread

Code itself:

    from pandas import ExcelWriter
import glob
import os
import pandas as pd

writer = ExcelWriter("output.xlsx")

for filename in glob.glob("*.xlsx"):
    excel_file = pd.ExcelFile(filename)
    (_, f_name) = os.path.split(filename) <---
    (f_short_name, _) = os.path.splitext(f_name)
    for sheet_name in excel_file.sheet_names:
        df_excel = pd.read_excel(filename, sheet_name=sheet_name)
        df_excel.to_excel(writer, f_short_name+'_'+sheet_name, index=False) <---

writer.save()

Body:
What you mark is just the creator try to name the sheet in a new excel file.

(_, f_name) = os.path.split(filename)

# _: 'C:\\Desktop'
#f_name: 'file.xlsx'

It returns head and tail of the directory. In this case the tail is file name.

df_excel.to_excel(writer, f_short_name+'_'+sheet_name, index=False)

This one is to save a dataframe to excel file.
First argument:

ExcelWriter if you want to create an excel file with multiple sheet inside.

If not, use file path (Where do you want to save it).

Second argument : Sheet name for each dataframe.

last argument : index or the row name

True : write

False : skip

for further information:

os.path.split : https://www.geeksforgeeks.org/python-os-path-split-method/

.to_excel : https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html


问:
laravel session key for groupby

Hi I need the $clave of the session for i can delete it session.how i can do it? Thanks

```<code>$carrito=Session::get('cart');

$grouped = Session::get('cart')->groupBy('vendedor');

foreach($carrito as $clave => $carro) {
    echo $clave ; //I need to put these keys in the <a> to be able to delete the session of that item because when applying groupby it does not give me the session key.
}

@foreach($grouped as $id => $value)
    @foreach($value as $key => $cartItem)
        <a href="#" onclick="removeFromCartView(event, {{ $clave}})" class="text-right pl-4"><i class="la la-trash"></i></a>
    @endforeach
@endforeach
</code>```

答:
I resolved it with ->groupBy('vendedor', $preserveKeys = true)

Answered by @Carlos in the comments

Title: laravel session key for groupby

Body:
Hi I need the $clave of the session for i can delete it session.how i can do it? Thanks

$carrito=Session::get('cart');

$grouped = Session::get('cart')->groupBy('vendedor');

foreach($carrito as $clave => $carro) {
    echo $clave ; //I need to put these keys in the  to be able to delete the session of that item because when applying groupby it does not give me the session key.
}

@foreach($grouped as $id => $value)
    @foreach($value as $key => $cartItem)

    @endforeach
@endforeach