问:
TypeError: unsupported operand type(s) for +: 'set' and 'set' returning multiple param vals
I'm kinda beginner using python from javascript, and wanting to return param vals together into an api... I've been trying to use + though it give's me error

"TypeError: unsupported operand type(s) for +: 'set' and 'set'"

How do correcting this?

def generate_ad(product_type: str, product_name: str, platform: str, audience: str) -> str:
    # Load your API key from an environment variable or secret management service
    product_type = f'Write a creative ad for {product_type} '
    product_name = f'named {product_name}'
    platform = f'to run on {platform} '
    audience = f'aimed at {audience}:'

    enriched_prompt = product_type + product_name + platform + audience```
</div>
</div>
</p>
<p>test API call:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>from fastapi import FastAPI
from riplir import generate_ad

app = FastAPI()

@app.get("/generate_snippet")
async def creative_ad_api(product_type: str, product_name: str , platform: str, audience: str):
    snippet = generate_ad({product_type} + {product_name} + {platform} + {audience})

    return {
        "message": snippet,
        }

# uvicorn riplir_api:app --reload</code>```

答:
Either the generate_ad function input is a string, which you can build using f-string:

```<code>@app.get("/generate_snippet")
async def creative_ad_api(product_type: str,
                          product_name: str,
                          platform: str,
                          audience: str):
    snippet = generate_ad(f'{product_type} + {product_name} + {platform} + {audience}')

    return {
    "message": snippet,
    }
</code>```

Or the input is a set, which can be built from the 4 string parameters:

```<code>@app.get("/generate_snippet")
async def creative_ad_api(product_type: str,
                          product_name: str,
                          platform: str,
                          audience: str):
    snippet = generate_ad(set(product_type, product_name, platform, audience))

    return {
    "message": snippet,
    }
</code>```

Or simply, you have 4 inputs:

```<code>@app.get("/generate_snippet")
async def creative_ad_api(product_type: str,
                          product_name: str,
                          platform: str,
                          audience: str):
    snippet = generate_ad(product_type, product_name, platform, audience)

    return {
    "message": snippet,
    }
</code>```

Body:
I'm kinda beginner using python from javascript, and wanting to return param vals together into an api... I've been trying to use + though it give's me error

"TypeError: unsupported operand type(s) for +: 'set' and 'set'"

How do correcting this?

def generate_ad(product_type: str, product_name: str, platform: str, audience: str) -> str:
    # Load your API key from an environment variable or secret management service
    product_type = f'Write a creative ad for {product_type} '
    product_name = f'named {product_name}'
    platform = f'to run on {platform} '
    audience = f'aimed at {audience}:'

    enriched_prompt = product_type + product_name + platform + audience

test API call:

from fastapi import FastAPI
from riplir import generate_ad

app = FastAPI()

@app.get("/generate_snippet")
async def creative_ad_api(product_type: str, product_name: str , platform: str, audience: str):
    snippet = generate_ad({product_type} + {product_name} + {platform} + {audience})

    return {
        "message": snippet,
        }

# uvicorn riplir_api:app --reload

Body:
Either the generate_ad function input is a string, which you can build using f-string:

@app.get("/generate_snippet")
async def creative_ad_api(product_type: str,
                          product_name: str,
                          platform: str,
                          audience: str):
    snippet = generate_ad(f'{product_type} + {product_name} + {platform} + {audience}')

    return {
    "message": snippet,
    }

Or the input is a set, which can be built from the 4 string parameters:

@app.get("/generate_snippet")
async def creative_ad_api(product_type: str,
                          product_name: str,
                          platform: str,
                          audience: str):
    snippet = generate_ad(set(product_type, product_name, platform, audience))

    return {
    "message": snippet,
    }

Or simply, you have 4 inputs:

@app.get("/generate_snippet")
async def creative_ad_api(product_type: str,
                          product_name: str,
                          platform: str,
                          audience: str):
    snippet = generate_ad(product_type, product_name, platform, audience)

    return {
    "message": snippet,
    }


来源: stackexchange

问:
Seam conditional render without parsing
I'm trying to make a conditional render in my Seam application (2.2.0), to display two different controls depending on a condition.

I'm using the s:fragment tag with the render attribute, but my problem is that I want whatever the control is displayed, to have the same id:

```<code><s:fragment render="${editable}">
  <rich:calendar id="entityDate"..../>
</s:fragment>
<s:fragment render="${!editable}">
  <h:outputText id="entityDate".../>
</s:fragment>
</code>```

My problem is that even when the render attribute set to false, the "not to be rendered" element is parsed, and I get an exception because of the duplicated id.

I also tried with the tag <ui:remove>, which effectively removes the element before the parsing phase, so I can have something like:

```<code><span id="myId"/>
<ui:remove>
  <span id="myId"/>
</ui:remove>
</code>```

Unfortunately the <ui:remove> tag doesn't allow conditional logic. Has anyone found a way to solve this?

答:
"Solve"? There is nothing to solve here: two elements in a GUI can not have the same ID. Hardly unnatural or unsound?

It's like asking: "I have a database table with two rows, I would like them both to have the same primary key value, but somehow I get these errors... has anyone managed to solve the problem and circumvent the constraints?".

Or even closer analogy: "I have two spans, one of them is invisible (has style="display: none") I would like them both to have the same id - and browsers seem not to like it, despite one of the spans being invisible".

Bottom line: rendered on not rendered, each component is still a part of the view tree, and therefore has a UNIQUE id.

I have a suspicion that you want to have some "polymorphic" code that should work with the currently visible element. Using ID for such code IS WRONG. If you show us your use case, we might find a right way to achieve the effect.

ContentLicense: CC BY-SA 3.0

Title: Seam conditional render without parsing

Body:
I'm trying to make a conditional render in my Seam application (2.2.0), to display two different controls depending on a condition.

I'm using the s:fragment tag with the render attribute, but my problem is that I want whatever the control is displayed, to have the same id:

<s:fragment render="${editable}">
  <rich:calendar id="entityDate"..../>
</s:fragment>
<s:fragment render="${!editable}">
  <h:outputText id="entityDate".../>
</s:fragment>

My problem is that even when the render attribute set to false, the "not to be rendered" element is parsed, and I get an exception because of the duplicated id.

I also tried with the tag <ui:remove>, which effectively removes the element before the parsing phase, so I can have something like:

<ui:remove>

</ui:remove>

Unfortunately the <ui:remove> tag doesn't allow conditional logic. Has anyone found a way to solve this?


问:
Ansible module to stop and start `ssh` service
Question:

This scenario is used to explain the usage of modules in Ansible.

For this you have to stop and start a service named ssh.

Tasks to be done:- Write a task in main.yml file present in fresco_module\tasks folder.

The task is to stop and start the service named ssh using the service module in Ansible.

Note:

Run project install to install ansible.mainplaybook.yml file is provided to ansible-playbook.

Use the localhost for the inventory for ansible-playbook.

My Code:

- hosts: localhost
  become: yes
  tasks:
  - name: Stop and Start ssh
    service:
      name: ssh
      state: "{{ item }}"
    with_items:
      - stopped
      - started
```
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>PLAY [localhost] *******************************************************************************

TASK [Gathering Facts] *************************************************************************
[DEPRECATION WARNING]: Distribution Ubuntu 16.04 on host localhost should use /usr/bin/python3,
 but is using /usr/bin/python for backward compatibility with prior Ansible releases. A future
Ansible release will default to using the discovered platform python for this host. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more
information. This feature will be removed in version 2.12. Deprecation warnings can be disabled
 by setting deprecation_warnings=False in ansible.cfg.
ok: [localhost]

TASK [Stop and Start ssh] **********************************************************************
changed: [localhost] => (item=stopped)
ok: [localhost] => (item=started)

PLAY RECAP *************************************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
</code>```

Issue: The service is already running after Ansible stopped it, which looks like sshd was never stopped in the first place.

Command used to check the status: service ssh status. I used this command with state:stopped also but the sshd is still running. I have been facing this issue for so long. I tried with state:restarted also.

答:
On AWS EC2 instances the ssh service is sshd.

```<code>- name: restart ssh daemon
  hosts: all
  remote_user: ec2-user
  become: yes
  become_method: sudo
  tasks:
  - name: Stop and Start ssh
    service:
      name: sshd
      state: restarted
</code>```

In the above YAML, replacing sshd with ssh will fail with "msg": "Could not find the requested service ssh

ContentLicense: CC BY-SA 4.0

Body:
Question:

This scenario is used to explain the usage of modules in Ansible.

For this you have to stop and start a service named ssh.

Tasks to be done:- Write a task in main.yml file present in fresco_module\tasks folder.

The task is to stop and start the service named ssh using the service module in Ansible.

Note:

Run project install to install ansible.mainplaybook.yml file is provided to ansible-playbook.

Use the localhost for the inventory for ansible-playbook.

My Code:

- hosts: localhost
  become: yes
  tasks:
  - name: Stop and Start ssh
    service:
      name: ssh
      state: "{{ item }}"
    with_items:
      - stopped
      - started

Output:

PLAY [localhost] *******************************************************************************

TASK [Gathering Facts] *************************************************************************
[DEPRECATION WARNING]: Distribution Ubuntu 16.04 on host localhost should use /usr/bin/python3,
 but is using /usr/bin/python for backward compatibility with prior Ansible releases. A future
Ansible release will default to using the discovered platform python for this host. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more
information. This feature will be removed in version 2.12. Deprecation warnings can be disabled
 by setting deprecation_warnings=False in ansible.cfg.
ok: [localhost]

TASK [Stop and Start ssh] **********************************************************************
changed: [localhost] => (item=stopped)
ok: [localhost] => (item=started)

PLAY RECAP *************************************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Issue: The service is already running after Ansible stopped it, which looks like sshd was never stopped in the first place.

Command used to check the status: service ssh status. I used this command with state:stopped also but the sshd is still running. I have been facing this issue for so long. I tried with state:restarted also.

Body:
On AWS EC2 instances the ssh service is sshd.

- name: restart ssh daemon
  hosts: all
  remote_user: ec2-user
  become: yes
  become_method: sudo
  tasks:
  - name: Stop and Start ssh
    service:
      name: sshd
      state: restarted

In the above YAML, replacing sshd with ssh will fail with "msg": "Could not find the requested service ssh


问:
error TS2769: No overload matches this call. when implementing a model in angular
I am running into an error when implementing a model in angular:

the component.ts:

```<code>import { Component, OnInit } from '@angular/core';
import { DamageAssessmentReportService } from 'src/app/damage-assessment-report.service';
import { Router } from '@angular/router';
import { Report } from 'src/app/models/report.model';

@Component({
  selector: 'app-fa-daform',
  templateUrl: './fa-daform.component.html',
  styleUrls: ['./fa-daform.component.css']
})
export class FADAFormComponent implements OnInit {

  constructor(private damageAssessmentReportService : DamageAssessmentReportService, private router: Router) { }

  createDamageAssessmentReport(assessmentDescription: string, author: string, reportDateString: string){

    const reportDateTime = new Date(reportDateString);
    this.damageAssessmentReportService.createDAReport(assessmentDescription,author, reportDateTime).subscribe((report : Report)=>{
      console.log(report);
      //navigate to /damageAssessments/damageAssessments._id
      this.router.navigate(['/detailed-daforms', report._id])
  })
  }

  ngOnInit(): void {
  }

  }
</code>```

and the model.ts:

```<code>export class Report{
    _id: string ="";
    assessmentDescription: string = "";
    author: string = "";
    reportDateTime: Date = new Date("");
}
</code>```

The error presented:

error TS2769: No overload matches this call.   Overload 1 of 3,
'(observer?: Partial<Observer> | undefined): Subscription',
gave the following error.
Type '(report: Report) => void' has no properties in common with type 'Partial<Observer>'.   Overload 2 of 3, '(next: (value:
Object) => void): Subscription', gave the following error.
Argument of type '(report: Report) => void' is not assignable to parameter of type '(value: Object) => void'.
Types of parameters 'report' and 'value' are incompatible.
The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
Type 'Object' is missing the following properties from type 'Report': _id, assessmentDescription, author, reportDateTime

Overload 3 of 3, '(next?: ((value: Object) => void) | null |
undefined, error?: ((error: any) => void) | null | undefined,
complete?: (() => void) | null | undefined): Subscription', gave the
following error.
Argument of type '(report: Report) => void' is not assignable to parameter of type '(value: Object) => void'.
Types of parameters 'report' and 'value' are incompatible.
Type 'Object' is not assignable to type 'Report'.
The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?

22

this.damageAssessmentReportService.createDAReport(assessmentDescription,author,
reportDateTime).subscribe((report : Report)=>{

```<code>                                     ~~~~~~~~~~~~~~~~~~~~
</code>```

× Failed to compile.

createDAReport method from DamageAssessmentReportService

```<code>createDAReport(assessmentDescription: string, author: string, reportDateTime: Date){
    //send web req to create DA report
    return this.webReqService.post('DamageAssessments', {assessmentDescription, author, reportDateTime})
  }
</code>```

webReqService:

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class WebRequestService {

  readonly ROOT_URL;

  constructor(private http: HttpClient) {
    this.ROOT_URL= 'http://localhost:3000';
  }

  get(uri: string) {
    return this.http.get(`${this.ROOT_URL}/${uri}`)
  }

</code>```

post(uri: string, payload: Object) {
return this.http.post(${this.ROOT_URL}/${uri}, payload);
}

patch(uri: string, payload: Object) {
return this.http.patch(${this.ROOT_URL}/${uri}, payload);
}

delete(uri: string) {
return this.http.delete(${this.ROOT_URL}/${uri});
}

}

答:
From the existing code and error message, as you want to get the Observable of T, would suggest you use Overload #15 for Angular - HttpClient (Post) by specifying the T type.

post<T>(url: string, body: any, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<T>
```
<blockquote>
<p>WebRequestService</p>
</blockquote>
<p>You can do similar as what Angular handle for HttpClient methods, by using function overloading.</p>
<pre class="lang-js prettyprint-override"><code>post<T>(uri: string, payload: Object): Observable<T>;
post(uri: string, payload: Object): Observable<any> {
  return this.http.post<any>(`${this.ROOT_URL}/${uri}`, payload);
}
</code>```

DamageAssessmentReportService

createDAReport(assessmentDescription: string, author: string, reportDateTime: Date): Observable<Report>{
  //send web req to create DA report
  return this.webReqService.post<Report>('DamageAssessments', {assessmentDescription, author, reportDateTime})
}
```

Body:
I am running into an error when implementing a model in angular:

the component.ts:

import { Component, OnInit } from '@angular/core';
import { DamageAssessmentReportService } from 'src/app/damage-assessment-report.service';
import { Router } from '@angular/router';
import { Report } from 'src/app/models/report.model';

@Component({
  selector: 'app-fa-daform',
  templateUrl: './fa-daform.component.html',
  styleUrls: ['./fa-daform.component.css']
})
export class FADAFormComponent implements OnInit {

  constructor(private damageAssessmentReportService : DamageAssessmentReportService, private router: Router) { }

  createDamageAssessmentReport(assessmentDescription: string, author: string, reportDateString: string){

    const reportDateTime = new Date(reportDateString);
    this.damageAssessmentReportService.createDAReport(assessmentDescription,author, reportDateTime).subscribe((report : Report)=>{
      console.log(report);
      //navigate to /damageAssessments/damageAssessments._id
      this.router.navigate(['/detailed-daforms', report._id])
  })
  }

  ngOnInit(): void {
  }

  }

and the model.ts:

export class Report{
    _id: string ="";
    assessmentDescription: string = "";
    author: string = "";
    reportDateTime: Date = new Date("");
}

The error presented:

error TS2769: No overload matches this call.   Overload 1 of 3,
'(observer?: Partial<Observer> | undefined): Subscription',
gave the following error.
Type '(report: Report) => void' has no properties in common with type 'Partial<Observer>'.   Overload 2 of 3, '(next: (value:
Object) => void): Subscription', gave the following error.
Argument of type '(report: Report) => void' is not assignable to parameter of type '(value: Object) => void'.
Types of parameters 'report' and 'value' are incompatible.
The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
Type 'Object' is missing the following properties from type 'Report': _id, assessmentDescription, author, reportDateTime

Overload 3 of 3, '(next?: ((value: Object) => void) | null |
undefined, error?: ((error: any) => void) | null | undefined,
complete?: (() => void) | null | undefined): Subscription', gave the
following error.
Argument of type '(report: Report) => void' is not assignable to parameter of type '(value: Object) => void'.
Types of parameters 'report' and 'value' are incompatible.
Type 'Object' is not assignable to type 'Report'.
The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?

22

this.damageAssessmentReportService.createDAReport(assessmentDescription,author,
reportDateTime).subscribe((report : Report)=>{

                                     ~~~~~~~~~~~~~~~~~~~~

× Failed to compile.

createDAReport method from DamageAssessmentReportService

createDAReport(assessmentDescription: string, author: string, reportDateTime: Date){
    //send web req to create DA report
    return this.webReqService.post('DamageAssessments', {assessmentDescription, author, reportDateTime})
  }

webReqService:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class WebRequestService {

  readonly ROOT_URL;

  constructor(private http: HttpClient) {
    this.ROOT_URL= 'http://localhost:3000';
  }

  get(uri: string) {
    return this.http.get(`${this.ROOT_URL}/${uri}`)
  }

post(uri: string, payload: Object) {
return this.http.post(${this.ROOT_URL}/${uri}, payload);
}

patch(uri: string, payload: Object) {
return this.http.patch(${this.ROOT_URL}/${uri}, payload);
}

delete(uri: string) {
return this.http.delete(${this.ROOT_URL}/${uri});
}

}

Body:
From the existing code and error message, as you want to get the Observable of T, would suggest you use Overload #15 for Angular - HttpClient (Post) by specifying the T type.

post<T>(url: string, body: any, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<T>

WebRequestService

You can do similar as what Angular handle for HttpClient methods, by using function overloading.

post<T>(uri: string, payload: Object): Observable<T>;
post(uri: string, payload: Object): Observable<any> {
  return this.http.post<any>(`${this.ROOT_URL}/${uri}`, payload);
}

DamageAssessmentReportService

createDAReport(assessmentDescription: string, author: string, reportDateTime: Date): Observable<Report>{
  //send web req to create DA report
  return this.webReqService.post<Report>('DamageAssessments', {assessmentDescription, author, reportDateTime})
}


问:
.NET MAUI Data binding and MVVM
This seems so straightforward, but i can't get it to working properly. The simplest MAUI app with a Label binding to "CountDisplay" and a Button binding to "IncreaseCount". The Command binding works, the Label binding reads the first time its value but then never refreshes. What i'm doing wrong ? Thanks for any help.

MainPage.xaml

```<code><ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="MauiApp1.MainPage"
         BackgroundColor="{DynamicResource SecondaryColor}">

<ScrollView>
    <Grid RowSpacing="25" RowDefinitions="Auto,Auto,Auto,Auto,*"
          Padding="{OnPlatform iOS='30,60,30,30', Default='30'}">

         <Label
            Text="{Binding CountDisplay}"
            Grid.Row="2"
            FontSize="18"
            FontAttributes="Bold"
            HorizontalOptions="Center"
            />

        <Button
            Text="Click me"
            FontAttributes="Bold"
            Grid.Row="3"
            SemanticProperties.Hint="Counts the number of times you click"
            Command="{Binding IncreaseCount}"
            HorizontalOptions="Center" />

    </Grid>

</ScrollView>
</code>```

MainPageViewModel.cs

```<code>public class MainPageViewModel:BindableObject
{
    public MainPageViewModel()
    {
        IncreaseCount = new Command(OnIncrease);
    }
    public ICommand IncreaseCount { get; }

    int count = 0;
    string countDisplay = "Click Me()!";

    public string CountDisplay
    {
        get { return countDisplay; }

        set
        {
            if (value == countDisplay)
                return;

            countDisplay = value;
            OnPropertyChanged();

        }
    }

    void OnIncrease()
    {
        count++;
        countDisplay = $"Current count: {count}";
    }
}
</code>```

答:
you are setting the private variable (lowercase "c")

```<code>void OnIncrease()
{
    count++;
    countDisplay = $"Current count: {count}";
}
</code>```

instead, you need to set the public property (upper case "C"), otherwise OnPropertyChanged is not called

```<code>void OnIncrease()
{
    count++;
    CountDisplay = $"Current count: {count}";
}
</code>```

a popular convention is to name the private variable with an _ so that the two names are harder to mix up (_countDisplay and CountDisplay)

Title: .NET MAUI Data binding and MVVM

Body:
This seems so straightforward, but i can't get it to working properly. The simplest MAUI app with a Label binding to "CountDisplay" and a Button binding to "IncreaseCount". The Command binding works, the Label binding reads the first time its value but then never refreshes. What i'm doing wrong ? Thanks for any help.

MainPage.xaml

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="MauiApp1.MainPage"
         BackgroundColor="{DynamicResource SecondaryColor}">

<ScrollView>
    <Grid RowSpacing="25" RowDefinitions="Auto,Auto,Auto,Auto,*"
          Padding="{OnPlatform iOS='30,60,30,30', Default='30'}">

        <Button
            Text="Click me"
            FontAttributes="Bold"
            Grid.Row="3"
            SemanticProperties.Hint="Counts the number of times you click"
            Command="{Binding IncreaseCount}"
            HorizontalOptions="Center" />

    </Grid>

</ScrollView>

MainPageViewModel.cs

public class MainPageViewModel:BindableObject
{
    public MainPageViewModel()
    {
        IncreaseCount = new Command(OnIncrease);
    }
    public ICommand IncreaseCount { get; }

    int count = 0;
    string countDisplay = "Click Me()!";

    public string CountDisplay
    {
        get { return countDisplay; }

        set
        {
            if (value == countDisplay)
                return;

            countDisplay = value;
            OnPropertyChanged();

        }
    }

    void OnIncrease()
    {
        count++;
        countDisplay = $"Current count: {count}";
    }
}

Body:
you are setting the private variable (lowercase "c")

void OnIncrease()
{
    count++;
    countDisplay = $"Current count: {count}";
}

instead, you need to set the public property (upper case "C"), otherwise OnPropertyChanged is not called

void OnIncrease()
{
    count++;
    CountDisplay = $"Current count: {count}";
}

a popular convention is to name the private variable with an _ so that the two names are harder to mix up (_countDisplay and CountDisplay)


问:
How to remove the DataTable's Row without using loops?
I have one datatable which has

DataTable:

```<code>         SeqNo        ItemID        ItemName
        -------       ------        --------
           1            10           AAA
           2            20           BBB
           3            30           CCC
</code>```

Now I want to remove the Row which has the SeqNo "3".

Now I am doing like this in GridView RowCommand Event:

```<code>    if (e.CommandName == "Delete")
        {
            string SeqNo = e.CommandArgument.ToString();
            for (int i = 0; i < DTItem.Rows.Count; i++)
            {
                if (SeqNo == DTItem.Rows[i]["SeqNo"].ToString())
                {
                    DTItem.Rows.Remove(DTItem.Rows[i]);
                }
            }
        }
</code>```

But without loops, How to remove the row based on this condition?

答:
If you are sure that there is only one and definitely one occurrence of the row you can achieve that as following</p>

```<code>dt1.Rows.Remove(dt1.Select("SeqNo= 3")[0]);
</code>```

Body:
I have one datatable which has

DataTable:

         SeqNo        ItemID        ItemName
        -------       ------        --------
           1            10           AAA
           2            20           BBB
           3            30           CCC

Now I want to remove the Row which has the SeqNo "3".

Now I am doing like this in GridView RowCommand Event:

    if (e.CommandName == "Delete")
        {
            string SeqNo = e.CommandArgument.ToString();
            for (int i = 0; i < DTItem.Rows.Count; i++)
            {
                if (SeqNo == DTItem.Rows[i]["SeqNo"].ToString())
                {
                    DTItem.Rows.Remove(DTItem.Rows[i]);
                }
            }
        }

But without loops, How to remove the row based on this condition?

Body:
If you are sure that there is only one and definitely one occurrence of the row you can achieve that as following

dt1.Rows.Remove(dt1.Select("SeqNo= 3")[0]);


问:
Split a string column and put the splits in different columns
```<code>import pandas as pd
df = pd.read_csv("product_2022-02-10.csv")
df["primary_category_name_en"]
</code>```

Result:

```<code>primary_category_name_en
Gadgets & Electronics > Desktop Computer & Computer Accessories > Connecting Cable & Unit Convertor > Lan Line
Electrical Appliances > Other Small Home Appliances & Accessories > Drill & Extension Cord & Battery > Battery & Battery Charger > Other Battery
Housewares > Hardware & Tools > Metal Tools & Hardware Tools > Switch
Electrical Appliances > Smart Home > Smart Extension Cord
</code>```

How can I split by > and put it back to different columns?

I know how to split it. df["primary_category_name_en”].str.split(">")

There are some only 3 categories in a row / 4 categories in a row / 5 categories in a row. I don't know how to solve the problem in this.

For example:

```<code>ROW 1:
df["Primary_category_1"] = "Gadgets & Electronics"
df["Primary_category_2"] = "Desktop Computer & Computer Accessories"
df["Primary_category_3"] = "Connecting Cable & Unit Convertor"
df["Primary_category_4"] = "Lan Line"

ROW 2:
df["Primary_category_1"] = "Electrical Appliances"
df["Primary_category_2"] = "Other Small Home Appliances & Accessories"
df["Primary_category_3"] = "Drill & Extension Cord & Battery"
df["Primary_category_4"] = "Battery & Battery Charger"
df["Primary_category_5"] = "Other Battery"

ROW 3:
...

ROW4:
...
</code>```

答:
Try using .str.split with expand=True:

```<code>split = df['primary_category_name_en'].str.split(' > ', expand=True).pipe(lambda x: x.set_axis(x.columns + 1, axis=1)).add_prefix('Primary_category_').fillna('')
</code>```

Output:

```<code>>>> split
      Primary_category_1                         Primary_category_2                 Primary_category_3         Primary_category_4 Primary_category_5
0  Gadgets & Electronics    Desktop Computer & Computer Accessories  Connecting Cable & Unit Convertor                   Lan Line
1  Electrical Appliances  Other Small Home Appliances & Accessories   Drill & Extension Cord & Battery  Battery & Battery Charger      Other Battery
2             Housewares                           Hardware & Tools       Metal Tools & Hardware Tools                     Switch
3  Electrical Appliances                                 Smart Home               Smart Extension Cord
</code>```

To add it back to your original dataframe, use pd.concat:

```<code>df = pd.concat([df, split], axis=1)
</code>```

(Note that your code stores the dataframe in the variable pd which overwrites the pandas import. You should do df = pd.read_csv(...) instead of pd = pd.read_csv(...).)

Body:
import pandas as pd
df = pd.read_csv("product_2022-02-10.csv")
df["primary_category_name_en"]

Result:

primary_category_name_en
Gadgets & Electronics > Desktop Computer & Computer Accessories > Connecting Cable & Unit Convertor > Lan Line
Electrical Appliances > Other Small Home Appliances & Accessories > Drill & Extension Cord & Battery > Battery & Battery Charger > Other Battery
Housewares > Hardware & Tools > Metal Tools & Hardware Tools > Switch
Electrical Appliances > Smart Home > Smart Extension Cord

How can I split by > and put it back to different columns?

I know how to split it. df["primary_category_name_en”].str.split(">")

There are some only 3 categories in a row / 4 categories in a row / 5 categories in a row. I don't know how to solve the problem in this.

For example:

ROW 1:
df["Primary_category_1"] = "Gadgets & Electronics"
df["Primary_category_2"] = "Desktop Computer & Computer Accessories"
df["Primary_category_3"] = "Connecting Cable & Unit Convertor"
df["Primary_category_4"] = "Lan Line"

ROW 2:
df["Primary_category_1"] = "Electrical Appliances"
df["Primary_category_2"] = "Other Small Home Appliances & Accessories"
df["Primary_category_3"] = "Drill & Extension Cord & Battery"
df["Primary_category_4"] = "Battery & Battery Charger"
df["Primary_category_5"] = "Other Battery"

ROW 3:
...

ROW4:
...

Body:
Try using .str.split with expand=True:

split = df['primary_category_name_en'].str.split(' > ', expand=True).pipe(lambda x: x.set_axis(x.columns + 1, axis=1)).add_prefix('Primary_category_').fillna('')

Output:

>>> split
      Primary_category_1                         Primary_category_2                 Primary_category_3         Primary_category_4 Primary_category_5
0  Gadgets & Electronics    Desktop Computer & Computer Accessories  Connecting Cable & Unit Convertor                   Lan Line
1  Electrical Appliances  Other Small Home Appliances & Accessories   Drill & Extension Cord & Battery  Battery & Battery Charger      Other Battery
2             Housewares                           Hardware & Tools       Metal Tools & Hardware Tools                     Switch
3  Electrical Appliances                                 Smart Home               Smart Extension Cord

To add it back to your original dataframe, use pd.concat:

df = pd.concat([df, split], axis=1)

(Note that your code stores the dataframe in the variable pd which overwrites the pandas import. You should do df = pd.read_csv(...) instead of pd = pd.read_csv(...).)


问:
error while getting function ordinal from the IDT table - mapping PE - c++
I'm trying to map a PE file in memory but I got to this point where I get to a read access violation.

The error happens when reading the address of the function used from DLLs from IDT and adding them to the IAT table.

Here is the error that was thrown:

```<code>Exception thrown at 0x772D500B (ntdll.dll) in PELoader.exe: 0xC0000005: Access violation reading location 0x80000013.

</code>```

I don't know why it's reading that location 0x80000013.

The address of the ordinal is 0x00000013, using CFF (a PE viewer).

What I found

I discovered that the error only happens when it reaches a function in the IDT that has an ordinal instead of a name.

Here is the code that gets the address from the IDT to the IAT:

```<code>for (int i = 0; import_descriptors[i].OriginalFirstThunk != 0; ++i) {

        // Get the name of the dll, and import it
        char* module_name = ImageBase + import_descriptors[i].Name;
        HMODULE import_module = LoadLibraryA(module_name);
        if (import_module == NULL) {
            return NULL;
        }

        // the lookup table points to function names or ordinals => it is the IDT
        IMAGE_THUNK_DATA* lookup_table = (IMAGE_THUNK_DATA*)(ImageBase + import_descriptors[i].OriginalFirstThunk);

        // the address table is a copy of the lookup table at first
        // but we put the addresses of the loaded function inside => that's the IAT
        IMAGE_THUNK_DATA* address_table = (IMAGE_THUNK_DATA*)(ImageBase + import_descriptors[i].FirstThunk);

    for (int i = 0; lookup_table[i].u1.AddressOfData != 0; ++i) {
            void* function_handle = NULL;

            // looping through the lookup table
            DWORD lookup_addr = lookup_table[i].u1.AddressOfData;

            if ((lookup_addr & IMAGE_ORDINAL_FLAG) == 0) {
                // This is where I import by name
                IMAGE_IMPORT_BY_NAME* image_import = (IMAGE_IMPORT_BY_NAME*)(ImageBase + lookup_addr);
                char* funct_name = (char*)&(image_import->Name);
                printf("[*] adding address of: %s\n", funct_name);
                function_handle = (void*)GetProcAddress(import_module, funct_name);
            }
            else {
                //the exception is thrown after this line is printed in the console
                printf("--------------- this one has an Ordinal------\n");
                // import by ordinal, directly
                function_handle = (void*)GetProcAddress(import_module, (LPSTR)lookup_addr);
            }

            //the exception is thrown when checking if the function_handle is != null
            if (function_handle == NULL) {return NULL;}

            // change the IAT, and put the function address inside.
            address_table[i].u1.Function = (DWORD)function_handle;
    }
}
</code>```

I think I may have misaligned the ordinal somehow, But I don't know how.

答:
I think you problem is that you need to zero out the 8 at the top of the ordinal. From msft docs

"The function or variable name, or the function's ordinal value. If this parameter is an ordinal value, it must be in the low-order word; the high-order word must be zero."

I think the high order word being zero vs not zero is how it know whether it getting a pointer to a string or an ordinal

so do this

```<code>funct_name &= 0x0000ffff
</code>```

Body:
I'm trying to map a PE file in memory but I got to this point where I get to a read access violation.

The error happens when reading the address of the function used from DLLs from IDT and adding them to the IAT table.

Here is the error that was thrown:

Exception thrown at 0x772D500B (ntdll.dll) in PELoader.exe: 0xC0000005: Access violation reading location 0x80000013.

I don't know why it's reading that location 0x80000013.

The address of the ordinal is 0x00000013, using CFF (a PE viewer).

What I found

I discovered that the error only happens when it reaches a function in the IDT that has an ordinal instead of a name.

Here is the code that gets the address from the IDT to the IAT:

for (int i = 0; import_descriptors[i].OriginalFirstThunk != 0; ++i) {

        // Get the name of the dll, and import it
        char* module_name = ImageBase + import_descriptors[i].Name;
        HMODULE import_module = LoadLibraryA(module_name);
        if (import_module == NULL) {
            return NULL;
        }

        // the lookup table points to function names or ordinals => it is the IDT
        IMAGE_THUNK_DATA* lookup_table = (IMAGE_THUNK_DATA*)(ImageBase + import_descriptors[i].OriginalFirstThunk);

        // the address table is a copy of the lookup table at first
        // but we put the addresses of the loaded function inside => that's the IAT
        IMAGE_THUNK_DATA* address_table = (IMAGE_THUNK_DATA*)(ImageBase + import_descriptors[i].FirstThunk);

    for (int i = 0; lookup_table[i].u1.AddressOfData != 0; ++i) {
            void* function_handle = NULL;

            // looping through the lookup table
            DWORD lookup_addr = lookup_table[i].u1.AddressOfData;

            if ((lookup_addr & IMAGE_ORDINAL_FLAG) == 0) {
                // This is where I import by name
                IMAGE_IMPORT_BY_NAME* image_import = (IMAGE_IMPORT_BY_NAME*)(ImageBase + lookup_addr);
                char* funct_name = (char*)&(image_import->Name);
                printf("[*] adding address of: %s\n", funct_name);
                function_handle = (void*)GetProcAddress(import_module, funct_name);
            }
            else {
                //the exception is thrown after this line is printed in the console
                printf("--------------- this one has an Ordinal------\n");
                // import by ordinal, directly
                function_handle = (void*)GetProcAddress(import_module, (LPSTR)lookup_addr);
            }

            //the exception is thrown when checking if the function_handle is != null
            if (function_handle == NULL) {return NULL;}

            // change the IAT, and put the function address inside.
            address_table[i].u1.Function = (DWORD)function_handle;
    }
}

I think I may have misaligned the ordinal somehow, But I don't know how.

Body:
I think you problem is that you need to zero out the 8 at the top of the ordinal. From msft docs

"The function or variable name, or the function's ordinal value. If this parameter is an ordinal value, it must be in the low-order word; the high-order word must be zero."

I think the high order word being zero vs not zero is how it know whether it getting a pointer to a string or an ordinal

so do this

funct_name &= 0x0000ffff


问:
Get value of editable  tags through onchange function?
I am trying to get the value of  tag which is set editable, in Javascript. code given below

```<code><td class="cent" contenteditable='true' id="value_per_visit"
onchange="myFunction()"> -- </td>
</code>```

Here is my javascript code

```<code><script type="text/javascript">
function myFunction() {
  var x = document.getElementById("value_per_visit").value;
  document.getElementById("value_per_visit").innerHTML ="gotit";
  alert("asad");
}

</script>
</code>```

But i am not able to reach the function. Is there any solution?

答:
use onblur instead of onchange works for me!</p>
 --

Title: Get value of editable <td> tags through onchange function?

Body:
I am trying to get the value of  tag which is set editable, in Javascript. code given below

 --

Here is my javascript code

But i am not able to reach the function. Is there any solution?

Body:
use onblur instead of onchange works for me!

 --


问:
SetMetadata changes guard execution order nestjs
when i include @Permissions('read') my acessGuard stops receiving JWT info, @Permissions simply sets metadata (code below)

export const Permissions = (...permissions: string[]) => SetMetadata('permissions', permissions);
```
<p>certificate.controller.ts:</p>
<pre class="lang-js prettyprint-override"><code>@UseGuards(LocalAuthGuard, AccessGuard)
@Controller('certificate')
export class CertificateController {
    constructor(private certificateService: CertificateService) {}

    @Get()
      @Permissions('read') // removing this req.user is filled with jwt data
      async getCertificates(@CurrentUser() user: User) {
        return this.certificateService.getCertificates(user.id);
    }
</code>```

Bellow is the a guard which will control if the user has permission to execute the action

export class AccessGuard implements CanActivate {
   constructor(
     private readonly accessService: AccessService,
     @Inject('Reflector') private readonly reflector: Reflector,
   ) {}

     async canActivate(context: ExecutionContext): Promise<boolean> {
        const permissions = this.reflector.get<enAccessPoliciesModules[]>(
          'permissions',
          context.getHandler(),
        );

        console.log(context.switchToHttp().getRequest().user); // when i include @Permission('read') this line is undefined
     }
}
```

i guess this has something to do with the execution order, at first it is
LocalAuthGuard -> AccessGuard
but after setting metadata it becomes AccessGuard -> LocalAuthGuard, that way request.user is undefined.

Any workarounds for that?

答:
I found the problem

```<code>@Module({
  imports: [CoreModule, AuthModule, AccessPoliciesModule, CertificateModule],
  controllers: [AppController],
  providers: [
    AppService,
    { provide: APP_GUARD, useClass: AccessPoliciesGuard },
  ],
})
export class AppModule {}
</code>```

as i was trying to fix an dependency error so i added that APP_GUARD inside appModule providers. I realized the guard was being executed 2 times, the first time it didn't had the token because it was a global guard, and i guess i has priority?

Body:
when i include @Permissions('read') my acessGuard stops receiving JWT info, @Permissions simply sets metadata (code below)

export const Permissions = (...permissions: string[]) => SetMetadata('permissions', permissions);

certificate.controller.ts:

@UseGuards(LocalAuthGuard, AccessGuard)
@Controller('certificate')
export class CertificateController {
    constructor(private certificateService: CertificateService) {}

    @Get()
      @Permissions('read') // removing this req.user is filled with jwt data
      async getCertificates(@CurrentUser() user: User) {
        return this.certificateService.getCertificates(user.id);
    }

Bellow is the a guard which will control if the user has permission to execute the action

export class AccessGuard implements CanActivate {
   constructor(
     private readonly accessService: AccessService,
     @Inject('Reflector') private readonly reflector: Reflector,
   ) {}

     async canActivate(context: ExecutionContext): Promise<boolean> {
        const permissions = this.reflector.get<enAccessPoliciesModules[]>(
          'permissions',
          context.getHandler(),
        );

        console.log(context.switchToHttp().getRequest().user); // when i include @Permission('read') this line is undefined
     }
}

i guess this has something to do with the execution order, at first it is
LocalAuthGuard -> AccessGuard
but after setting metadata it becomes AccessGuard -> LocalAuthGuard, that way request.user is undefined.

Any workarounds for that?

Body:
I found the problem

@Module({
  imports: [CoreModule, AuthModule, AccessPoliciesModule, CertificateModule],
  controllers: [AppController],
  providers: [
    AppService,
    { provide: APP_GUARD, useClass: AccessPoliciesGuard },
  ],
})
export class AppModule {}

as i was trying to fix an dependency error so i added that APP_GUARD inside appModule providers. I realized the guard was being executed 2 times, the first time it didn't had the token because it was a global guard, and i guess i has priority?


问:
Calculating the total and average of marks using Javascript and HTML
I am new into Javascript btw thus I really hope someone can help me point out my mistake. I have done all the things that the question asked except for the calculation for total and average part. I got it wrong and I dont know what went wrong. Example marks I have keyed in were 1,2,3,4. Supposed to be the total and average should be 10 and 2.5 but it displayed 1234 and 308.5. Here`s what I have tried :

function findTotal() {
  var num1 = document.getElementById("Mark1").value;
  var num2 = document.getElementById("Mark2").value;
  var num3 = document.getElementById("Mark3").value;
  var num4 = document.getElementById("Mark4").value;
  document.getElementById("result").innerHTML = num1 + num2 + num3 + num4;
}

function findAverage() {
  var num1 = document.getElementById("Mark1").value;
  var num2 = document.getElementById("Mark2").value;
  var num3 = document.getElementById("Mark3").value;
  var num4 = document.getElementById("Mark4").value;
document.getElementById("result").innerHTML = (num1 + num2 + num3 + num4) / 4;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  Mark : <input type="text" id="Mark1" /><br>
  Mark : <input type="text" id="Mark2" /><br>
  Mark : <input type="text" id="Mark3" /><br>
  Mark : <input type="text" id="Mark4" /><br> <br>
  <input type="button" onClick="findTotal()" Value="Find Total" />
  <input type="button" onClick="findAverage()" Value="Find Average" />
</form><br>

Result : <br>
<span id = "result"></span></code>```

答:
Because the value is string "1"+"2"+"3"+"4" = "1234"
so you need to convert it to number so you could just add parseFloat();

<!DOCTYPE html>

            <title>MARK</title>

    <form>
    Mark : <input type="text" id="Mark1" />

    Mark : <input type="text" id="Mark2" />

    Mark : <input type="text" id="Mark3" />

    Mark : <input type="text" id="Mark4" />

    <input type="button" onClick="findTotal()" Value="Find Total" />
    <input type="button" onClick="findAverage()" Value="Find Average" />
    </form>

    Result :

    ```

Body:
I am new into Javascript btw thus I really hope someone can help me point out my mistake. I have done all the things that the question asked except for the calculation for total and average part. I got it wrong and I dont know what went wrong. Example marks I have keyed in were 1,2,3,4. Supposed to be the total and average should be 10 and 2.5 but it displayed 1234 and 308.5. Here`s what I have tried :

function findTotal() {
  var num1 = document.getElementById("Mark1").value;
  var num2 = document.getElementById("Mark2").value;
  var num3 = document.getElementById("Mark3").value;
  var num4 = document.getElementById("Mark4").value;
  document.getElementById("result").innerHTML = num1 + num2 + num3 + num4;
}

function findAverage() {
  var num1 = document.getElementById("Mark1").value;
  var num2 = document.getElementById("Mark2").value;
  var num3 = document.getElementById("Mark3").value;
  var num4 = document.getElementById("Mark4").value;
document.getElementById("result").innerHTML = (num1 + num2 + num3 + num4) / 4;
}

<form>
  Mark : <input type="text" id="Mark1" />

  Mark : <input type="text" id="Mark2" />

  Mark : <input type="text" id="Mark3" />

  Mark : <input type="text" id="Mark4" />

  <input type="button" onClick="findTotal()" Value="Find Total" />
  <input type="button" onClick="findAverage()" Value="Find Average" />
</form>

Result :

Body:
Because the value is string "1"+"2"+"3"+"4" = "1234"
so you need to convert it to number so you could just add parseFloat();

<!DOCTYPE html>
    <html>
        <head>
            <title>MARK</title>
        </head>
        <body>
          <script src="mark.js"></script>
    <form>
    Mark : <input type="text" id="Mark1" /><br>
    Mark : <input type="text" id="Mark2" /><br>
    Mark : <input type="text" id="Mark3" /><br>
    Mark : <input type="text" id="Mark4" /><br>
    <br>
    <input type="button" onClick="findTotal()" Value="Find Total" />
    <input type="button" onClick="findAverage()" Value="Find Average" />
    </form>
    <br>
    Result : <br>
    <span id = "result"></span>

    </body>
    <script>

function findTotal()
{
        var num1 =parseFloat( document.getElementById("Mark1").value);
        var num2 =parseFloat( document.getElementById("Mark2").value);
        var num3 =parseFloat( document.getElementById("Mark3").value);
        var num4 =parseFloat( document.getElementById("Mark4").value);
        document.getElementById("result").innerHTML = (num1 + num2 + num3 + num4);
}

function findAverage()
{
        var num1 =parseFloat( document.getElementById("Mark1").value);
        var num2 =parseFloat( document.getElementById("Mark2").value);
        var num3 =parseFloat( document.getElementById("Mark3").value);
        var num4 =parseFloat( document.getElementById("Mark4").value);
document.getElementById("result").innerHTML = (num1 + num2 + num3 + num4) / 4;
}
    </script>
    </html>


问:
What IDE should I use for Linux module development?
I have Ubuntu 11.04 and am looking to start developing Linux modules. I use Visual Studio for C development in Windows, but I guess that's not an option for Linux. What would be a good IDE to work Linux modules ?</p>

答:
Depending on what you want to do there are number to choose from. However I think the closest one to  visual studio equivalent will be eclipse.

From the FAQ:

Eclipse is an open source community whose projects are focused on
building an extensible development platform, runtimes and application
frameworks for building, deploying and managing software across the
entire software lifecycle. Many people know us, and hopefully love us,
as a Java IDE but Eclipse is much more than a Java IDE.

The Eclipse open source community has over 200 open source projects.
These projects can be conceptually organized into seven different
"pillars" or categories:

Enterprise Development

Embedded and Device Development

Rich Client Platform

Rich Internet Applications

Application Frameworks

Application Lifecycle Management (ALM)

Service Oriented Architecture (SOA)

The Eclipse community is also supported by a large and vibrant ecosystem of major IT > > > solution providers, innovative start-ups, universities and research institutions and > individuals that extend, support and complement the Eclipse Platform.

One very exciting thing about Eclipse is that many people are using
Eclipse in ways that we have never imagined. The common thread is that
they are building innovative, industrial-strength software and want to
use great tools, frameworks and runtimes to make their job easier.


问:
Android Webview net::ERR_UNKNOWN_URL_SCHEME
Could you give me a hand? I have a WebView display page, and when I click on buttons like (Join our telegra channel or share articles via Whatsapp and other social networks) this error appears: net::ERR_UNKNOWN_URL_SCHEME

I kindly ask you for some advice as I have tried several suggestions but without results

This is my code

```<code>import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {
    WebView webView;
    SwipeRefreshLayout mySwipeRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = findViewById(R.id.webView);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("https://myurl");
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        //Swipe to refresh functionality
        mySwipeRefreshLayout = (SwipeRefreshLayout)this.findViewById(R.id.swipeContainer);

        mySwipeRefreshLayout.setOnRefreshListener(
                new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        webView.reload();
                    }
                }
        );
    }

    public class Mainactiv extends WebViewClient{

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

    }

    @Override
    public void onBackPressed() {
        if(webView.isFocused() && webView.canGoBack())
        {
            webView.goBack();
        }else{
            super.onBackPressed();
        }

    }
}```
```

答:
replace shouldOverrideUrlLoading with this:</p>
```<code>public boolean shouldOverrideUrlLoading(WebView wv, String url) {
    if(url.startsWith("tel:") || url.startsWith("whatsapp:")) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        startActivity(intent);
        return true;
    }
    return false;
}
</code>```

Body:
Could you give me a hand? I have a WebView display page, and when I click on buttons like (Join our telegra channel or share articles via Whatsapp and other social networks) this error appears: net::ERR_UNKNOWN_URL_SCHEME

I kindly ask you for some advice as I have tried several suggestions but without results

This is my code

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {
    WebView webView;
    SwipeRefreshLayout mySwipeRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = findViewById(R.id.webView);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("https://myurl");
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        //Swipe to refresh functionality
        mySwipeRefreshLayout = (SwipeRefreshLayout)this.findViewById(R.id.swipeContainer);

        mySwipeRefreshLayout.setOnRefreshListener(
                new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        webView.reload();
                    }
                }
        );
    }

    public class Mainactiv extends WebViewClient{

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

    }

    @Override
    public void onBackPressed() {
        if(webView.isFocused() && webView.canGoBack())
        {
            webView.goBack();
        }else{
            super.onBackPressed();
        }

    }
}```

Body:
replace shouldOverrideUrlLoading with this:

public boolean shouldOverrideUrlLoading(WebView wv, String url) {
    if(url.startsWith("tel:") || url.startsWith("whatsapp:")) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        startActivity(intent);
        return true;
    }
    return false;
}


问:
Encountering out of memory error while reversing a short doubly linked list in java
I am trying to reverse a doubly-linked list and print it by overriding the toString method. I used a template for the implementation of a doubly-linked list in java, and only added one method: reverse().

I've spent quite some time debugging, and was able to print out the entire reversed list properly. However, when the testReverse() function runs and calls the overridden toString() method on the new reversed list, I get a java.lang.outofmemoryerror java heap space error thrown at me. I've included the entire implementation of the doubly-linked list I used below, but I'm almost certain the issue concerns my algorithm.

Any and all insight or advice would be greatly appreciated. Thank you!

```<code>public class LinkedList<T> implements Iterable<T> {

    private int size;
    private Node<T> beginMarker;
    private Node<T> endMarker;

    private class Node<NodeT> {
        public Node(NodeT d, Node<NodeT> p, Node<NodeT> n) {
            data = d;
            prev = p;
            next = n;
        }

        public NodeT data;
        public Node<NodeT> prev;
        public Node<NodeT> next;
    }

    public LinkedList() {
        doClear();
    }

    public void doClear() {
        beginMarker = new Node<>(null, null, null);
        endMarker = new Node<>(null, beginMarker, null);
        beginMarker.next = endMarker;
        size = 0;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size() == 0;
    }

    private Node<T> getNode(int idx, int lower, int upper) {
        Node<T> p;

        if (idx < lower || idx > upper)
            throw new IndexOutOfBoundsException("getNode index: " + idx + "; size: "+ size());

        if (idx < size() / 2) { // Search through list from the beginning
            p = beginMarker.next;
            for (int i = 0; i < idx; i++)
                p = p.next;
        } else { // serch through the list from the end
            p = endMarker;
            for (int i = size(); i > idx; i--)
                p = p.prev;
        }
        return p;
    }

    private Node<T> getNode(int idx) {
        return getNode(idx, 0, size() - 1);
    }

    public T get(int idx) {
        return getNode(idx).data;
    }

    public T set(int idx, T newVal) {
        Node<T> p = getNode(idx);
        T oldVal = p.data;

        p.data = newVal;
        return oldVal;
    }

    private void addBefore(Node<T> p, T x) {
        Node<T> newNode = new Node<>(x, p.prev, p);
        newNode.prev.next = newNode;
        p.prev = newNode;
        size++;
    }

    public void add(int idx, T x) {
        addBefore(getNode(idx, 0, size()), x);
    }

    public void add(T x) {
        add(size(), x);
    }

    private T remove(Node<T> p) {
        p.next.prev = p.prev;
        p.prev.next = p.next;
        size--;
        return p.data;
    }

    public T remove(int idx) {
        return remove(getNode(idx));
    }

    public void reverse() {

        Node current = beginMarker.next;
        Node temp = null;

        while (current != endMarker) {
            temp = current.next; // store reference to next node
            current.next = current.prev; // next points to previous node
            current.prev = temp; // prev points to next node
            current = temp; // current references temp (next node).
        }

        // changing references of beginning and end nodes
        temp = beginMarker.next;
        beginMarker.next = endMarker.prev;
        endMarker.prev = temp;

        /* TESTING THE PROGRAM, THIS PRINTS THE REVERSED LIST 'PROPERLY' BUT THE TESTER METHOD DOESN'T WORK */
        current = beginMarker;
        for (int i = 0; i <= size() + 1; i++) {
            System.out.println(current.data);
            current = current.next;

            /* END TEST */
        }
    }

    public String toString() {
        StringBuilder sb = new StringBuilder("[ ");
        for (T x : this) {
            sb.append(x + " ");
        }
        sb.append("]");
        return new String(sb);
    }

    public java.util.Iterator<T> iterator() {
        return new LinkedListIterator();
    }

    private class LinkedListIterator implements java.util.Iterator<T> {
        private Node<T> current = beginMarker.next;
        private boolean okToRemove = false;

        public boolean hasNext() {
            return current != endMarker;
        }

        public T next() {
            if (!hasNext())
                throw new java.util.NoSuchElementException();

            T nextItem = current.data;
            current = current.next;
            okToRemove = true;
            return nextItem;
        }

        public void remove() {
            if (!okToRemove)
                throw new IllegalStateException();

            LinkedList.this.remove(current.prev);
            okToRemove = false;
        }
    }

  public static void testReverse(){

    LinkedList<Integer> lst = new LinkedList<>();

        for (int i = 0; i < 10; i++)
            lst.add(i);
        for (int i = 20; i < 30; i++)
            lst.add(0, i);

    System.out.println("Testing reverse:");
    System.out.println("Original list:");
    // Should print [ 29 28 27 26 25 24 23 22 21 20 0 1 2 3 4 5 6 7 8 9 ]
        System.out.println(lst);
    lst.reverse();
    System.out.println("After reversal:");
    // Should print [ 9 8 7 6 5 4 3 2 1 0 20 21 22 23 24 25 26 27 28 29 ]
        System.out.println(lst);

  }
    public static void main(String[] args) {
        testReverse();
    }
}
</code>```

答:
```<code>public void reverse() {

        Node current = beginMarker.next;
        Node temp = null;

        while (current != endMarker) {
            temp = current.next; // store reference to next node
            if (current == beginMarker.next) {
                current.next = endMarker;
            } else {
                current.next = current.prev; // next points to previous node
            }
            current.prev = temp; // prev points to next node
            current = temp; // current references temp (next node).
        }

        // changing references of beginning and end nodes
        temp = beginMarker.next;
        beginMarker.next = endMarker.prev;
        endMarker.prev = temp;

        /* TESTING THE PROGRAM, THIS PRINTS THE REVERSED LIST 'PROPERLY' BUT THE TESTER METHOD DOESN'T WORK */
        current = beginMarker;
        for (int i = 0; i <= size() + 1; i++) {
            System.out.println(current.data);
            current = current.next;

            /* END TEST */
        }
    }
</code>```

Body:
I am trying to reverse a doubly-linked list and print it by overriding the toString method. I used a template for the implementation of a doubly-linked list in java, and only added one method: reverse().

I've spent quite some time debugging, and was able to print out the entire reversed list properly. However, when the testReverse() function runs and calls the overridden toString() method on the new reversed list, I get a java.lang.outofmemoryerror java heap space error thrown at me. I've included the entire implementation of the doubly-linked list I used below, but I'm almost certain the issue concerns my algorithm.

Any and all insight or advice would be greatly appreciated. Thank you!

public class LinkedList<T> implements Iterable<T> {

    private int size;
    private Node<T> beginMarker;
    private Node<T> endMarker;

    private class Node<NodeT> {
        public Node(NodeT d, Node<NodeT> p, Node<NodeT> n) {
            data = d;
            prev = p;
            next = n;
        }

        public NodeT data;
        public Node<NodeT> prev;
        public Node<NodeT> next;
    }

    public LinkedList() {
        doClear();
    }

    public void doClear() {
        beginMarker = new Node<>(null, null, null);
        endMarker = new Node<>(null, beginMarker, null);
        beginMarker.next = endMarker;
        size = 0;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size() == 0;
    }

    private Node<T> getNode(int idx, int lower, int upper) {
        Node<T> p;

        if (idx < lower || idx > upper)
            throw new IndexOutOfBoundsException("getNode index: " + idx + "; size: "+ size());

        if (idx < size() / 2) { // Search through list from the beginning
            p = beginMarker.next;
            for (int i = 0; i < idx; i++)
                p = p.next;
        } else { // serch through the list from the end
            p = endMarker;
            for (int i = size(); i > idx; i--)
                p = p.prev;
        }
        return p;
    }

    private Node<T> getNode(int idx) {
        return getNode(idx, 0, size() - 1);
    }

    public T get(int idx) {
        return getNode(idx).data;
    }

    public T set(int idx, T newVal) {
        Node<T> p = getNode(idx);
        T oldVal = p.data;

        p.data = newVal;
        return oldVal;
    }

    private void addBefore(Node<T> p, T x) {
        Node<T> newNode = new Node<>(x, p.prev, p);
        newNode.prev.next = newNode;
        p.prev = newNode;
        size++;
    }

    public void add(int idx, T x) {
        addBefore(getNode(idx, 0, size()), x);
    }

    public void add(T x) {
        add(size(), x);
    }

    private T remove(Node<T> p) {
        p.next.prev = p.prev;
        p.prev.next = p.next;
        size--;
        return p.data;
    }

    public T remove(int idx) {
        return remove(getNode(idx));
    }

    public void reverse() {

        Node current = beginMarker.next;
        Node temp = null;

        while (current != endMarker) {
            temp = current.next; // store reference to next node
            current.next = current.prev; // next points to previous node
            current.prev = temp; // prev points to next node
            current = temp; // current references temp (next node).
        }

        // changing references of beginning and end nodes
        temp = beginMarker.next;
        beginMarker.next = endMarker.prev;
        endMarker.prev = temp;

        /* TESTING THE PROGRAM, THIS PRINTS THE REVERSED LIST 'PROPERLY' BUT THE TESTER METHOD DOESN'T WORK */
        current = beginMarker;
        for (int i = 0; i <= size() + 1; i++) {
            System.out.println(current.data);
            current = current.next;

            /* END TEST */
        }
    }

    public String toString() {
        StringBuilder sb = new StringBuilder("[ ");
        for (T x : this) {
            sb.append(x + " ");
        }
        sb.append("]");
        return new String(sb);
    }

    public java.util.Iterator<T> iterator() {
        return new LinkedListIterator();
    }

    private class LinkedListIterator implements java.util.Iterator<T> {
        private Node<T> current = beginMarker.next;
        private boolean okToRemove = false;

        public boolean hasNext() {
            return current != endMarker;
        }

        public T next() {
            if (!hasNext())
                throw new java.util.NoSuchElementException();

            T nextItem = current.data;
            current = current.next;
            okToRemove = true;
            return nextItem;
        }

        public void remove() {
            if (!okToRemove)
                throw new IllegalStateException();

            LinkedList.this.remove(current.prev);
            okToRemove = false;
        }
    }

  public static void testReverse(){

    LinkedList<Integer> lst = new LinkedList<>();

        for (int i = 0; i < 10; i++)
            lst.add(i);
        for (int i = 20; i < 30; i++)
            lst.add(0, i);

    System.out.println("Testing reverse:");
    System.out.println("Original list:");
    // Should print [ 29 28 27 26 25 24 23 22 21 20 0 1 2 3 4 5 6 7 8 9 ]
        System.out.println(lst);
    lst.reverse();
    System.out.println("After reversal:");
    // Should print [ 9 8 7 6 5 4 3 2 1 0 20 21 22 23 24 25 26 27 28 29 ]
        System.out.println(lst);

  }
    public static void main(String[] args) {
        testReverse();
    }
}


问:
jquery reset the css value of an animation?
I have a created a snippet of code that basically animates an h2 onto an image on hover and then off the right on hover off, so i've initially set the h2 to be left: -200px off the page on load, then on hover to animate to left: 10px inside the .image and then on hover off to animate to left: 500px to zoom off. Now when I hover the image again the h2 is being animated in from the right, how can I reset the h2 to be -200px as soon as the hover off has happened or can you suggest a better way for me to achieve this effect?

My attempt can be found here http://jsfiddle.net/kyllle/GPve7/

Thanks

答:
Look at the animate function from jquery, it has a callback property, just set the CSS after that:

Updated fiddle


问:
MongoDB/DocumentDB bson_append_array(): invalid array detected. first element of array parameter is not "0"
Recently I have migrated one of my projects (PHP 7.4/Lumen/Ubuntu 20.04) from MongoDB to MongoDB compatible AWS DocumentDB. Since the migration all the CLI Scripts are triggering this strange notice/warning

```<code>bson_append_array(): invalid array detected. first element of array parameter is not "0".
</code>```

Everything seems to be functionally working apart from this message (Even though I have all the PHP errors hidden from ini file this still shows up). Not really sure what is going on.

Message is actually coming from "find" method. I also did try to suppress the msg but no luck.

Does anyone have any idea what is going on here ? Appreciate and thanks for all your responses in advance.

DocumentDB version 4.0

PHP SDK Composer version 1.9.0

答:
I am answering my own questions based on my findings so far.

Seems like there is no solution for this issue since AWS DocumentDB is not 100% compatible with MongoDB (As per mongoDb documentation over 66% of all of the correctness tests have failed for DocumentDB). Also it is extremely difficult get AWS support for these sort of incompatibility issues, they always refer you to public user forum.

MongoDB recently put up a blog post summering incompatibility issues with DocumentDB and it makes a lot of sense. You can read it in detail here - https://www.mongodb.com/atlas-vs-amazon-documentdb/compatibility

My recommendation is if you are considering using documentDB as a replacement of Mongo do not bother. Save your precious time by sticking with MongoDB.

Body:
Recently I have migrated one of my projects (PHP 7.4/Lumen/Ubuntu 20.04) from MongoDB to MongoDB compatible AWS DocumentDB. Since the migration all the CLI Scripts are triggering this strange notice/warning

bson_append_array(): invalid array detected. first element of array parameter is not "0".

Everything seems to be functionally working apart from this message (Even though I have all the PHP errors hidden from ini file this still shows up). Not really sure what is going on.

Message is actually coming from "find" method. I also did try to suppress the msg but no luck.

Does anyone have any idea what is going on here ? Appreciate and thanks for all your responses in advance.

DocumentDB version 4.0

PHP SDK Composer version 1.9.0


问:
sqlite3.OperationalError: no such table: sqlite_schema
I am facing a weird issue. In TablePlus when I run the following command it returns table but same query does not work in Python.

```<code>SELECT
    name
FROM
    sqlite_schema
WHERE
    type ='table'
    AND
    name NOT LIKE 'lookup%';
</code>```

Python code is given below:

```<code>def get_connection():
    path = 'data.sqlite3'
    connection = sqlite3.connect(path)
    return connection

sql_select = "SELECT name FROM sqlite_schema WHERE type ='table' AND name NOT LIKE 'lookup%';"
cursor = connection.execute(sql_select)
</code>```

Error:

```<code>cursor = connection.execute(sql_select)
sqlite3.OperationalError: no such table: sqlite_schema
</code>```

I am using SQLite 3.36

答: Change sqlite_schema for sqlite_master in PHP CPANEL VERSION 92, SUCCESS</p>

Body:
I am facing a weird issue. In TablePlus when I run the following command it returns table but same query does not work in Python.

SELECT
    name
FROM
    sqlite_schema
WHERE
    type ='table'
    AND
    name NOT LIKE 'lookup%';

Python code is given below:

def get_connection():
    path = 'data.sqlite3'
    connection = sqlite3.connect(path)
    return connection

sql_select = "SELECT name FROM sqlite_schema WHERE type ='table' AND name NOT LIKE 'lookup%';"
cursor = connection.execute(sql_select)

Error:

cursor = connection.execute(sql_select)
sqlite3.OperationalError: no such table: sqlite_schema

I am using SQLite 3.36


问:
Why is test >= 0 true when test is null?
Let's say I have the following javascript code:

const test = null

if ( test >= 0 ){
    console.log("Hello World")
}```
</div>
</div>
</p>
<p>This code will print <code>Hello World</code>... In my mind, it should work only if <code>test === null</code>. But all the times that I use the condition <code>test >= 0</code> the code falls on it. Is there any reason why it happens? I see it as a problem in some situations... For example on the next code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const test = null

if ( test >= 0 ){
    console.log("1")
}
else if ( test === null ){
    console.log("Hello World")
}</code>```

In this case, the code is not doing what apparently it should be doing. The workaround to make it work would be having the habit of always putting the === null condition at first on if/else or switch/cases. Is that how I'm supposed to work with Javascript? Or is there a better way of doing it?

答:
I thought it was a simple question but I was wrong.
I went check ECMAScript Language Specification, which specified how "a>=b" works.

It turned out it is not doing "a>b || a==b", but instead, it is returning the oppsite answer of "a= 0) is returning true, because (null < 0) is returning false.

 ES3 spec

11.8.4 The Greater-than-or-equal Operator ( >= ) The production RelationalExpression : RelationalExpression >= ShiftExpression is
evaluated as follows:

Evaluate RelationalExpression.

Call GetValue(Result(1)).

Evaluate ShiftExpression.

Call GetValue(Result(3)).

Perform the comparison Result(2) < Result(4). (see 11.8.5).**

If Result(5) is true or undefined, return false. Otherwise, return true.

And, I found another reference which plots the Relational and Equality Operators of some special cases.

Relational and Equality Operators

Body:
Let's say I have the following javascript code:

const test = null

if ( test >= 0 ){
    console.log("Hello World")
}

This code will print Hello World... In my mind, it should work only if test === null. But all the times that I use the condition test >= 0 the code falls on it. Is there any reason why it happens? I see it as a problem in some situations... For example on the next code:

const test = null

if ( test >= 0 ){
    console.log("1")
}
else if ( test === null ){
    console.log("Hello World")
}

In this case, the code is not doing what apparently it should be doing. The workaround to make it work would be having the habit of always putting the === null condition at first on if/else or switch/cases. Is that how I'm supposed to work with Javascript? Or is there a better way of doing it?

Body:
I thought it was a simple question but I was wrong.
I went check ECMAScript Language Specification, which specified how "a>=b" works.

It turned out it is not doing "a>b || a==b", but instead, it is returning the oppsite answer of "a<b".
I think that is why (null >= 0) is returning true, because (null < 0) is returning false.

 ES3 spec

11.8.4 The Greater-than-or-equal Operator ( >= ) The production RelationalExpression : RelationalExpression >= ShiftExpression is
evaluated as follows:

Evaluate RelationalExpression.

Call GetValue(Result(1)).

Evaluate ShiftExpression.

Call GetValue(Result(3)).

Perform the comparison Result(2) < Result(4). (see 11.8.5).**

If Result(5) is true or undefined, return false. Otherwise, return true.

And, I found another reference which plots the Relational and Equality Operators of some special cases.

Relational and Equality Operators


问:
DialogFlow CX how to declare parameters in the start page?
I need to declare a parameter to store username as input in the first message of dialogflow session, "My name is John" will be the first message the user type to dialogflow cx,
I noticed it's not possible to create a parameter on the Start page, is there is a way to detect parameters using EntityType from the first message of the session ?</p>

答:
To detect parameter values from the first end-user input, you can use intent parameters.

First, create an intent and add training phrases like "My name is John" and similar. See how the intent may look like.

Then, add an intent route on the Start page and define agent response in fulfillment. See how the route and a simulator test may look like.

You can also check the general agent design best practices for more information.


问:
DataView Sort - C#/ASP.NET
I am using the DataView.Sort to sort a column in the dataset. By default, does this assume the data is of type string when it does a sort. If so, how do I make it be datatype aware?

EDIT: How does it infer the datatype? I am creating a dataset from scratch

答: .Sort will honor the datatype of the column.  Now, if you've already converted the column to a string type for display you have a problem.  But if it's still a datetime then you're okay.

OwnerDisplayName: DotnetDude

ContentLicense: CC BY-SA 2.5

Title: DataView Sort - C#/ASP.NET

LastEditorDisplayName: DotnetDude

OwnerDisplayName: Joel Coehoorn


答: Just reset the position after the second animation is finished using the callback argument in animate() like here http://jsfiddle.net/geko/GPve7/9/</p>

Title: jquery reset the css value of an animation?

Body:
I have a created a snippet of code that basically animates an h2 onto an image on hover and then off the right on hover off, so i've initially set the h2 to be left: -200px off the page on load, then on hover to animate to left: 10px inside the .image and then on hover off to animate to left: 500px to zoom off. Now when I hover the image again the h2 is being animated in from the right, how can I reset the h2 to be -200px as soon as the hover off has happened or can you suggest a better way for me to achieve this effect?

My attempt can be found here http://jsfiddle.net/kyllle/GPve7/

Thanks


问:
Extend SQL Query Timeout in Azure Logic Apps
I am running a logic app that triggers multiple SQL queries. When these queries have ran for 10 minutes and not completed the query, they timeout. Is there any way to extend this timeout length?</p>

答:
Is there any way to extend this timeout length

If you require extended timeout for logic apps then as per this Microsoft document Either it may be Inbound or Outbound requests it has been defined as 120 sec. if you are running operations/queries for longer try using asynchronous calling.

For increasing SQL query timeout we have an option of using Azure Elastic Job agent as per this Microsoft Document.

You can even try using Azure functions where you can run queries longer time without interruption and if you still want to use logic apps you can call functions from logic apps using HTTP trigger.

Here are a few related links about Azure functions and SQL stored procedures and calling azure function in logic apps.


问:
Generate dynamic div containers on submit in Flask app
I am new in Flask. My goal is to generate dynamic div containers every time I upload a dxf file and next submit happens. For example: one file uploaded- one div shown; two files uploaded- two divs shown and so on.
I can convert uploaded dxf files to .png images and I would like to show these images in div elements displayed after every upload.
I use input tag to upload files (type='file') and Java Script to generate dynamic elements (divs and their child tags).
The problem is that every time I upload file, the template is loading again and no new content is shown except the image of the last uploaded dxf. Please, give me a piece of advice to solve it.

HTML

```<code>...
<form enctype="multipart/form-data"  id="uploadForm" action="/upload_files" name="uploadForm"  method="post">
   DXF file: <input type="file" id="dxfUpload" onchange="form.submit(); createConfigure();"   name="dxfUpload" />

    <div id="calcHolder" name="calcHolder">

            <script type="text/javascript">

                function createConfigure() {

                    var div = document.createElement("div");
                    div.id = "dxf-"+Math.random() * 100000000000000000 + "-"
                    + window.performance.now() * 100000000000000000;
                    id_div=div.id;
                    div.className = 'border pad';
                    div.style.width = "640px";
                    div.style.height = "200px";
                    document.getElementById("calcHolder").appendChild(div);

                    var img = document.createElement("img");
                    img.setAttribute("src", "{{url_for('static', filename=dxfName+'.png')}}");
                    img.setAttribute("alt", "no image");
                    img.setAttribute("height", "120px");
                    img.setAttribute("width", "120px");
                    document.getElementById(id_div).appendChild(img);

                    var array = ["Carbon Steel","Stainless Steel","Aluminium"];

                    var selectMaterial = document.createElement("select");
                    document.getElementById(id_div).appendChild(selectMaterial);

                    for (var i = 0; i < array.length; i++) {
                       var option = document.createElement("option");
                       option.value = array[i];
                       option.text = array[i];
                       selectMaterial.appendChild(option);
                    }

                    var selectThickness = document.createElement("select");
                    document.getElementById(id_div).appendChild(selectThickness);

                    for (i = 1; i <= 16; i++) {
                        var opt = document.createElement('option');
                        //opt.value = i;
                        opt.innerHTML = i + ' mm';
                        selectThickness.appendChild(opt);
                    }

                    var quantity = document.createElement("input")
                    quantity.type="number";
                    quantity.value="1";
                    quantity.name="quantity";
                    quantity.min="1";
                    quantity.max="50";
                    quantity.onkeyup= function maxReach(){if(quantity.value > 50) quantity.value=50;};
                    document.getElementById(id_div).appendChild(quantity);

                    var btn = document.createElement("button");
                    btn.innerHTML = "Delete";
                    btn.type = "button";
                    document.getElementById(id_div).appendChild(btn);

                    btn.onclick = function() {div.remove();};

                }
                </script>
                    {{ html | safe }}
        </div>

</form>
...
</code>```

Python

```<code>@app.route('/upload_files', methods=['POST'])
def upload_files():
     try:
       if request.method == 'POST':
        dxf_file = request.files['dxfUpload']
        full_filename = os.path.join(app.config['UPLOAD_FOLDER'],dxf_file.filename)
        dxf_file.save(full_filename)
        first =  DXF2IMG()
        first.convert_dxf2img([full_filename],img_format='.png')

        html="<img src="+url_for('static', filename=dxf_file.filename+'.png' )+" width='120' height='120' />"

        return render_template('upload_files.html',dxfName=dxf_file.filename, html=html)
     except:
        ...
        #something happens
</code>```

The result now

Desired result

答:
Once the form.submit() function is executed, the form will be sent as a regular post request. For this reason, the following function is no longer executed and the entire page is reloaded.

In order to submit the form and change the content of the existing page, it is necessary to use AJAX.

This example shows you how to submit the form to the server and receive a JSON response containing the URLs of the received file and the generated image.

As soon as the submit button is pressed, the form data is packed into a FormData object and sent via AJAX using the fetch function. The browser's default behavior for a submit event is suppressed and the form is reset. The received file is processed by the server and the associated URLs are sent back to the client in JSON format. Now the document can be changed with the received data.

Remember this is just a minimal example to help you achieve your goals and implement your concept.

Flask (app.py)

```<code>import os
import ezdxf
from ezdxf.addons.drawing import matplotlib
from flask import Flask
from flask import (
    jsonify,
    make_response,
    render_template,
    url_for
)
from werkzeug.utils import secure_filename

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

def dxf2png(source, target):
    doc = ezdxf.readfile(source)
    msp = doc.modelspace()
    auditor = doc.audit()
    if auditor.has_errors:
        raise Exception('Conversion failed.')
    matplotlib.qsave(doc.modelspace(), target)

@app.route('/upload', methods=['POST'])
def upload():
    if 'dxf-file' in request.files:
        file = request.files['dxf-file']
        if file.filename != '':
            filename = secure_filename(file.filename)
            filepath = os.path.join(app.static_folder, filename)
            destname, _ = os.path.splitext(filename)
            destname = f'{destname}.png'
            destpath = os.path.join(app.static_folder, destname)
            file.save(filepath)
            try:
                dxf2png(filepath, destpath)
            except:
                os.remove(filepath)
                return make_response('', 400)
            return make_response(
                jsonify(
                    target=url_for('static', filename=filename),
                    preview=url_for('static', filename=destname)
                ),
                200
            )
    return make_response('', 400)
</code>```

HTML (templates/index.html)

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index</title>
    <style media="screen">
      .preview {
        width: 120px;
        height: auto;
      }
    </style>
  </head>
  <body>
    <form name="dxf-upload" method="post" enctype="multipart/form-data">
      <input type="file" name="dxf-file" />
      <input type="submit" />
    </form>

    <div id="dxf-files"></div>

    <script type="text/javascript">
      ((uri) => {
        function createPreview(target, preview) {
          const divElem = document.createElement('div');
          divElem.innerHTML = `<a href="${target}"><img src="${preview}" class="preview" /></a>`;
          const outElem = document.getElementById('dxf-files');
          outElem.append(divElem);
        }

        const form = document.querySelector('form[name="dxf-upload"]');
        form.addEventListener('submit', evt => {
          evt.preventDefault();
          const formData = new FormData(evt.target);
          fetch(uri, {
            method: 'POST',
            body: formData
          }).then(resp => resp.json())
            .then(data => {
              const { target, preview } = data;
              createPreview(target, preview);
            });
          evt.target.reset();
        });
      })({{ url_for('.upload') | tojson }});
    </script>
  </body>
</html>
</code>```

Body:
I am new in Flask. My goal is to generate dynamic div containers every time I upload a dxf file and next submit happens. For example: one file uploaded- one div shown; two files uploaded- two divs shown and so on.
I can convert uploaded dxf files to .png images and I would like to show these images in div elements displayed after every upload.
I use input tag to upload files (type='file') and Java Script to generate dynamic elements (divs and their child tags).
The problem is that every time I upload file, the template is loading again and no new content is shown except the image of the last uploaded dxf. Please, give me a piece of advice to solve it.

HTML

...
<form enctype="multipart/form-data"  id="uploadForm" action="/upload_files" name="uploadForm"  method="post">
   DXF file: <input type="file" id="dxfUpload" onchange="form.submit(); createConfigure();"   name="dxfUpload" />

                    {{ html | safe }}

</form>
...

Python

@app.route('/upload_files', methods=['POST'])
def upload_files():
     try:
       if request.method == 'POST':
        dxf_file = request.files['dxfUpload']
        full_filename = os.path.join(app.config['UPLOAD_FOLDER'],dxf_file.filename)
        dxf_file.save(full_filename)
        first =  DXF2IMG()
        first.convert_dxf2img([full_filename],img_format='.png')

        html=""

        return render_template('upload_files.html',dxfName=dxf_file.filename, html=html)
     except:
        ...
        #something happens

The result now

Desired result

Body:
Once the form.submit() function is executed, the form will be sent as a regular post request. For this reason, the following function is no longer executed and the entire page is reloaded.

In order to submit the form and change the content of the existing page, it is necessary to use AJAX.

This example shows you how to submit the form to the server and receive a JSON response containing the URLs of the received file and the generated image.

As soon as the submit button is pressed, the form data is packed into a FormData object and sent via AJAX using the fetch function. The browser's default behavior for a submit event is suppressed and the form is reset. The received file is processed by the server and the associated URLs are sent back to the client in JSON format. Now the document can be changed with the received data.

Remember this is just a minimal example to help you achieve your goals and implement your concept.

Flask (app.py)

import os
import ezdxf
from ezdxf.addons.drawing import matplotlib
from flask import Flask
from flask import (
    jsonify,
    make_response,
    render_template,
    url_for
)
from werkzeug.utils import secure_filename

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

def dxf2png(source, target):
    doc = ezdxf.readfile(source)
    msp = doc.modelspace()
    auditor = doc.audit()
    if auditor.has_errors:
        raise Exception('Conversion failed.')
    matplotlib.qsave(doc.modelspace(), target)

@app.route('/upload', methods=['POST'])
def upload():
    if 'dxf-file' in request.files:
        file = request.files['dxf-file']
        if file.filename != '':
            filename = secure_filename(file.filename)
            filepath = os.path.join(app.static_folder, filename)
            destname, _ = os.path.splitext(filename)
            destname = f'{destname}.png'
            destpath = os.path.join(app.static_folder, destname)
            file.save(filepath)
            try:
                dxf2png(filepath, destpath)
            except:
                os.remove(filepath)
                return make_response('', 400)
            return make_response(
                jsonify(
                    target=url_for('static', filename=filename),
                    preview=url_for('static', filename=destname)
                ),
                200
            )
    return make_response('', 400)

HTML (templates/index.html)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index</title>
    <style media="screen">
      .preview {
        width: 120px;
        height: auto;
      }
    </style>
  </head>
  <body>
    <form name="dxf-upload" method="post" enctype="multipart/form-data">
      <input type="file" name="dxf-file" />
      <input type="submit" />
    </form>

    <div id="dxf-files"></div>

    <script type="text/javascript">
      ((uri) => {
        function createPreview(target, preview) {
          const divElem = document.createElement('div');
          divElem.innerHTML = `<a href="${target}"><img src="${preview}" class="preview" /></a>`;
          const outElem = document.getElementById('dxf-files');
          outElem.append(divElem);
        }

        const form = document.querySelector('form[name="dxf-upload"]');
        form.addEventListener('submit', evt => {
          evt.preventDefault();
          const formData = new FormData(evt.target);
          fetch(uri, {
            method: 'POST',
            body: formData
          }).then(resp => resp.json())
            .then(data => {
              const { target, preview } = data;
              createPreview(target, preview);
            });
          evt.target.reset();
        });
      })({{ url_for('.upload') | tojson }});
    </script>
  </body>
</html>


问:
Placeholder Margin on Xamarin Forms Editor using Custom Renderer
I've an Editor on a page in my Xamarin Forms Project and I'm looking to amend the placeholder text position by adding a slight margin.

I was able to add a margin to the text the user types (but not the placeholder) using "TextContainerInset" in my iOS Custom renderer.

```<code>
protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
        {

                base.OnElementChanged(e);
                this.Control.InputAccessoryView = null;
                this.Control.Layer.CornerRadius = 10;
                this.Control.Layer.BorderColor = UIColor.LightGray.CGColor;
                this.Control.Layer.BorderWidth = (nfloat)0.5;
                this.Control.TextContainerInset = new UIEdgeInsets(15,15,15,15);

        }

</code>```

However, this inset doesn't apply to the placeholder position.

Is there a way to move the placeholder position using the custom renderer?

答:
You could set the padding like:

```<code>       public class MyEntryRenderer : EntryRenderer
        {
            protected override void OnElementChanged (ElementChangedEventArgs<Entry> e)
            {
                base.OnElementChanged (e);

                if (Control != null) {
            Control.LeftView = new UIView(new CGRect(0,0,15,0));
            Control.LeftViewMode = UITextFieldViewMode.Always;
            Control.RightView = new UIView(new CGRect(0, 0, 15, 0));
            Control.RightViewMode = UITextFieldViewMode.Always;
                }
            }
}
</code>```

Workaournd for editor:

warp the editor in the frame and set the padding like:

```<code><StackLayout Margin="20">
    <Frame CornerRadius="10" BorderColor="Gray" HeightRequest="50" Padding="5,10,5,10" HasShadow="False">
        <Editor Placeholder="Enter the editor text" ></Editor>
    </Frame>
</StackLayout>
</code>```

Body:
I've an Editor on a page in my Xamarin Forms Project and I'm looking to amend the placeholder text position by adding a slight margin.

I was able to add a margin to the text the user types (but not the placeholder) using "TextContainerInset" in my iOS Custom renderer.

protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
        {

                base.OnElementChanged(e);
                this.Control.InputAccessoryView = null;
                this.Control.Layer.CornerRadius = 10;
                this.Control.Layer.BorderColor = UIColor.LightGray.CGColor;
                this.Control.Layer.BorderWidth = (nfloat)0.5;
                this.Control.TextContainerInset = new UIEdgeInsets(15,15,15,15);

        }

However, this inset doesn't apply to the placeholder position.

Is there a way to move the placeholder position using the custom renderer?

Body:
You could set the padding like:

       public class MyEntryRenderer : EntryRenderer
        {
            protected override void OnElementChanged (ElementChangedEventArgs<Entry> e)
            {
                base.OnElementChanged (e);

                if (Control != null) {
            Control.LeftView = new UIView(new CGRect(0,0,15,0));
            Control.LeftViewMode = UITextFieldViewMode.Always;
            Control.RightView = new UIView(new CGRect(0, 0, 15, 0));
            Control.RightViewMode = UITextFieldViewMode.Always;
                }
            }
}

Workaournd for editor:

warp the editor in the frame and set the padding like:

<StackLayout Margin="20">
    <Frame CornerRadius="10" BorderColor="Gray" HeightRequest="50" Padding="5,10,5,10" HasShadow="False">
        <Editor Placeholder="Enter the editor text" ></Editor>
    </Frame>
</StackLayout>