问:
webpack package the ts file used the exist sourcemap
I have a program like this:
First , I have a list of typescript files.Then I have a compiler compile the ts file to *.obf.ts(this is a special typescript file) and generate the sourcemap.

After this, Webpack will take the after compile steps (ts-loader, babel-loader).
But the sourcemap just convert the file to the *.obf.ts file ,not the original ts file.

I already used the source-map-loader plugin, but the ts-loader seems don't accept the input sourcemap.

So how can I convert back to the original ts file?


来源: stackexchange

问:
On Sourcetree can't do a discard hunk
On Sourcetree, when I do a Commit, and I click on the project.pbxproj file I can't do a "discard hunk" because it doesn't show me inside the file, there is some preference in Sourcetree that I have to flag to be able to do a "discard hunk" even with the project.pbxproj file?</p>

ContentLicense: CC BY-SA 4.0

Title: On Sourcetree can't do a discard hunk


问:
Chinese characters get corrupted when send in Content Disposition in Java
I have been trying to download an attachment with a Chinese filename but somehow their encoding changes to some gibberish filename while downloading.

Here's my code -

```<code>String fileName = "出口项目.zip";

final HttpHeaders headers = new HttpHeaders();

headers.setContentDisposition(ContentDisposition
                    .builder("attachment")
                    .filename(fileName).build());

return ResponseEntity.ok()
                     .contentType(MediaType.APPLICATION_OCTET_STREAM)
                     .headers(headers)
                     .body(fileInputStreamResource);
</code>```

I have already tried  filename= URLEncoder.encode(fileName, "UTF-8"); and all other solutions available on Stack overflow but always get only 2 types of response-

either the file name changes to '????.zip'.

or if the encoded characters fall in ASCII then the filename is the encoded name. (eg: \u51FA\u53E3\u9879\u76EE.zip)

Technology used-
Java 17 for Spring Boot and using Postman for requests.

Is there any way I can preserve the Chinese characters in Content-Disposition or any workaround?

Body:
I have been trying to download an attachment with a Chinese filename but somehow their encoding changes to some gibberish filename while downloading.

Here's my code -

String fileName = "出口项目.zip";

final HttpHeaders headers = new HttpHeaders();

headers.setContentDisposition(ContentDisposition
                    .builder("attachment")
                    .filename(fileName).build());

return ResponseEntity.ok()
                     .contentType(MediaType.APPLICATION_OCTET_STREAM)
                     .headers(headers)
                     .body(fileInputStreamResource);

I have already tried  filename= URLEncoder.encode(fileName, "UTF-8"); and all other solutions available on Stack overflow but always get only 2 types of response-

either the file name changes to '????.zip'.

or if the encoded characters fall in ASCII then the filename is the encoded name. (eg: \u51FA\u53E3\u9879\u76EE.zip)

Technology used-
Java 17 for Spring Boot and using Postman for requests.

Is there any way I can preserve the Chinese characters in Content-Disposition or any workaround?


问:
Exclude logs from fluentd using exclude directive not working
Trying to exclude logs using the grep's exclude directive.

<filter kubernetes.var.log.containers.**>
  @type grep
  <exclude>
    key kubernetes.pod_name
    pattern /^podname-*/
  </exclude>
</filter>
```

I tried with different key names e.g. container and namespace as well. I am trying to exclude logs from a certain pod using the pattern but it's not working. Using type forward source type to send logs.

Want to exclude logs from certain pods starting with the same name from var log containers.

Body:
Trying to exclude logs using the grep's exclude directive.

<filter kubernetes.var.log.containers.**>
  @type grep
  <exclude>
    key kubernetes.pod_name
    pattern /^podname-*/
  </exclude>
</filter>

I tried with different key names e.g. container and namespace as well. I am trying to exclude logs from a certain pod using the pattern but it's not working. Using type forward source type to send logs.

Want to exclude logs from certain pods starting with the same name from var log containers.


问:
React hook form and React select - multi select and controller, unable to retrieve string output
I am unable to get a string array output when using react-hook-form with react-select

I am using this interface:

```<code>export interface IMyInterface{
    customerId: string;
    application: string[];
}
</code>```

getting customerId works great.
this is my dataset for both:

```<code>    const data: Itest[] = [
        { value: "ocean", label: "Ocean", color: "#00B8D9", isFixed: true },
        { value: "blue", label: "Blue", color: "#0052CC", isDisabled: true },
        { value: "purple", label: "Purple", color: "#5243AA" },
        { value: "red", label: "Red", color: "#FF5630", isFixed: true },
        { value: "orange", label: "Orange", color: "#FF8B00" },
        { value: "yellow", label: "Yellow", color: "#FFC400" },
        { value: "green", label: "Green", color: "#36B37E" },
        { value: "forest", label: "Forest", color: "#00875A" },
        { value: "slate", label: "Slate", color: "#253858" },
        { value: "silver", label: "Silver", color: "#666666" },
    ];
</code>```
```<code>    interface ITest {
        value: string;
        label: string;
        color: string;
        isFixed?: boolean;
        isDisabled?: boolean;
    }
</code>```

The code for getting customerId: customerId: string

```<code><Controller
    control={control}
    defaultValue={data[0].color}
    name="customerId"
    render={({ field: { onChange, value, name, ref } }) => (
        <Select
            className="basic-single"
            classNamePrefix="select"
            defaultValue={data[0]}
            isLoading={isLoading}
            isClearable={true}
            onChange={(val) => onChange(val?.value)}
            isSearchable={true}
            value={data.filter((c) => c.value === value)}
            name="color"
            options={data}
        />
    )}
</code>```

the code for getting application application: string[]

```<code><Controller
    control={control}
    defaultValue={[]}
    name="application"
    render={({ field: { onChange, value, name, ref } }) => (
        <Select
            isMulti
            className="basic-single"
            classNamePrefix="select"
            ref={ref}
            defaultValue={value}
            isLoading={isLoading}
            isClearable={true}
            onChange={(val) => {
                onChange(val.map((el) => el));
            }}
            isSearchable={true}
            value={value}
            name={name}
            options={data2}
        />
    )}
/>
</code>```

first of all i get an error saying the type is wrong:

```<code>Type 'Itest[]' is not assignable to type 'readonly (string | GroupBase<string>)[]'.
  Type 'Itest' is not assignable to type 'string | GroupBase<string>'.
    Property 'options' is missing in type 't' but required in type 'GroupBase<string>'.
    130 |                                   value={value}
    131 |                                   name={name}
  > 132 |                                   options={data}
        |                                   ^^^^^^^
    133 |                               />
    134 |                           )}
    135 |                       />
</code>```

if i change the options to options={data as any}
i get the output:

{
    "application": [
        {
            "value": "purple",
            "label": "Purple"
        }
    ],
    "customerId": "purple"
}
```
<p><strong>the output i'd like:</strong></p>
<pre class="lang-json prettyprint-override"><code>{
    "application": ["purple"],
    "customerId": "purple"
}
</code>```

Body:
I am unable to get a string array output when using react-hook-form with react-select

I am using this interface:

export interface IMyInterface{
    customerId: string;
    application: string[];
}

getting customerId works great.
this is my dataset for both:

    const data: Itest[] = [
        { value: "ocean", label: "Ocean", color: "#00B8D9", isFixed: true },
        { value: "blue", label: "Blue", color: "#0052CC", isDisabled: true },
        { value: "purple", label: "Purple", color: "#5243AA" },
        { value: "red", label: "Red", color: "#FF5630", isFixed: true },
        { value: "orange", label: "Orange", color: "#FF8B00" },
        { value: "yellow", label: "Yellow", color: "#FFC400" },
        { value: "green", label: "Green", color: "#36B37E" },
        { value: "forest", label: "Forest", color: "#00875A" },
        { value: "slate", label: "Slate", color: "#253858" },
        { value: "silver", label: "Silver", color: "#666666" },
    ];

    interface ITest {
        value: string;
        label: string;
        color: string;
        isFixed?: boolean;
        isDisabled?: boolean;
    }

The code for getting customerId: customerId: string

<Controller
    control={control}
    defaultValue={data[0].color}
    name="customerId"
    render={({ field: { onChange, value, name, ref } }) => (
        <Select
            className="basic-single"
            classNamePrefix="select"
            defaultValue={data[0]}
            isLoading={isLoading}
            isClearable={true}
            onChange={(val) => onChange(val?.value)}
            isSearchable={true}
            value={data.filter((c) => c.value === value)}
            name="color"
            options={data}
        />
    )}

the code for getting application application: string[]

<Controller
    control={control}
    defaultValue={[]}
    name="application"
    render={({ field: { onChange, value, name, ref } }) => (
        <Select
            isMulti
            className="basic-single"
            classNamePrefix="select"
            ref={ref}
            defaultValue={value}
            isLoading={isLoading}
            isClearable={true}
            onChange={(val) => {
                onChange(val.map((el) => el));
            }}
            isSearchable={true}
            value={value}
            name={name}
            options={data2}
        />
    )}
/>

first of all i get an error saying the type is wrong:

Type 'Itest[]' is not assignable to type 'readonly (string | GroupBase<string>)[]'.
  Type 'Itest' is not assignable to type 'string | GroupBase<string>'.
    Property 'options' is missing in type 't' but required in type 'GroupBase<string>'.
    130 |                                   value={value}
    131 |                                   name={name}
  > 132 |                                   options={data}
        |                                   ^^^^^^^
    133 |                               />
    134 |                           )}
    135 |                       />

if i change the options to options={data as any}
i get the output:

{
    "application": [
        {
            "value": "purple",
            "label": "Purple"
        }
    ],
    "customerId": "purple"
}

the output i'd like:

{
    "application": ["purple"],
    "customerId": "purple"
}


问:
I am stuck in writing in OR & AND condition in python code. Actually there is a one little tricky condition
Basically there are two columns: Customer_column and Company_column. Customer_column is taking input from customer also there is a rule to insert data in (OR,AND) condition.

I want check one column value into the another column. The tricky part is like there is an OR , AND condition values available in column which I want to check. The pipe (|) symbol stands for OR condition, and the comma (,) stands for AND condition.

For example: (1) if my one column (Customer_column) has (Oil|Leak) that means I want to check 'oil' or 'leak'. One of them should be available in respective column (Company_column).(2) If it contains ((Oil)|(Leak,engine)) that means I want to check whether 'oil' word should be available or 'leak' + 'engine' word should be available in the respective column.(3)If it contains like((Oil|Leak),engine) that means I want to check here whether  a combination of  'oil'+ 'engine' word should be available or 'leak' + 'engine' word should be available in the respective column.(4) )If it contains like ((Oil|Leak|Water),engine,Machine) that means I want to check here whether  a combination of  'oil'+'engine'+'machine' word should be available or 'leak' +'engine'+'machine' word or 'water' +'engine'+'machine' word should be available in the respective column.

Below is my data frame:

```<code>import pandas as pd

data = {'Customer_column': ['(Oil|Leak)', '((Oil)|(Leak,engine))', '(Oil|Leak),engine)', '((Oil|Leak|Water),engine,Machine)', '(Leak,water,There)|(Mark,water,There)'],
        'Company_column': ['(leak is present in radiator)', '(engine is leaking)', '(water leak from radiator)', '(water & oil is available in engine machine)', '(there is a water leak mark at engine)']
        }

df = pd.DataFrame(data)

print (df)
</code>```

Below is my expected output:

```<code>data = {'Customer_column': ['(Oil|Leak)', '((Oil)|(Leak,engine))', '(Oil|Leak),engine)', '((Oil|Leak|Water),engine,Machine)', '(Leak,water,There)|(Mark,water,There)'],
        'Company_column': ['(leak is present in radiator)', '(engine is leaking)', '(water leak from radiator)', '(water & oil is available in engine machine)', '(there is a water leak mark at engine)'],
        'Result': ['Leak', 'Leak,engine', 'None', 'oil engine machine,water engine machine', 'Leak water There,Mark water There'],
        }

df = pd.DataFrame(data)

print (df)
</code>```

I tried regex and contain method to solve this. For the OR condition I got my result but I am getting wrong output where the AND condition is written.

```<code>import re
df['match'] = [m.group() if (m:=re.search(fr'\b{re.escape(b)}\b', a, flags=re.I)) else None
               for a,b in zip(df['Customer_column'], df['Company_column'])]
</code>```

The second code I tried:

```<code>def matches(cust, comp):
    words_comp = set(comp[1:-1].casefold().split())
    return '+'.join([x for x in cust[1:-1].split('|')
                     if set(x.casefold().split(','))
                           .issubset(words_comp)
                    ])

df['match'] = [matches(cust, comp) for cust, comp in
               zip(df['Customer_column'], df['Company_column'])]

df
</code>```

The above one is some how giving me correct result with some limitation of brackets but gives wrong output in condition 3rd and 4th.

Body:
Basically there are two columns: Customer_column and Company_column. Customer_column is taking input from customer also there is a rule to insert data in (OR,AND) condition.

I want check one column value into the another column. The tricky part is like there is an OR , AND condition values available in column which I want to check. The pipe (|) symbol stands for OR condition, and the comma (,) stands for AND condition.

For example: (1) if my one column (Customer_column) has (Oil|Leak) that means I want to check 'oil' or 'leak'. One of them should be available in respective column (Company_column).(2) If it contains ((Oil)|(Leak,engine)) that means I want to check whether 'oil' word should be available or 'leak' + 'engine' word should be available in the respective column.(3)If it contains like((Oil|Leak),engine) that means I want to check here whether  a combination of  'oil'+ 'engine' word should be available or 'leak' + 'engine' word should be available in the respective column.(4) )If it contains like ((Oil|Leak|Water),engine,Machine) that means I want to check here whether  a combination of  'oil'+'engine'+'machine' word should be available or 'leak' +'engine'+'machine' word or 'water' +'engine'+'machine' word should be available in the respective column.

Below is my data frame:

import pandas as pd

data = {'Customer_column': ['(Oil|Leak)', '((Oil)|(Leak,engine))', '(Oil|Leak),engine)', '((Oil|Leak|Water),engine,Machine)', '(Leak,water,There)|(Mark,water,There)'],
        'Company_column': ['(leak is present in radiator)', '(engine is leaking)', '(water leak from radiator)', '(water & oil is available in engine machine)', '(there is a water leak mark at engine)']
        }

df = pd.DataFrame(data)

print (df)

Below is my expected output:

data = {'Customer_column': ['(Oil|Leak)', '((Oil)|(Leak,engine))', '(Oil|Leak),engine)', '((Oil|Leak|Water),engine,Machine)', '(Leak,water,There)|(Mark,water,There)'],
        'Company_column': ['(leak is present in radiator)', '(engine is leaking)', '(water leak from radiator)', '(water & oil is available in engine machine)', '(there is a water leak mark at engine)'],
        'Result': ['Leak', 'Leak,engine', 'None', 'oil engine machine,water engine machine', 'Leak water There,Mark water There'],
        }

df = pd.DataFrame(data)

print (df)

I tried regex and contain method to solve this. For the OR condition I got my result but I am getting wrong output where the AND condition is written.

import re
df['match'] = [m.group() if (m:=re.search(fr'\b{re.escape(b)}\b', a, flags=re.I)) else None
               for a,b in zip(df['Customer_column'], df['Company_column'])]

The second code I tried:

def matches(cust, comp):
    words_comp = set(comp[1:-1].casefold().split())
    return '+'.join([x for x in cust[1:-1].split('|')
                     if set(x.casefold().split(','))
                           .issubset(words_comp)
                    ])

df['match'] = [matches(cust, comp) for cust, comp in
               zip(df['Customer_column'], df['Company_column'])]

df

The above one is some how giving me correct result with some limitation of brackets but gives wrong output in condition 3rd and 4th.


问:
Add cookies to a request using IHttpClientFactory in Blazor
I have a Blazor project which depends on an external API. When I login into my website I make an API call to get a session token, then I store this token into a claim.

This token must be send in any call as a cookie. For this, since I'm trying to use HttpClient, I use Header Propagation as seen here.

So my builder has a service like this:

```<code>services.AddHttpClient<ServiceClient>(client =>
{
    client.BaseAddress = new Uri(url);
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
})
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler()
{
    ClientCertificateOptions = ClientCertificateOption.Manual,
    ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) => { return true; },
})
.AddHeaderPropagation(options =>
{
    options.Headers.Add("Cookie");
});

services.AddHeaderPropagation(options =>
    options.Headers.Add("Cookie", context =>
    {
        var identity = context.HttpContext.User.Identities.FirstOrDefault(x => x.AuthenticationType == "AppAuthenticationType");
        if (identity?.IsAuthenticated ?? false)
            return $"SESSION={identity.GetSession()}";
        return String.Empty;
    }));
</code>```

Then I add app.UseHeaderPropagation(); after app.UseAuthentication(); and app.UseAuthorization(); to get it to work.

The problem I have is when I first open my website, I'm not logged in so my claims are not set yet. When I log-in, I set my claims so I can get my session token, but the service is already done so my token is not been at all.

How can I force this header propagation to be resolved for every call?

Body:
I have a Blazor project which depends on an external API. When I login into my website I make an API call to get a session token, then I store this token into a claim.

This token must be send in any call as a cookie. For this, since I'm trying to use HttpClient, I use Header Propagation as seen here.

So my builder has a service like this:

services.AddHttpClient<ServiceClient>(client =>
{
    client.BaseAddress = new Uri(url);
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
})
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler()
{
    ClientCertificateOptions = ClientCertificateOption.Manual,
    ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) => { return true; },
})
.AddHeaderPropagation(options =>
{
    options.Headers.Add("Cookie");
});

services.AddHeaderPropagation(options =>
    options.Headers.Add("Cookie", context =>
    {
        var identity = context.HttpContext.User.Identities.FirstOrDefault(x => x.AuthenticationType == "AppAuthenticationType");
        if (identity?.IsAuthenticated ?? false)
            return $"SESSION={identity.GetSession()}";
        return String.Empty;
    }));

Then I add app.UseHeaderPropagation(); after app.UseAuthentication(); and app.UseAuthorization(); to get it to work.

The problem I have is when I first open my website, I'm not logged in so my claims are not set yet. When I log-in, I set my claims so I can get my session token, but the service is already done so my token is not been at all.

How can I force this header propagation to be resolved for every call?


问:
How to get reference of Component from projected content
I am writing a common angular library component, where the consumers can pass on optional content/template/component through angular content projection mechanism. Below are some example classes to explain better.

The hierarchy tree:

consuming-component - projects component-to-project ----->

common-container - forwards projected content to it's child ------>

common-item - projected content renders here.

Common Library:

component-to-project.component.ts - this is the component that will finally render inside common-item and is projected from the consuming component.

```<code>@Component({
  selector: 'component-to-project',
  template: '<p>Projected Successfully!</p>',
})
export class ComponentToProjectComponent { … }
</code>```

common-container.component.ts - This is the intermediate component that passes on the projected content to common-item.

```<code>@Component({
  selector: 'common-container',
  templateUrl: './common-container.component.html',
  styleUrls: ['./common-container.component.scss'],
})
export class CommonContainerComponent {
    @ContentChild(TemplateRef) projectedTemplateRef!: TemplateRef<any>;
(…)
}
</code>```

common-container.component.html

```<code>...

<div>
    <common-item>
        <ng-template let-context>
            <ng-container [ngTemplateOutlet]="projectedTemplateRef" [ngTemplateOutletContext]="{$implicit: context}">
            </ng-container>
        </ng-template>
    </common-item>
</div>
(…)
</code>```

common-item.component.ts - This is where the projected content actually renders.

```<code>@Component({
  selector: 'common-item',
  templateUrl: './common-item.component.html',
  styleUrls: ['./common-item.component.scss'],
})
export class CommonItemComponent {
    @ContentChild(TemplateRef) projectedTemplateRef!: TemplateRef<any>;

    templateContext: MyContextData = { … };

    ngAfterContentInit() {
        // This is where I need the reference to the component passed through content projection.
        projectedComponent: ComponentToProject = // get component
    }
    (…)
}
</code>```

common-item.component.html

```<code>(…)
<div>
    <ng-container [ngTemplateOutlet]="projectedTemplateRef" [ngTemplateOutletContext]="{$implicit: templateContext}">
    </ng-container>
</div>
(…)
</code>```

Consuming Application (Common Library is added as dependency)

consuming-app.component.html

```<code>(…)
<common-container>
    <ng-template let-context>
        <component-to-project (data)="context.data"></component-to-project>
    </ng-template>
</common-container>
(…)
</code>```

I want the reference to the component-to-project component inside common-item component if this is what is being projected from consuming app.

I have tried few different approaches to get the projected component reference in the common-child component but got undefined in all cases.

Added a reference (<component-to-project #myComponent>) to the projected component and resolve it using @ContentChild in common-item component

```<code>  @ContentChild('myComponent', { descendants: true })
   projectedComponent?: ComponentToProjectComponent;
</code>```

Resolve it using component class as selector of @ContentChild in common-item component

```<code>  @ContentChild(ComponentToProjectComponent, { descendants: true })
   projectedComponent?: ComponentToProjectComponent;
</code>```

Define an injection token for the component and use that injection token in @ContentChild to resolve.

component to project declaration module providers array

```<code>  { provide: TokenClass, useExisting: forwardRef(
    () => ComponentToProjectComponent).
</code>```

common-child

```<code>  @ContentChild(TokenClass) projectedComponent?:
  ComponentToProjectComponent;
</code>```

However, none of the above approach worked.

Body:
I am writing a common angular library component, where the consumers can pass on optional content/template/component through angular content projection mechanism. Below are some example classes to explain better.

The hierarchy tree:

consuming-component - projects component-to-project ----->

common-container - forwards projected content to it's child ------>

common-item - projected content renders here.

Common Library:

component-to-project.component.ts - this is the component that will finally render inside common-item and is projected from the consuming component.

@Component({
  selector: 'component-to-project',
  template: '
Projected Successfully!
',
})
export class ComponentToProjectComponent { … }

common-container.component.ts - This is the intermediate component that passes on the projected content to common-item.

@Component({
  selector: 'common-container',
  templateUrl: './common-container.component.html',
  styleUrls: ['./common-container.component.scss'],
})
export class CommonContainerComponent {
    @ContentChild(TemplateRef) projectedTemplateRef!: TemplateRef<any>;
(…)
}

common-container.component.html

...

    <common-item>
        <ng-template let-context>
            <ng-container [ngTemplateOutlet]="projectedTemplateRef" [ngTemplateOutletContext]="{$implicit: context}">
            </ng-container>
        </ng-template>
    </common-item>

(…)

common-item.component.ts - This is where the projected content actually renders.

@Component({
  selector: 'common-item',
  templateUrl: './common-item.component.html',
  styleUrls: ['./common-item.component.scss'],
})
export class CommonItemComponent {
    @ContentChild(TemplateRef) projectedTemplateRef!: TemplateRef<any>;

    templateContext: MyContextData = { … };

    ngAfterContentInit() {
        // This is where I need the reference to the component passed through content projection.
        projectedComponent: ComponentToProject = // get component
    }
    (…)
}

common-item.component.html

(…)

    <ng-container [ngTemplateOutlet]="projectedTemplateRef" [ngTemplateOutletContext]="{$implicit: templateContext}">
    </ng-container>

(…)

Consuming Application (Common Library is added as dependency)

consuming-app.component.html

(…)
<common-container>
    <ng-template let-context>
        <component-to-project (data)="context.data"></component-to-project>
    </ng-template>
</common-container>
(…)

I want the reference to the component-to-project component inside common-item component if this is what is being projected from consuming app.

I have tried few different approaches to get the projected component reference in the common-child component but got undefined in all cases.

Added a reference (<component-to-project #myComponent>) to the projected component and resolve it using @ContentChild in common-item component

  @ContentChild('myComponent', { descendants: true })
   projectedComponent?: ComponentToProjectComponent;

Resolve it using component class as selector of @ContentChild in common-item component

  @ContentChild(ComponentToProjectComponent, { descendants: true })
   projectedComponent?: ComponentToProjectComponent;

Define an injection token for the component and use that injection token in @ContentChild to resolve.

component to project declaration module providers array

  { provide: TokenClass, useExisting: forwardRef(
    () => ComponentToProjectComponent).

common-child

  @ContentChild(TokenClass) projectedComponent?:
  ComponentToProjectComponent;

However, none of the above approach worked.


问:
MongoTemplate with Count, group By, Conditional Sum
I have an application that runs with spring boot, Spring-Data, JPA-Hibernate and Postgresql. I want to see the inputs using mongoDb.
For this I create a model by replacing the layers: Spring-Data, JPA-Hibernate - Postgresql
by: Spring-Mongo and MongoDb.

I'm new to Mongo and only know the basics. I've been stuck on two questions for several days:

1- I can't find the equivalent of the following query existing in JPA with the use of the mongoTemplate:

```<code>SELECT mse.procedure, mse.etat, mse.flux,
        COUNT(mse.id) AS total,
            SUM(CASE WHEN mse.natureMse = 'MSEAT' THEN 1 ELSE 0 END) AS mseatCount,
            SUM(CASE WHEN mse.natureMse = 'MSEDF' THEN 1 ELSE 0 END) AS msedfCount,
        FROM MseEntity mse
        WHERE mse.etat IS NOT NULL
        GROUP BY mse.procedure, mse.etat, mse.flux
</code>```

2- The method returns a ResultSet in the form of List<Object[]>. Is there an equivalence with the mongoTemplate?

Thanks for your help

Body:
I have an application that runs with spring boot, Spring-Data, JPA-Hibernate and Postgresql. I want to see the inputs using mongoDb.
For this I create a model by replacing the layers: Spring-Data, JPA-Hibernate - Postgresql
by: Spring-Mongo and MongoDb.

I'm new to Mongo and only know the basics. I've been stuck on two questions for several days:

1- I can't find the equivalent of the following query existing in JPA with the use of the mongoTemplate:

SELECT mse.procedure, mse.etat, mse.flux,
        COUNT(mse.id) AS total,
            SUM(CASE WHEN mse.natureMse = 'MSEAT' THEN 1 ELSE 0 END) AS mseatCount,
            SUM(CASE WHEN mse.natureMse = 'MSEDF' THEN 1 ELSE 0 END) AS msedfCount,
        FROM MseEntity mse
        WHERE mse.etat IS NOT NULL
        GROUP BY mse.procedure, mse.etat, mse.flux

2- The method returns a ResultSet in the form of List<Object[]>. Is there an equivalence with the mongoTemplate?

Thanks for your help


问:
(Pyscript) website showing No module named 'mysql'
I'm uploading the following .html to WinSCP, but facing ModuleNotFoundError: No module named 'mysql'

html script

```<code><html>
    <head>
      <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
      <script defer src="https://pyscript.net/latest/pyscript.js"></script>
    </head>

  <body>
    <b><p>title <u><label id="AAA"></label></u> </p></b>
    <br>

    <py-script>
        import mysql.connector

        mydb = mysql.connector.connect(
          host="196.168.100.141",
          user="root",
          password="password123",
          database="database_db",
          auth_plugin='mysql_native_password'
        )

        mycursor = mydb.cursor()
        mycursor.execute("SELECT row_01 FROM database")

        myresult = mycursor.fetchall()

        list_01 = []

        for row in myresult:
          temp_val = row[0]
          list_01.append(temp_val)
    </py-script>
  </body>
</html>
</code>```

error message

```<code>Traceback (most recent call last):
  File "/lib/python3.10/site-packages/_pyodide/_base.py", line 435, in eval_code
    .run(globals, locals)
  File "/lib/python3.10/site-packages/_pyodide/_base.py", line 304, in run
    coroutine = eval(self.code, globals, locals)
  File "<exec>", line 1, in <module>
ModuleNotFoundError: No module named 'mysql'
</code>```

pic: the ModuleNotFoundError on online website

I already do pip install mysql on my pc, but online website still get this error, so where show I pip install or what shall I do

UPDATE:

making sure I get mysql.connector installed on website host pc

```<code>>>> import mysql.connector
>>> print(mysql.connector.__version__)
8.0.31
</code>```

the showing of hosting website with model

```<code>[root@localhost bin]# pip3 show mysql-connector-python
Name: mysql-connector-python
Version: 8.0.31
Summary: MySQL driver written in Python
Home-page: http://dev.mysql.com/doc/connector-python/en/index.html
Author: Oracle and/or its affiliates
Author-email:
License: GNU GPLv2 (with FOSS License Exception)
Location: /usr/local/lib/python3.6/site-packages
Requires: protobuf
</code>```

I know to fix ModuleNotFoundError: No module named 'mysql'is to pip install mysql-connector-python

and I did pip3 install mysql-connector-python, and successfully download under python3.6

what else I can do?

Body:
I'm uploading the following .html to WinSCP, but facing ModuleNotFoundError: No module named 'mysql'

html script

      <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />

title

    <py-script>
        import mysql.connector

        mydb = mysql.connector.connect(
          host="196.168.100.141",
          user="root",
          password="password123",
          database="database_db",
          auth_plugin='mysql_native_password'
        )

        mycursor = mydb.cursor()
        mycursor.execute("SELECT row_01 FROM database")

        myresult = mycursor.fetchall()

        list_01 = []

        for row in myresult:
          temp_val = row[0]
          list_01.append(temp_val)
    </py-script>

error message

Traceback (most recent call last):
  File "/lib/python3.10/site-packages/_pyodide/_base.py", line 435, in eval_code
    .run(globals, locals)
  File "/lib/python3.10/site-packages/_pyodide/_base.py", line 304, in run
    coroutine = eval(self.code, globals, locals)
  File "<exec>", line 1, in <module>
ModuleNotFoundError: No module named 'mysql'

pic: the ModuleNotFoundError on online website

I already do pip install mysql on my pc, but online website still get this error, so where show I pip install or what shall I do

UPDATE:

making sure I get mysql.connector installed on website host pc

>>> import mysql.connector
>>> print(mysql.connector.__version__)
8.0.31

the showing of hosting website with model

[root@localhost bin]# pip3 show mysql-connector-python
Name: mysql-connector-python
Version: 8.0.31
Summary: MySQL driver written in Python
Home-page: http://dev.mysql.com/doc/connector-python/en/index.html
Author: Oracle and/or its affiliates
Author-email:
License: GNU GPLv2 (with FOSS License Exception)
Location: /usr/local/lib/python3.6/site-packages
Requires: protobuf

I know to fix ModuleNotFoundError: No module named 'mysql'is to pip install mysql-connector-python

and I did pip3 install mysql-connector-python, and successfully download under python3.6

what else I can do?


问:
How to analyze the number of packets from one source?
There are situations when one source spams a huge number of snmp traps to the server. How can you make sure that if there are more than 1000 traps per second from one source, then do not receive anything from it for an hour
listener script:

```<code>from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import ntfrcv
from datetime import datetime

snmpEngine = engine.SnmpEngine()

print('Agent is listening SNMP2 Trap on {} , Port : {}'.format(
    TrapAgentAddress, Port))
print(
    '--------------------------------------------------------------------------'
)
config.addTransport(
    snmpEngine, udp.domainName + (1, ),
    udp.UdpTransport().openServerMode(('localhost', 162)))

# Configure community here
config.addV1System(snmpEngine, ' ', 'public')

def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds,
          cbCtx):
    print('\n{0}New trap message received on {1} {0}'.format(
        '-' * 20,
        datetime.now().strftime('%d-%b-%Y at %H:%M:%S')))
    execContext = snmpEngine.observer.getExecutionContext(
            'rfc3412.receiveMessage:request')
    print('Trap is coming from %s:%s' % execContext['transportAddress'])
    for name, val in varBinds:
        print('{0} = {1}'.format(name.prettyPrint(), val.prettyPrint()))
    print('{0}Trap message ends{0}\n'.format('-' * 20))

ntfrcv.NotificationReceiver(snmpEngine, cbFun)

snmpEngine.transportDispatcher.jobStarted(1)

try:
    snmpEngine.transportDispatcher.runDispatcher()
except:
    snmpEngine.transportDispatcher.closeDispatcher()
    raise
</code>```

As a result, if there are more than 1000 packets per second from one source, block it

Body:
There are situations when one source spams a huge number of snmp traps to the server. How can you make sure that if there are more than 1000 traps per second from one source, then do not receive anything from it for an hour
listener script:

from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import ntfrcv
from datetime import datetime

snmpEngine = engine.SnmpEngine()

print('Agent is listening SNMP2 Trap on {} , Port : {}'.format(
    TrapAgentAddress, Port))
print(
    '--------------------------------------------------------------------------'
)
config.addTransport(
    snmpEngine, udp.domainName + (1, ),
    udp.UdpTransport().openServerMode(('localhost', 162)))

# Configure community here
config.addV1System(snmpEngine, ' ', 'public')

def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds,
          cbCtx):
    print('\n{0}New trap message received on {1} {0}'.format(
        '-' * 20,
        datetime.now().strftime('%d-%b-%Y at %H:%M:%S')))
    execContext = snmpEngine.observer.getExecutionContext(
            'rfc3412.receiveMessage:request')
    print('Trap is coming from %s:%s' % execContext['transportAddress'])
    for name, val in varBinds:
        print('{0} = {1}'.format(name.prettyPrint(), val.prettyPrint()))
    print('{0}Trap message ends{0}\n'.format('-' * 20))

ntfrcv.NotificationReceiver(snmpEngine, cbFun)

snmpEngine.transportDispatcher.jobStarted(1)

try:
    snmpEngine.transportDispatcher.runDispatcher()
except:
    snmpEngine.transportDispatcher.closeDispatcher()
    raise

As a result, if there are more than 1000 packets per second from one source, block it


问:
How to send JSON data of AWSJSON Type through one AppSync to another Appsync?
I am sending the request from one AppSync to another AppSync GraphQL endpoint.

Receiving error while sending JSON data for the FIELD data. In VTL Template, $ctx.args.input.data will hold the value for data field.
I have tried to parse the data in a different way in the VTL request mapping template, but still unable to fix the issue. Anybody, please provide a solution for this issue.

```<code>Schema:
input CreatecaseInput {
    caseid: String!
    subjectid: String!
    data: AWSJSON
}

type Mutation {
    createcase(input: CreatecaseInput!): case
}

type case {
    caseid: String
    subjectid: String!
    data: AWSJSON
}
Query:
mutation MyMutation {
  CreatecaseInput(input: {caseid: "99", subjectid: "99", data: "{\"rase\":{\"createdDate\":\"2020-10-19T12:13:43\",\"createdBy\":\"tester\",\"subject\":{\"ethnicity\":\"indian\",\"dob\":\"11-07-1981\"},\"caseid\":\"99\",\"incident\":{\"variant\":\"clade2a\",\"threat\":\"monkeypox\"},\"subjectid\":\"99\",\"contacts\":{\"contact1\":{\"postcode\":\"ls110es\",\"country\":\"uk\"},\"contact2\":{\"postcode\":\"mt220ft\",\"country\":\"uk\"}}}}"}) {
    caseid
    subjectid
    data
  }
}

VTL Request Template:
{
  "version": "2018-05-29",
  "method": "POST",
  "resourcePath": "/graphql",
  "params":{
  "body" : {
      "query": "mutation MyMutation { CreatecaseInput (input: {'caseid': \"$ctx.args.input.caseid\", 'subjectid': \"$ctx.args.input.subjectid\", 'data': \"$util.escapeJavaScript($utils.toJson($ctx.args.input.data))\"}) {caseid subjectid data}}"},
      "headers": {
          "Authorization": "$ctx.request.headers.Authorization",
          "Content-Type": "application/json"
      }
  }
}

Error:
"result": {
            "headers": {
                "content-length": "126",
                "Content-Type": "application/json;charset=UTF-8",
                "Date": "Mon, 09 Jan 2023 08:01:24 GMT",
                "Via": "1.1 743e66b1e30941456613f43d795162e.cloudfront.net (CloudFront)",
                "X-Amz-Cf-Id": "yvXk34csQ5CyEe0dT_EIO5niBE8deApDSPereaCdF0OQRrtaH-iBMJA==",
                "X-Amz-Cf-Pop": "LHR50-P8",
                "x-amzn-appsync-TokensConsumed": "1",
                "x-amzn-ErrorType": "MalformedHttpRequestException",
                "x-amzn-RequestId": "10be00d4-742d-4029-a998-b59448e663ba",
                "X-Cache": "Error from cloudfront"
            },
            "statusCode": 400,
            "body": "{\n  \"errors\" : [ {\n    \"message\" : \"Unable to parse GraphQL query.\",\n    \"errorType\" : \"MalformedHttpRequestException\"\n  } ]\n}"
        },
        "stash": {},
        "outErrors": [
            {
                "message": "{\n  \"errors\" : [ {\n    \"message\" : \"Unable to parse GraphQL query.\",\n    \"errorType\" : \"MalformedHttpRequestException\"\n  } ]\n}",
                "type": "400"
            }
        ]
    },
    "fieldInError": true,
    "errors": [
        "Unable to transform the template: Template transformation yielded an empty response.."
    ],
    "parentType": "Mutation",
    "graphQLAPIId": "6gzqzrg6ynhvbkw2tc3ox2smbe"
}

Tried all the below way to send AWSJSON Type data as request.
Format 1:
Request mapping template:

{
  "version": "2018-05-29",
  "method": "POST",
  "resourcePath": "/graphql",
  "params":{
  "body" : {
      "query": "mutation MyMutation { CreatecaseInput ('input': {'caseid': \"$ctx.args.input.caseid\", 'subjectid': \"$ctx.args.input.subjectid\", 'data': $ctx.args.input.data}) {caseid subjectid data}}"},
      "headers": {
          "Authorization": "$ctx.request.headers.Authorization",
          "Content-Type": "application/json"
      }
  }
}

Error:

{
    "message": "{\n  \"errors\" : [ {\n    \"message\" : \"Unable to parse GraphQL query.\",\n    \"errorType\" : \"MalformedHttpRequestException\"\n  } ]\n}",
    "type": "400"
}
************************************************************************************************
Format 2:
Request mapping template:

{
  "version": "2018-05-29",
  "method": "POST",
  "resourcePath": "/graphql",
  "params":{
  "body" : {
      "query": "mutation MyMutation { CreatecaseInput ('input': {'caseid': \"$ctx.args.input.caseid\", 'subjectid': \"$ctx.args.input.subjectid\", 'data': "$ctx.args.input.data"}) {caseid subjectid data}}"},
      "headers": {
          "Authorization": "$ctx.request.headers.Authorization",
          "Content-Type": "application/json"
      }
  }
}

Error:

"Unexpected character ('{' (code 123)): was expecting comma to separate Object entries\n at [Source: (String)\"{\n  \"version\": \"2018-05-29\",\n  \"method\": \"POST\",\n    \"resourcePath\": \"/graphql\",\n  \"params\":{\n  \"body\" : {\n      \"query\": \"mutation MyMutation { CreatecaseInput ('input': {'caseid': \\\"99\\\", 'subjectid': \\\"99\\\", 'data': \"{case={createdDate=2020-10-19T12:13:43, createdBy=tester, subject={ethnicity=indian, dob=11-07-1981}, caseid=99, incident={variant=clade2a, threat=monkeypox}, subjectid=99, contacts={contact1={postcode=ls110es, country=uk}, contact2={postcode=mt220ft, country=uk}}}}\"}) {caseid subjectid\"[truncated 1222 chars]; line: 7, column: 110]"
    }
  ]
}

************************************************************************************************
Format 3:
Request mapping template:

{
  "version": "2018-05-29",
  "method": "POST",
  ## E.G. if full path is https://api.xxxxxxxxx.com/posts then resourcePath would be /posts **
  "resourcePath": "/graphql",
  "params":{
  "body" : {
      "query": "mutation MyMutation { CreatecaseInput ('input': {'caseid': \"$ctx.args.input.caseid\", 'subjectid': \"$ctx.args.input.subjectid\", 'data': \"$ctx.args.input.data\"}) {caseid subjectid data}}"},
      "headers": {
          "Authorization": "$ctx.request.headers.Authorization",
          "Content-Type": "application/json"
      }
  }
}

Error:
body": "{\"data\":null,\"errors\":[{\"path\":null,\"locations\":[{\"line\":1,\"column\":36,\"sourceName\":null}],\"message\":\"Validation error of type WrongType: argument 'input.data' with value 'StringValue{value='{case={createdDate=2020-10-19T12:13:43, createdBy=tester, subject={ethnicity=indian, dob=11-07-1981}, caseid=99, incident={variant=clade2a, threat=monkeypox}, subjectid=99, contacts={contact1={postcode=ls110es, country=uk}, contact2={postcode=mt220ft, country=uk}}}}'}' is not a valid 'AWSJSON' @ 'CreatecaseInput'\"}]}"
        }

************************************************************************************************
Format 4:
Request mapping template:

{
  "version": "2018-05-29",
  "method": "POST",
  "resourcePath": "/graphql",
  "params":{
  "body" : {
      "query": "mutation MyMutation { CreatecaseInput (input: {'caseid': \"$ctx.args.input.caseid\", 'subjectid': \"$ctx.args.input.subjectid\", 'data': \"$util.toJson($ctx.args.input.data)\"}) {caseid subjectid data}}"},
      "headers": {
          "Authorization": "$ctx.request.headers.Authorization",
          "Content-Type": "application/json"
      }
  }
}

Error:

"message": "Unexpected character ('r' (code 114)): was expecting comma to separate Object entries\n at [Source: (String)\"{\n  \"version\": \"2018-05-29\",\n  \"method\": \"POST\",\n    \"resourcePath\": \"/graphql\",\n  \"params\":{\n  \"body\" : {\n      \"query\": \"mutation MyMutation { CreatecaseInput (input: {'caseid': \\\"99\\\", 'subjectid': \\\"99\\\", 'data': \\\"{\"rase\":{\"createdDate\":\"2020-10-19T12:13:43\",\"createdBy\":\"tester\",\"subject\":{\"ethnicity\":\"indian\",\"dob\":\"11-07-1981\"},\"caseid\":\"99\",\"incident\":{\"variant\":\"clade2a\",\"threat\":\"monkeypox\"},\"subjectid\":\"99\",\"contacts\":{\"contact1\":{\"postcode\":\"ls110es\",\"country\":\"uk\"},\"contact2\":{\"postcode\":\"\"[truncated 1277 chars]; line: 7, column: 111]"
    }
  ]
}

************************************************************************************************

Format 5:
Request mapping template:

{
  "version": "2018-05-29",
  "method": "POST",
  "resourcePath": "/graphql",
  "params":{
  "body" : {
      "query": "mutation MyMutation { CreatecaseInput (input: {'caseid': \"$ctx.args.input.caseid\", 'subjectid': \"$ctx.args.input.subjectid\", 'data': $util.toJson($ctx.args.input.data)}) {caseid subjectid data}}"},
      "headers": {
          "Authorization": "$ctx.request.headers.Authorization",
          "Content-Type": "application/json"
      }
  }
}

Error:

 "message": "Unexpected character ('r' (code 114)): was expecting comma to separate Object entries\n at [Source: (String)\"{\n  \"version\": \"2018-05-29\",\n  \"method\": \"POST\",\n    \"resourcePath\": \"/graphql\",\n  \"params\":{\n  \"body\" : {\n      \"query\": \"mutation MyMutation { CreatecaseInput (input: {'caseid': \\\"99\\\", 'subjectid': \\\"99\\\", 'data': {\"rase\":{\"createdDate\":\"2020-10-19T12:13:43\",\"createdBy\":\"tester\",\"subject\":{\"ethnicity\":\"indian\",\"dob\":\"11-07-1981\"},\"caseid\":\"99\",\"incident\":{\"variant\":\"clade2a\",\"threat\":\"monkeypox\"},\"subjectid\":\"99\",\"contacts\":{\"contact1\":{\"postcode\":\"ls110es\",\"country\":\"uk\"},\"contact2\":{\"postcode\":\"mt\"[truncated 1273 chars]; line: 7, column: 109]"
    }
  ]
}
</code>```

Body:
I am sending the request from one AppSync to another AppSync GraphQL endpoint.

Receiving error while sending JSON data for the FIELD data. In VTL Template, $ctx.args.input.data will hold the value for data field.
I have tried to parse the data in a different way in the VTL request mapping template, but still unable to fix the issue. Anybody, please provide a solution for this issue.

Schema:
input CreatecaseInput {
    caseid: String!
    subjectid: String!
    data: AWSJSON
}

type Mutation {
    createcase(input: CreatecaseInput!): case
}

type case {
    caseid: String
    subjectid: String!
    data: AWSJSON
}
Query:
mutation MyMutation {
  CreatecaseInput(input: {caseid: "99", subjectid: "99", data: "{\"rase\":{\"createdDate\":\"2020-10-19T12:13:43\",\"createdBy\":\"tester\",\"subject\":{\"ethnicity\":\"indian\",\"dob\":\"11-07-1981\"},\"caseid\":\"99\",\"incident\":{\"variant\":\"clade2a\",\"threat\":\"monkeypox\"},\"subjectid\":\"99\",\"contacts\":{\"contact1\":{\"postcode\":\"ls110es\",\"country\":\"uk\"},\"contact2\":{\"postcode\":\"mt220ft\",\"country\":\"uk\"}}}}"}) {
    caseid
    subjectid
    data
  }
}

VTL Request Template:
{
  "version": "2018-05-29",
  "method": "POST",
  "resourcePath": "/graphql",
  "params":{
  "body" : {
      "query": "mutation MyMutation { CreatecaseInput (input: {'caseid': \"$ctx.args.input.caseid\", 'subjectid': \"$ctx.args.input.subjectid\", 'data': \"$util.escapeJavaScript($utils.toJson($ctx.args.input.data))\"}) {caseid subjectid data}}"},
      "headers": {
          "Authorization": "$ctx.request.headers.Authorization",
          "Content-Type": "application/json"
      }
  }
}

Error:
"result": {
            "headers": {
                "content-length": "126",
                "Content-Type": "application/json;charset=UTF-8",
                "Date": "Mon, 09 Jan 2023 08:01:24 GMT",
                "Via": "1.1 743e66b1e30941456613f43d795162e.cloudfront.net (CloudFront)",
                "X-Amz-Cf-Id": "yvXk34csQ5CyEe0dT_EIO5niBE8deApDSPereaCdF0OQRrtaH-iBMJA==",
                "X-Amz-Cf-Pop": "LHR50-P8",
                "x-amzn-appsync-TokensConsumed": "1",
                "x-amzn-ErrorType": "MalformedHttpRequestException",
                "x-amzn-RequestId": "10be00d4-742d-4029-a998-b59448e663ba",
                "X-Cache": "Error from cloudfront"
            },
            "statusCode": 400,
            "body": "{\n  \"errors\" : [ {\n    \"message\" : \"Unable to parse GraphQL query.\",\n    \"errorType\" : \"MalformedHttpRequestException\"\n  } ]\n}"
        },
        "stash": {},
        "outErrors": [
            {
                "message": "{\n  \"errors\" : [ {\n    \"message\" : \"Unable to parse GraphQL query.\",\n    \"errorType\" : \"MalformedHttpRequestException\"\n  } ]\n}",
                "type": "400"
            }
        ]
    },
    "fieldInError": true,
    "errors": [
        "Unable to transform the template: Template transformation yielded an empty response.."
    ],
    "parentType": "Mutation",
    "graphQLAPIId": "6gzqzrg6ynhvbkw2tc3ox2smbe"
}

Tried all the below way to send AWSJSON Type data as request.
Format 1:
Request mapping template:

{
  "version": "2018-05-29",
  "method": "POST",
  "resourcePath": "/graphql",
  "params":{
  "body" : {
      "query": "mutation MyMutation { CreatecaseInput ('input': {'caseid': \"$ctx.args.input.caseid\", 'subjectid': \"$ctx.args.input.subjectid\", 'data': $ctx.args.input.data}) {caseid subjectid data}}"},
      "headers": {
          "Authorization": "$ctx.request.headers.Authorization",
          "Content-Type": "application/json"
      }
  }
}

Error:

{
    "message": "{\n  \"errors\" : [ {\n    \"message\" : \"Unable to parse GraphQL query.\",\n    \"errorType\" : \"MalformedHttpRequestException\"\n  } ]\n}",
    "type": "400"
}
************************************************************************************************
Format 2:
Request mapping template:

{
  "version": "2018-05-29",
  "method": "POST",
  "resourcePath": "/graphql",
  "params":{
  "body" : {
      "query": "mutation MyMutation { CreatecaseInput ('input': {'caseid': \"$ctx.args.input.caseid\", 'subjectid': \"$ctx.args.input.subjectid\", 'data': "$ctx.args.input.data"}) {caseid subjectid data}}"},
      "headers": {
          "Authorization": "$ctx.request.headers.Authorization",
          "Content-Type": "application/json"
      }
  }
}

Error:

"Unexpected character ('{' (code 123)): was expecting comma to separate Object entries\n at [Source: (String)\"{\n  \"version\": \"2018-05-29\",\n  \"method\": \"POST\",\n    \"resourcePath\": \"/graphql\",\n  \"params\":{\n  \"body\" : {\n      \"query\": \"mutation MyMutation { CreatecaseInput ('input': {'caseid': \\\"99\\\", 'subjectid': \\\"99\\\", 'data': \"{case={createdDate=2020-10-19T12:13:43, createdBy=tester, subject={ethnicity=indian, dob=11-07-1981}, caseid=99, incident={variant=clade2a, threat=monkeypox}, subjectid=99, contacts={contact1={postcode=ls110es, country=uk}, contact2={postcode=mt220ft, country=uk}}}}\"}) {caseid subjectid\"[truncated 1222 chars]; line: 7, column: 110]"
    }
  ]
}

************************************************************************************************
Format 3:
Request mapping template:

{
  "version": "2018-05-29",
  "method": "POST",
  ## E.G. if full path is https://api.xxxxxxxxx.com/posts then resourcePath would be /posts **
  "resourcePath": "/graphql",
  "params":{
  "body" : {
      "query": "mutation MyMutation { CreatecaseInput ('input': {'caseid': \"$ctx.args.input.caseid\", 'subjectid': \"$ctx.args.input.subjectid\", 'data': \"$ctx.args.input.data\"}) {caseid subjectid data}}"},
      "headers": {
          "Authorization": "$ctx.request.headers.Authorization",
          "Content-Type": "application/json"
      }
  }
}

Error:
body": "{\"data\":null,\"errors\":[{\"path\":null,\"locations\":[{\"line\":1,\"column\":36,\"sourceName\":null}],\"message\":\"Validation error of type WrongType: argument 'input.data' with value 'StringValue{value='{case={createdDate=2020-10-19T12:13:43, createdBy=tester, subject={ethnicity=indian, dob=11-07-1981}, caseid=99, incident={variant=clade2a, threat=monkeypox}, subjectid=99, contacts={contact1={postcode=ls110es, country=uk}, contact2={postcode=mt220ft, country=uk}}}}'}' is not a valid 'AWSJSON' @ 'CreatecaseInput'\"}]}"
        }

************************************************************************************************
Format 4:
Request mapping template:

{
  "version": "2018-05-29",
  "method": "POST",
  "resourcePath": "/graphql",
  "params":{
  "body" : {
      "query": "mutation MyMutation { CreatecaseInput (input: {'caseid': \"$ctx.args.input.caseid\", 'subjectid': \"$ctx.args.input.subjectid\", 'data': \"$util.toJson($ctx.args.input.data)\"}) {caseid subjectid data}}"},
      "headers": {
          "Authorization": "$ctx.request.headers.Authorization",
          "Content-Type": "application/json"
      }
  }
}

Error:

"message": "Unexpected character ('r' (code 114)): was expecting comma to separate Object entries\n at [Source: (String)\"{\n  \"version\": \"2018-05-29\",\n  \"method\": \"POST\",\n    \"resourcePath\": \"/graphql\",\n  \"params\":{\n  \"body\" : {\n      \"query\": \"mutation MyMutation { CreatecaseInput (input: {'caseid': \\\"99\\\", 'subjectid': \\\"99\\\", 'data': \\\"{\"rase\":{\"createdDate\":\"2020-10-19T12:13:43\",\"createdBy\":\"tester\",\"subject\":{\"ethnicity\":\"indian\",\"dob\":\"11-07-1981\"},\"caseid\":\"99\",\"incident\":{\"variant\":\"clade2a\",\"threat\":\"monkeypox\"},\"subjectid\":\"99\",\"contacts\":{\"contact1\":{\"postcode\":\"ls110es\",\"country\":\"uk\"},\"contact2\":{\"postcode\":\"\"[truncated 1277 chars]; line: 7, column: 111]"
    }
  ]
}

************************************************************************************************

Format 5:
Request mapping template:

{
  "version": "2018-05-29",
  "method": "POST",
  "resourcePath": "/graphql",
  "params":{
  "body" : {
      "query": "mutation MyMutation { CreatecaseInput (input: {'caseid': \"$ctx.args.input.caseid\", 'subjectid': \"$ctx.args.input.subjectid\", 'data': $util.toJson($ctx.args.input.data)}) {caseid subjectid data}}"},
      "headers": {
          "Authorization": "$ctx.request.headers.Authorization",
          "Content-Type": "application/json"
      }
  }
}

Error:

 "message": "Unexpected character ('r' (code 114)): was expecting comma to separate Object entries\n at [Source: (String)\"{\n  \"version\": \"2018-05-29\",\n  \"method\": \"POST\",\n    \"resourcePath\": \"/graphql\",\n  \"params\":{\n  \"body\" : {\n      \"query\": \"mutation MyMutation { CreatecaseInput (input: {'caseid': \\\"99\\\", 'subjectid': \\\"99\\\", 'data': {\"rase\":{\"createdDate\":\"2020-10-19T12:13:43\",\"createdBy\":\"tester\",\"subject\":{\"ethnicity\":\"indian\",\"dob\":\"11-07-1981\"},\"caseid\":\"99\",\"incident\":{\"variant\":\"clade2a\",\"threat\":\"monkeypox\"},\"subjectid\":\"99\",\"contacts\":{\"contact1\":{\"postcode\":\"ls110es\",\"country\":\"uk\"},\"contact2\":{\"postcode\":\"mt\"[truncated 1273 chars]; line: 7, column: 109]"
    }
  ]
}


问:
Virtual background
How do I add an image as a virtual background using ML Kit Selfie segmentation? I am following the example project from github and I got it working with a colored overlay. But I dont understand how to replace that overlay with a picture. In this question, I can see that it is possible: Poor selfie segmentation with Google ML Kit. I copied code from https://github.com/googlesamples/mlkit/tree/master/android/vision-quickstart to get the pink overlay. I should also mention that I am using this in streaming mode.</p>

Title: Virtual background


问:
on a null object reference :Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()'

Logcat

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at com.example.medcareinapp.UserSideScreens.PatientDashboardActivity.onCreate(PatientDashboardActivity.java:89)

PatientDashboardActivity.java

private static FirebaseAuth mAuth;
public static String UserName;

```<code>DrawerLayout drawerLayout;
TextView nav_name;
CardView  bookRideCard, profileCard, activeRideCard, historyCard, book_doctor, active_appointments;
Intent i;

FirebaseFirestore firebaseFirestore;
FirebaseAuth firebaseAuth;
String currentUserKey;

private int PERMISSION_CODE = 1;

//shared prefs variables
public static final String SHARED_PREFS = "SharedPrefs";
public static final String userType = "userType";
public static final String userNodeKey = "userKey";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_patient_dashboard);

    // check if the permissions are granted
    if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(PatientDashboardActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_CODE);
        Toast.makeText(getApplicationContext(), "Provide the permissions to continue", Toast.LENGTH_SHORT).show();
        return;
    }

    SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();

    firebaseAuth = FirebaseAuth.getInstance();
    firebaseFirestore = FirebaseFirestore.getInstance();
    currentUserKey = firebaseAuth.getCurrentUser().getUid();

    mAuth = FirebaseAuth.getInstance();
    UserName = getIntent().getStringExtra("UserName");

    drawerLayout = findViewById(R.id.drawer);
    nav_name = findViewById(R.id.nav_name);
    nav_name.setText(UserName);

    book_doctor = findViewById(R.id.book_doctor);
    active_appointments = findViewById(R.id.active_appointments);
    bookRideCard = findViewById(R.id.bookRideCardPDashboard);
</code>```

Body:
Logcat

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at com.example.medcareinapp.UserSideScreens.PatientDashboardActivity.onCreate(PatientDashboardActivity.java:89)

PatientDashboardActivity.java

private static FirebaseAuth mAuth;
public static String UserName;

DrawerLayout drawerLayout;
TextView nav_name;
CardView  bookRideCard, profileCard, activeRideCard, historyCard, book_doctor, active_appointments;
Intent i;

FirebaseFirestore firebaseFirestore;
FirebaseAuth firebaseAuth;
String currentUserKey;

private int PERMISSION_CODE = 1;

//shared prefs variables
public static final String SHARED_PREFS = "SharedPrefs";
public static final String userType = "userType";
public static final String userNodeKey = "userKey";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_patient_dashboard);

    // check if the permissions are granted
    if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(PatientDashboardActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_CODE);
        Toast.makeText(getApplicationContext(), "Provide the permissions to continue", Toast.LENGTH_SHORT).show();
        return;
    }

    SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();

    firebaseAuth = FirebaseAuth.getInstance();
    firebaseFirestore = FirebaseFirestore.getInstance();
    currentUserKey = firebaseAuth.getCurrentUser().getUid();

    mAuth = FirebaseAuth.getInstance();
    UserName = getIntent().getStringExtra("UserName");

    drawerLayout = findViewById(R.id.drawer);
    nav_name = findViewById(R.id.nav_name);
    nav_name.setText(UserName);

    book_doctor = findViewById(R.id.book_doctor);
    active_appointments = findViewById(R.id.active_appointments);
    bookRideCard = findViewById(R.id.bookRideCardPDashboard);


问:
Create new Dataframe with rows from another Dataframe given the rows index
I have a pandas dataframe and I need to create a new dataframe only with the rows which satisfy a certain condition. I got these rows indexes using:

```<code>position = df.index[df.iloc[:, 0] == value].tolist()
</code>```

How should I create the new dataframe using only the rows which indexes are in the position variable?

Body:
I have a pandas dataframe and I need to create a new dataframe only with the rows which satisfy a certain condition. I got these rows indexes using:

position = df.index[df.iloc[:, 0] == value].tolist()

How should I create the new dataframe using only the rows which indexes are in the position variable?


问:
while loop in python diamond pattern
Please code with only while loop to print the diamond pattern in python. This is the code I tried but it prints only the half diamond correctly.

```<code>n = int(input())
h=1
k=1
while h <=(n+1)/2:
    b=1
    while b<=(n+1)/2-h:
        print(' ',end='')
        b=b+1
    j=1
    while j<=k:
        print('*',end='')
        j=j+1
    k=k+2
    print()
    h=h+1

n=(n-((n+1)/2))
h=1
while n>=0:
    b=1
    while b<= h:
        print(" ",end='')
        b=b+1
    j=1
    while j<=(n*2)- h:
        print("*",end='')
        j=j+1
    print()
    n=n-1
    h=h+1`
</code>```

Please correct and add .I am not able to print the whole diamond. Thank you

Title: while loop in python diamond pattern

Body:
Please code with only while loop to print the diamond pattern in python. This is the code I tried but it prints only the half diamond correctly.

n = int(input())
h=1
k=1
while h <=(n+1)/2:
    b=1
    while b<=(n+1)/2-h:
        print(' ',end='')
        b=b+1
    j=1
    while j<=k:
        print('*',end='')
        j=j+1
    k=k+2
    print()
    h=h+1

n=(n-((n+1)/2))
h=1
while n>=0:
    b=1
    while b<= h:
        print(" ",end='')
        b=b+1
    j=1
    while j<=(n*2)- h:
        print("*",end='')
        j=j+1
    print()
    n=n-1
    h=h+1`

Please correct and add .I am not able to print the whole diamond. Thank you


问:
Why does setw misbehave when displaying the second variable (you.date)?
Im using setw to display my content, but one value has too much spaces which decreases the spaces from others

this is my code:

```<code>#include <iostream>
#include <cstring>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{
    struct customerinfo
    {
        int policy;
        string date;
        string loc;
        string state;
        string region;
        double ivalue;
        string cons;
        string btype;
        char earth;
        char flood;
        string dummy;
    };

    customerinfo you;

    cout<<"Enter your 8-digit policy number: ";
    cin>>you.policy;
    cout<<"Enter your account expiry date [MM/DD/YYYY]: ";
    getline(cin,you.date);
    cin.ignore();
    cout<<"Enter your location [Urban or Rural]: ";
    getline(cin,you.loc);
    cin.ignore();
    cout<<"Enter your current residing state: ";
    getline(cin,you.state);
    getline(cin,you.dummy);
    cout<<"Enter your current residing region: ";
    cin>>you.region;
    cin.ignore();
    cout<<"Enter property value: ";
    cin>>you.ivalue;
    cin.ignore();
    cout<<"Enter property construction type: ";
    getline(cin,you.cons);
    cout<<"Enter your business type: ";
    getline(cin,you.btype);
    cout<<"Is earthquake coverage included? [Y or N]: ";
    cin>>you.earth;
    cout<<"Is flood coverage included? [Y or N]: ";
    cin>>you.flood;

    system("CLS");

    cout<<setw(11)<<"Policy #"<<setw(13)<<"Expiry Date"<<setw(11)<<"Location"<<setw(8)<<"State"<<setw(9)<<"Region"<<setw(16)<<"Insured Value"<<setw(14)<<"Const. Type"<<setw(10)<<"B. Type"<<setw(13)<<"Earthquake"<<setw(8)<<"Flood"<<setw(11)<<endl;
    cout<<"---------------------------------------------------------------------------------------------------------------------"<<endl;
    cout<<setw(11)<<you.policy<<setw(13)<<you.date<<setw(11)<<you.loc<<setw(8)<<you.state<<setw(9)<<you.region<<setw(16)<<you.ivalue<<setw(14)<<you.cons<<setw(10)<<you.btype<<setw(13)<<you.earth<<setw(8)<<you.flood<<setw(11);
}
</code>```

after running my code and after data input:
This is what i get. I has an excessive amount of spaces before "you.date" which causes the other variables to suffer

for reference, my inputs were:
12345678
date
loc
state
reg
123
cons
bus
y
y

Body:
Im using setw to display my content, but one value has too much spaces which decreases the spaces from others

this is my code:

#include <iostream>
#include <cstring>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{
    struct customerinfo
    {
        int policy;
        string date;
        string loc;
        string state;
        string region;
        double ivalue;
        string cons;
        string btype;
        char earth;
        char flood;
        string dummy;
    };

    customerinfo you;

    cout<<"Enter your 8-digit policy number: ";
    cin>>you.policy;
    cout<<"Enter your account expiry date [MM/DD/YYYY]: ";
    getline(cin,you.date);
    cin.ignore();
    cout<<"Enter your location [Urban or Rural]: ";
    getline(cin,you.loc);
    cin.ignore();
    cout<<"Enter your current residing state: ";
    getline(cin,you.state);
    getline(cin,you.dummy);
    cout<<"Enter your current residing region: ";
    cin>>you.region;
    cin.ignore();
    cout<<"Enter property value: ";
    cin>>you.ivalue;
    cin.ignore();
    cout<<"Enter property construction type: ";
    getline(cin,you.cons);
    cout<<"Enter your business type: ";
    getline(cin,you.btype);
    cout<<"Is earthquake coverage included? [Y or N]: ";
    cin>>you.earth;
    cout<<"Is flood coverage included? [Y or N]: ";
    cin>>you.flood;

    system("CLS");

    cout<<setw(11)<<"Policy #"<<setw(13)<<"Expiry Date"<<setw(11)<<"Location"<<setw(8)<<"State"<<setw(9)<<"Region"<<setw(16)<<"Insured Value"<<setw(14)<<"Const. Type"<<setw(10)<<"B. Type"<<setw(13)<<"Earthquake"<<setw(8)<<"Flood"<<setw(11)<<endl;
    cout<<"---------------------------------------------------------------------------------------------------------------------"<<endl;
    cout<<setw(11)<<you.policy<<setw(13)<<you.date<<setw(11)<<you.loc<<setw(8)<<you.state<<setw(9)<<you.region<<setw(16)<<you.ivalue<<setw(14)<<you.cons<<setw(10)<<you.btype<<setw(13)<<you.earth<<setw(8)<<you.flood<<setw(11);
}

after running my code and after data input:
This is what i get. I has an excessive amount of spaces before "you.date" which causes the other variables to suffer

for reference, my inputs were:
12345678
date
loc
state
reg
123
cons
bus
y
y


问:
RN-0.70.6 error- Execution failed for task ':app:processDebugResources'
Just upgraded the RN-0.63.3 to latest RN-0.70.6
giving Execution failed for task ':app:processDebugResources'. error  with
A failure occurred while executing com.android.build.gradle.internal.res.LinkApplicationAndroidResourcesTask$TaskAction

Android resource linking failed
com.APPNAME.app-mergeDebugResources-33:/values/values.xml:913: error: resource drawable/rn_edit_text_material (aka com.pushthivardhan.foods.consumer:drawable/rn_edit_text_material) not found.

tried the recommended changes from stackoverflow(previous solution) , but didn't worked.


问:
React custom hooks showing undefined error in Axios
I have a cutom hook created as below. It is using axios and useEffect().

```<code>import { useState, useEffect } from 'react';
import axios from 'axios';

axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';
const baseURL="http://127.0.0.1:5000/v1/test_server/"

const useAxios = ({ url, method='get', body = null, headers = JSON.stringify({ accept: '*/*' }),
}) => {
    const [response, setResponse] = useState(null);
    const [error, setError] = useState('');
    const [loading, setloading] = useState(true);

    const fetchData = () => {
        axios[method](baseURL+url, JSON.parse(headers), JSON.parse(body))
            .then((res) => {
                setResponse(res.data);
            })
            .catch((err) => {
                setError(err);
            })
            .finally(() => {
                setloading(false);
            });
    };

    useEffect(() => {
        fetchData();
    }, [method, url, body, headers]);

    return { response, error, loading };
};

export default useAxios;
</code>```

I'm using this hook in another component as

```<code>const [playerData, setPlayerData] = useState();
const { playerResponse, playerError, playerLoading} = useAxios({ url: 'player/get_player'})

if (playerResponse !== null ) {
      setPlayerData(playerResponse.result);
      console.log("Response", playerData);
    }
</code>```

Everything seems correct but the code is showing Cannot read properties of undefined (reading 'result'). Why this is happening?

Body:
I have a cutom hook created as below. It is using axios and useEffect().

import { useState, useEffect } from 'react';
import axios from 'axios';

axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';
const baseURL="http://127.0.0.1:5000/v1/test_server/"

const useAxios = ({ url, method='get', body = null, headers = JSON.stringify({ accept: '*/*' }),
}) => {
    const [response, setResponse] = useState(null);
    const [error, setError] = useState('');
    const [loading, setloading] = useState(true);

    const fetchData = () => {
        axios[method](baseURL+url, JSON.parse(headers), JSON.parse(body))
            .then((res) => {
                setResponse(res.data);
            })
            .catch((err) => {
                setError(err);
            })
            .finally(() => {
                setloading(false);
            });
    };

    useEffect(() => {
        fetchData();
    }, [method, url, body, headers]);

    return { response, error, loading };
};

export default useAxios;

I'm using this hook in another component as

const [playerData, setPlayerData] = useState();
const { playerResponse, playerError, playerLoading} = useAxios({ url: 'player/get_player'})

if (playerResponse !== null ) {
      setPlayerData(playerResponse.result);
      console.log("Response", playerData);
    }

Everything seems correct but the code is showing Cannot read properties of undefined (reading 'result'). Why this is happening?


问:
Proper way to compare duplicate dates in Javascript?
I'm currently making something that will first check if an element exists in an array, if it does exist already, it will remove it, else if not it will insert it. The element type here is a date, however, I seem to be having problems comparing it with itself.

Here is an example data set I'm using:

```<code> const data = [
    {
      day: "Sun",
      index: 0,
      date: new Date(2099, 0, 4)
    },
    {
      day: "Mon",
      index: 1,
      date: new Date(2099, 0, 5)
    },
    {
      day: "Tue",
      index: 2,
      date: new Date(2099, 0, 6)
    }
]
</code>```

Then, when a user click the button, here's the check:

```<code>
  let [dates, setDates] = useState([]);

  const handleDayClick = (ind, day) => {
    const datesCpy = [...dates];
    let found = 0;
    for(let i = 0; i < datesCpy.length; i++) {
      console.log(`Comparing ${datesCpy[i]} to ${day}!`);
      if(datesCpy[i].toDateString() === day.toDateString()) {
        found = 1;
        datesCpy.splice(i, 1); //if already exists.. remove it.
        break;
      }
    }
    if(found === 0) {
      datesCpy.push(day);
    }
    ... //do other stuff here, irrelevant to question
</code>```

I even get this in the console, which has identical values(but doesn't get into the if statement):
Comparing Mon Jan 05 2099 00:00:00 GMT-0600 (Central Standard Time) to Mon Jan 05 2099 00:00:00 GMT-0600 (Central Standard Time)!

I have tried using indexOf and of course contains, but they never find the actual duplicate, so I resorted to using a c-style approach with a for loop and iterating. I also have tried comparing the actual date values rather than stringify-ing them, I had tried previous solutions from other SO questions, but they mentioned IndexOf, contains, etc. Is there something obvious I'm overlooking?

Body:
I'm currently making something that will first check if an element exists in an array, if it does exist already, it will remove it, else if not it will insert it. The element type here is a date, however, I seem to be having problems comparing it with itself.

Here is an example data set I'm using:

 const data = [
    {
      day: "Sun",
      index: 0,
      date: new Date(2099, 0, 4)
    },
    {
      day: "Mon",
      index: 1,
      date: new Date(2099, 0, 5)
    },
    {
      day: "Tue",
      index: 2,
      date: new Date(2099, 0, 6)
    }
]

Then, when a user click the button, here's the check:

  let [dates, setDates] = useState([]);

  const handleDayClick = (ind, day) => {
    const datesCpy = [...dates];
    let found = 0;
    for(let i = 0; i < datesCpy.length; i++) {
      console.log(`Comparing ${datesCpy[i]} to ${day}!`);
      if(datesCpy[i].toDateString() === day.toDateString()) {
        found = 1;
        datesCpy.splice(i, 1); //if already exists.. remove it.
        break;
      }
    }
    if(found === 0) {
      datesCpy.push(day);
    }
    ... //do other stuff here, irrelevant to question

I even get this in the console, which has identical values(but doesn't get into the if statement):
Comparing Mon Jan 05 2099 00:00:00 GMT-0600 (Central Standard Time) to Mon Jan 05 2099 00:00:00 GMT-0600 (Central Standard Time)!

I have tried using indexOf and of course contains, but they never find the actual duplicate, so I resorted to using a c-style approach with a for loop and iterating. I also have tried comparing the actual date values rather than stringify-ing them, I had tried previous solutions from other SO questions, but they mentioned IndexOf, contains, etc. Is there something obvious I'm overlooking?


问:
Kubeflow Parallel For how to report progress
In Kubeflow, how can I log the progress of the for loop to see if it is progressing?
Moreover, in the graph view, the graph renderer is having a hard time to draw 1000s of tasks. Can it be grouped?</p>


问:
Why is it not possible to delete files quickly (<60s) across threads in aspnet?
I get error

System.IO.IOException: 'The process cannot access the file 'xxx' because it is being used by another process.'

when I try to delete a temp file in a background worker service in aspnet core.
I am eventually allowed to delete the file after about a minute (52s, 73s).
If I change garbage collection to workstation mode, I may instead delete after ~1s (but still, a delay).

I have tried a combination of FileOptions to no avail, including FileOptions.WriteThrough.

When the controller writes the file, I use
FlushAsync(), Close(), Dispose() and 'using' (I know it's overkill.)
I also tried using just File.WriteAllBytesAsync, with same result.

In the background reader, I as well use Close() and Dispose().
(hint: background reader will not allow me to use DeleteOnClose,
which would have been ideal.)

As I search stackoverflow for similar 'used by another process' issues,
all those I have found eventually resolve to
'argh it turns out I/he still had an extra open instance/reference
he forgot about',
but I have not been able to figure out that I am doing that.

Another hint:
In the writing controller, I am able to delete the file immediately
after writing it, I presume because I am still on the same thread?

Is there some secret knowledge I should read somewhere,
about being able to delete recently open files, across threads?

UPDATE: Here relevant(?) code snippets:

```<code>// (AspNet Controller)
        [RequestSizeLimit(9999999999)]
        [DisableFormValueModelBinding]
        [RequestFormLimits(MultipartBodyLengthLimit = MaxFileSize)]
        [HttpPost("{sessionId}")]
        public async Task<IActionResult> UploadRevisionChunk(Guid sessionId) {
            log.LogWarning($"UploadRevisionChunk: {sessionId}");
            string uploadFolder = UploadFolder.sessionFolderPath(sessionId);
            if (!Directory.Exists(uploadFolder)) { throw new Exception($"chunk-upload failed"); }
            var cr = parseContentRange(Request);
            if (cr == null) { return this.BadRequest("no content range header specified"); }
            string chunkName = $"{cr.From}-{cr.To}";
            string saveChunkPath = Path.Combine(uploadFolder,chunkName);
            await streamToChunkFile_WAB(saveChunkPath); // write-all-bytes.
            //await streamToChunkFile_MAN(saveChunkPath); // Manual.
            long crTo   = cr.To ?? 0;
            long crFrom = cr.From ?? 0;
            long expected = (crTo - crFrom) + 1;
            var fi = new FileInfo(saveChunkPath);
            var dto = new ChunkResponse { wrote = fi.Length, expected = expected, where = "?" };
            string msg = $"at {crFrom}, wrote {dto.wrote} bytes (expected {dto.expected}) to {dto.where}";
            log.LogWarning(msg);
            return Ok(dto);
        }
        private async Task streamToChunkFile_WAB(string saveChunkPath) {
            using (MemoryStream ms = new MemoryStream()) {
                Request.Body.CopyTo(ms);
                byte[] allBytes = ms.ToArray();
                await System.IO.File.WriteAllBytesAsync(saveChunkPath, allBytes);
            }
        }
</code>```
```<code>// stream reader in the backgroundService:
    public class MyMultiStream : Stream {
        string[] filePaths;
        FileStream curStream = null;
        IEnumerator<string> i;
        ILogger log;
        QueueItem qItem;

        public MyMultiStream(string[] filePaths_, Stream[] streams_, ILogger log_, QueueItem qItem_) {
            qItem = qItem_;
            log = log_;
            filePaths = filePaths_;

            log.LogWarning($"filepaths has #items: {filePaths.Length}");
            IEnumerable<string> enumerable = filePaths;
            i = enumerable.GetEnumerator();
            i.MoveNext();// necessary to prime the iterator.
        }

        public override bool CanRead { get { return true; } }
        public override bool CanWrite { get { return false; } }
        public override bool CanSeek { get { return false; } }
        public override long Length { get { throw new Exception("dont get length"); } }
        public override long Position {
            get { throw new Exception("dont get Position"); }
            set { throw new Exception("dont set Position"); }
        }
        public override void SetLength(long value) { throw new Exception("dont set length"); }
        public override long Seek(long offset, SeekOrigin origin) { throw new Exception("dont seek"); }
        public override void Write(byte[] buffer, int offset, int count) { throw new Exception("dont write"); }
        public override void Flush() { throw new Exception("dont flush"); }

        public static int openStreamCounter = 0;
        public static int closedStreamCounter = 0;
        string curFileName = "?";
        private FileStream getNextStream() {
            string nextFileName = i.Current;
            if (nextFileName == null) { throw new Exception("getNextStream should not be called past file list"); }
            //tryDelete(nextFileName,log);
            FileStream nextStream = new FileStream(
                path:nextFileName,
                mode: FileMode.Open,
                access: FileAccess.Read,
                share: FileShare.ReadWrite| FileShare.Delete,
                bufferSize:4096, // apparently default.
                options: 0
                | FileOptions.Asynchronous
                | FileOptions.SequentialScan
                // | FileOptions.DeleteOnClose // (1) this ought to be possible, (2) we should fix this approach (3) if we can fix this, our issue is solved, and our code much simpler.
            ); // None); // ReadWrite); // None); // ReadWrite); //| FileShare.Read);
            log.LogWarning($"TELLUS making new stream [{nextFileName}] opened:[{++openStreamCounter}] closed:[{closedStreamCounter}]");

            curFileName = nextFileName;
            ++qItem.chunkCount;
            return nextStream;
        }

        public override int Read(byte[] buffer, int offset, int count) {
            int bytesRead = 0;
            while (true) {
                bytesRead = 0;
                if (curStream == null) { curStream = getNextStream(); }
                try {
                    bytesRead = curStream.Read(buffer, offset, count);
                    log.LogWarning($"..bytesRead:{bytesRead} [{Path.GetFileName(curFileName)}]"); // (only show a short name.)
                } catch (Exception e) {
                    log.LogError($"failed reading [{curFileName}] [{e.Message}]",e);
                }
                if (bytesRead > 0) { break; }

                curStream.Close();
                curStream.Dispose();
                curStream = null;
                log.LogWarning($"TELLUS closing stream [{curFileName}] opened:[{openStreamCounter}] closed:[{++closedStreamCounter}]");
                //tryDelete(curFileName); Presumably we can't delete so soon.
                bool moreFileNames = i.MoveNext();
                log.LogWarning($"moreFileNames?{moreFileNames}");
                if (!moreFileNames) {
                    break;
                }
            }
            return bytesRead;
        }

..
// Background worker operating multistream:
    public class BackgroundChunkWorker: BackgroundService {
        ILogger L;
        ChunkUploadQueue q;

        public readonly IServiceScopeFactory scopeFactory;

        public BackgroundChunkWorker(ILogger<int> log_, ChunkUploadQueue q_, IServiceScopeFactory scopeFactory_) {
            q = q_; L = log_;
            scopeFactory = scopeFactory_;
        }

        override protected async Task ExecuteAsync(CancellationToken cancel) { await BackgroundProcessing(cancel); }

        private async Task BackgroundProcessing(CancellationToken cancel) {
            while (!cancel.IsCancellationRequested) {
                try {
                    await Task.Delay(1000,cancel);
                    bool ok = q.q.TryDequeue(out var item);
                    if (!ok) { continue; }
                    L.LogInformation($"item found! {item}");
                    await treatItemScope(item);
                } catch (Exception ex) {
                    L.LogCritical("An error occurred when processing. Exception: {@Exception}", ex);
                }
            }
        }

        private async Task<bool> treatItemScope(QueueItem Qitem) {
            using (var scope = scopeFactory.CreateScope()) {
                var ris = scope.ServiceProvider.GetRequiredService<IRevisionIntegrationService>();
                return await treatItem(Qitem, ris);
            }
        }

        private async Task<bool> treatItem(QueueItem Qitem, IRevisionIntegrationService ris) {
            await Task.Delay(0);
            L.LogWarning($"TryAddValue from P {Qitem.sessionId}");
            bool addOK = q.p.TryAdd(Qitem.sessionId, Qitem);
            if (!addOK) {
                L.LogError($"why couldnt we add session {Qitem.sessionId} to processing-queue?");
                return false;
            }

            var startTime = DateTime.UtcNow;
            Guid revisionId = Qitem.revisionId;

            string[] filePaths = getFilePaths(Qitem.sessionId);

            Stream[] streams = filePaths.Select(fileName => new FileStream(fileName, FileMode.Open)).ToArray();
            MyMultiStream multiStream = new MyMultiStream(filePaths, streams, this.L, Qitem);
            BimRevisionStatus brs = await ris.UploadRevision(revisionId, multiStream, startTime);
            // (launchDeletes is my current hack/workaround,
            // it is not part of the problem)
            // await multiStream.launchDeletes();
            Qitem.status = brs;
            return true;
        }
..
</code>```

Body:
I get error

System.IO.IOException: 'The process cannot access the file 'xxx' because it is being used by another process.'

when I try to delete a temp file in a background worker service in aspnet core.
I am eventually allowed to delete the file after about a minute (52s, 73s).
If I change garbage collection to workstation mode, I may instead delete after ~1s (but still, a delay).

I have tried a combination of FileOptions to no avail, including FileOptions.WriteThrough.

When the controller writes the file, I use
FlushAsync(), Close(), Dispose() and 'using' (I know it's overkill.)
I also tried using just File.WriteAllBytesAsync, with same result.

In the background reader, I as well use Close() and Dispose().
(hint: background reader will not allow me to use DeleteOnClose,
which would have been ideal.)

As I search stackoverflow for similar 'used by another process' issues,
all those I have found eventually resolve to
'argh it turns out I/he still had an extra open instance/reference
he forgot about',
but I have not been able to figure out that I am doing that.

Another hint:
In the writing controller, I am able to delete the file immediately
after writing it, I presume because I am still on the same thread?

Is there some secret knowledge I should read somewhere,
about being able to delete recently open files, across threads?

UPDATE: Here relevant(?) code snippets:

// (AspNet Controller)
        [RequestSizeLimit(9999999999)]
        [DisableFormValueModelBinding]
        [RequestFormLimits(MultipartBodyLengthLimit = MaxFileSize)]
        [HttpPost("{sessionId}")]
        public async Task<IActionResult> UploadRevisionChunk(Guid sessionId) {
            log.LogWarning($"UploadRevisionChunk: {sessionId}");
            string uploadFolder = UploadFolder.sessionFolderPath(sessionId);
            if (!Directory.Exists(uploadFolder)) { throw new Exception($"chunk-upload failed"); }
            var cr = parseContentRange(Request);
            if (cr == null) { return this.BadRequest("no content range header specified"); }
            string chunkName = $"{cr.From}-{cr.To}";
            string saveChunkPath = Path.Combine(uploadFolder,chunkName);
            await streamToChunkFile_WAB(saveChunkPath); // write-all-bytes.
            //await streamToChunkFile_MAN(saveChunkPath); // Manual.
            long crTo   = cr.To ?? 0;
            long crFrom = cr.From ?? 0;
            long expected = (crTo - crFrom) + 1;
            var fi = new FileInfo(saveChunkPath);
            var dto = new ChunkResponse { wrote = fi.Length, expected = expected, where = "?" };
            string msg = $"at {crFrom}, wrote {dto.wrote} bytes (expected {dto.expected}) to {dto.where}";
            log.LogWarning(msg);
            return Ok(dto);
        }
        private async Task streamToChunkFile_WAB(string saveChunkPath) {
            using (MemoryStream ms = new MemoryStream()) {
                Request.Body.CopyTo(ms);
                byte[] allBytes = ms.ToArray();
                await System.IO.File.WriteAllBytesAsync(saveChunkPath, allBytes);
            }
        }

// stream reader in the backgroundService:
    public class MyMultiStream : Stream {
        string[] filePaths;
        FileStream curStream = null;
        IEnumerator<string> i;
        ILogger log;
        QueueItem qItem;

        public MyMultiStream(string[] filePaths_, Stream[] streams_, ILogger log_, QueueItem qItem_) {
            qItem = qItem_;
            log = log_;
            filePaths = filePaths_;

            log.LogWarning($"filepaths has #items: {filePaths.Length}");
            IEnumerable<string> enumerable = filePaths;
            i = enumerable.GetEnumerator();
            i.MoveNext();// necessary to prime the iterator.
        }

        public override bool CanRead { get { return true; } }
        public override bool CanWrite { get { return false; } }
        public override bool CanSeek { get { return false; } }
        public override long Length { get { throw new Exception("dont get length"); } }
        public override long Position {
            get { throw new Exception("dont get Position"); }
            set { throw new Exception("dont set Position"); }
        }
        public override void SetLength(long value) { throw new Exception("dont set length"); }
        public override long Seek(long offset, SeekOrigin origin) { throw new Exception("dont seek"); }
        public override void Write(byte[] buffer, int offset, int count) { throw new Exception("dont write"); }
        public override void Flush() { throw new Exception("dont flush"); }

        public static int openStreamCounter = 0;
        public static int closedStreamCounter = 0;
        string curFileName = "?";
        private FileStream getNextStream() {
            string nextFileName = i.Current;
            if (nextFileName == null) { throw new Exception("getNextStream should not be called past file list"); }
            //tryDelete(nextFileName,log);
            FileStream nextStream = new FileStream(
                path:nextFileName,
                mode: FileMode.Open,
                access: FileAccess.Read,
                share: FileShare.ReadWrite| FileShare.Delete,
                bufferSize:4096, // apparently default.
                options: 0
                | FileOptions.Asynchronous
                | FileOptions.SequentialScan
                // | FileOptions.DeleteOnClose // (1) this ought to be possible, (2) we should fix this approach (3) if we can fix this, our issue is solved, and our code much simpler.
            ); // None); // ReadWrite); // None); // ReadWrite); //| FileShare.Read);
            log.LogWarning($"TELLUS making new stream [{nextFileName}] opened:[{++openStreamCounter}] closed:[{closedStreamCounter}]");

            curFileName = nextFileName;
            ++qItem.chunkCount;
            return nextStream;
        }

        public override int Read(byte[] buffer, int offset, int count) {
            int bytesRead = 0;
            while (true) {
                bytesRead = 0;
                if (curStream == null) { curStream = getNextStream(); }
                try {
                    bytesRead = curStream.Read(buffer, offset, count);
                    log.LogWarning($"..bytesRead:{bytesRead} [{Path.GetFileName(curFileName)}]"); // (only show a short name.)
                } catch (Exception e) {
                    log.LogError($"failed reading [{curFileName}] [{e.Message}]",e);
                }
                if (bytesRead > 0) { break; }

                curStream.Close();
                curStream.Dispose();
                curStream = null;
                log.LogWarning($"TELLUS closing stream [{curFileName}] opened:[{openStreamCounter}] closed:[{++closedStreamCounter}]");
                //tryDelete(curFileName); Presumably we can't delete so soon.
                bool moreFileNames = i.MoveNext();
                log.LogWarning($"moreFileNames?{moreFileNames}");
                if (!moreFileNames) {
                    break;
                }
            }
            return bytesRead;
        }

..
// Background worker operating multistream:
    public class BackgroundChunkWorker: BackgroundService {
        ILogger L;
        ChunkUploadQueue q;

        public readonly IServiceScopeFactory scopeFactory;

        public BackgroundChunkWorker(ILogger<int> log_, ChunkUploadQueue q_, IServiceScopeFactory scopeFactory_) {
            q = q_; L = log_;
            scopeFactory = scopeFactory_;
        }

        override protected async Task ExecuteAsync(CancellationToken cancel) { await BackgroundProcessing(cancel); }

        private async Task BackgroundProcessing(CancellationToken cancel) {
            while (!cancel.IsCancellationRequested) {
                try {
                    await Task.Delay(1000,cancel);
                    bool ok = q.q.TryDequeue(out var item);
                    if (!ok) { continue; }
                    L.LogInformation($"item found! {item}");
                    await treatItemScope(item);
                } catch (Exception ex) {
                    L.LogCritical("An error occurred when processing. Exception: {@Exception}", ex);
                }
            }
        }

        private async Task<bool> treatItemScope(QueueItem Qitem) {
            using (var scope = scopeFactory.CreateScope()) {
                var ris = scope.ServiceProvider.GetRequiredService<IRevisionIntegrationService>();
                return await treatItem(Qitem, ris);
            }
        }

        private async Task<bool> treatItem(QueueItem Qitem, IRevisionIntegrationService ris) {
            await Task.Delay(0);
            L.LogWarning($"TryAddValue from P {Qitem.sessionId}");
            bool addOK = q.p.TryAdd(Qitem.sessionId, Qitem);
            if (!addOK) {
                L.LogError($"why couldnt we add session {Qitem.sessionId} to processing-queue?");
                return false;
            }

            var startTime = DateTime.UtcNow;
            Guid revisionId = Qitem.revisionId;

            string[] filePaths = getFilePaths(Qitem.sessionId);

            Stream[] streams = filePaths.Select(fileName => new FileStream(fileName, FileMode.Open)).ToArray();
            MyMultiStream multiStream = new MyMultiStream(filePaths, streams, this.L, Qitem);
            BimRevisionStatus brs = await ris.UploadRevision(revisionId, multiStream, startTime);
            // (launchDeletes is my current hack/workaround,
            // it is not part of the problem)
            // await multiStream.launchDeletes();
            Qitem.status = brs;
            return true;
        }
..


问:
PancakeSwap Response is encoded
I want to get the output amount of a Swap on PancakeSwap ( https://pancakeswap.finance/swap ) automatically.

For example:

Fist token = BNB

Second token = CAKE

When I fill out the BNB amount in the first field, in the second one I get the CAKE amount. I want to get that value from the response.

I found the response (at least I think) but it is encrypted somehow.

I'm not sure if that's the correct request. I also tried to check the WebSockets because it's updated in real-time. Without success. If someone has an idea about how to get it, please let me know.

Title: PancakeSwap Response is encoded


问:
.net Core C# Linux Copy Windows File Permissions (ACL)
I am running a .net Core 3.1 application on a Debian 10 Server. The application has to copy a given Windows source Directory to a Windows network drive. When copying the files and Directories, it has to set the Destination Files and Directories acl to the Source acl.

I tried doing this using Mono.Unix. To access the Windows Network drive on Linux, I mounted to a Diretory in /media.

```<code>// get Source Directories Info
var unixSrcDirInfo = new Mono.Unix.UnixDirectoryInfo(dir.FullName);

//get Destination Directory info
var unixDestDirInfo = new Mono.Unix.UnixDirectoryInfo(destinationDir);

//set Destination Directory File Permissions to Source Directory File Permission
unixDestDirInfo.FileAccessPermissions = unixSrcDirInfo.FileAccessPermissions;

unixDestDirInfo.Refresh();
</code>```

Does somebody have an Idea how to copy the ACL of a file on a Linux Machine?

I tried using System.IO.FileSystem.AccessControl, but that's not allowed on Linux. I tried using Mono.Unix, but it doesn't copy the permissions.

I just want to set the Destination Directorys ACL to the Source Directorys ACL.

Body:
I am running a .net Core 3.1 application on a Debian 10 Server. The application has to copy a given Windows source Directory to a Windows network drive. When copying the files and Directories, it has to set the Destination Files and Directories acl to the Source acl.

I tried doing this using Mono.Unix. To access the Windows Network drive on Linux, I mounted to a Diretory in /media.

// get Source Directories Info
var unixSrcDirInfo = new Mono.Unix.UnixDirectoryInfo(dir.FullName);

//get Destination Directory info
var unixDestDirInfo = new Mono.Unix.UnixDirectoryInfo(destinationDir);

//set Destination Directory File Permissions to Source Directory File Permission
unixDestDirInfo.FileAccessPermissions = unixSrcDirInfo.FileAccessPermissions;

unixDestDirInfo.Refresh();

Does somebody have an Idea how to copy the ACL of a file on a Linux Machine?

I tried using System.IO.FileSystem.AccessControl, but that's not allowed on Linux. I tried using Mono.Unix, but it doesn't copy the permissions.

I just want to set the Destination Directorys ACL to the Source Directorys ACL.


问:
How to toggle bookmark in current file
I usually used bookmark in Android Studio and

when I use short cut to next bookmark or previous bookmark, will only be on current file.

But now in Android Studio new version, it will go to bookmark in other file, what a annoying change.

how to change it back? thanks for help.

Title: How to toggle bookmark in current file