问:
Angular - template checkboxes in ngFor are linked
For a role assignment website, it is possible to assign a role to a user for a specific application. These roles can have some linked "entities", such as Brands. The content of such entities can be repeated for multiple roles, so I placed it in a ng-template. Based on the linked property, the template is setup. At the same time, there can multiple Brands templates for multiple roles.

In the template, there are checkboxes which are bound to brand countries. When I check a brand country, the same brand country of another role.

Currently, I have no idea how these are bound to each other.

E.g. I've two roles AssignmentAdmin and UserAdmin. Both roles are linked to Brands. When I check Belgium in the TestMichael brand, the same country/brand is checked for UserAdmin.

roles JSON, this body is complemented with other Brands data, but this is the basic structure of assigned countries.

```<code>"applications": [
    {
        "id": "173043ae-00f4-49d5-ba15-41488fc09ef4",
        "name": "MyAccount",
        "roles": [
            {
                "id": "e187b0d2-4b3d-60a3-9d14-1a6f48b465b8",
                "name": "UserAdmin",
                "brands": [
                    {
                        "id": "b2f3815c-1501-13b1-9d14-e03e18b0aa67",
                        "name": "Reynaers",
                        "countries": [
                            {
                                "id": "b2f3815c-1501-13b1-9d14-e03e2825e967",
                                "country": "BE",
                                "companyTypes": null
                            },
                            {
                                "id": "b2f3815c-1501-13b1-9d14-e03e406ff567",
                                "country": "DZ",
                                "companyTypes": null
                            },
                            {
                                "id": "b2f3815c-1501-13b1-9d14-e03e90860168",
                                "country": "AT",
                                "companyTypes": null
                            },
                            {
                                "id": "b2f3815c-1501-13b1-9d14-e03e7846d267",
                                "country": "AU",
                                "companyTypes": null
                            }
                        ]
                    }
                ],
                "applications": null,
                "companyTypes": null,
                "linked": "Brands"
            },
            {
                "id": "e187b0d2-4b3d-60a3-9d14-646fb0402ecf",
                "name": "AssignmentAdmin",
                "brands": [
                    {
                        "id": "b2f3815c-1501-13b1-9d14-e03e18b0aa67",
                        "name": "Reynaers",
                        "countries": [
                            {
                                "id": "b2f3815c-1501-13b1-9d14-e03e406ff567",
                                "country": "DZ",
                                "companyTypes": null
                            },
                            {
                                "id": "b2f3815c-1501-13b1-9d14-e03e90860168",
                                "country": "AT",
                                "companyTypes": null
                            },
                            {
                                "id": "b2f3815c-1501-13b1-9d14-e03e2825e967",
                                "country": "BE",
                                "companyTypes": null
                            }
                        ]
                    }
                ],
                "applications": [
                    {
                        "id": "a6656547-2d5b-44f6-8d51-30dd737c1759",
                        "name": "Article",
                        "companyTypes": null
                    }
                ],
                "companyTypes": null,
                "linked": "Brands,Applications"
            }
        ]
    }
]
</code>```

Create templates

```<code><h5 *ngIf="bSelectRoleEntities && role.linked != 'None'">Linked entities of {{role.name}}</h5>
<mat-tab-group *ngIf="bSelectRoleEntities && role.linked != 'None'" animationDuration="0ms" dynamicHeight>
    <mat-tab *ngFor="let linked of role.linked" label="{{linked}}">
        <ng-container #entity [ngTemplateOutlet]="linked == 'Brands' ? Brands : Applications"
            [ngTemplateOutletContext]="{role: role}" ></ng-container>
    </mat-tab>
</mat-tab-group>
</code>```

Brands template

```<code><ng-template #Brands let-role="role">
    <div class="ds-card ds-card--primary">
        <div class="ds-card__body ds-card__body--lg">
        <div>{{role.id}} - {{role.name}}</div>
          <div *ngFor="let brand of role.brands">
            <div class="ds-grid-auto-xl ds-grid-auto-gap-lg" >
              <div class="ds-card ds-card--tertiary ds-card--success">
                <div class="ds-card__body">
                  <details class="ds-details">
                    <summary class="ds-details__summary ds-details__summary--block">
                        <div class="row">
                          <div class="col-md-2"><h4><span [matBadgeHidden]="brand.assignedCountries === 0"  matBadge="{{brand.assignedCountries}}" matBadgeOverlap="false">{{brand.name}}</span></h4></div>
                          <div class="col-md-3 ds-input-check ds-input-check--inline">
                            <input id="check-{{brand.name}}" type="checkbox" class="ds-input-check__input">
                            <label for="check-{{brand.name}}" class="ds-input-check__label">Assign to all countries</label>
                          </div>
                          <div class="col-md-4">
                            <input class="form-control inputField" type="text" placeholder="Filter countries" [(ngModel)]="brand.countryFilter" />
                          </div>
                        </div>
                    </summary>
                    <div class="col-md-3 box-border" *ngFor="let country of brand.countries">
                      <div class="ds-input-check ds-input-check--inline">
                        <input id="check-{{role.id}}-{{brand.name}}-{{country.country}}" type="checkbox" class="ds-input-check__input" [name]="role.id + brand.name" [(ngModel)]="country.isAssigned" (change)="assignRoleBrands($event,role.id,brand.id,country.id)" >
                        <label for="check-{{role.id}}-{{brand.name}}-{{country.country}}" class="ds-input-check__label"><span><img class="ds-button__icon--left" src="https://flagcdn.com/w20/{{country.country.toLowerCase()}}.png" width="20"/>{{ country.country | translate }}</span></label>
                      </div>
                      <!-- <mat-chip-list selectable multiple>
                        <mat-chip *ngFor="let companyType of country.companyTypes" #c="matChip" (click)="setCountryCompanyType(c, brand.id, country.id, companyType.id)" selected="{{companyType.isAssigned}}">
                          {{companyType.name}}
                        </mat-chip>
                      </mat-chip-list> -->
                    </div>
                  </details>
                </div>
              </div>
            </div>
            <br />
          </div>
        </div>
    </div>
</ng-template>
</code>```

EDIT

The checkbox in the template has a binding method linked to it. This is the code.

```<code> assignRoleBrands(e: any, roleId: string, brandId: string, countryId: string) {
      var brand = this.applicationRoleDetail.roles.find(r => r.id == roleId).brands.find(b => b.id == brandId);
      //var brand = this.selectedRole.brands.find(b => b.id == brandId);
      brand.countries.find(c => c.id == countryId).isAssigned = e.currentTarget.checked;
      brand.assignedCountries = brand.countries.filter(c => c.isAssigned).length;

      this.selectedRole.entitiesSet = this.determineEntitiesSet(this.applicationRoleDetail.roles.find(r => r.id == roleId)); //this.selectedRole.brands?.some(b => b.assignedCountries > 0) && this.selectedRole.applications?.some(a => a.assignedApplications > 0);

      console.log(this.applicationRoleDetail);

      this.checkForApplicationChanges();
    }
</code>```

Can someone help me with this?

Body:
For a role assignment website, it is possible to assign a role to a user for a specific application. These roles can have some linked "entities", such as Brands. The content of such entities can be repeated for multiple roles, so I placed it in a ng-template. Based on the linked property, the template is setup. At the same time, there can multiple Brands templates for multiple roles.

In the template, there are checkboxes which are bound to brand countries. When I check a brand country, the same brand country of another role.

Currently, I have no idea how these are bound to each other.

E.g. I've two roles AssignmentAdmin and UserAdmin. Both roles are linked to Brands. When I check Belgium in the TestMichael brand, the same country/brand is checked for UserAdmin.

roles JSON, this body is complemented with other Brands data, but this is the basic structure of assigned countries.

"applications": [
    {
        "id": "173043ae-00f4-49d5-ba15-41488fc09ef4",
        "name": "MyAccount",
        "roles": [
            {
                "id": "e187b0d2-4b3d-60a3-9d14-1a6f48b465b8",
                "name": "UserAdmin",
                "brands": [
                    {
                        "id": "b2f3815c-1501-13b1-9d14-e03e18b0aa67",
                        "name": "Reynaers",
                        "countries": [
                            {
                                "id": "b2f3815c-1501-13b1-9d14-e03e2825e967",
                                "country": "BE",
                                "companyTypes": null
                            },
                            {
                                "id": "b2f3815c-1501-13b1-9d14-e03e406ff567",
                                "country": "DZ",
                                "companyTypes": null
                            },
                            {
                                "id": "b2f3815c-1501-13b1-9d14-e03e90860168",
                                "country": "AT",
                                "companyTypes": null
                            },
                            {
                                "id": "b2f3815c-1501-13b1-9d14-e03e7846d267",
                                "country": "AU",
                                "companyTypes": null
                            }
                        ]
                    }
                ],
                "applications": null,
                "companyTypes": null,
                "linked": "Brands"
            },
            {
                "id": "e187b0d2-4b3d-60a3-9d14-646fb0402ecf",
                "name": "AssignmentAdmin",
                "brands": [
                    {
                        "id": "b2f3815c-1501-13b1-9d14-e03e18b0aa67",
                        "name": "Reynaers",
                        "countries": [
                            {
                                "id": "b2f3815c-1501-13b1-9d14-e03e406ff567",
                                "country": "DZ",
                                "companyTypes": null
                            },
                            {
                                "id": "b2f3815c-1501-13b1-9d14-e03e90860168",
                                "country": "AT",
                                "companyTypes": null
                            },
                            {
                                "id": "b2f3815c-1501-13b1-9d14-e03e2825e967",
                                "country": "BE",
                                "companyTypes": null
                            }
                        ]
                    }
                ],
                "applications": [
                    {
                        "id": "a6656547-2d5b-44f6-8d51-30dd737c1759",
                        "name": "Article",
                        "companyTypes": null
                    }
                ],
                "companyTypes": null,
                "linked": "Brands,Applications"
            }
        ]
    }
]

Create templates

Linked entities of {{role.name}}

<mat-tab-group *ngIf="bSelectRoleEntities && role.linked != 'None'" animationDuration="0ms" dynamicHeight>
    <mat-tab *ngFor="let linked of role.linked" label="{{linked}}">
        <ng-container #entity [ngTemplateOutlet]="linked == 'Brands' ? Brands : Applications"
            [ngTemplateOutletContext]="{role: role}" ></ng-container>
    </mat-tab>
</mat-tab-group>

Brands template

<ng-template #Brands let-role="role">

{{role.id}} - {{role.name}}

{{brand.name}}

                            <input id="check-{{brand.name}}" type="checkbox" class="ds-input-check__input">
                            Assign to all countries

                            <input class="form-control inputField" type="text" placeholder="Filter countries" [(ngModel)]="brand.countryFilter" />

                        <input id="check-{{role.id}}-{{brand.name}}-{{country.country}}" type="checkbox" class="ds-input-check__input" [name]="role.id + brand.name" [(ngModel)]="country.isAssigned" (change)="assignRoleBrands($event,role.id,brand.id,country.id)" >
                        {{ country.country | translate }}

</ng-template>

EDIT

The checkbox in the template has a binding method linked to it. This is the code.

 assignRoleBrands(e: any, roleId: string, brandId: string, countryId: string) {
      var brand = this.applicationRoleDetail.roles.find(r => r.id == roleId).brands.find(b => b.id == brandId);
      //var brand = this.selectedRole.brands.find(b => b.id == brandId);
      brand.countries.find(c => c.id == countryId).isAssigned = e.currentTarget.checked;
      brand.assignedCountries = brand.countries.filter(c => c.isAssigned).length;

      this.selectedRole.entitiesSet = this.determineEntitiesSet(this.applicationRoleDetail.roles.find(r => r.id == roleId)); //this.selectedRole.brands?.some(b => b.assignedCountries > 0) && this.selectedRole.applications?.some(a => a.assignedApplications > 0);

      console.log(this.applicationRoleDetail);

      this.checkForApplicationChanges();
    }

Can someone help me with this?


来源: stackexchange

问:
<input> change color when it is correct
I have a problem with <input>. I want to check whether the user has filled it out or not.

By default, the input border will be gray. When the user did not fill in the fields it will have a red border otherwise green.

I added two CSS codes:

```<code>input:not(:focus):not(:placeholder-shown):invalid {
  border-color: red;
}

input:not(:focus):not(:placeholder-shown):valid {
  border-color: green;
}
</code>```

In <input> where I added required, the border is red, and here where I don't have required, the border is green. Can I change it somehow?

These are default fields that are not required.

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"/>

<form name="companies" method="post" class="default_ajax was-validated" enctype="multipart/form-data">

        <input type="text" placeholder="Place #1" id="company_name" name="company_name" class="enable_character_count form-control" required>
        Input 1

        <input type="text" placeholder="Place #2" id="company_service_name_1" name="company_service_name_1" class="enable_character_count form-control"/>
        Input 2

</form>```

ContentLicense: CC BY-SA 4.0

Title: <input> change color when it is correct

Body:
I have a problem with <input>. I want to check whether the user has filled it out or not.

By default, the input border will be gray. When the user did not fill in the fields it will have a red border otherwise green.

I added two CSS codes:

input:not(:focus):not(:placeholder-shown):invalid {
  border-color: red;
}

input:not(:focus):not(:placeholder-shown):valid {
  border-color: green;
}

In <input> where I added required, the border is red, and here where I don't have required, the border is green. Can I change it somehow?

These are default fields that are not required.

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"/>

<form name="companies" method="post" class="default_ajax was-validated" enctype="multipart/form-data">

        <input type="text" placeholder="Place #1" id="company_name" name="company_name" class="enable_character_count form-control" required>
        Input 1

        <input type="text" placeholder="Place #2" id="company_service_name_1" name="company_service_name_1" class="enable_character_count form-control"/>
        Input 2

</form>


问:
why mmap is faster than traditional file io
there are a bunch of blogs saying mmap is faster than traditional file io. One main reason is mmap reduce one copy between user and kernel space. This is where I quite don't understand.

Suppose I have a byte array char* bytes in user space. I want to write bytes to a file called some-file.txt.

traditional file write: copy bytes to kernel, then kernel write the bytes to file

mmap write: copy bytes to the memory location where mmap returns to you, then kernel flush the memory back to disk at some point in the future using paging mechanism.

Both are two copies.

The only advantage I'm sure is that mmap write reduce system calls since each write just manipulate memory byte array, but every file write involves one system call which has many context switches.

I've search many blogs but none explains much about this.


问:
Elasticsearch: get latest records for values in a column
I have an elasticsearch-kibana instance which I need to query to get required data records. The data should follow the following conditions:

Need to get ONLY the latest record for each value in column app_name.

The record should be from between time 15 minutes - 1 year.

If, for any value, there exists a record in last 15 minutes, that value and its corresponding latest record should be skipped.

I have tried using query DSL in Kibana discover page or GUI on Kibana lens pages but haven't been able to get the data that I require. Any help is appreciated.


问:
dynamically loading a dylib (Objective-c) in a swift project
I created a dylib in Objective-c with
myLib.h

```<code> #import <Foundation/Foundation.h>

@interface myLib : NSObject
{
    int value;

}
-(void)print;
-(void)setValue:(int)val;
-(int)getValue;
@end
</code>```

and myLib.m

```<code>#import "myLib.h"

@implementation myLib

-(void)print {
    NSLog(@"Printed from myLib");
}
-(void)setValue:(int)val {
     value = val;
}
-(int)getValue {
     return value;
}
@end
</code>```

and tried to load it dynamically on another command line app

```<code>@class myLib;
int main(int argc, const char * argv[]) {
    @autoreleasepool {

        void *handle = dlopen("libmyLib.dylib", RTLD_LAZY);

        //method - 1
        id t = [[NSClassFromString(@"myLib") alloc] init];
        myLib *libObj = [[t alloc] init];
        [libObj print];  // Error: Receiver type 'myLib' for instance message is a forward declaration

        //method - 2
        Class class = (__bridge Class)(dlsym(handle, "OBJC_CLASS_$_myLib"));
        if(class){
            myLib *libObj = [[class alloc] init];
            [libObj print];        // Error: Receiver type 'myLib' for instance message is a forward declaration
            [libObj setValue:5];  // Error: Receiver type 'myLib' for instance message is a forward declaration
            [libObj getValue]    // Error: Receiver type 'myLib' for instance message is a forward declaration
        }
        dlclose(handle);
    }
    return 0;
}
</code>```

got some errors, and also dlopen fails , can anyone figure out the problem with this code.

Can we use swift code instead of Objective-c for dylib, if so how can we call the functions inside the dylib.

Body:
I created a dylib in Objective-c with
myLib.h

 #import <Foundation/Foundation.h>

@interface myLib : NSObject
{
    int value;

}
-(void)print;
-(void)setValue:(int)val;
-(int)getValue;
@end

and myLib.m

#import "myLib.h"

@implementation myLib

-(void)print {
    NSLog(@"Printed from myLib");
}
-(void)setValue:(int)val {
     value = val;
}
-(int)getValue {
     return value;
}
@end

and tried to load it dynamically on another command line app

@class myLib;
int main(int argc, const char * argv[]) {
    @autoreleasepool {

        void *handle = dlopen("libmyLib.dylib", RTLD_LAZY);

        //method - 1
        id t = [[NSClassFromString(@"myLib") alloc] init];
        myLib *libObj = [[t alloc] init];
        [libObj print];  // Error: Receiver type 'myLib' for instance message is a forward declaration

        //method - 2
        Class class = (__bridge Class)(dlsym(handle, "OBJC_CLASS_$_myLib"));
        if(class){
            myLib *libObj = [[class alloc] init];
            [libObj print];        // Error: Receiver type 'myLib' for instance message is a forward declaration
            [libObj setValue:5];  // Error: Receiver type 'myLib' for instance message is a forward declaration
            [libObj getValue]    // Error: Receiver type 'myLib' for instance message is a forward declaration
        }
        dlclose(handle);
    }
    return 0;
}

got some errors, and also dlopen fails , can anyone figure out the problem with this code.

Can we use swift code instead of Objective-c for dylib, if so how can we call the functions inside the dylib.


问:
"TryParseValueFromString not implemented" even when it is
Below is the empty component I am working on:

DatePicker.razor

```<code>@typeparam TValue
@inherits InputBase<TValue>

<h3>DatePicker</h3>
</code>```

DatePicker.razor.cs

```<code>using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;

namespace Accounting.Web.Components.Forms
{
    public partial class DatePicker<TValue> : InputBase<TValue>
    {

        protected override bool TryParseValueFromString(string? value, out TValue result, out string? validationErrorMessage)
        {
            if (BindConverter.TryConvertTo<TValue>(value, null, out result))
            {
                validationErrorMessage = "";
                return true;
            }
            else
            {
                validationErrorMessage = "Err : Select value";
                return false;
            }
        }
    }
}
</code>```

Usage in Index.razor

```<code><DatePicker Value="2023-01-01"></DatePicker>
</code>```

When compiling the above code produces the followng error?

```<code>Error : 'DatePicker<TValue>' does not implement inherited abstract member 'InputBase<TValue>.TryParseValueFromString(string?, out TValue, out string?)'
</code>```

Which is confusing because TryParseValueFromString override is asyou can see present in DatePicker.razor.cs.

Where could I be going wrong?

Body:
Below is the empty component I am working on:

DatePicker.razor

@typeparam TValue
@inherits InputBase<TValue>

DatePicker

DatePicker.razor.cs

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;

namespace Accounting.Web.Components.Forms
{
    public partial class DatePicker<TValue> : InputBase<TValue>
    {

        protected override bool TryParseValueFromString(string? value, out TValue result, out string? validationErrorMessage)
        {
            if (BindConverter.TryConvertTo<TValue>(value, null, out result))
            {
                validationErrorMessage = "";
                return true;
            }
            else
            {
                validationErrorMessage = "Err : Select value";
                return false;
            }
        }
    }
}

Usage in Index.razor

<DatePicker Value="2023-01-01"></DatePicker>

When compiling the above code produces the followng error?

Error : 'DatePicker<TValue>' does not implement inherited abstract member 'InputBase<TValue>.TryParseValueFromString(string?, out TValue, out string?)'

Which is confusing because TryParseValueFromString override is asyou can see present in DatePicker.razor.cs.

Where could I be going wrong?


问:
React Infinite Loop Causes State to Freeze
I have a react amplify project for which I've just added Cognito. When not logged into the site, (i.e. in guest mode) I am able to call the API, however when I am logged in it only calls once on page load. When I try to trigger it manually it makes the API call, then everything freezes and the page goes unresponsive.

useEffect(() => {
        const getArticlesOnceUE = async() => {
            console.log("Calling the API")
            var arts = await atlasAPI.getCountryNews(selectedCountry, null) // This line runs and cloudwatch indicates the lambda finishes.
            console.log("Getting Data from Response") // This line doesn't run
            var articleData = arts.data
            console.log("Sorting Articles")
            const sorted_arts_r = articleData.sort((a,b) => b.datetime-a.datetime)
            const seper_arts = seperateArticles(sorted_arts, 30)
            console.log(seper_arts)
            setArticles(seper_arts)
        }

        getArticlesOnceUE()
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [selectedCountry]);
```
<p>The code above is where the code fails when <code>selectedCountry</code> is updated the comments show where the issue is. The code below is the API code that is called.</p>
<pre class="lang-js prettyprint-override"><code>async function GetCountryNews(country) {
        try {
            const apiName = "AtlasAPI";
            const path = "/get-country-news/";

            const data = {
                body: {
                    "country": country
                }
            };

            console.log("Before POST") // This runs
            const res = await API.post(apiName, path, data);
            console.log("After POST") // This does not run

            return res
        } catch(error) {
            console.log("Error calling API: ", error);
            return null;
        }
    }
</code>```

In cloudwatch every print statement up to the return runs, but the data never comes back to the react app. Is this a common issue? What are some potential solutions.

EDIT:

Apparently it's not just the API. If I call anything that sets state the app, or at least react, seems to crash.

EDIT 2:

I changed the name to reflect what I've learned. An infinite re-render that react didn't catch caused the app to freeze continuously.

Body:
I have a react amplify project for which I've just added Cognito. When not logged into the site, (i.e. in guest mode) I am able to call the API, however when I am logged in it only calls once on page load. When I try to trigger it manually it makes the API call, then everything freezes and the page goes unresponsive.

useEffect(() => {
        const getArticlesOnceUE = async() => {
            console.log("Calling the API")
            var arts = await atlasAPI.getCountryNews(selectedCountry, null) // This line runs and cloudwatch indicates the lambda finishes.
            console.log("Getting Data from Response") // This line doesn't run
            var articleData = arts.data
            console.log("Sorting Articles")
            const sorted_arts_r = articleData.sort((a,b) => b.datetime-a.datetime)
            const seper_arts = seperateArticles(sorted_arts, 30)
            console.log(seper_arts)
            setArticles(seper_arts)
        }

        getArticlesOnceUE()
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [selectedCountry]);

The code above is where the code fails when selectedCountry is updated the comments show where the issue is. The code below is the API code that is called.

async function GetCountryNews(country) {
        try {
            const apiName = "AtlasAPI";
            const path = "/get-country-news/";

            const data = {
                body: {
                    "country": country
                }
            };

            console.log("Before POST") // This runs
            const res = await API.post(apiName, path, data);
            console.log("After POST") // This does not run

            return res
        } catch(error) {
            console.log("Error calling API: ", error);
            return null;
        }
    }

In cloudwatch every print statement up to the return runs, but the data never comes back to the react app. Is this a common issue? What are some potential solutions.

EDIT:

Apparently it's not just the API. If I call anything that sets state the app, or at least react, seems to crash.

EDIT 2:

I changed the name to reflect what I've learned. An infinite re-render that react didn't catch caused the app to freeze continuously.


问:
Why need '//' in windows with git-bash to access container
I am using git-bash in windows laptop, and I want to execute some CLI in POD.

But I got some error like:

```<code>$ kubectl -n bow exec $POD -- ls /tmp
ls: cannot access 'C:/Users/xxx/AppData/Local/Temp': No such file or directory
command terminated with exit code 2
</code>```

But if I use '//' in the path, it works:

```<code>$ kubectl -n bow exec $POD -- ls //tmp
busybox.tar.gz
</code>```

Can anyone know the reason and how to avoid the error?

Body:
I am using git-bash in windows laptop, and I want to execute some CLI in POD.

But I got some error like:

$ kubectl -n bow exec $POD -- ls /tmp
ls: cannot access 'C:/Users/xxx/AppData/Local/Temp': No such file or directory
command terminated with exit code 2

But if I use '//' in the path, it works:

$ kubectl -n bow exec $POD -- ls //tmp
busybox.tar.gz

Can anyone know the reason and how to avoid the error?


问:
How to close npm local tunnel port?
I had opened my localhost to the internet for a webhook using npm local tunnel and done my job. Now I'm exposing my port unnecessarily, I could still access my port using the URL. Now I need to close the tunnel. What should I do?

Long time ago, I shut down node service and the port closed. But now I can't find npm or node in my service.
I need a simple command to close the port i.e. unexpose my port.

Commands I used:

```<code>npm install localtunnel
lt --port=8080
</code>```

Title: How to close npm local tunnel port?

Body:
I had opened my localhost to the internet for a webhook using npm local tunnel and done my job. Now I'm exposing my port unnecessarily, I could still access my port using the URL. Now I need to close the tunnel. What should I do?

Long time ago, I shut down node service and the port closed. But now I can't find npm or node in my service.
I need a simple command to close the port i.e. unexpose my port.

Commands I used:

npm install localtunnel
lt --port=8080


问:
Docker build issue with conda (miniconda)
First, a bit of context : I'm curently trying to work on MineRL, and to put this in a docker. I'm using WSL 2 on my Windows machine to make docker work correctly. There is the github where i found the dockerfile I used : GitHub.

When running the dockerfile with

docker build - < Dockerfile
```
<p>Everything works perfectly until i reach step <strong>[9/18]</strong>, Which is about <strong>conda</strong>.
Here is the error i had :</p>
```=> ERROR [ 9/18] RUN /home/user/miniconda/bin/conda install conda-build  && /home/user/miniconda/bin/conda create -y --name py37 python=3.7.3    0.8s
------
 > [ 9/18] RUN /home/user/miniconda/bin/conda install conda-build  && /home/user/miniconda/bin/conda create -y --name py37 python=3.7.3  && /home/user/miniconda/bin/conda clean -ya:
#12 0.739 /bin/sh: 1: /home/user/miniconda/bin/conda: not found
------
executor failed running [/bin/sh -c /home/user/miniconda/bin/conda install conda-build  && /home/user/miniconda/bin/conda create -y --name py37 python=3.7.3  && /home/user/miniconda/bin/conda clean -ya]: exit code: 127
```
<p>I found a solution on this stack overflow post but it couldn't resolve my problems.</p>
<p>Then i am asking anyone who is used to docker, conda and maybe MineRL some help on this please!</p>
<p>EDIT : Thanks to @lote and @DobbyTheElf, I mannaged to <strong>modify some part of the dockerfil</strong>e to correspond to <strong>my configuration</strong>, but it still cannot find the conda file. Here is my new Dockerfile.</p>
<p>To be sure about what @DobbyTheElf told me, I ran this command to find the path to the folder "<strong>miniconda3</strong>" and the result is underneath the request :</p>
```bloster@DESKTOP-UATBDIM:~/miniconda3/bin$ find / -name miniconda3
/home/bloster/miniconda3
```

So i edited again my code to what it is now (by the time my last git commit is called "first push").
The error remains the same for now...

Body:
First, a bit of context : I'm curently trying to work on MineRL, and to put this in a docker. I'm using WSL 2 on my Windows machine to make docker work correctly. There is the github where i found the dockerfile I used : GitHub.

When running the dockerfile with

docker build - < Dockerfile

Everything works perfectly until i reach step [9/18], Which is about conda.
Here is the error i had :

=> ERROR [ 9/18] RUN /home/user/miniconda/bin/conda install conda-build  && /home/user/miniconda/bin/conda create -y --name py37 python=3.7.3    0.8s
------
 > [ 9/18] RUN /home/user/miniconda/bin/conda install conda-build  && /home/user/miniconda/bin/conda create -y --name py37 python=3.7.3  && /home/user/miniconda/bin/conda clean -ya:
#12 0.739 /bin/sh: 1: /home/user/miniconda/bin/conda: not found
------
executor failed running [/bin/sh -c /home/user/miniconda/bin/conda install conda-build  && /home/user/miniconda/bin/conda create -y --name py37 python=3.7.3  && /home/user/miniconda/bin/conda clean -ya]: exit code: 127

I found a solution on this stack overflow post but it couldn't resolve my problems.

Then i am asking anyone who is used to docker, conda and maybe MineRL some help on this please!

EDIT : Thanks to @lote and @DobbyTheElf, I mannaged to modify some part of the dockerfile to correspond to my configuration, but it still cannot find the conda file. Here is my new Dockerfile.

To be sure about what @DobbyTheElf told me, I ran this command to find the path to the folder "miniconda3" and the result is underneath the request :

bloster@DESKTOP-UATBDIM:~/miniconda3/bin$ find / -name miniconda3
/home/bloster/miniconda3

So i edited again my code to what it is now (by the time my last git commit is called "first push").
The error remains the same for now...


问:
shell script to set display settings on linux server
Dear Linux masters....

My shell script to set display settings on linux server isnt working as expected! need your expert advise

#! /bin/bash xauth list > /home/usr1/utilities/xauthlist.txt #generates the list of display settings in xauth file  display=$(tail -n 1 /home/usr1/utilities/xauthlist.txt) #reads & stores the last line of the xauthlist.txt sudo -iu admin1 xauth add $display #setting the display xterm #this command does not throw up any visual output

My mobaxterm gives the following error

MoTTY X11 proxy: Unsupported authorisation protocol xterm: Xt error: Can't open display: 10.161.28.189:14.0

On the contrary if I do the same thing manually (without the script), all works fine.


问:
how to fix this material top bar issue in react native: 'boolean android.graphics.Path.isEmpty()' on a null object reference?
```<code><Tab.Navigator
            tabBar={props=><CustomBookingTopTab{...props}/>}>

export default function CustomBookingTopTab({
    state,
    descriptors,
    navigation,
    position,
}) {
    return (
        <View>
            <ScrollView contentContainerStyle={{ flexDirection: 'row' }} style={{ flexDirection: 'row',paddingHorizontal:10 }} horizontal showsHorizontalScrollIndicator={false}>
                {state.routes.map((route, index) => {
                    const { options } = descriptors[route.key];
                    const label = options.tabBarLabel;
                    const isFocused = state.index === index;

                    const onPress = () => {
                        const event = navigation.emit({
                            type: 'tabPress',
                            target: route.key,
                            canPreventDefault: true,
                        });

                        if (!isFocused && !event.defaultPrevented) {
                            // The `merge: true` option makes sure that the params inside the tab screen are preserved
                            navigation.navigate({ name: route.name, merge: true });
                        }
                    };

                    const onLongPress = () => {
                        navigation.emit({
                            type: 'tabLongPress',
                            target: route.key,
                        });
                    };

                    const inputRange = state.routes.map((_, i) => i);
                    const opacity = position.interpolate({
                        inputRange,
                        outputRange: inputRange.map(i => (i === index ? 1 : 0)),
                    });

                    return (
                        <View key={parseInt(index)} style={{ paddingBottom: 10, borderBottomWidth: isFocused ? 2 : 0,borderBottomColor:isFocused?"#FD6D56":null,alignContent:'center' }}>
                            <TouchableOpacity
                                accessibilityRole="button"
                                accessibilityState={isFocused ? { selected: true } : {}}
                                accessibilityLabel={options.tabBarAccessibilityLabel}
                                testID={options.tabBarTestID}
                                onPress={onPress}
                                onLongPress={onLongPress}
                                style={{

                                   backgroundColor:isFocused?"#FD6D56":null,
                                     alignItems: 'center',

                                    paddingVertical:10,
                                    borderTopLeftRadius:isFocused?6:null,
                                    borderTopRightRadius:isFocused?6:null,
                                    borderBottomLeftRadius:isFocused?6:null,
                                    borderBottomRightRadius:isFocused?6:null,
                                     paddingHorizontal: 13,
                                }}>
                                {/* <LinearGradient
                                    start={{ x: 0, y: 0 }}
                                    colors={
                                        isFocused ? [COLORS.mainBackground, COLORS.mainBackground]
                                            :
                                            [COLORS.mainBackground, COLORS.mainBackground]
                                    }
                                    style={styles.linearGradient}> */}
                                    <Text
                                        style={{
                                            color: isFocused ? "#ffffff" : "#555555",
                                            fontSize: 14,
                                            fontFamily: FONTS.PoppinsMedium500
                                        }}>
                                       {label}
                                    </Text>
                                {/* </LinearGradient> */}
                            </TouchableOpacity>
                        </View>
                    );
                })}

            </ScrollView>
            {/* <View style={{
                borderBottomColor:"#FD6D56",
                borderBottomWidth: 1,
                paddingBottom: 0
            }} /> */}

        </View>
    );
}

const styles = StyleSheet.create({
    linearGradient: {
        alignItems: 'center',
        paddingTop: 20,
        paddingHorizontal: 13,
    },
});
</code>```

enter image description here

I want to integrate a custom top bar and it is working fine on ios but I am getting these errors in android kindly help

Body:
<Tab.Navigator
            tabBar={props=><CustomBookingTopTab{...props}/>}>

export default function CustomBookingTopTab({
    state,
    descriptors,
    navigation,
    position,
}) {
    return (
        <View>
            <ScrollView contentContainerStyle={{ flexDirection: 'row' }} style={{ flexDirection: 'row',paddingHorizontal:10 }} horizontal showsHorizontalScrollIndicator={false}>
                {state.routes.map((route, index) => {
                    const { options } = descriptors[route.key];
                    const label = options.tabBarLabel;
                    const isFocused = state.index === index;

                    const onPress = () => {
                        const event = navigation.emit({
                            type: 'tabPress',
                            target: route.key,
                            canPreventDefault: true,
                        });

                        if (!isFocused && !event.defaultPrevented) {
                            // The `merge: true` option makes sure that the params inside the tab screen are preserved
                            navigation.navigate({ name: route.name, merge: true });
                        }
                    };

                    const onLongPress = () => {
                        navigation.emit({
                            type: 'tabLongPress',
                            target: route.key,
                        });
                    };

                    const inputRange = state.routes.map((_, i) => i);
                    const opacity = position.interpolate({
                        inputRange,
                        outputRange: inputRange.map(i => (i === index ? 1 : 0)),
                    });

                    return (
                        <View key={parseInt(index)} style={{ paddingBottom: 10, borderBottomWidth: isFocused ? 2 : 0,borderBottomColor:isFocused?"#FD6D56":null,alignContent:'center' }}>
                            <TouchableOpacity
                                accessibilityRole="button"
                                accessibilityState={isFocused ? { selected: true } : {}}
                                accessibilityLabel={options.tabBarAccessibilityLabel}
                                testID={options.tabBarTestID}
                                onPress={onPress}
                                onLongPress={onLongPress}
                                style={{

                                   backgroundColor:isFocused?"#FD6D56":null,
                                     alignItems: 'center',

                                    paddingVertical:10,
                                    borderTopLeftRadius:isFocused?6:null,
                                    borderTopRightRadius:isFocused?6:null,
                                    borderBottomLeftRadius:isFocused?6:null,
                                    borderBottomRightRadius:isFocused?6:null,
                                     paddingHorizontal: 13,
                                }}>
                                {/* <LinearGradient
                                    start={{ x: 0, y: 0 }}
                                    colors={
                                        isFocused ? [COLORS.mainBackground, COLORS.mainBackground]
                                            :
                                            [COLORS.mainBackground, COLORS.mainBackground]
                                    }
                                    style={styles.linearGradient}> */}
                                    <Text
                                        style={{
                                            color: isFocused ? "#ffffff" : "#555555",
                                            fontSize: 14,
                                            fontFamily: FONTS.PoppinsMedium500
                                        }}>
                                       {label}
                                    </Text>
                                {/* </LinearGradient> */}
                            </TouchableOpacity>
                        </View>
                    );
                })}

            </ScrollView>
            {/* <View style={{
                borderBottomColor:"#FD6D56",
                borderBottomWidth: 1,
                paddingBottom: 0
            }} /> */}

        </View>
    );
}

const styles = StyleSheet.create({
    linearGradient: {
        alignItems: 'center',
        paddingTop: 20,
        paddingHorizontal: 13,
    },
});

enter image description here

I want to integrate a custom top bar and it is working fine on ios but I am getting these errors in android kindly help


问:
can´t PUT with node.js
I keep getting a Cannot POST /discos/edit/ message, with a 404 error at my terminal.
I can´t seem to find the correct path, as i believe it may be a URL error somewhere i can´t find.

Thanks for your help.

My code:

```<code>`router.get(`/discos/edit/:id`, editRecord)`

discosCtrl.editRecord = async (req, res) => {
const disco = await DiscoSchema.findById(req.params.id).lean()
//console.log(disco)
res.render(`discos/edit-record`, {disco})
}`
</code>```

This get method works fine.

Then, this is my PUT method, where i can´t post the info i´ve received from my previous GET request.

```<code>`router.put(`/discos/edit/:id`, updateRecord)`

`discosCtrl.updateRecord =  (req, res) => {
console.log(req.body)
}`
</code>```

My Html line, where i override the POST method:

```<code><form action="/discos/edit/{{disco.id}}?_method=PUT" method="POST">
<input type="hidden" name="_method" value="PUT">
</code>```

`
Thanks for your help.

I can´t seem to find my mistake. I´m following some tutorial using the same code but they´re succeeding while i´m just getting the same 404 error.

Title: can´t PUT with node.js

Body:
I keep getting a Cannot POST /discos/edit/ message, with a 404 error at my terminal.
I can´t seem to find the correct path, as i believe it may be a URL error somewhere i can´t find.

Thanks for your help.

My code:

`router.get(`/discos/edit/:id`, editRecord)`

discosCtrl.editRecord = async (req, res) => {
const disco = await DiscoSchema.findById(req.params.id).lean()
//console.log(disco)
res.render(`discos/edit-record`, {disco})
}`

This get method works fine.

Then, this is my PUT method, where i can´t post the info i´ve received from my previous GET request.

`router.put(`/discos/edit/:id`, updateRecord)`

`discosCtrl.updateRecord =  (req, res) => {
console.log(req.body)
}`

My Html line, where i override the POST method:

<form action="/discos/edit/{{disco.id}}?_method=PUT" method="POST">
<input type="hidden" name="_method" value="PUT">

`
Thanks for your help.

I can´t seem to find my mistake. I´m following some tutorial using the same code but they´re succeeding while i´m just getting the same 404 error.


问:
Diff. between .write (parser-inserted method) and appendChild method to head. (Difference on the basis of parser-inserted script)
I am loading recaptcha in a module and both are in iframe. I need to insert an external script so that anyone can include that module by just including the script in their application. So when adding the script in the module through write method ie. parser-inserted script, the recaptcha is working fine, but when I use appendChild method, the recaptcha is breaking.

Working Script

```<code>const iframeScript = `\<script src="${\__API_\_}/checking.js" async defer\>\</script\>`;
document.write(iframeScript); document.close();
</code>```

Failing Script

```<code>const iframeScript = iframeDoc.createElement('script');
document.src = __API__ + '/checking.js';
document.setAttribute('async', true);
document.setAttribute('defer', true);
document.head.appendChild(iframeScript);
</code>```

Body:
I am loading recaptcha in a module and both are in iframe. I need to insert an external script so that anyone can include that module by just including the script in their application. So when adding the script in the module through write method ie. parser-inserted script, the recaptcha is working fine, but when I use appendChild method, the recaptcha is breaking.

Working Script

const iframeScript = `\<script src="${\__API_\_}/checking.js" async defer\>\</script\>`;
document.write(iframeScript); document.close();

Failing Script

const iframeScript = iframeDoc.createElement('script');
document.src = __API__ + '/checking.js';
document.setAttribute('async', true);
document.setAttribute('defer', true);
document.head.appendChild(iframeScript);


问:
Why does my OSMDROID MapView slowly move and interrupt keypresses?
I am creating a React Native application, with Native Base and I use a map. As I would Like to have it usable on both Android and IOS I decided to use the package react-native-maps-osmdroid. Currently I am trying to make it work on Android. I am successful in showing the map, moving the map and adding markers to the map, but I see that the map is slowly moving northwest without me understanding why. To save a marker with the button I have added on the bottom of the map, the map either has to be tapped so it stands still or one has to continually tap the save-button until one triggers the save function between map-movements. Below is the map code.

```<code>import React, {useEffect, useState} from 'react';
import {StyleSheet, View} from 'react-native';
import {Button, Box, Text} from 'native-base';
import MapView, {
  PROVIDER_OSMDROID,
  Marker,
  Polyline,
} from 'react-native-maps-osmdroid';
import {MarkerType} from '../helpers';
import CustomPin from '../../custom/CustomPin'; //svg
import CustomPosition from '../../custom/CustomPosition'; //svg
import {requestLocation} from '../../helpers/LocationService';

const style = StyleSheet.create({
  map: {
    ...StyleSheet.absoluteFillObject,
  },
  button: {
    padding: 10,
    bottom: 10,
    marginLeft: 2,
    marginRight: 2,
  },
});

/**
 * Route parameters it might expect
 * markers: List of lat/long positions to set as markers on the map.
 * showControls: Whether the add / delete markers controls should be visible
 * selfPosition:
 */

export default TripMap = ({navigation, route}) => {
  const [markers, addMarkers] = useState(
    route.params.markers ? [...route.params.markers] : [],
  ); //Current marker on the map. Will be populated through props when opening the map from a trip screen. Either through logging or adding a location. Will also be filled by this screen's add marker button.
  const [markerControl, setMarkerControl] = useState(
    route.params.showControls ? true : false,
  ); //Should the add marker/delete markers be shown
  const positionSelf = route.params.selfPosition
    ? route.params.selfPosition
    : null;
  const [coordinatesArray, setCoordinatesArray] = useState([]);
  const [selectedMarker, setSelectedMarker] = useState(null);
  /*
        Initial region to show on the map.
        latitude and longitude are the values for the center of the map on the screen. Delta is how much around that point is showing, aka controls zoom. Lower the values to get better zoom.
    */

  const [myRegion, setRegion] = useState(
    route.params.position
      ? {
          latitude: route.params.position.latitude,
          longitude: route.params.position.longitude,
          latitudeDelta: 0.05,
          longitudeDelta: 0.09,
        }
      : {
          latitude: route.params.markers
            ? route.params.markers[0].latlng.latitude
            : 59.91355589226327,
          longitude: route.params.markers
            ? route.params.markers[0].latlng.longitude
            : 10.751138495614148,
          latitudeDelta: 0.05,
          longitudeDelta: 0.09,
        },
  );

  useEffect(() => {
    if (route.params.position) return;
    getLocation();
    if (route.params.markers) {
      let tempArray = [];
      route.params.markers.forEach(marker => {
        tempArray.push(marker.latlng);
      });
      setCoordinatesArray(tempArray);
    }
  }, []);

  const regionChange = async function (region) {
    if (region !== null || region !== undefined)
      region.latitudeDelta = Math.min(
        region.latitudeDelta,
        85 - Math.abs(region.latitude),
      );
    if (region.latitude >= 85) {
      region.latitude = -85 + (region.latitude - 85);
    } else if (region.latitude <= -85) {
      region.latitude = 85 + (region.latitude + 85);
    }
    region.longitudeDelta = Math.min(
      region.longitudeDelta,
      180 - Math.abs(region.longitude),
    );
    if (region.longitude >= 180) {
      region.longitude = -180 + (region.longitude - 180);
    } else if (region.longitude <= -180) {
      region.longitude = 180 + (region.longitude + 180);
    }
    setRegion(region);
  };

  const addMarker = async (lat, lng) => {
    if (route.params.singleMarker === true) {
      if (markers.length > 0) {
        replaceMarker(lat, lng);
        return;
      }
    }
    let newMarker = {
      title: 'Anchorage marker',
      description: 'New anchorage marker',
      latlng: {
        latitude: lat,
        longitude: lng,
      },
      draggable: true,
      type: MarkerType.POSITION,
    };
    addMarkers(oldArray => [...oldArray, newMarker]);
  };

  const replaceMarker = async (lat, lng) => {
    let newMarker = {
      title: 'Anchorage marker',
      description: 'New anchorage marker',
      latlng: {
        latitude: lat,
        longitude: lng,
      },
      draggable: true,
      type: MarkerType.POSITION,
    };
    addMarkers([newMarker]);
  };

  const saveMarker = async function () {
    const returnScreen = route.params.returnScreen
      ? route.params.returnScreen
      : 'LandingPage';
    navigation.navigate(returnScreen, {
      ...route.params,
      location: markers[0].latlng,
      targetLocation: route.params.targetLocation
        ? route.params.targetLocation
        : null,
    });
  };

  const MarkerControlView = function () {
    return (
      <Box justifyContent="flex-end" style={{flexDirection: 'row'}}>
        {route.params.singleMarker === true && markers.length > 0 && (
          <Button
            mt="3"
            style={style.button}
            onPress={saveMarker}
            disabled={markers.length === 0}>
            Lagre pin
          </Button>
        )}
        {markers.length === 0 && (
          <Button mt="2" style={style.button} onPress={addMarker}>
            Legg til pin
          </Button>
        )}
      </Box>
    );
  };

  const DisplayControls = function (props) {
    if (props.showControls) {
      return <MarkerControlView />;
    }
    return <Box></Box>;
  };

  const getLocation = function () {
    requestLocation(setRegion);
  };

  return (
    <Box style={style.map} justifyContent="center">
      <MapView
        provider={PROVIDER_OSMDROID}
        style={style.map}
        minZoomLevel={3}
        initialRegion={myRegion}
        region={myRegion}
        onRegionChangeComplete={regionChange}
        onPress={mapEvent => {
          addMarker(
            mapEvent.nativeEvent.coordinate.latitude,
            mapEvent.nativeEvent.coordinate.longitude,
          );
        }}>
        <Polyline
          coordinates={coordinatesArray}
          strokeColor="#000"
          strokeWidth={4}></Polyline>
        {markers.map((marker, index) => (
          <Marker
            key={Math.random()}
            rea
            coordinate={marker.latlng}
            title={marker.title}
            description={marker.description}
            draggable={marker.draggable}
            onDragEnd={e => (marker.latlng = e.nativeEvent.coordinate)}
            onPress={() => setSelectedMarker(marker)}
            pinColor={'red'}>
            <View style={{width: 50, height: 50}}>
              <CustomPin width="50px" height="50px" color={marker.type.color} />
            </View>
          </Marker>
        ))}
        {positionSelf !== null && (
          <Marker key={positionSelf.latitude} coordinate={positionSelf}>
            <View style={{width: 50, height: 50}}>
              <CustomPosition />
            </View>
          </Marker>
        )}
      </MapView>
      <Box alignItems="center" justifyContent="flex-end" style={style.map}>
        <DisplayControls showControls={markerControl} />
      </Box>
      {selectedMarker && (
        <Box alignItems="center" justifyContent="flex-end" style={style.map}>
          <Text>{selectedMarker.title}</Text>
        </Box>
      )}
    </Box>
  );
};

</code>```

I can clearly see the map move even without having touched it once, but it moves slowly.
The route parameter is versions of this: route:  {"key": "TripMap-Zl5rO2SgH8kyJjYhWQumK", "name": "TripMap", "params": {"returnScreen": "AnchorageTabView", "showControls": true, "singleMarker": true}, "path": undefined}.

Body:
I am creating a React Native application, with Native Base and I use a map. As I would Like to have it usable on both Android and IOS I decided to use the package react-native-maps-osmdroid. Currently I am trying to make it work on Android. I am successful in showing the map, moving the map and adding markers to the map, but I see that the map is slowly moving northwest without me understanding why. To save a marker with the button I have added on the bottom of the map, the map either has to be tapped so it stands still or one has to continually tap the save-button until one triggers the save function between map-movements. Below is the map code.

import React, {useEffect, useState} from 'react';
import {StyleSheet, View} from 'react-native';
import {Button, Box, Text} from 'native-base';
import MapView, {
  PROVIDER_OSMDROID,
  Marker,
  Polyline,
} from 'react-native-maps-osmdroid';
import {MarkerType} from '../helpers';
import CustomPin from '../../custom/CustomPin'; //svg
import CustomPosition from '../../custom/CustomPosition'; //svg
import {requestLocation} from '../../helpers/LocationService';

const style = StyleSheet.create({
  map: {
    ...StyleSheet.absoluteFillObject,
  },
  button: {
    padding: 10,
    bottom: 10,
    marginLeft: 2,
    marginRight: 2,
  },
});

/**
 * Route parameters it might expect
 * markers: List of lat/long positions to set as markers on the map.
 * showControls: Whether the add / delete markers controls should be visible
 * selfPosition:
 */

export default TripMap = ({navigation, route}) => {
  const [markers, addMarkers] = useState(
    route.params.markers ? [...route.params.markers] : [],
  ); //Current marker on the map. Will be populated through props when opening the map from a trip screen. Either through logging or adding a location. Will also be filled by this screen's add marker button.
  const [markerControl, setMarkerControl] = useState(
    route.params.showControls ? true : false,
  ); //Should the add marker/delete markers be shown
  const positionSelf = route.params.selfPosition
    ? route.params.selfPosition
    : null;
  const [coordinatesArray, setCoordinatesArray] = useState([]);
  const [selectedMarker, setSelectedMarker] = useState(null);
  /*
        Initial region to show on the map.
        latitude and longitude are the values for the center of the map on the screen. Delta is how much around that point is showing, aka controls zoom. Lower the values to get better zoom.
    */

  const [myRegion, setRegion] = useState(
    route.params.position
      ? {
          latitude: route.params.position.latitude,
          longitude: route.params.position.longitude,
          latitudeDelta: 0.05,
          longitudeDelta: 0.09,
        }
      : {
          latitude: route.params.markers
            ? route.params.markers[0].latlng.latitude
            : 59.91355589226327,
          longitude: route.params.markers
            ? route.params.markers[0].latlng.longitude
            : 10.751138495614148,
          latitudeDelta: 0.05,
          longitudeDelta: 0.09,
        },
  );

  useEffect(() => {
    if (route.params.position) return;
    getLocation();
    if (route.params.markers) {
      let tempArray = [];
      route.params.markers.forEach(marker => {
        tempArray.push(marker.latlng);
      });
      setCoordinatesArray(tempArray);
    }
  }, []);

  const regionChange = async function (region) {
    if (region !== null || region !== undefined)
      region.latitudeDelta = Math.min(
        region.latitudeDelta,
        85 - Math.abs(region.latitude),
      );
    if (region.latitude >= 85) {
      region.latitude = -85 + (region.latitude - 85);
    } else if (region.latitude <= -85) {
      region.latitude = 85 + (region.latitude + 85);
    }
    region.longitudeDelta = Math.min(
      region.longitudeDelta,
      180 - Math.abs(region.longitude),
    );
    if (region.longitude >= 180) {
      region.longitude = -180 + (region.longitude - 180);
    } else if (region.longitude <= -180) {
      region.longitude = 180 + (region.longitude + 180);
    }
    setRegion(region);
  };

  const addMarker = async (lat, lng) => {
    if (route.params.singleMarker === true) {
      if (markers.length > 0) {
        replaceMarker(lat, lng);
        return;
      }
    }
    let newMarker = {
      title: 'Anchorage marker',
      description: 'New anchorage marker',
      latlng: {
        latitude: lat,
        longitude: lng,
      },
      draggable: true,
      type: MarkerType.POSITION,
    };
    addMarkers(oldArray => [...oldArray, newMarker]);
  };

  const replaceMarker = async (lat, lng) => {
    let newMarker = {
      title: 'Anchorage marker',
      description: 'New anchorage marker',
      latlng: {
        latitude: lat,
        longitude: lng,
      },
      draggable: true,
      type: MarkerType.POSITION,
    };
    addMarkers([newMarker]);
  };

  const saveMarker = async function () {
    const returnScreen = route.params.returnScreen
      ? route.params.returnScreen
      : 'LandingPage';
    navigation.navigate(returnScreen, {
      ...route.params,
      location: markers[0].latlng,
      targetLocation: route.params.targetLocation
        ? route.params.targetLocation
        : null,
    });
  };

  const MarkerControlView = function () {
    return (
      <Box justifyContent="flex-end" style={{flexDirection: 'row'}}>
        {route.params.singleMarker === true && markers.length > 0 && (
          <Button
            mt="3"
            style={style.button}
            onPress={saveMarker}
            disabled={markers.length === 0}>
            Lagre pin
          </Button>
        )}
        {markers.length === 0 && (
          <Button mt="2" style={style.button} onPress={addMarker}>
            Legg til pin
          </Button>
        )}
      </Box>
    );
  };

  const DisplayControls = function (props) {
    if (props.showControls) {
      return <MarkerControlView />;
    }
    return <Box></Box>;
  };

  const getLocation = function () {
    requestLocation(setRegion);
  };

  return (
    <Box style={style.map} justifyContent="center">
      <MapView
        provider={PROVIDER_OSMDROID}
        style={style.map}
        minZoomLevel={3}
        initialRegion={myRegion}
        region={myRegion}
        onRegionChangeComplete={regionChange}
        onPress={mapEvent => {
          addMarker(
            mapEvent.nativeEvent.coordinate.latitude,
            mapEvent.nativeEvent.coordinate.longitude,
          );
        }}>
        <Polyline
          coordinates={coordinatesArray}
          strokeColor="#000"
          strokeWidth={4}></Polyline>
        {markers.map((marker, index) => (
          <Marker
            key={Math.random()}
            rea
            coordinate={marker.latlng}
            title={marker.title}
            description={marker.description}
            draggable={marker.draggable}
            onDragEnd={e => (marker.latlng = e.nativeEvent.coordinate)}
            onPress={() => setSelectedMarker(marker)}
            pinColor={'red'}>
            <View style={{width: 50, height: 50}}>
              <CustomPin width="50px" height="50px" color={marker.type.color} />
            </View>
          </Marker>
        ))}
        {positionSelf !== null && (
          <Marker key={positionSelf.latitude} coordinate={positionSelf}>
            <View style={{width: 50, height: 50}}>
              <CustomPosition />
            </View>
          </Marker>
        )}
      </MapView>
      <Box alignItems="center" justifyContent="flex-end" style={style.map}>
        <DisplayControls showControls={markerControl} />
      </Box>
      {selectedMarker && (
        <Box alignItems="center" justifyContent="flex-end" style={style.map}>
          <Text>{selectedMarker.title}</Text>
        </Box>
      )}
    </Box>
  );
};

I can clearly see the map move even without having touched it once, but it moves slowly.
The route parameter is versions of this: route:  {"key": "TripMap-Zl5rO2SgH8kyJjYhWQumK", "name": "TripMap", "params": {"returnScreen": "AnchorageTabView", "showControls": true, "singleMarker": true}, "path": undefined}.


问:
How to consolidate vue-tsc generated types in single file?
I have Vue 3 project with a lot of typings there (every component has its own typed props etc). Before build I run this command: vue-tsc --skipLibCheck --declaration --emitDeclarationOnly and the problem is that creates .d.ts and .d.ts.map for every single .vue/.ts file in my project and it looks like this (consider dozens of components):

```<code>components
    componentA.vue
    componentA.vue.d.ts
    componentA.vue.d.ts.map
    componentB.vue
    componentB.vue.d.ts
    componentB.vue.d.ts.map

main.ts
main.d.ts
main.d.ts.map
</code>```

It feels kinda wrong, but I couldn't find a way around.

Body:
I have Vue 3 project with a lot of typings there (every component has its own typed props etc). Before build I run this command: vue-tsc --skipLibCheck --declaration --emitDeclarationOnly and the problem is that creates .d.ts and .d.ts.map for every single .vue/.ts file in my project and it looks like this (consider dozens of components):

components
    componentA.vue
    componentA.vue.d.ts
    componentA.vue.d.ts.map
    componentB.vue
    componentB.vue.d.ts
    componentB.vue.d.ts.map

main.ts
main.d.ts
main.d.ts.map

It feels kinda wrong, but I couldn't find a way around.


问:
Referencing a cell in a query transformation to create a reverse running total
I have been working on this for several days now and am having no luck in figuring it out, but feel like I am very close.

In Excel, I am trying to create a reverse running total for a budget by referencing a cell which can be modified or updated.

The only way I have been able to make this work so far is by hard-wiring the starting amount in manually. this is what I want, except every time we receive money I have to change the starting amount manually again.

```<code>= Excel.CurrentWorkbook(){[Name="Q4Rec"]}[Content][QT4_Received]{0}
</code>```

I used this to break down one of my input tables into queries that result in singular numeric values. (The table sums all of the revenue received into annual and quarter) How do I how to reference the new single-quantity queries in my previously built queries to conduct the transformation. I keep getting null values.

Body:
I have been working on this for several days now and am having no luck in figuring it out, but feel like I am very close.

In Excel, I am trying to create a reverse running total for a budget by referencing a cell which can be modified or updated.

The only way I have been able to make this work so far is by hard-wiring the starting amount in manually. this is what I want, except every time we receive money I have to change the starting amount manually again.

= Excel.CurrentWorkbook(){[Name="Q4Rec"]}[Content][QT4_Received]{0}

I used this to break down one of my input tables into queries that result in singular numeric values. (The table sums all of the revenue received into annual and quarter) How do I how to reference the new single-quantity queries in my previously built queries to conduct the transformation. I keep getting null values.


问:
Internal Server Error after running NextJS app with PM2
I got Internal Server Error after starting PM2 on my servers.

But when I did npm run start, the app works normally. How is that possible?


问:
Is it possible to load gitignore file into npm ignore
Let's say I have .gitignore file and .npmignore file. I just want to add one extra folder to be ignored by the npm to what I have in the .gitignore. For example I have:

```<code>//.npmingore
npm/ignored/path

//.gitignore
git/ignored/path
</code>```

Is it possible to just load the .gitignore into the .npmignore, so i do not have to add git/ignored/path into .npmignore?

Body:
Let's say I have .gitignore file and .npmignore file. I just want to add one extra folder to be ignored by the npm to what I have in the .gitignore. For example I have:

//.npmingore
npm/ignored/path

//.gitignore
git/ignored/path

Is it possible to just load the .gitignore into the .npmignore, so i do not have to add git/ignored/path into .npmignore?


问:
SQL Server Management Studio can't open new query
I installed VS 2022 and Microsoft SQL Server Management Studio v18.12.1 on my new computer. After opening SQL Server Management Studio and connecting to a database, if I click "New Query" or "Select Top 1000 Rows" from a table, I get this error:

The type initializer for  'System.Collections.Immutable.ImmutableHashSet`1' threw an exception. (mscorlib)

Could not load file or assembly 'System.Collections, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The module was expected to contain an assembly manifest. (System.Collections.Immutable)

Could not load file or assembly 'System.Collections, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The module was expected to contain an assembly manifest.

If I try to uninstall SQL Server Management Studio in control panel, after clicking uninstall, nothing happens.

I have installed .NET Framework 4.6.2 - 4.7.1, 4.8 SDK by vs installer. What I can do to resolve this problem?

I want to use Microsoft SQL Server Management Studio to query data from database


问:
Why it is not showing image in a recycler view?
(https://i.stack.imgur.com/2DxeM.jpg)](https://i.stack.imgur.com/8XcPR.jpg)(https://i.stack.imgur.com/8HZoq.jpg)](https://i.stack.imgur.com/fVNtz.jpg)](https://i.stack.imgur.com/8XWnf.jpg)

i am expecting that it should display images in the recycler view as wallpapers.


问:
py ceODBC can't fetch result of select statement
I am trying to use ceODBC to try and improve some query times, and I have a problem starting with ceODBC library.
I import the lib, connect, execute the select statement, but when running cursor.fetchall(), or similar, I get the error.
this error seems to happen only with labels that could have spaces or special characters
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc1 in position 26: invalid start byte

sample

```<code>import ceODBC
conn = ceODBC.connect('cnx string', autocommit=False)
cursor = conn.cursor()
cursor.execute("select [name], [label] from table1")
# error because of label having a "héllo world" value for eg
# none works
[print(row) for row in cursor]
print(cursor.fetchall())
</code>```

I tried looking for decode/encode methods but found none on ceODBC

Body:
I am trying to use ceODBC to try and improve some query times, and I have a problem starting with ceODBC library.
I import the lib, connect, execute the select statement, but when running cursor.fetchall(), or similar, I get the error.
this error seems to happen only with labels that could have spaces or special characters
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc1 in position 26: invalid start byte

sample

import ceODBC
conn = ceODBC.connect('cnx string', autocommit=False)
cursor = conn.cursor()
cursor.execute("select [name], [label] from table1")
# error because of label having a "héllo world" value for eg
# none works
[print(row) for row in cursor]
print(cursor.fetchall())

I tried looking for decode/encode methods but found none on ceODBC


问:
Make Checkstyle IntelliJ plug in use a rule relative to the project
I work on a project that uses a microservice architecture.
We externalized the checkstyle configuration in a separated library, we use IntelliJ and the checkstyle plug in.
The checkstyle plug in refers to a static xml file (example of configuration : IntelliJ IDEA code format from checkstyle configuration ) and the configuration of the plug in is automatically is the same for all projects.

When we change the version of our checkstyle configuration, we do not want to adapt the code of all microservices at once and so, at the same time, some services will use the old checkstyle config and some others will use the new one until we upgrade the version.

So, I want to make the checkstyle IntelliJ plug in to refer in every project to the file {project directory}/target/checkstyle-checker.xml and not an unique checkstyle.xml

Does it exist a way to achieve this ? Or at least to make the configuration of the plug in different for all projects ?

Thank you for reading !


问:
Asp.net core API returning 404 when using policy based authorization on action method
I am using jwt authentication and policy based authorization. When using the attribute with [Authorize(Policy = "Admin")] I get a 404 with even my jwt token contains claim with type 'RoleType'.

Here's my ConfigureServices:

```<code> public void ConfigureServices(IServiceCollection services)
 {

            #region UserLogin Lock

            services.Configure<IdentityOptions>(opts =>
            {
                opts.Lockout.AllowedForNewUsers = true;
                opts.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(10);
                opts.Lockout.MaxFailedAccessAttempts = 3;
            });

            #endregion

            #region API Version

            services.AddApiVersioning(config =>
            {
                config.DefaultApiVersion = new ApiVersion(1, 0);
                config.ReportApiVersions = true;
                config.AssumeDefaultVersionWhenUnspecified = true;

                config.ApiVersionReader = new QueryStringApiVersionReader("api-version");
                SwaggerConfig.UseQueryStringApiVersion("api-version");
            });

            services.AddHostedService<Worker>();
                        services.Configure<Settings>(Configuration.GetSection("Settings"));

            services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration["Settings:DbConnection"]));

            services.AddIdentity<IdentityUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
             .AddJwtBearer(options =>
             {
                 options.RequireHttpsMetadata = false;
                 options.SaveToken = true;
                 options.TokenValidationParameters = new TokenValidationParameters
                 {
                     ValidateIssuer = true,
                     ValidateAudience = true,
                     ValidateLifetime = true,
                     ValidateIssuerSigningKey = true,
                     ValidIssuer = Configuration["Jwt:Issuer"],
                     ValidAudience = Configuration["Jwt:Issuer"],
                     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                 };
             });
            services.AddAuthorization(options =>
            {
                options.AddPolicy("Admin", policy =>
                {
                    policy.RequireClaim("RoleType", "Admin");
                });
                            });

            services.AddMvc();
            services.AddControllers().AddNewtonsoftJson(options =>
                    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

}
</code>```

And here is my action method where I am using policy

```<code>        [Authorize(Policy = "Admin")]
        [HttpGet]
        [MapToApiVersion("1.0")]
        public async Task<ActionResult> GetAllCompany()
        {
            try
            {
                var resultData = await _companyService.GetAllCompany();
                if (resultData == null)
                {
                    return NotFound();
                }
                return Ok(resultData);
            }
            catch (Exception ex)
            {
                _
            }
            return Ok();

        }
</code>```

It is working fine with tags [Authorize(AuthenticationSchemes = "Bearer")] and [Authorize(AuthenticationSchemes = "Bearer", Roles = UserPolicy.CompanyUsersAndPatients)] but not with policy

Body:
I am using jwt authentication and policy based authorization. When using the attribute with [Authorize(Policy = "Admin")] I get a 404 with even my jwt token contains claim with type 'RoleType'.

Here's my ConfigureServices:

 public void ConfigureServices(IServiceCollection services)
 {

            #region UserLogin Lock

            services.Configure<IdentityOptions>(opts =>
            {
                opts.Lockout.AllowedForNewUsers = true;
                opts.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(10);
                opts.Lockout.MaxFailedAccessAttempts = 3;
            });

            #endregion

            #region API Version

            services.AddApiVersioning(config =>
            {
                config.DefaultApiVersion = new ApiVersion(1, 0);
                config.ReportApiVersions = true;
                config.AssumeDefaultVersionWhenUnspecified = true;

                config.ApiVersionReader = new QueryStringApiVersionReader("api-version");
                SwaggerConfig.UseQueryStringApiVersion("api-version");
            });

            services.AddHostedService<Worker>();
                        services.Configure<Settings>(Configuration.GetSection("Settings"));

            services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration["Settings:DbConnection"]));

            services.AddIdentity<IdentityUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
             .AddJwtBearer(options =>
             {
                 options.RequireHttpsMetadata = false;
                 options.SaveToken = true;
                 options.TokenValidationParameters = new TokenValidationParameters
                 {
                     ValidateIssuer = true,
                     ValidateAudience = true,
                     ValidateLifetime = true,
                     ValidateIssuerSigningKey = true,
                     ValidIssuer = Configuration["Jwt:Issuer"],
                     ValidAudience = Configuration["Jwt:Issuer"],
                     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                 };
             });
            services.AddAuthorization(options =>
            {
                options.AddPolicy("Admin", policy =>
                {
                    policy.RequireClaim("RoleType", "Admin");
                });
                            });

            services.AddMvc();
            services.AddControllers().AddNewtonsoftJson(options =>
                    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

}

And here is my action method where I am using policy

        [Authorize(Policy = "Admin")]
        [HttpGet]
        [MapToApiVersion("1.0")]
        public async Task<ActionResult> GetAllCompany()
        {
            try
            {
                var resultData = await _companyService.GetAllCompany();
                if (resultData == null)
                {
                    return NotFound();
                }
                return Ok(resultData);
            }
            catch (Exception ex)
            {
                _
            }
            return Ok();

        }

It is working fine with tags [Authorize(AuthenticationSchemes = "Bearer")] and [Authorize(AuthenticationSchemes = "Bearer", Roles = UserPolicy.CompanyUsersAndPatients)] but not with policy


问:
How should a browser extension modify the elements on an iframe?
There is a web page whose URL is like https://some.site.com/page, but that page itself is just for hosting menus and the real content page, whose URL is like https://some.site.com/realpage,is embedded as an iframe.

I want to modify some elements on the actual content pages starting with https://some.site.com/realpage. I created a FireFox extension and set the permissions and content_scripts/matches to https://some.site.com/realpage* and visited https://some.site.com/page, but my extension was not loaded (I could not see it in the Debugger -> Sources tree).

I modified the permissions and content_scripts/matches to https://some.site.com/* and then visited https://some.site.com/page. My extension was in the Debugger -> Sources -> Main Thread and when I console.log(document.URL), I see only https://some.site.com/page printed. But my extension was not there under https://some.site.com/realpage node.

Why is my extension not loaded under the https://some.site.com/realpage node in Debugger -> Sources? I wondered if extensions are not loaded for iframe pages, but I can see other extensions like uBlock Origin loaded for it.

In this case, what is the correct way to modify the actual content (https://some.site.com/realpage). Load my extension at the outer page https://some.site.com/page, and then try to get the iframe and modify it there? Or, load my extension at the real page https://some.site.com/realpage and modify the page as usual (non-iframe pages)?


问:
Cannot step into code at breakpoints in WebStorm
I write some JavaScript code in WebStorm. I can't step into code at breakpoints at line 3, but I can do this at line 10.

I expect to be able to step into code at both breakpoints.


Title: Processing a nxn matrix with multiple batches of 10x10 in R

Body:
I have a matrix_function which can do at max 10x10 operations at a given time. Now, I have a data frame with 25 points from where I need an output of 25x25 from that function.

Sample data:

id <- LETTERS[1:25]

set.seed(04)
value <- runif(25,30, 40)

data <- data.frame(id, value)

#dummy function for reproducibility
matrix_function <- function(x_id, x, y_id, y){

  computed_matrix <- matrix(NA, nrow = 10, ncol = 10)

  for (i in 1:10) {

    for (j in 1:10) {
      computed_matrix[i,j] <- x[i] + y[j]
    }

  }

  colnames(computed_matrix) <- y_id
  rownames(computed_matrix) <- x_id

  return(computed_matrix)
}

Output:

> matrix_function(x_id=data$id[1:10], x=data$value[1:10], y_id=data$id[11:20], y=data$value[11:20])
         K        L        M        N        O        P        Q        R        S        T
A 73.40475 68.71801 66.85854 75.39869 70.01407 70.40903 75.56856 71.69788 75.48005 73.47503
B 67.63621 62.94946 61.08999 69.63015 64.24553 64.64048 69.80001 65.92934 69.71150 67.70648
C 70.48415 65.79740 63.93793 72.47808 67.09347 67.48842 72.64795 68.77728 72.55944 70.55442
D 70.32050 65.63376 63.77428 72.31444 66.92982 67.32477 72.48431 68.61363 72.39580 70.39077
E 75.68249 70.99575 69.13628 77.67643 72.29181 72.68677 77.84630 73.97562 77.75779 75.75277
F 70.15103 65.46428 63.60481 72.14497 66.76035 67.15530 72.31483 68.44416 72.22632 70.22130
G 74.79081 70.10407 68.24459 76.78475 71.40013 71.79508 76.95462 73.08394 76.86611 74.86108
H 76.60767 71.92093 70.06146 78.60161 73.21699 73.61195 78.77148 74.90080 78.68297 76.67795
I 77.03715 72.35041 70.49094 79.03109 73.64647 74.04143 79.20096 75.33028 79.11245 77.10743
J 68.27819 63.59145 61.73198 70.27213 64.88752 65.28247 70.44200 66.57132 70.35349 68.34847

My aim is to wrap the matrix_function with a function which can do all the operations for the points in batches (in this case there will be 7 batches) and give me a 25x25 matrix output.

So far I am trying with for loops but no luck.


问:
Calendar in (form) html template like in Django admin panel
I thought it might be useful to someone. How to make a calendar widget like in the Django admin panel.

```<code>INSTALLED_APPS = [
    'django.forms',
]
</code>```

header.html

```<code><link rel="stylesheet" href="{% static 'css/base.css' %}">
<link rel="stylesheet" href="{% static 'css/widgets.css' %}">
<script type="text/javascript" src="/admin/jsi18n/"></script>
</code>```

footer.html

```<code><script src="{% static 'js/calendar.js' %}"></script>
<script src="{% static 'js/DateTimeShortcuts.js' %}"></script>
<script src="{% static "js/core.js" %}"></script>
</code>```

forms.html

```<code>{{ form.date_production }}
{% if form.date_production.errors %}
{% for error in form.date_production.errors %}
{{ error|escape }}
{% endfor %}
</code>```

forms.py

```<code>from score.models import Score
from django import forms
from django.contrib.admin.widgets import AdminDateWidget

class CreateScoreForm(forms.ModelForm):

date_production = forms.DateField(widget=AdminDateWidget(attrs={'placeholder': 'Production'}), required=False)
date_shipping = forms.DateField(widget=AdminDateWidget(attrs={'placeholder': 'Shipping'}), required=False)
date_payment = forms.DateField(widget=AdminDateWidget(attrs={'placeholder': 'Payment'}), required=False)

class Meta:
    model = Score
    fields = ['date_production', 'date_shipping', 'date_payment',]
</code>```

models.py

```<code>
from django.db import models
from django.urls import reverse_lazy

class Score(models.Model):

date_production = models.DateField(blank=True, null=True, verbose_name='Production')
date_shipping = models.DateField(blank=True, null=True, verbose_name='Shipping')
date_payment = models.DateField(blank=True, null=True, verbose_name='Payment')

def get_absolute_url(self):
    return reverse_lazy('delete_score', kwargs={'pk': self.pk})

def __str__(self):
    return self.number

class Meta:
    ordering = ['-date_creation']
</code>```

Body:
I thought it might be useful to someone. How to make a calendar widget like in the Django admin panel.

INSTALLED_APPS = [
    'django.forms',
]

header.html

<link rel="stylesheet" href="{% static 'css/base.css' %}">
<link rel="stylesheet" href="{% static 'css/widgets.css' %}">

footer.html

forms.html

{{ form.date_production }}
{% if form.date_production.errors %}
{% for error in form.date_production.errors %}
{{ error|escape }}
{% endfor %}

forms.py

from score.models import Score
from django import forms
from django.contrib.admin.widgets import AdminDateWidget

class CreateScoreForm(forms.ModelForm):

date_production = forms.DateField(widget=AdminDateWidget(attrs={'placeholder': 'Production'}), required=False)
date_shipping = forms.DateField(widget=AdminDateWidget(attrs={'placeholder': 'Shipping'}), required=False)
date_payment = forms.DateField(widget=AdminDateWidget(attrs={'placeholder': 'Payment'}), required=False)

class Meta:
    model = Score
    fields = ['date_production', 'date_shipping', 'date_payment',]

models.py

from django.db import models
from django.urls import reverse_lazy

class Score(models.Model):

date_production = models.DateField(blank=True, null=True, verbose_name='Production')
date_shipping = models.DateField(blank=True, null=True, verbose_name='Shipping')
date_payment = models.DateField(blank=True, null=True, verbose_name='Payment')

def get_absolute_url(self):
    return reverse_lazy('delete_score', kwargs={'pk': self.pk})

def __str__(self):
    return self.number

class Meta:
    ordering = ['-date_creation']


问:
.net Maui MVVM sample running on android not running on windows machine. System.AccessViolationException: 'Attempted to read or write protected memory
A sample App on .net maui with MVVM community.toolkit is running on Android simulator but not on windows machine, when i press the add button get this exception

System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'

MainViewModel.cs

```<code>using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Maui.Networking;
using System.Collections.ObjectModel;

namespace ShoppingCart.ViewModel
{
    public partial class MainViewModel : ObservableObject
    {
        IConnectivity connectivity;
        public MainViewModel(IConnectivity connectivity)
        {
            items = new ObservableCollection<string>();
            this.connectivity = connectivity;
        }

        [ObservableProperty]
        ObservableCollection<string> items;

        [ObservableProperty]
        string text;

        [RelayCommand]
        async Task Add()
        {
            if (string.IsNullOrWhiteSpace(Text))
            {
                return;
            }

            if (connectivity.NetworkAccess != NetworkAccess.Internet)
            {
                await Shell.Current.DisplayAlert("Uh oh", "No Internet", "OK");
                return;
            }

            items.Add(Text);
            // add our item
            Text = string.Empty;
        }

        [RelayCommand]
        void Delete(string s)
        {
            if (items.Contains(s))
            {
                items.Remove(s);
            }
        }

        [RelayCommand]
        async Task Tap(string s)
        {
            await Shell.Current.GoToAsync($"{nameof(DetailPage)}?Text={s}");
        }

    }
}
</code>```

MainPage.xaml

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="ShoppingCart.MainPage"
             xmlns:viewmodel="clr-namespace:ShoppingCart.ViewModel"
             x:DataType="viewmodel:MainViewModel">

    <Grid RowDefinitions="100 , Auto, *"
          ColumnDefinitions=".75* , .25*"
          Padding="10"
          RowSpacing="10"
          ColumnSpacing="10">

        <Image Grid.ColumnSpan="2"
               Source="shopping_cart2.png"
               BackgroundColor="Transparent"/>

        <Entry Placeholder="Enter Product"
               Text="{Binding Text}"
               Grid.Row="1" />

        <Button Text="Add"
                Command="{Binding AddCommand}"
                Grid.Column="1"
                Grid.Row="1" />

        <CollectionView Grid.Row="2" Grid.ColumnSpan="2"
                        ItemsSource="{Binding Items}"
                        SelectionMode="None">
            <CollectionView.ItemTemplate>
                <DataTemplate x:DataType="{x:Type x:String}">
                    <Frame x:Name="frame" CornerRadius="10" Margin="10" Padding="0" HasShadow="False"> <!--adding round corner to SwipeView-->
                        <SwipeView>
                            <SwipeView.RightItems>
                                <SwipeItems>
                                    <SwipeItem Text="Delete"
                                           BackgroundColor="Gray"
                                           Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:MainViewModel}}, Path=DeleteCommand}"
                                           CommandParameter="{Binding .}"/>
                                </SwipeItems>
                            </SwipeView.RightItems>
                            <Grid Padding="0.5">
                                <Frame>
                                    <Frame.GestureRecognizers>
                                        <TapGestureRecognizer
                                           Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:MainViewModel}}, Path=TapCommand}"
                                           CommandParameter="{Binding .}"/>
                                    </Frame.GestureRecognizers>
                                    <Label Text="{Binding .}"
                                   FontSize="20"/>
                                </Frame>
                            </Grid>
                        </SwipeView>
                    </Frame>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>

    </Grid>

</ContentPage>

</code>```

i try cleaning up the project and rebuild but nothing

Body:
A sample App on .net maui with MVVM community.toolkit is running on Android simulator but not on windows machine, when i press the add button get this exception

System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'

MainViewModel.cs

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Maui.Networking;
using System.Collections.ObjectModel;

namespace ShoppingCart.ViewModel
{
    public partial class MainViewModel : ObservableObject
    {
        IConnectivity connectivity;
        public MainViewModel(IConnectivity connectivity)
        {
            items = new ObservableCollection<string>();
            this.connectivity = connectivity;
        }

        [ObservableProperty]
        ObservableCollection<string> items;

        [ObservableProperty]
        string text;

        [RelayCommand]
        async Task Add()
        {
            if (string.IsNullOrWhiteSpace(Text))
            {
                return;
            }

            if (connectivity.NetworkAccess != NetworkAccess.Internet)
            {
                await Shell.Current.DisplayAlert("Uh oh", "No Internet", "OK");
                return;
            }

            items.Add(Text);
            // add our item
            Text = string.Empty;
        }

        [RelayCommand]
        void Delete(string s)
        {
            if (items.Contains(s))
            {
                items.Remove(s);
            }
        }

        [RelayCommand]
        async Task Tap(string s)
        {
            await Shell.Current.GoToAsync($"{nameof(DetailPage)}?Text={s}");
        }

    }
}

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="ShoppingCart.MainPage"
             xmlns:viewmodel="clr-namespace:ShoppingCart.ViewModel"
             x:DataType="viewmodel:MainViewModel">

    <Grid RowDefinitions="100 , Auto, *"
          ColumnDefinitions=".75* , .25*"
          Padding="10"
          RowSpacing="10"
          ColumnSpacing="10">

        <Image Grid.ColumnSpan="2"
               Source="shopping_cart2.png"
               BackgroundColor="Transparent"/>

        <Entry Placeholder="Enter Product"
               Text="{Binding Text}"
               Grid.Row="1" />

        <Button Text="Add"
                Command="{Binding AddCommand}"
                Grid.Column="1"
                Grid.Row="1" />

        <CollectionView Grid.Row="2" Grid.ColumnSpan="2"
                        ItemsSource="{Binding Items}"
                        SelectionMode="None">
            <CollectionView.ItemTemplate>
                <DataTemplate x:DataType="{x:Type x:String}">
                    <Frame x:Name="frame" CornerRadius="10" Margin="10" Padding="0" HasShadow="False">
                        <SwipeView>
                            <SwipeView.RightItems>
                                <SwipeItems>
                                    <SwipeItem Text="Delete"
                                           BackgroundColor="Gray"
                                           Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:MainViewModel}}, Path=DeleteCommand}"
                                           CommandParameter="{Binding .}"/>
                                </SwipeItems>
                            </SwipeView.RightItems>
                            <Grid Padding="0.5">
                                <Frame>
                                    <Frame.GestureRecognizers>
                                        <TapGestureRecognizer
                                           Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:MainViewModel}}, Path=TapCommand}"
                                           CommandParameter="{Binding .}"/>
                                    </Frame.GestureRecognizers>

                                </Frame>
                            </Grid>
                        </SwipeView>
                    </Frame>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>

    </Grid>

</ContentPage>

i try cleaning up the project and rebuild but nothing