问:
Python displaying details in flask form when editing item so that user doesn't have to retype the same details
I made a edit product function where you can change stock, name, discount of the product but i cannot seem to retrieve the details and 'GET' method it in the form so that user does not have to retype the details they don't wish to change

I'm using flask forms and python jinja, to do this

This is my routes.py

```<code>@app.route('/updateProduct/<int:id>', methods=['GET','POST]'])
def update_product(id):
    form = UpdateProduct()
    product = AddProduct.query.get_or_404(id)
    if request.method == "POST" and form.validate_on_submit():
        product.name = form.name.data
        product.price = form.price.data
        product.stock = form.stock.data
        product.discount = form.discount.data
        product.desc = form.description.data
        try:
            db.session.add(product)
            db.session.commit()
            flash(f'Your product has been successfully updated!')
            print("a product has been updated")
            return redirect(url_for('retrieve_products', id=product.id))
        except:
            print("error updating product")
            return redirect(url_for('retrieve_products', id=product.id))
    form.name.data = product.name
    form.price.data = product.price
    form.stock.data = product.stock
    form.discount.data = product.discount
    form.description.data = product.desc
    return render_template('retrieveProducts.html', form=form)
</code>```

this is the edit form modal in my retrieveproducts.html

```<code>  <td style="color:black">
              <button type="button" class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#myModal2_{{ product.id }}">
            Edit
              </button>

              <div class="modal" id="myModal2_{{product.id}}">
                <div class="modal-dialog">
                  <div class="modal-content">
                    <div class="modal-header">
                      <h4 class="modal-title" style="color:black">Update Inventory</h4>
                      <button type="button" class="btn-close" data-bs-dismiss="modal">X</button>
                    </div>
                    <div class="modal-body">
                  <form action="{{ url_for('update_product',id=product.id) }}" method="POST" enctype="multipart/form-data">
                      {{ form.hidden_tag() }}
              <div class="form-group">
                  {{ form.name.label(class="form-control-label") }}
                  {{ form.name(class="form-control") }}
              </div>
              <div class="form-group">
                  {{ form.price.label(class="form-control-label") }}
                  {{ form.price(class="form-control") }}

              </div>
              <div class="form-group">
                  {{ form.discount.label(class="form-control-label") }}
                  {{ form.discount(class="form-control") }}

              </div>
              <div class="form-group">
                  {{ form.stock.label(class="form-control-label") }}
                  {{ form.stock(class="form-control") }}

              </div>
                  <div class="form-group">
                  {{ form.description.label(class="form-control-label") }}
                      {{ form.description(class="form-control") }}

                </div>

  <div class="modal-footer">
                  {{ form.edit_submit(class="btn btn-primary") }}
                      <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    </div>
        </form>

                    </div>

                  </div>
                </div>
              </div>
             </td>

</code>```

答:
I think you don't have to write

db.session.add(product)

db.session.commit()

because adding means you are creating a new record in your database, so just remove the part: ' db.session.add(product) ' and
keep only: ' db.session.commit() '

commit will update the existing content.

I hope this would help you, just try it a once and notify here.

Body:
I made a edit product function where you can change stock, name, discount of the product but i cannot seem to retrieve the details and 'GET' method it in the form so that user does not have to retype the details they don't wish to change

I'm using flask forms and python jinja, to do this

This is my routes.py

@app.route('/updateProduct/<int:id>', methods=['GET','POST]'])
def update_product(id):
    form = UpdateProduct()
    product = AddProduct.query.get_or_404(id)
    if request.method == "POST" and form.validate_on_submit():
        product.name = form.name.data
        product.price = form.price.data
        product.stock = form.stock.data
        product.discount = form.discount.data
        product.desc = form.description.data
        try:
            db.session.add(product)
            db.session.commit()
            flash(f'Your product has been successfully updated!')
            print("a product has been updated")
            return redirect(url_for('retrieve_products', id=product.id))
        except:
            print("error updating product")
            return redirect(url_for('retrieve_products', id=product.id))
    form.name.data = product.name
    form.price.data = product.price
    form.stock.data = product.stock
    form.discount.data = product.discount
    form.description.data = product.desc
    return render_template('retrieveProducts.html', form=form)

this is the edit form modal in my retrieveproducts.html

              <button type="button" class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#myModal2_{{ product.id }}">
            Edit
              </button>

Update Inventory

                      <button type="button" class="btn-close" data-bs-dismiss="modal">X</button>

                  <form action="{{ url_for('update_product',id=product.id) }}" method="POST" enctype="multipart/form-data">
                      {{ form.hidden_tag() }}

                  {{ form.name.label(class="form-control-label") }}
                  {{ form.name(class="form-control") }}

                  {{ form.price.label(class="form-control-label") }}
                  {{ form.price(class="form-control") }}

                  {{ form.discount.label(class="form-control-label") }}
                  {{ form.discount(class="form-control") }}

                  {{ form.stock.label(class="form-control-label") }}
                  {{ form.stock(class="form-control") }}

                  {{ form.description.label(class="form-control-label") }}
                      {{ form.description(class="form-control") }}

                  {{ form.edit_submit(class="btn btn-primary") }}
                      <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>

        </form>


来源: stackexchange

问:
MiniProfiler .Ignore() extension method does not disable profiling
I have a method with a portion of code I want to ignore from profiling when using MiniProfiler.

As from documentation, the extension method that does this is .Ignore(), that when used in a using statement should disable profiling for the duration.

Unfortunately I'm not getting the results as expected. Suppose I have this method structure:

```<code>public async Task<IActionResult> FirstMethod()
{
    using (MiniProfiler.Current.Step("FirstMethod"))
    {
        IActionResult result = this.SecondMethod();

        using (MiniProfiler.Current.Ignore())
        {
            Thread.Sleep(100);
        }

        return result;
    }
}

internal virtual IActionResult SecondMethod()
{
    using (MiniProfiler.Current.CustomTiming("SQL", "QuerySecondMethod"))
    {
        // Some data logic
    }
}
</code>```

What I expected is that on profiler the FirstMethod step duration and the SecondMethod custom timing would be approximately the same, since FirstMethod only calls SecondMethod and is ignoring the Thread.Sleep().

But I keep getting that FirstMethod duration is 100 milliseconds longer than SecondMethod, which makes it looks like the Ignore is not really disabling the profiler for the code inside it.

What am I doing wrong? Am I misunderstanding the documentation and purpose of the Ignore method?

答:
The .Ignore() method is for suppressing the code inside it, not the overall.

If you want to stop and throw away the profiler, your options are:

```<code>MiniProfiler.Current.Stop(discardResults: true);
</code>```

For more details, you can check this issue in github.

ContentLicense: CC BY-SA 4.0

Body:
I have a method with a portion of code I want to ignore from profiling when using MiniProfiler.

As from documentation, the extension method that does this is .Ignore(), that when used in a using statement should disable profiling for the duration.

Unfortunately I'm not getting the results as expected. Suppose I have this method structure:

public async Task<IActionResult> FirstMethod()
{
    using (MiniProfiler.Current.Step("FirstMethod"))
    {
        IActionResult result = this.SecondMethod();

        using (MiniProfiler.Current.Ignore())
        {
            Thread.Sleep(100);
        }

        return result;
    }
}

internal virtual IActionResult SecondMethod()
{
    using (MiniProfiler.Current.CustomTiming("SQL", "QuerySecondMethod"))
    {
        // Some data logic
    }
}

What I expected is that on profiler the FirstMethod step duration and the SecondMethod custom timing would be approximately the same, since FirstMethod only calls SecondMethod and is ignoring the Thread.Sleep().

But I keep getting that FirstMethod duration is 100 milliseconds longer than SecondMethod, which makes it looks like the Ignore is not really disabling the profiler for the code inside it.

What am I doing wrong? Am I misunderstanding the documentation and purpose of the Ignore method?

Body:
The .Ignore() method is for suppressing the code inside it, not the overall.

If you want to stop and throw away the profiler, your options are:

MiniProfiler.Current.Stop(discardResults: true);

For more details, you can check this issue in github.


问:
Android - How to tap ListView item programmatically
How to call ItemClickListener programmatically? listView.performItemClick() does not work. Is that possible?

答:
This will work!!</p>
```<code> listview.performItemClick(listview.getChildAt(position),
                    position,
                    listview.getChildAt(position).getId());
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This will work!!

 listview.performItemClick(listview.getChildAt(position),
                    position,
                    listview.getChildAt(position).getId());


问:
filter unknown string from pandas dataframe
I am currently working with database which is generated directly from machine instruments.(PI Data)
I am trying to remove information from the database which is mainly related to communication error.
For example

```<code>df_ex = pd.DataFrame({'Ambient': [20.11112, 'Bad',200.22222],
                  'Humidity': [50.47585, 89.14251,'Bad Input'],
                  'Compressor Temp': [50.47585, 89.14251,72.89657],
                  'Bearing Temp': ['Scan off', 74.45551, 52.2227]})
</code>```

df_ex:

```<code>     Ambient   Humidity  Compressor Temp Bearing Temp
0   20.11112   50.47585         50.47585     Scan off
1        Bad   89.14251         89.14251     74.45551
2  200.22222  Bad Input         72.89657      52.2227
</code>```

Errors received with df is filtered out by using below code.

```<code>df_ex.replace(['Bad','Bad Input','Scan Off'],np.nan, inplace=True)
df_ex.replace(" ", np.nan, inplace=True)
df_ex.dropna(inplace = True)
</code>```

I am trying to figure out way on how can I remove errors "Bad", "Bad Input" etc from dataframe by filtering out unknown error. I am filtering errors manually most of the time from excel file.

Due to huge size of data base trying unique value also doesn't help in filtering as there are many unique decimal values.

I used this code to find unique values to find error in the dataframe

```<code>df_ex['Ambient'].unique()
</code>```

Errors are changing time to time depending on network communication failure (Unknown error). So instead of "Bad" it may have "Bad Data" which I need to remove manually. If I fail to find out correct name of error my code doesn't run.

Can some one help on this?

Thank you for your time.

I tried out = df.apply(pd.to_numeric, errors = 'coerce') which removed errors but changed Date time in to nan.

答:
IIUC, you have a dataframe with numerical data and sometimes string values which denote incorrect data.

You could convert to numeric with errors="coerce" to force invalid data to NaN:

```<code>out = df_ex.apply(pd.to_numeric, errors='coerce')
</code>```

output:

```<code>     Ambient  Humidity  Compressor Temp  Bearing Temp
0   20.11112  50.47585         50.47585           NaN
1        NaN  89.14251         89.14251      74.45551
2  200.22222       NaN         72.89657      52.22270
</code>```

Body:
I am currently working with database which is generated directly from machine instruments.(PI Data)
I am trying to remove information from the database which is mainly related to communication error.
For example

df_ex = pd.DataFrame({'Ambient': [20.11112, 'Bad',200.22222],
                  'Humidity': [50.47585, 89.14251,'Bad Input'],
                  'Compressor Temp': [50.47585, 89.14251,72.89657],
                  'Bearing Temp': ['Scan off', 74.45551, 52.2227]})

df_ex:

     Ambient   Humidity  Compressor Temp Bearing Temp
0   20.11112   50.47585         50.47585     Scan off
1        Bad   89.14251         89.14251     74.45551
2  200.22222  Bad Input         72.89657      52.2227

Errors received with df is filtered out by using below code.

df_ex.replace(['Bad','Bad Input','Scan Off'],np.nan, inplace=True)
df_ex.replace(" ", np.nan, inplace=True)
df_ex.dropna(inplace = True)

I am trying to figure out way on how can I remove errors "Bad", "Bad Input" etc from dataframe by filtering out unknown error. I am filtering errors manually most of the time from excel file.

Due to huge size of data base trying unique value also doesn't help in filtering as there are many unique decimal values.

I used this code to find unique values to find error in the dataframe

df_ex['Ambient'].unique()

Errors are changing time to time depending on network communication failure (Unknown error). So instead of "Bad" it may have "Bad Data" which I need to remove manually. If I fail to find out correct name of error my code doesn't run.

Can some one help on this?

Thank you for your time.

I tried out = df.apply(pd.to_numeric, errors = 'coerce') which removed errors but changed Date time in to nan.

Body:
IIUC, you have a dataframe with numerical data and sometimes string values which denote incorrect data.

You could convert to numeric with errors="coerce" to force invalid data to NaN:

out = df_ex.apply(pd.to_numeric, errors='coerce')

output:

     Ambient  Humidity  Compressor Temp  Bearing Temp
0   20.11112  50.47585         50.47585           NaN
1        NaN  89.14251         89.14251      74.45551
2  200.22222       NaN         72.89657      52.22270


问:
I have a problem with if statement and numbers
my problem is I want to make the elif statement work on numbers only but the elif statement work on any datatype, is there any way i can separate the numbers in string type from the other data types

The Code

```<code>```address_book = {'1111': 'Amal', '2222': 'Mohammed', '3333': "Khadijah", '4444': 'Abdullah'}

def enter():
    i = input('Please Enter The number: ')
    if len(i) != 4:
        print('This is invalid number')
    elif i in list(address_book):
        print(address_book[i])
    elif i in list(address_book.values()):
        print(list(address_book.keys())[list(address_book.values()).index(i)])
    **elif i.isdigit() not in list(address_book.keys()):
        print('Sorry, the number is not found')
        m = input('do you want to add new number? ')
        if m == 'yes':
            d = input('Please Enter The new number: ')
            w = input('Please Enter the number owner name: ')
            address_book[d] = w
            f = input('Do yo want to see address book: ')
            if f == 'yes':
                print(address_book)
            else:
                pass**
        else:
            pass
    else:
        print('This is invalid number')

enter()```
</code>```

OutPut

```<code>```Please Enter The number: sdaa
Sorry, the number is not found
do you want to add new number? yes
Please Enter The new number: 3333
Please Enter the number owner name: Waleed
Do yo want to see address book: yes
{'1111': 'Amal', '2222': 'Mohammed', '3333': 'Waleed', '4444': 'Abdullah'}

Process finished with exit code 0```
</code>```

答:
in your dictionary, the key is a string and the default input method takes a string as input, it's simple to take input as int

```<code> i = int( input('Please Enter The number: '))
</code>```

as the keys are in string format you have to convert to string while checking in elif.

```<code>elif str(i) in list(address_book):
elif str(i) in list(address_book.values()):
elif str(i) not in list(address_book.keys()):
</code>```

full code :

address_book = {'1111': 'Amal', '2222': 'Mohammed', '3333': "Khadijah", '4444': 'Abdullah'}

def enter():
    i = int( input('Please Enter The number: '))
    if len(str(i)) != 4:
        print('This is invalid number')
    elif str(i) in list(address_book):
        print(address_book[i])
    elif str(i) in list(address_book.values()):
        print(list(address_book.keys())[list(address_book.values()).index(i)])
    elif str(i) not in list(address_book.keys()):
        print('Sorry, the number is not found')
        m = input('do you want to add new number? ')
        if m == 'yes':
            d = input('Please Enter The new number: ')
            w = input('Please Enter the number owner name: ')
            address_book[d] = w
            f = input('Do yo want to see address book: ')
            if f == 'yes':
                print(address_book)
            else:
                print(address_book)
        else:
            pass
    else:
        print('This is invalid number')

enter()
```

Body:
my problem is I want to make the elif statement work on numbers only but the elif statement work on any datatype, is there any way i can separate the numbers in string type from the other data types

The Code

```address_book = {'1111': 'Amal', '2222': 'Mohammed', '3333': "Khadijah", '4444': 'Abdullah'}

def enter():
    i = input('Please Enter The number: ')
    if len(i) != 4:
        print('This is invalid number')
    elif i in list(address_book):
        print(address_book[i])
    elif i in list(address_book.values()):
        print(list(address_book.keys())[list(address_book.values()).index(i)])
    **elif i.isdigit() not in list(address_book.keys()):
        print('Sorry, the number is not found')
        m = input('do you want to add new number? ')
        if m == 'yes':
            d = input('Please Enter The new number: ')
            w = input('Please Enter the number owner name: ')
            address_book[d] = w
            f = input('Do yo want to see address book: ')
            if f == 'yes':
                print(address_book)
            else:
                pass**
        else:
            pass
    else:
        print('This is invalid number')

enter()```

OutPut

```Please Enter The number: sdaa
Sorry, the number is not found
do you want to add new number? yes
Please Enter The new number: 3333
Please Enter the number owner name: Waleed
Do yo want to see address book: yes
{'1111': 'Amal', '2222': 'Mohammed', '3333': 'Waleed', '4444': 'Abdullah'}

Process finished with exit code 0```

Body:
in your dictionary, the key is a string and the default input method takes a string as input, it's simple to take input as int

 i = int( input('Please Enter The number: '))

as the keys are in string format you have to convert to string while checking in elif.

elif str(i) in list(address_book):
elif str(i) in list(address_book.values()):
elif str(i) not in list(address_book.keys()):

full code :

address_book = {'1111': 'Amal', '2222': 'Mohammed', '3333': "Khadijah", '4444': 'Abdullah'}

def enter():
    i = int( input('Please Enter The number: '))
    if len(str(i)) != 4:
        print('This is invalid number')
    elif str(i) in list(address_book):
        print(address_book[i])
    elif str(i) in list(address_book.values()):
        print(list(address_book.keys())[list(address_book.values()).index(i)])
    elif str(i) not in list(address_book.keys()):
        print('Sorry, the number is not found')
        m = input('do you want to add new number? ')
        if m == 'yes':
            d = input('Please Enter The new number: ')
            w = input('Please Enter the number owner name: ')
            address_book[d] = w
            f = input('Do yo want to see address book: ')
            if f == 'yes':
                print(address_book)
            else:
                print(address_book)
        else:
            pass
    else:
        print('This is invalid number')

enter()


问:
Excel formula to enhance depreciation pro-rated formula
I am building a file to calculate the depreciation amount of several items with various capitalization dates and depreciation rates. I currently have worked something out but it seems too basic, I am trying to fit as many of the already created formulas from column I to N into one to make it nice and clean. I am struggling to mix & match formuals to get there. Any suggestions on which formuals I should use is most welcomed.

From column A to G, it is data generated by a system. From Column I to N is the couple of basic formulas I have added.

Cell I13 has: =YEAR($C$10)-YEAR(B13)
Cell J13 has: =MONTH($C$10)-MONTH(B13)+1
Cell K13 has: =(I13*12)+J13
Cell L13 has: =VLOOKUP(A13,$B$4:$D$8,3,FALSE)
Cell M13 has: =VLOOKUP(A13,$B$4:$E$8,4,FALSE)
Cell N13 has: =IF(K13<M13,-C13*K13/M13,-C13)

The depreciation is calculated from the month of purchase of the asset (capitalisation date) and not by day.

Body:
I to N on one formula

=-MIN($C13,$C13/VLOOKUP($A13,$B$4:$E$8,4,0)*(DATEDIF($B13,$C$10,"M")+1))


问:
GORM Database.First(&tableStruct, id) without deleted_at IS NULL
When tableStruct have gorm.Model inside, how to get first record by id without gorm automatically adding deleted_at IS NULL? Is there such function?

答:
best answer here : https://gorm.io/docs/delete.html#Find-soft-deleted-records</p>
```<code>db.Unscoped().First(&tableStruct, id)
</code>```

Body:
best answer here : https://gorm.io/docs/delete.html#Find-soft-deleted-records

db.Unscoped().First(&tableStruct, id)


问:
Whats wrong in the following cpp Bucubic interpolation code for Image Resizing
I am trying to upsample an Image using Bicubic Interpoloation, I need the accurate values matching the cvResize() function of opencv, but the results of following code is not matching the results from cvResize(), can you take a look and help me to fix the bug.
```
Image *Image::resize_using_Bicubic(int w, int h) {
    float dx,dy;
    float x,y;
    float tx, ty;
    float i,j,m,n;</p>

<code>Image *result=new Image(w, h);
tx = (float)this->m_width/(float)w;
ty = (float)this->m_height/(float)h;
for(i=0; i< w; i++)
{
    for(j=0; j< h; j++)
    {
        x = i*tx;
        y = j*ty;
        dx = float(i-x)-(int)(i-x);
        dy = float(j-y)-(int)(j-y);
        float temp=0.0;
        for(m=-1;m<=2;m++)
        {
            for(n=-1;n<=2;n++)
            {

                int HIndex,WIndex;
                HIndex=(y+n);
                WIndex=(x+m);

                if (HIndex<0) {
                    HIndex=0;
                }
                else if(HIndex>this->getHeight())
                {
                    HIndex=this->getHeight()-1;

                }
                if (WIndex<0) {
                    WIndex=0;
                }
                else if(WIndex>this->getWidth())
                {
                    WIndex=this->getWidth()-1;

                }

                temp+=this->getPixel(HIndex,WIndex)*R(m-dx)*R(dy-n);
            }
        }

        result->setPixel(j, i, temp);
    }
}
return result;
</code>```

<p>}</p>

答:
You haven't said how different the results are. If they're very close, say within 1 or 2 in each RGB channel, this could be explained simply by roundoff differences.

There is more than one algorithm for Bicubic interpolation. Don Mitchell and Arun Netravali did an analysis and came up with a single formula to describe a number of them: http://www.mentallandscape.com/Papers_siggraph88.pdf

Edit: One more thing, the individual filter coefficients should be summed up and used to divide the final value at the end, to normalize the values. And I'm not sure why you have m-dx for one and dy-n for the other, shouldn't they be the same sign?

```<code>r=R(m-dx)*R(dy-n);
r_sum+=r;
temp+=this->getPixel(HIndex,WIndex)*r;
. . .
result->setPixel(j, i, temp/r_sum);
</code>```

Body:
I am trying to upsample an Image using Bicubic Interpoloation, I need the accurate values matching the cvResize() function of opencv, but the results of following code is not matching the results from cvResize(), can you take a look and help me to fix the bug.

Image *Image::resize_using_Bicubic(int w, int h) {
    float dx,dy;
    float x,y;
    float tx, ty;
    float i,j,m,n;

Image *result=new Image(w, h);
tx = (float)this->m_width/(float)w;
ty = (float)this->m_height/(float)h;
for(i=0; i< w; i++)
{
    for(j=0; j< h; j++)
    {
        x = i*tx;
        y = j*ty;
        dx = float(i-x)-(int)(i-x);
        dy = float(j-y)-(int)(j-y);
        float temp=0.0;
        for(m=-1;m<=2;m++)
        {
            for(n=-1;n<=2;n++)
            {

                int HIndex,WIndex;
                HIndex=(y+n);
                WIndex=(x+m);

                if (HIndex<0) {
                    HIndex=0;
                }
                else if(HIndex>this->getHeight())
                {
                    HIndex=this->getHeight()-1;

                }
                if (WIndex<0) {
                    WIndex=0;
                }
                else if(WIndex>this->getWidth())
                {
                    WIndex=this->getWidth()-1;

                }

                temp+=this->getPixel(HIndex,WIndex)*R(m-dx)*R(dy-n);
            }
        }

        result->setPixel(j, i, temp);
    }
}
return result;

}

Body:
You haven't said how different the results are. If they're very close, say within 1 or 2 in each RGB channel, this could be explained simply by roundoff differences.

There is more than one algorithm for Bicubic interpolation. Don Mitchell and Arun Netravali did an analysis and came up with a single formula to describe a number of them: http://www.mentallandscape.com/Papers_siggraph88.pdf

Edit: One more thing, the individual filter coefficients should be summed up and used to divide the final value at the end, to normalize the values. And I'm not sure why you have m-dx for one and dy-n for the other, shouldn't they be the same sign?

r=R(m-dx)*R(dy-n);
r_sum+=r;
temp+=this->getPixel(HIndex,WIndex)*r;
. . .
result->setPixel(j, i, temp/r_sum);


问:
Compare two xml files ignoring certain elements using XPath in Java
How can I compare two XML files, ignoring certain elements using
XPath?

For example, I need to compare the below two XML files, but I need to ignore 'Date' element, by passing the Xpath(//Set[1]/Product[\1]/Date) of this element during the run. The element to ignore could vary each time.

XML file 1:

```<code><?xml version="1.0" encoding="utf-8"?>
<Set
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="urn:abc:product:v3" xsi:schemaLocation="urn:abc:product:v3 abc.xsd">
    <Product>
        <id>1</id>
        <ref>1</ref>
        <Date>2021-09-19</Date>
        <company>JJ</company>
        <lastModified>2021-09-20T21:00:30</lastModified>
        <productOne>
            <partProduct>
                <Level>3.0</Level>
                <Flag>0</Flag>
                <Code>EN</Code>
            </partProduct>
        </productOne>
    </Product>
</Set>
</code>```

XML file 2:

```<code><?xml version="1.0" encoding="utf-8"?>
<Set
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="urn:abc:product:v3" xsi:schemaLocation="urn:abc:product:v3 abc.xsd">
    <Product>
        <id>2</id>
        <ref>2</ref>
        <Date>2021-09-20</Date>
        <company>JJ</company>
        <lastModified>2021-09-20T21:00:30</lastModified>
        <productOne>
            <partProduct>
                <Level>3.0</Level>
                <Flag>0</Flag>
                <Code>EN</Code>
            </partProduct>
        </productOne>
    </Product>
</Set>
</code>```

答:
You need to transform both files into a form where they compare equal, by removing the elements you want to ignore. You would typically do this using XSLT. After the transformation you could either compare the results using the XPath 2.0 function deep-equal(), or serialise both documents as canonical XML and compare the files at the character or binary level.

I would do this by running XQuery Update to delete the nodes selected by the path expression, and then comparing the resulting documents either using fn:deep-equal(), or by doing canonical serialization and comparing the resulting lexical forms.

As an alternative to XQuery Update you could use xmlstarlet or Saxon's Gizmo tool.

But it might depend on what you want from the comparison. The above is fine if you want a yes/no answer, but getting details of the differences is more difficult. You could write your own query to find the differences, or use a tool such as DeltaXML.

NOTE: This answer has been subsequently edited by a third party in a way that makes nonsense of the comment thread. Please ignore the comments.

Body:
How can I compare two XML files, ignoring certain elements using
XPath?

For example, I need to compare the below two XML files, but I need to ignore 'Date' element, by passing the Xpath(//Set[1]/Product[\1]/Date) of this element during the run. The element to ignore could vary each time.

XML file 1:

<?xml version="1.0" encoding="utf-8"?>
<Set
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="urn:abc:product:v3" xsi:schemaLocation="urn:abc:product:v3 abc.xsd">
    <Product>
        <id>1</id>
        <ref>1</ref>
        <Date>2021-09-19</Date>
        <company>JJ</company>
        <lastModified>2021-09-20T21:00:30</lastModified>
        <productOne>
            <partProduct>
                <Level>3.0</Level>
                <Flag>0</Flag>
                EN
            </partProduct>
        </productOne>
    </Product>
</Set>

XML file 2:

<?xml version="1.0" encoding="utf-8"?>
<Set
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="urn:abc:product:v3" xsi:schemaLocation="urn:abc:product:v3 abc.xsd">
    <Product>
        <id>2</id>
        <ref>2</ref>
        <Date>2021-09-20</Date>
        <company>JJ</company>
        <lastModified>2021-09-20T21:00:30</lastModified>
        <productOne>
            <partProduct>
                <Level>3.0</Level>
                <Flag>0</Flag>
                EN
            </partProduct>
        </productOne>
    </Product>
</Set>


问:
Why QWidget::Mask based on QPixmap works fine, but Bitmap doesn't
Target: make my widget rounded, using QWidget::setMask

At first, I want to make a mask using QRegion, but later I found that, make a rounded Rect based on region is a not simple way.
So I decided to use QBitmap.

```<code>    QBitmap pixmap(size());//create image
    QPainter pixmapPainter(&pixmap);
    QPainterPath path;
    path.addRoundedRect(0, 0, width(), height(), m_borderRadius, m_borderRadius);//fill rounded rect
    pixmapPainter.fillPath(path, Qt::color1);
    QWidget::setMask(pixmap.mask());
</code>```

Result is:

But when I change my type to QPixmap and add the fill method

```<code>QBitmap pixmap(size());//
pixmap.fill(Qt::transparent);//
QPainter pixmapPainter(&pixmap);
pixmapPainter.setRenderHint(QPainter::Antialiasing, true);
QPainterPath path;
path.addRoundedRect(0, 0, width(), height(), m_borderRadius, m_borderRadius);//
pixmapPainter.fillPath(path, Qt::white);
QWidget::setMask(pixmap.mask());
</code>```

It shows me:

What's wrong with my first code?

答:
As the comment by G.M. explains, the bitmap needs to be cleared first.

Also, a widget mask is not really the best choice here. A widget mask is intended for defining the areas where your widget will take mouse input. On most window systems, it will also cause transparency. But the edges will be aliased and not pretty. In order to make a non-rectangular widget with nice edges, one should use translucent widget background and anti-aliased painting - in addition to the widget mask for the mouse input.
This is shown and explained in Qt's shapedclock example.

Body:
Target: make my widget rounded, using QWidget::setMask

At first, I want to make a mask using QRegion, but later I found that, make a rounded Rect based on region is a not simple way.
So I decided to use QBitmap.

    QBitmap pixmap(size());//create image
    QPainter pixmapPainter(&pixmap);
    QPainterPath path;
    path.addRoundedRect(0, 0, width(), height(), m_borderRadius, m_borderRadius);//fill rounded rect
    pixmapPainter.fillPath(path, Qt::color1);
    QWidget::setMask(pixmap.mask());

Result is:

But when I change my type to QPixmap and add the fill method

QBitmap pixmap(size());//
pixmap.fill(Qt::transparent);//
QPainter pixmapPainter(&pixmap);
pixmapPainter.setRenderHint(QPainter::Antialiasing, true);
QPainterPath path;
path.addRoundedRect(0, 0, width(), height(), m_borderRadius, m_borderRadius);//
pixmapPainter.fillPath(path, Qt::white);
QWidget::setMask(pixmap.mask());

It shows me:

What's wrong with my first code?


问:
Gridlayout height based on Label height in recycleview not aligned
I have managed to get the size of a box layout to change based on the corresponding Label height, however, it doesn't line up perfectly and I cannot figure out why.

I have looked at adding offsets but have had no luck since it ended up making the issue worse

Thank you for any help

```<code>MainInterface:

<MainInterface@BoxLayout>:
    orientation: "vertical"
    Label:
        #font_name: "Nunito-Black.ttf"
        text: "T            R           U             T            H"
        size_hint: 1, 0.1
    GridLayout:
        size_hint: 1, 0.12
        cols: 4
        Button:
            text: "Menu1"
        Button:
            text: "Menu2"
        Button:
            text: "Menu3"
        Button:
            text: "Menu4"
    PageLayout:
        border: "20dp"
        swipe_threshold: 0.2
        RecycleView:
            viewclass: 'PostGrid'
            scroll_y: 1
            id: rv
            data: app.posts
            RecycleBoxLayout:
                id: box
                default_size: None, None
                default_size_hint: 1, None
                size_hint_y: None
                padding: ["10dp", "16dp"]
                spacing: "8dp"
                height: self.minimum_height
                orientation: 'vertical'
                key_size: '_size'
        BoxLayout:
            orientation: "vertical"
            Button:
                text: "peni"
            Button:
                text: "tag @ will J"
            Button:
                text: "Input"

<PostGrid@BoxLayout>:
    message_id: -1
    orientation: "horizontal"
    text: ''
    spacing: "10dp"
    #size_hint: self.width, None
    _size: 0, 74
    size: 0, 74
    text_size: None, None
    BoxLayout:
        orientation: "vertical"
        spacing: "10dp"
        size_hint: .1, 1
        size: self.size
        Button:
            text: "UP"
            font_size: "5dp"
            size_hint: 1, 0.2
        Button:
            text: "DOWN"
            font_size: "5dp"
            size_hint: 1, 0.2
        Label:
            text: "test"
            font_size: "5dp"
            size_hint: 1, 0.6
    Label:
        text: root.text
        padding: 5, 5
        size_hint: .9, 1
        #size: self.texture_size
        height: self.texture_size[1]
        text_size: self.width, None
        color: 0,0,0,1
        #text_size: self.width, None
        #size_hint: None, 1
        #size: self.texture_size
        #font_name: "Nunito-Bold.ttf"
        #font_size: "12dp"
        multiline: True
        #size: 1, root.min_height

        on_texture_size:
            app.update_message_size(
            root.message_id,
            self.texture_size,
            root.width)

        pos: self.pos

        canvas.before:
            Color:
                rgba: (0.8, 0.8, 0.8, 1)
            RoundedRectangle:
                size: self.texture_size
                radius: [5, 5, 5, 5]
                pos: self.x, self.y
        canvas:
            Color:
                rgba:0,0.9,0.9,1
            Line:
                width:0.8
                rounded_rectangle:(self.x,self.y,self.width,self.height, 5)
</code>```
```<code>from kivy.app import App
from kivy.lang import Builder
from kivy.clock import Clock
from kivy.properties import ListProperty
from kivy.animation import Animation
from kivy.metrics import dp

class TruthApp(App):
    posts = ListProperty([{'message_id':0, 'text':"testskjhfjksdhfkjshfjshfjkhskjdfhskjdhfkjshfdkjhsjkdfhskjhdfkjshdfjkhzxczxczxczxcxzczxcxsjkdfhjksdhfkjshkjdfhksjdhfjkshdfjkhsdkjhfkjshdfjkshkjfhskjhfkjshfjkshdkjfhskjhfjshfkjshdfjkshdjkfhskjhfkjshfjksdhjfhsjkdhfjkhsdkjfhskjhfjk\ngdgdgd\ndgdgdg\ndgdgdg\ndggdgd",'_size':[0,0] }, {'message_id':1, 'text':"testskjhfjksdhfkjshfjshfjkhskjdfhskjdhfkjshfdkjhsjkdfhskjhjfhskjhfjk,'_size':[0,0]"}])

    def update_message_size(self, message_id, texture_size, max_width):
        #print(self.posts)
        #print("Here")
        self.posts[message_id] = {**self.posts[message_id], '_size':[0, texture_size[1]]}

if __name__ == '__main__':
    TruthApp().run()
</code>```

^ Image showing how the code above runs

答:
The problem is in the viewclass of RecycleView (i.e. PostGrid). You set its heightas such it could not accomodate its children which is supposed to be the minimum height that will place all its children.

Now that's exactly the attr. minimum_height does. With this being applied you also don't need default_size: None, None (especially the height attr.)

With this and other modifications your .kv file should now look like,

MainInterface:

<MainInterface@BoxLayout>:
    orientation: "vertical"
    Label:
        #font_name: "Nunito-Black.ttf"
        text: "T            R           U             T            H"
        size_hint: 1, 0.1
    GridLayout:
        size_hint: 1, 0.12
        cols: 4
        Button:
            text: "Menu1"
        Button:
            text: "Menu2"
        Button:
            text: "Menu3"
        Button:
            text: "Menu4"
    PageLayout:
        border: "20dp"
        swipe_threshold: 0.2
        RecycleView:
            viewclass: 'PostGrid'
            scroll_y: 1
            id: rv
            data: app.posts
            RecycleBoxLayout:
                id: box
                default_size_hint: 1, None
                size_hint_y: None
                padding: ["10dp", "16dp"]
                spacing: "8dp"
                height: self.minimum_height
                orientation: 'vertical'
                key_size: '_size'
        BoxLayout:
            orientation: "vertical"
            Button:
                text: "peni"
            Button:
                text: "tag @ will J"
            Button:
                text: "Input"

<PostGrid@BoxLayout>:
    message_id: -1
    orientation: "horizontal"
    text: ''
    spacing: "10dp"
    size_hint_y: None
    #_size: 0, 74
    height: self.minimum_height
    text_size: None, None
    BoxLayout:
        orientation: "vertical"
        spacing: "10dp"
        size_hint: .1, 1
        Button:
            text: "UP"
            font_size: "5dp"
            size_hint: 1, 0.2
        Button:
            text: "DOWN"
            font_size: "5dp"
            size_hint: 1, 0.2
        Label:
            text: "test"
            font_size: "5dp"
            size_hint: 1, 0.6
    Label:
        text: root.text
        padding: 5, 5
        #size_hint: .9, 1
        #size: self.texture_size
        size_hint_y: None
        height: self.texture_size[1]
        text_size: self.width, None
        color: 0,0,0,1
        #text_size: self.width, None
        #size_hint: None, 1
        #size: self.texture_size
        #font_name: "Nunito-Bold.ttf"
        #font_size: "12dp"
        multiline: True
        #size: 1, root.min_height

        on_texture_size:
            app.update_message_size(
            root.message_id,
            self.texture_size,
            root.width)

        pos: self.pos

        canvas.before:
            Color:
                rgba: (0.8, 0.8, 0.8, 1)
            RoundedRectangle:
                size: self.texture_size
                radius: [5, 5, 5, 5]
                pos: self.x, self.y
        canvas:
            Color:
                rgba:0,0.9,0.9,1
            Line:
                width:0.8
                rounded_rectangle:(self.x,self.y,self.width,self.height, 5)
```

Body:
I have managed to get the size of a box layout to change based on the corresponding Label height, however, it doesn't line up perfectly and I cannot figure out why.

I have looked at adding offsets but have had no luck since it ended up making the issue worse

Thank you for any help

MainInterface:

<MainInterface@BoxLayout>:
    orientation: "vertical"
    Label:
        #font_name: "Nunito-Black.ttf"
        text: "T            R           U             T            H"
        size_hint: 1, 0.1
    GridLayout:
        size_hint: 1, 0.12
        cols: 4
        Button:
            text: "Menu1"
        Button:
            text: "Menu2"
        Button:
            text: "Menu3"
        Button:
            text: "Menu4"
    PageLayout:
        border: "20dp"
        swipe_threshold: 0.2
        RecycleView:
            viewclass: 'PostGrid'
            scroll_y: 1
            id: rv
            data: app.posts
            RecycleBoxLayout:
                id: box
                default_size: None, None
                default_size_hint: 1, None
                size_hint_y: None
                padding: ["10dp", "16dp"]
                spacing: "8dp"
                height: self.minimum_height
                orientation: 'vertical'
                key_size: '_size'
        BoxLayout:
            orientation: "vertical"
            Button:
                text: "peni"
            Button:
                text: "tag @ will J"
            Button:
                text: "Input"

<PostGrid@BoxLayout>:
    message_id: -1
    orientation: "horizontal"
    text: ''
    spacing: "10dp"
    #size_hint: self.width, None
    _size: 0, 74
    size: 0, 74
    text_size: None, None
    BoxLayout:
        orientation: "vertical"
        spacing: "10dp"
        size_hint: .1, 1
        size: self.size
        Button:
            text: "UP"
            font_size: "5dp"
            size_hint: 1, 0.2
        Button:
            text: "DOWN"
            font_size: "5dp"
            size_hint: 1, 0.2
        Label:
            text: "test"
            font_size: "5dp"
            size_hint: 1, 0.6
    Label:
        text: root.text
        padding: 5, 5
        size_hint: .9, 1
        #size: self.texture_size
        height: self.texture_size[1]
        text_size: self.width, None
        color: 0,0,0,1
        #text_size: self.width, None
        #size_hint: None, 1
        #size: self.texture_size
        #font_name: "Nunito-Bold.ttf"
        #font_size: "12dp"
        multiline: True
        #size: 1, root.min_height

        on_texture_size:
            app.update_message_size(
            root.message_id,
            self.texture_size,
            root.width)

        pos: self.pos

        canvas.before:
            Color:
                rgba: (0.8, 0.8, 0.8, 1)
            RoundedRectangle:
                size: self.texture_size
                radius: [5, 5, 5, 5]
                pos: self.x, self.y
        canvas:
            Color:
                rgba:0,0.9,0.9,1
            Line:
                width:0.8
                rounded_rectangle:(self.x,self.y,self.width,self.height, 5)

from kivy.app import App
from kivy.lang import Builder
from kivy.clock import Clock
from kivy.properties import ListProperty
from kivy.animation import Animation
from kivy.metrics import dp

class TruthApp(App):
    posts = ListProperty([{'message_id':0, 'text':"testskjhfjksdhfkjshfjshfjkhskjdfhskjdhfkjshfdkjhsjkdfhskjhdfkjshdfjkhzxczxczxczxcxzczxcxsjkdfhjksdhfkjshkjdfhksjdhfjkshdfjkhsdkjhfkjshdfjkshkjfhskjhfkjshfjkshdkjfhskjhfjshfkjshdfjkshdjkfhskjhfkjshfjksdhjfhsjkdhfjkhsdkjfhskjhfjk\ngdgdgd\ndgdgdg\ndgdgdg\ndggdgd",'_size':[0,0] }, {'message_id':1, 'text':"testskjhfjksdhfkjshfjshfjkhskjdfhskjdhfkjshfdkjhsjkdfhskjhjfhskjhfjk,'_size':[0,0]"}])

    def update_message_size(self, message_id, texture_size, max_width):
        #print(self.posts)
        #print("Here")
        self.posts[message_id] = {**self.posts[message_id], '_size':[0, texture_size[1]]}

if __name__ == '__main__':
    TruthApp().run()

^ Image showing how the code above runs


问:
NodeJS Express allow handeful requests to skip authentication check
Is there a request path regex matcher in NodeJS , basically I would like to build a capability to allow certain paths to skip token validation.
How to do it in Express.</p>
```<code>function verifyToken(req, res, next) {
  // Get auth header value
  const whitelistPaths = ["/ping","**/swagger-ui.html/**","/health/*"];
  if(req.path matches any of values in whitelist array) , call next()
  const bearerHeader = req.headers["Authorization"];
  Authentication check
</code>```
```<code>router.get("*", verifyToken, apiProxy);
</code>```

答:
Just use a regex as the path :

router.get((\/ping)|(.*\/swagger-ui\.html)|(\/health\/.*), verifyToken, apiProxy);

this will catch /ping or /swagger-ui.html or /health

here is the docs: https://expressjs.com/en/guide/routing.html

Body:
Is there a request path regex matcher in NodeJS , basically I would like to build a capability to allow certain paths to skip token validation.
How to do it in Express.

function verifyToken(req, res, next) {
  // Get auth header value
  const whitelistPaths = ["/ping","**/swagger-ui.html/**","/health/*"];
  if(req.path matches any of values in whitelist array) , call next()
  const bearerHeader = req.headers["Authorization"];
  Authentication check

router.get("*", verifyToken, apiProxy);


问:
The multi-part identifier "t.subjectId" could not be bound. Entity Framework Core
I am facing problem, I write a query in Entity Framework Core using C#, but I am unable to get my final result. It will be great favour if someone help me.

I want to show students result of entry test, if subject result is not posted then it should show 0, means need to add left outer join. I write the below query, but when I execute it returns the error.

```<code>var result = _db.palSundayTests
                .Where(w => w.testId == testId)
                .Select(s => new
                             {
                                 testId = s.testId,
                                 testDate = s.testDate,
                                 students = _db.palSundayTestStudents
                                               .Where(w => w.testGroupId == s.testGroupId)
                                               .Select(st => new
                                                             {
                                                                 students = st,
                                                                 results = (from tp in _db.palSubjInfo
                                                                            join rs in _db.palStudentTestResult.Where(r => r.studentId == st.studentId)
                                                                                on tp.subjectId equals rs.subjectId
                                                                            into myres
                                                                            from myview in myres.DefaultIfEmpty()
                                                                            select new
                                                                                {
                                                                                myview.obtainedMarks
                                                                                }).ToList()
                                                              }).FirstOrDefault(),
                                 subjects = s.sundayTestTopic
                             });
</code>```

When I run in POSTMAN, I get this error

The multi-part identifier "t.subjectId" could not be bound

The multi-part identifier "t.obtainedMarks" could not be bound

The multi-part identifier "t.studentId" could not be bound

The multi-part identifier "t.testId" could not be bound

答: You are mixing implicit joins with explicit joins. That is allowed, but you need to be aware of how to do that properly. may it help https://stackoverflow.com/a/7314936/11143288</p>

Body:
I am facing problem, I write a query in Entity Framework Core using C#, but I am unable to get my final result. It will be great favour if someone help me.

I want to show students result of entry test, if subject result is not posted then it should show 0, means need to add left outer join. I write the below query, but when I execute it returns the error.

var result = _db.palSundayTests
                .Where(w => w.testId == testId)
                .Select(s => new
                             {
                                 testId = s.testId,
                                 testDate = s.testDate,
                                 students = _db.palSundayTestStudents
                                               .Where(w => w.testGroupId == s.testGroupId)
                                               .Select(st => new
                                                             {
                                                                 students = st,
                                                                 results = (from tp in _db.palSubjInfo
                                                                            join rs in _db.palStudentTestResult.Where(r => r.studentId == st.studentId)
                                                                                on tp.subjectId equals rs.subjectId
                                                                            into myres
                                                                            from myview in myres.DefaultIfEmpty()
                                                                            select new
                                                                                {
                                                                                myview.obtainedMarks
                                                                                }).ToList()
                                                              }).FirstOrDefault(),
                                 subjects = s.sundayTestTopic
                             });

When I run in POSTMAN, I get this error

The multi-part identifier "t.subjectId" could not be bound

The multi-part identifier "t.obtainedMarks" could not be bound

The multi-part identifier "t.studentId" could not be bound

The multi-part identifier "t.testId" could not be bound


问:
Intellij Does not have run button when running Springboot Applications
I downloaded Intellij to follow a Springboot tutorial. It begins by going to Spring Initializr to get all relevant dependencies in a folder and open it up on Intellij. As I open up Intellij, the run button is not visible. Instead it says "Add Configuration".

If I open up Intellij for a normal java program, I was easily able to click run and choose "Main.java"

This is a freshly installed Intellj and settings were set up as default. Is there a trick to find the run button when dealing with Springboot? I tried doing as if it was a normal program but as you can see, I can't find it. I tried looking up similar questions but there doesn't seem any that matches mine. I would appreciate any help. Thank you!

EDIT 1:
I tried right clicking on src directory and select option Mark Directory As > Sources Root. But breaks program instead.

EDIT 2:
I tried adding a new configuration --> Add new --> Application --> then look for Main class entitled 'DemoApplication' but its not found. (I thought that this would be my main class)

答:
You have imported the project at the wrong folder level.
your folder structure seems to be like demo/demo/src.

You imported the project at demo whereas you should have imported it at demo/demo.
When you import it you want src/ and pom.xml to be at the root of the project.
Also when you import it the src/ folder should be blue, that is how you know you have imported it correctly.

As a rule of thumb you should always make sure a pom.xml is at the root of the import when working with maven


问:
Use filename insted of 'Download'
On my Django page I have a paragraph to download attached files:

```<code>{% for i in post.file_set.all %}<p class="article-content mt-2 mb-1"><strong>Attachment {{ forloop.counter }}: </strong><a href="{{i.file.url}}" >Download</a></p>{% endfor %}
</code>```

How can I show File name insted of word 'Download'. Users don't know which file is which when downloading, in case of many files. Also, if extension is possible.

So, insted of:

```<code>Attachment: Download
</code>```

I would like to have:

```<code>Attachment: image.png
</code>```

答:
Just replace Download with {{i.file.name}}

```<code>{% for i in post.file_set.all %}<p class="article-content mt-2 mb-1"><strong>Attachment {{ forloop.counter }}: </strong><a href="{{i.file.url}}" >{{i.file.name}}</a></p>{% endfor %}
</code>```

Title: Use filename insted of 'Download'

Body:
On my Django page I have a paragraph to download attached files:

{% for i in post.file_set.all %}
Attachment {{ forloop.counter }}: Download
{% endfor %}

How can I show File name insted of word 'Download'. Users don't know which file is which when downloading, in case of many files. Also, if extension is possible.

So, insted of:

Attachment: Download

I would like to have:

Attachment: image.png

Body:
Just replace Download with {{i.file.name}}

{% for i in post.file_set.all %}<p class="article-content mt-2 mb-1"><strong>Attachment {{ forloop.counter }}: </strong><a href="{{i.file.url}}" >{{i.file.name}}</a></p>{% endfor %}


问:
How to add a day to Date field in RTF template for BIP
I have a small requirement where i have to add +1 day in a given date and then compare it with a different date to fetch a set of records, please make me understand how can this be achieved in BIP (RTF).

something like-

if CompletetdDate+ 1 = ReportedDate , then print "Successful"

Kindly help me.

Thanks,

答:
Maybe 'xdoxslt:ora_format_date_offset' would help you.
You can see an example in https://help.aconex.com/DisplayContent/advanced-functions-in-the-offline-template-builder.</p>


问:
Can't make filter work with Immer.js to remove nested object in array
I'm starting with Immer.js for immutability in JS and I can't find a way to remove an object in an array using the filter method. It returns the same object. BTW, I'm doing it in React with state but to make it more straightforward I made up simple snippets that reflect my problem.

```<code>const sampleArr = [
      {
        items: [
          { slug: "prod1", qnty: 1 },
          { slug: "prod2", qnty: 3 },
          { slug: "prod3", qnty: 2 },
        ],
      },
    ];

    const newState = produce(sampleArr, (draft) => {
      draft[0].items.filter((item) => item.slug !== "prod1");
    });

    console.log(newState);
</code>```

Console.log was supposed to give me the same whole array but without the first item. However, what I get is the same array without any change.

I googled it and searched on immer docs but couldn't find my answer. Immer.js docs about Array mutation => https://immerjs.github.io/immer/docs/update-patterns

Obs. To test it out on chrome dev tools you can copy-paste the immer lib (https://unpkg.com/immer@6.0.3/dist/immer.umd.production.min.js) and change produce method to immer.produce

答:
Using destructuring for making immutable objects goes against Immert.
The way of solving this issue is by reassigning the filtered part to draft.
The solution looks like this:

```<code>const sampleArr = [
  {
    items: [
      { slug: "prod1", qnty: 1 },
      { slug: "prod2", qnty: 3 },
      { slug: "prod3", qnty: 2 },
    ],
  },
];

const newState = produce(sampleArr, (draft) => {
  draft[0].items = draft[0].items.filter((item) => item.slug !== "prod1");
});
</code>```

You can play around in the repleit here:
https://replit.com/@GaborOttlik/stackoverflow-immer#index.js

Body:
I'm starting with Immer.js for immutability in JS and I can't find a way to remove an object in an array using the filter method. It returns the same object. BTW, I'm doing it in React with state but to make it more straightforward I made up simple snippets that reflect my problem.

const sampleArr = [
      {
        items: [
          { slug: "prod1", qnty: 1 },
          { slug: "prod2", qnty: 3 },
          { slug: "prod3", qnty: 2 },
        ],
      },
    ];

    const newState = produce(sampleArr, (draft) => {
      draft[0].items.filter((item) => item.slug !== "prod1");
    });

    console.log(newState);

Console.log was supposed to give me the same whole array but without the first item. However, what I get is the same array without any change.

I googled it and searched on immer docs but couldn't find my answer. Immer.js docs about Array mutation => https://immerjs.github.io/immer/docs/update-patterns

Obs. To test it out on chrome dev tools you can copy-paste the immer lib (https://unpkg.com/immer@6.0.3/dist/immer.umd.production.min.js) and change produce method to immer.produce

Body:
Using destructuring for making immutable objects goes against Immert.
The way of solving this issue is by reassigning the filtered part to draft.
The solution looks like this:

const sampleArr = [
  {
    items: [
      { slug: "prod1", qnty: 1 },
      { slug: "prod2", qnty: 3 },
      { slug: "prod3", qnty: 2 },
    ],
  },
];

const newState = produce(sampleArr, (draft) => {
  draft[0].items = draft[0].items.filter((item) => item.slug !== "prod1");
});

You can play around in the repleit here:
https://replit.com/@GaborOttlik/stackoverflow-immer#index.js