问:
Adding custom arrows with labels in seaborn relplot or a facetgrid
I am trying to add two custom arrows with labels in a seaborn relplot graph.
I tried using the matplot arrow function which is not working because the seaborne relplot is a "facetgrid". I did not see a specific arrow pointer function in seaborn docu. I want to draw an arrow at a specific x value between the y values of two benchmarks (b1 b2 in example)

Is there an easy way to do this?
I added a simple code example, data and 2 images of what i try to achieve.

CODE:

```<code>import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import gc
import sys

if __name__ == '__main__':
        pfad = sys.argv[1]
        label = 'test'
        df1 = pd.read_csv(pfad, sep=';')

        sns_plot = sns.relplot(x="selectivity", ci=None, y="throughput", hue='benchmark', kind="line", data=df1,
                           dashes=False, markers=True, style="benchmark")

        sns_plot.savefig(label + ".png")
        plt.savefig(label + ".pdf", bbox_inches='tight')

        plt.show()
</code>```

DATASET (example.csv in same folder)

```<code>benchmark;selectivity;throughput
b1;0.01;1426.89
b2;0.01;531.434
b1;0.03;826.89
b2;0.03;531.434
b1;0.05;626.89
b2;0.05;520.434
</code>```

Currently my Graph looks like this:

This is what I want to achieve:

答:
As mentioned in the comments, I flattened the axes, got the values from the line chart, and added text annotations and arrows respectively.

```<code>if __name__ == '__main__':
    pfad = sys.argv[1]
    label = 'test'
    df1 = pd.read_csv(pfad, sep=';')

    sns_plot = sns.relplot(x="selectivity", ci=None, y="throughput", hue='benchmark', kind="line", data=df1,
                       dashes=False, markers=True, style="benchmark")
    xydata = []
    for ax in sns_plot.axes.flat:
        for li in ax.lines:
            xydata.append(li.get_xydata())

    ax.text(xydata[0][0][0]+0.001, (xydata[0][0][1]+xydata[1][0][1])/2, '2.5X speedup')
    ax.text(xydata[1][2][0]+0.001, (xydata[0][2][1]+xydata[1][2][1])/2, '1.3X speedup')
    ax.annotate('',
                xy=(xydata[0][0][0], xydata[0][0][1]),
                xytext=(xydata[0][0][0], xydata[1][0][1]),
                xycoords='data',
                arrowprops=dict(facecolor='black',width=2.0,headwidth=7.0,headlength=7.0,shrink=0.01))
    ax.annotate('',
                xy=(xydata[1][2][0], xydata[0][2][1]),
                xytext=(xydata[1][2][0], xydata[1][2][1]),
                xycoords='data',
                arrowprops=dict(facecolor='black',width=2.0,headwidth=7.0,headlength=7.0,shrink=0.01))

    #sns_plot.savefig(label + ".png")
    #plt.savefig(label + ".pdf", bbox_inches='tight')

    plt.show()
</code>```

Body:
I am trying to add two custom arrows with labels in a seaborn relplot graph.
I tried using the matplot arrow function which is not working because the seaborne relplot is a "facetgrid". I did not see a specific arrow pointer function in seaborn docu. I want to draw an arrow at a specific x value between the y values of two benchmarks (b1 b2 in example)

Is there an easy way to do this?
I added a simple code example, data and 2 images of what i try to achieve.

CODE:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import gc
import sys

if __name__ == '__main__':
        pfad = sys.argv[1]
        label = 'test'
        df1 = pd.read_csv(pfad, sep=';')

        sns_plot = sns.relplot(x="selectivity", ci=None, y="throughput", hue='benchmark', kind="line", data=df1,
                           dashes=False, markers=True, style="benchmark")

        sns_plot.savefig(label + ".png")
        plt.savefig(label + ".pdf", bbox_inches='tight')

        plt.show()

DATASET (example.csv in same folder)

benchmark;selectivity;throughput
b1;0.01;1426.89
b2;0.01;531.434
b1;0.03;826.89
b2;0.03;531.434
b1;0.05;626.89
b2;0.05;520.434

Currently my Graph looks like this:

This is what I want to achieve:

Body:
As mentioned in the comments, I flattened the axes, got the values from the line chart, and added text annotations and arrows respectively.

if __name__ == '__main__':
    pfad = sys.argv[1]
    label = 'test'
    df1 = pd.read_csv(pfad, sep=';')

    sns_plot = sns.relplot(x="selectivity", ci=None, y="throughput", hue='benchmark', kind="line", data=df1,
                       dashes=False, markers=True, style="benchmark")
    xydata = []
    for ax in sns_plot.axes.flat:
        for li in ax.lines:
            xydata.append(li.get_xydata())

    ax.text(xydata[0][0][0]+0.001, (xydata[0][0][1]+xydata[1][0][1])/2, '2.5X speedup')
    ax.text(xydata[1][2][0]+0.001, (xydata[0][2][1]+xydata[1][2][1])/2, '1.3X speedup')
    ax.annotate('',
                xy=(xydata[0][0][0], xydata[0][0][1]),
                xytext=(xydata[0][0][0], xydata[1][0][1]),
                xycoords='data',
                arrowprops=dict(facecolor='black',width=2.0,headwidth=7.0,headlength=7.0,shrink=0.01))
    ax.annotate('',
                xy=(xydata[1][2][0], xydata[0][2][1]),
                xytext=(xydata[1][2][0], xydata[1][2][1]),
                xycoords='data',
                arrowprops=dict(facecolor='black',width=2.0,headwidth=7.0,headlength=7.0,shrink=0.01))

    #sns_plot.savefig(label + ".png")
    #plt.savefig(label + ".pdf", bbox_inches='tight')

    plt.show()


来源: stackexchange

问:
Nested Reactive Form to count from main Object
I want to create a nested form from Data:

My Actual Data is:

```<code>mainObject = {
  adminname: 'Saqib',
  adminemail: 'email@example.com',
  users: [
    { user_type: 'Adult', count: 3 },
    { user_type: 'Child', count: 1 },
    { user_type: 'infant', count: 0 },
  ],
};
</code>```

I want to show nested forms for these Counts in Users Array. like there should be 3 adult forms, 1 child form and no Infant form as infant count is 0. And these counts can be changed like there could be 0 child and 1 infant.

.html

```<code><form [formGroup]="myForm" (ngSubmit)="onSubmit()">
  <input formControlName="name" placeholder="Enter Admin Name" />
  <br />
  <input formControlName="admin_email" placeholder="Enter Admin Email" />

  <div formArrayName="users">
    <div *ngFor="let pro of myForm.get('users').controls; let i = index">
      <br />
      <div [formGroupName]="i" style="border: 1px solid; padding: 10px">
        <div>User Type: {{ pro.value.user_type }}</div>
        User Name:<br />
        <input type="text" formControlName="user_name" /> <br />

        Email:<br />
        <input type="text" formControlName="user_email" />
      </div>
    </div>
  </div>

  <p>
    <button type="submit">Submit</button>
  </p>
</form>
</code>```

.ts

```<code>myForm: FormGroup;

  mainObject = {
    adminname: 'Saqib',
    adminemail: 'email@example.com',
    users: [
      { user_type: 'Adult', count: 3 },
      { user_type: 'Child', count: 1 },
      { user_type: 'infant', count: 0 },
    ],
  };
  // I want to Show forms according to this users count with their Type:
  // according to this data there should be 3 adult forms, 1 hchild form and no infant Form.

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.formInit();
  }

  formInit() {
    this.myForm = this.fb.group({
      name: '',
      admin_email: '',
      users: this.fb.array(
        this.mainObject.users.map((e) => this.newUsers(e.user_type, e.count))
      ),
    });
  }

  get users(): FormArray {
    return this.myForm.get('users') as FormArray;
  }

  newUsers(t, c): FormGroup {
    console.log(t, c);
    return this.fb.group({
      user_type: t,
      user_name: '',
      user_email: '',
    });
  }

  onSubmit() {
    console.log(this.myForm.value);
  }
</code>```

I have create example Stackblitz for better understanding:

Example Stackblitz

答:
Perhaps you can achieve the concept as below:

Concept:

Create a dictionary with group by key: user_type and value: an Array with (number of) object(s) created based on count.

Get the value from result 1, perform flatten nested array and add those objects into an array.

toFormUsers(users: any[]): any[] {
  // Generate array by user_type
  let userTypeGroup = users.reduce((accumulator, current) => {
    accumulator[current.user_type] = accumulator[current.user_type] || [];

    for (let i = 0; i < current.count; i++)
      accumulator[current.user_type].push({ user_type: current.user_type });

    return accumulator;
  }, {});

   // Flatten array of array for userTypeGroup
  return [].concat(
    ...Object.keys(userTypeGroup).map((x) => userTypeGroup[x])
  );
}
```
<p>And modify your <code>FormGroup</code> to apply the method above by passing <code>mainObject.users</code>.</p>
<pre class="lang-js prettyprint-override"><code>this.myForm = this.fb.group({
  name: '',
  admin_email: '',
  users: this.fb.array(
    this.toFormUsers(this.mainObject.users).map((e) => this.newUsers(e.user_type, e.count))
  ),
});
</code>```

Sample Demo on StackBlitz

ContentLicense: CC BY-SA 4.0

Body:
I want to create a nested form from Data:

My Actual Data is:

mainObject = {
  adminname: 'Saqib',
  adminemail: 'email@example.com',
  users: [
    { user_type: 'Adult', count: 3 },
    { user_type: 'Child', count: 1 },
    { user_type: 'infant', count: 0 },
  ],
};

I want to show nested forms for these Counts in Users Array. like there should be 3 adult forms, 1 child form and no Infant form as infant count is 0. And these counts can be changed like there could be 0 child and 1 infant.

.html

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
  <input formControlName="name" placeholder="Enter Admin Name" />

  <input formControlName="admin_email" placeholder="Enter Admin Email" />

User Type: {{ pro.value.user_type }}

        User Name:

        <input type="text" formControlName="user_name" />

        Email:

        <input type="text" formControlName="user_email" />

    <button type="submit">Submit</button>

</form>

.ts

myForm: FormGroup;

  mainObject = {
    adminname: 'Saqib',
    adminemail: 'email@example.com',
    users: [
      { user_type: 'Adult', count: 3 },
      { user_type: 'Child', count: 1 },
      { user_type: 'infant', count: 0 },
    ],
  };
  // I want to Show forms according to this users count with their Type:
  // according to this data there should be 3 adult forms, 1 hchild form and no infant Form.

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.formInit();
  }

  formInit() {
    this.myForm = this.fb.group({
      name: '',
      admin_email: '',
      users: this.fb.array(
        this.mainObject.users.map((e) => this.newUsers(e.user_type, e.count))
      ),
    });
  }

  get users(): FormArray {
    return this.myForm.get('users') as FormArray;
  }

  newUsers(t, c): FormGroup {
    console.log(t, c);
    return this.fb.group({
      user_type: t,
      user_name: '',
      user_email: '',
    });
  }

  onSubmit() {
    console.log(this.myForm.value);
  }

I have create example Stackblitz for better understanding:

Example Stackblitz

Body:
Perhaps you can achieve the concept as below:

Concept:

Create a dictionary with group by key: user_type and value: an Array with (number of) object(s) created based on count.

Get the value from result 1, perform flatten nested array and add those objects into an array.

toFormUsers(users: any[]): any[] {
  // Generate array by user_type
  let userTypeGroup = users.reduce((accumulator, current) => {
    accumulator[current.user_type] = accumulator[current.user_type] || [];

    for (let i = 0; i < current.count; i++)
      accumulator[current.user_type].push({ user_type: current.user_type });

    return accumulator;
  }, {});

   // Flatten array of array for userTypeGroup
  return [].concat(
    ...Object.keys(userTypeGroup).map((x) => userTypeGroup[x])
  );
}

And modify your FormGroup to apply the method above by passing mainObject.users.

this.myForm = this.fb.group({
  name: '',
  admin_email: '',
  users: this.fb.array(
    this.toFormUsers(this.mainObject.users).map((e) => this.newUsers(e.user_type, e.count))
  ),
});

Sample Demo on StackBlitz


问:
git push all branches from one remote to another remote iteratively
I am having a use case where we are migrating from one remote to another for a project.

legacy_remote : The existing remote which has been existing so far.
new_remote : The new remote on which all data has to be pushed from legacy remote.

I am using in following commands.

```<code>git remote set-url origin <legacy_remote>
git checkout master
git pull
git remote set-url origin <new_remote>
git push --force -u origin --all
git push origin --tags
</code>```

The reason i am using force keyword is that every time i do a merge i don't want to resolve the conflicts in new remote but rather replace the content in there on new remote as its not being used so far.

The problem which is happening is that command :

```<code>git push --force -u origin --all
</code>```

This command is only syncing master to master but not moving all branches from legacy remote onto the new remote.
Can anyone please tell what's missing in command.

答:
reason not using mirror is that there are couple of new branches created on new remote which don't want to be overridden

Then try

```<code>git push newremote --tags refs/remotes/origin/*:refs/heads/*
</code>```

Compared to git push --force -u origin --all, the branches don't have to be checked out first, as mentioned here.

Body:
I am having a use case where we are migrating from one remote to another for a project.

legacy_remote : The existing remote which has been existing so far.
new_remote : The new remote on which all data has to be pushed from legacy remote.

I am using in following commands.

git remote set-url origin <legacy_remote>
git checkout master
git pull
git remote set-url origin <new_remote>
git push --force -u origin --all
git push origin --tags

The reason i am using force keyword is that every time i do a merge i don't want to resolve the conflicts in new remote but rather replace the content in there on new remote as its not being used so far.

The problem which is happening is that command :

git push --force -u origin --all

This command is only syncing master to master but not moving all branches from legacy remote onto the new remote.
Can anyone please tell what's missing in command.

Body:
reason not using mirror is that there are couple of new branches created on new remote which don't want to be overridden

Then try

git push newremote --tags refs/remotes/origin/*:refs/heads/*

Compared to git push --force -u origin --all, the branches don't have to be checked out first, as mentioned here.


问:
Command times out when executing
```<code>Laravel version:
8.x

PHP version:
8.0

MySQL version:
8.0

Server:
Larave Forge
</code>```

I'm running a command on one of my websites

php artisan command:here

after a few minutes I get this status "Timed Out", is there anything that can be optimized here to prevent the time out?

subscriptions table has 40,000 records and incomes table has 8,000,000. Every subscription has a maximum of 200 records in the incomes table.

To explain what this command does, this is fixing (by inserting) the lacking of income of every ACTIVE subscription, which will be identified based on the hour difference from the last income that has been inserted. Every subscription has a max of 200 records in the incomes table, so if the script detected that a subscription has already reached the 200 income records, it will update the status to
COMPLETED.

Subscription.php (model)

```<code>public function latestIncome()
{
    return $this->hasOne(Income::class)->latestOfMany();
}
</code>```

Income.php (model)

```<code>public function subscription()
{
    return $this->belongsTo(Subscription::class);
}
</code>```
```<code>namespace App\Console\Commands;

class SomeCommand extends Command
{
    protected $signature = 'command:here';

    public function handle()
    {
        ini_set('max_execution_time', 0);

        foreach (Subscription::with('latestIncome')->withCount('income')->where('status', 'ACTIVE')->lazy() as $subscription) {
            $count_earnings = $subscription->income_count;
            $recent_bonus = $subscription->latestIncome;

            if ($recent_bonus) {
                if ($count_earnings < 200) {
                    $hour_difference = now()->diffInHours($recent_bonus->created_at);

                    if ($hour_difference > 1) {
                        $to_insert = 200 - $count_earnings;
                        $max = $hour_difference;

                        if ($hour_difference > $to_insert) {
                            $max = $to_insert;
                        }

                        for ($i = 0; $i < $max; $i++) {
                            $income = new Income;
                            $income->user_id = $subscription->user_id;
                            $income->subscription_id = $subscription->id;
                            $income->amount = (100 * 0.002) * 100;
                            $income->save();
                        }

                        if (($count_earnings + $max) >= 200) {
                            $subscription->update(['status' => 'COMPLETED']);
                        }

                        Log::info('Fix for:'.$subscription->id.' | User:'.$subscription->user_id.' | Total:'.$max);
                    }
                } else {
                    $subscription->update(['status' => 'COMPLETED']);
                }
            }
        }
    }
}
</code>```

答:
You might gain some performance if you do your updates in bulk:</p>
```<code>namespace App\Console\Commands;

class SomeCommand extends Command
{
    protected $signature = 'command:here';

    public function handle()
    {
        ini_set('max_execution_time', 0);

        // Update everything you can before the loop
        Subscription::has('income', '>=', 200)
                ->where('status', '!=' 'COMPLETED')
                ->update([ 'status' => 'COMPLETED' ]);

        foreach (Subscription::with('latestIncome')->withCount('income')->where('status', 'ACTIVE')->lazy() as $subscription) {
            $count_earnings = $subscription->income_count;
            $recent_bonus = $subscription->latestIncome;

            if ($recent_bonus) {
              $hour_difference = now()->diffInHours($recent_bonus->created_at);

              if ($hour_difference > 1) {
                   $to_insert = 200 - $count_earnings;
                   $max = $hour_difference;

                   if ($hour_difference > $to_insert) {
                       $max = $to_insert;
                   }

                   // Some performance gain here possibly
                   Income::insert(collect()->pad($max, [
                         'user_id' => $subscription->user_id,
                         'subscription_id' => $subscription->id,
                         'amount' => (100 * 0.002) * 100,
                   ])->all());

                   Log::info('Fix for:'.$subscription->id.' | User:'.$subscription->user_id.' | Total:'.$max);
                }
            }
        }
       // Update anything that got pushed over that threshold
       Subscription::has('income', '>=', 200)
            ->where('status', '!=' 'COMPLETED')
            ->update([ 'status' => 'COMPLETED' ]);
    }
}

</code>```

Title: Command times out when executing

Body:
Laravel version:
8.x

PHP version:
8.0

MySQL version:
8.0

Server:
Larave Forge

I'm running a command on one of my websites

php artisan command:here

after a few minutes I get this status "Timed Out", is there anything that can be optimized here to prevent the time out?

subscriptions table has 40,000 records and incomes table has 8,000,000. Every subscription has a maximum of 200 records in the incomes table.

To explain what this command does, this is fixing (by inserting) the lacking of income of every ACTIVE subscription, which will be identified based on the hour difference from the last income that has been inserted. Every subscription has a max of 200 records in the incomes table, so if the script detected that a subscription has already reached the 200 income records, it will update the status to
COMPLETED.

Subscription.php (model)

public function latestIncome()
{
    return $this->hasOne(Income::class)->latestOfMany();
}

Income.php (model)

public function subscription()
{
    return $this->belongsTo(Subscription::class);
}

namespace App\Console\Commands;

class SomeCommand extends Command
{
    protected $signature = 'command:here';

    public function handle()
    {
        ini_set('max_execution_time', 0);

        foreach (Subscription::with('latestIncome')->withCount('income')->where('status', 'ACTIVE')->lazy() as $subscription) {
            $count_earnings = $subscription->income_count;
            $recent_bonus = $subscription->latestIncome;

            if ($recent_bonus) {
                if ($count_earnings < 200) {
                    $hour_difference = now()->diffInHours($recent_bonus->created_at);

                    if ($hour_difference > 1) {
                        $to_insert = 200 - $count_earnings;
                        $max = $hour_difference;

                        if ($hour_difference > $to_insert) {
                            $max = $to_insert;
                        }

                        for ($i = 0; $i < $max; $i++) {
                            $income = new Income;
                            $income->user_id = $subscription->user_id;
                            $income->subscription_id = $subscription->id;
                            $income->amount = (100 * 0.002) * 100;
                            $income->save();
                        }

                        if (($count_earnings + $max) >= 200) {
                            $subscription->update(['status' => 'COMPLETED']);
                        }

                        Log::info('Fix for:'.$subscription->id.' | User:'.$subscription->user_id.' | Total:'.$max);
                    }
                } else {
                    $subscription->update(['status' => 'COMPLETED']);
                }
            }
        }
    }
}

Body:
You might gain some performance if you do your updates in bulk:

namespace App\Console\Commands;

class SomeCommand extends Command
{
    protected $signature = 'command:here';

    public function handle()
    {
        ini_set('max_execution_time', 0);

        // Update everything you can before the loop
        Subscription::has('income', '>=', 200)
                ->where('status', '!=' 'COMPLETED')
                ->update([ 'status' => 'COMPLETED' ]);

        foreach (Subscription::with('latestIncome')->withCount('income')->where('status', 'ACTIVE')->lazy() as $subscription) {
            $count_earnings = $subscription->income_count;
            $recent_bonus = $subscription->latestIncome;

            if ($recent_bonus) {
              $hour_difference = now()->diffInHours($recent_bonus->created_at);

              if ($hour_difference > 1) {
                   $to_insert = 200 - $count_earnings;
                   $max = $hour_difference;

                   if ($hour_difference > $to_insert) {
                       $max = $to_insert;
                   }

                   // Some performance gain here possibly
                   Income::insert(collect()->pad($max, [
                         'user_id' => $subscription->user_id,
                         'subscription_id' => $subscription->id,
                         'amount' => (100 * 0.002) * 100,
                   ])->all());

                   Log::info('Fix for:'.$subscription->id.' | User:'.$subscription->user_id.' | Total:'.$max);
                }
            }
        }
       // Update anything that got pushed over that threshold
       Subscription::has('income', '>=', 200)
            ->where('status', '!=' 'COMPLETED')
            ->update([ 'status' => 'COMPLETED' ]);
    }
}


问:
How to add new attributes to Material UI Shadows | Typescript
I am trying to customize the Material UI types for shadow, but getting the below error when I try to use it in my code.

```<code>Tuple type Shadows of length 25 has no element at index 25.
</code>```

I have tried many solutions but none helped. Below is what I have tried:

I have a index.d.ts file defined at root level and adding the declare module to customize the shadow property of Mui theme.

```<code>declare module '@material-ui/core/styles/shadows' {
  type Shadows = [
    {
      a1: string;
      a2: string;
      a3: string;
    }
  ];
}
</code>```

答:
Hi you can customize any of shadow using ES6 spread operator.</p>
```<code>const theme = createMuiTheme({
  shadows: [...createMuiTheme({}).shadows.map((shadow, i) => (
    i === 1 ? '0 0 18px 0 rgba(9, 32, 46, 0.2)' : shadow
  ))],
});
</code>```

Body:
I am trying to customize the Material UI types for shadow, but getting the below error when I try to use it in my code.

Tuple type Shadows of length 25 has no element at index 25.

I have tried many solutions but none helped. Below is what I have tried:

I have a index.d.ts file defined at root level and adding the declare module to customize the shadow property of Mui theme.

declare module '@material-ui/core/styles/shadows' {
  type Shadows = [
    {
      a1: string;
      a2: string;
      a3: string;
    }
  ];
}

Body:
Hi you can customize any of shadow using ES6 spread operator.

const theme = createMuiTheme({
  shadows: [...createMuiTheme({}).shadows.map((shadow, i) => (
    i === 1 ? '0 0 18px 0 rgba(9, 32, 46, 0.2)' : shadow
  ))],
});


问:
Interpreting ProcessingInstruction as space with itertext
I want to have all my text of a tag using lxml.etree._Element.itertext()

However, in my text I have PI and this does not generate space. Is there a parameter to do this? Or should I make a first pass by adding a space next to the PI if there is none?

```<code><p><?PI ?>Some text<?PI ?>continue the text</p>
</code>```

So with this exemple I want have:

"Some text continue the text"

But have:

"Some textcontinue the text"

Thanks for your help

答:
You can replace the PI tag with a space.</p>
```<code>import xml.etree.ElementTree as ET
xml = '<p><?PI ?>Some text<?PI ?>continue the text</p>'
xml = xml.replace('<?PI ?>',' ')
text = ''.join(ET.fromstring(xml).itertext())
text.strip()
</code>```

Body:
I want to have all my text of a tag using lxml.etree._Element.itertext()

However, in my text I have PI and this does not generate space. Is there a parameter to do this? Or should I make a first pass by adding a space next to the PI if there is none?

<?PI ?>Some text<?PI ?>continue the text

So with this exemple I want have:

"Some text continue the text"

But have:

"Some textcontinue the text"

Thanks for your help

Body:
You can replace the PI tag with a space.

import xml.etree.ElementTree as ET
xml = '<p><?PI ?>Some text<?PI ?>continue the text</p>'
xml = xml.replace('<?PI ?>',' ')
text = ''.join(ET.fromstring(xml).itertext())
text.strip()


问:
Display Day of the Week dynamically in Arrowhead TimeStamp on Hover
Currently 'Day' is not displayed in timestamp of the Arrowhead when hovered on a particular bar  .

str.format() does provide this function but the barindex has to be specified separately in code (and isn't recognised on hover).(here)

In PineScript is there a way to modify the arrowhead timestamp and show the Day (on hover)?

答:
No, the date format only supports combinations of day/month/year.

If you are looking for a way to display the day of the week on your chart, a workaround might be displaying it in a table.

```<code>//@version=5
indicator("My script", overlay=true)

f_get_day() =>
    switch dayofweek
        1 => "Sunday"
        2 => "Monday"
        3 => "Tuesday"
        4 => "Wednesday"
        5 => "Thursday"
        6 => "Friday"
        7 => "Saturday"

var testTable = table.new(position = position.top_right, columns = 1, rows = 1, bgcolor = color.yellow, border_width = 1)

if barstate.islast
    table.cell(table_id = testTable, column = 0, row = 0, text = f_get_day())
</code>```

Body:
No, the date format only supports combinations of day/month/year.

If you are looking for a way to display the day of the week on your chart, a workaround might be displaying it in a table.

//@version=5
indicator("My script", overlay=true)

f_get_day() =>
    switch dayofweek
        1 => "Sunday"
        2 => "Monday"
        3 => "Tuesday"
        4 => "Wednesday"
        5 => "Thursday"
        6 => "Friday"
        7 => "Saturday"

var testTable = table.new(position = position.top_right, columns = 1, rows = 1, bgcolor = color.yellow, border_width = 1)

if barstate.islast
    table.cell(table_id = testTable, column = 0, row = 0, text = f_get_day())


问:
memory-efficient built-in SqlAlchemy iterator/generator?
I have a ~10M record MySQL table that I interface with using SqlAlchemy.  I have found that queries on large subsets of this table will consume too much memory even though I thought I was using a built-in generator that intelligently fetched bite-sized chunks of the dataset:

```<code>for thing in session.query(Things):
    analyze(thing)
</code>```

To avoid this, I find I have to build my own iterator that bites off in chunks:

```<code>lastThingID = None
while True:
    things = query.filter(Thing.id < lastThingID).limit(querySize).all()
    if not rows or len(rows) == 0:
        break
    for thing in things:
        lastThingID = row.id
        analyze(thing)
</code>```

Is this normal or is there something I'm missing regarding SA built-in generators?

The answer to this question seems to indicate that the memory consumption is not to be expected.

答:
If you're working with Postgres or an RDBMS that supports cursors, it is very simple to iterate efficiently over a lot of rows:

```<code> with db_session() as session:
     for partition in session.stream(select(Thing.id)).partitions(1000):
         for item in partition:
             analyze(item)
</code>```

This creates a forward cursor that fetches the result in batches of 1000 rows, which results in minimal memory usage on the server and on the client.

ContentLicense: CC BY-SA 3.0

Body:
I have a ~10M record MySQL table that I interface with using SqlAlchemy.  I have found that queries on large subsets of this table will consume too much memory even though I thought I was using a built-in generator that intelligently fetched bite-sized chunks of the dataset:

for thing in session.query(Things):
    analyze(thing)

To avoid this, I find I have to build my own iterator that bites off in chunks:

lastThingID = None
while True:
    things = query.filter(Thing.id < lastThingID).limit(querySize).all()
    if not rows or len(rows) == 0:
        break
    for thing in things:
        lastThingID = row.id
        analyze(thing)

Is this normal or is there something I'm missing regarding SA built-in generators?

The answer to this question seems to indicate that the memory consumption is not to be expected.

Body:
If you're working with Postgres or an RDBMS that supports cursors, it is very simple to iterate efficiently over a lot of rows:

 with db_session() as session:
     for partition in session.stream(select(Thing.id)).partitions(1000):
         for item in partition:
             analyze(item)

This creates a forward cursor that fetches the result in batches of 1000 rows, which results in minimal memory usage on the server and on the client.


问:
How to remove non-printable characters from string?
I am reading a word file using below code :

```<code>import win32com.client as win32

word = win32.dynamic.Dispatch("Word.Application")
word.Visible = 0
doc = word.Documents.Open(SigLexiconFilePath)
</code>```

I get strings from the file which has lot of non-printable characters:

```<code>str = "\xa0keine\xa0freigäbü\xa0\x0b\r\x07"
</code>```

I tried below codes to remove non-printable characters :

```<code>import string

str = "\xa0keine\xa0freigäbü\xa0\x0b\r\x07"
filtered_string = "".join(filter(lambda x:x in string.printable, str))
</code>```

This gives me below output:

```<code>keinefreigb\x0b\r
</code>```

Other piece of code which I tried :

```<code>str = str.split('\r')[0]
str = str.strip()
</code>```

This gives me below output:

```<code>keine\xa0freigäbü
</code>```

How can i remove all these non-printable characters to get below desired output using minimum code :

```<code>keine freigäbü
</code>```

答:
An elegant pythonic solution to stripping 'non printable' characters from a string in python is to use the isprintable() string method together with a generator expression or list comprehension depending on the use case ie. size of the string:

```<code>''.join(c for c in str if c.isprintable())
</code>```

returns 'keinefreigäbü'

str.isprintable() Return True if all characters in the string are printable or the string is empty, False otherwise. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when repr() is invoked on a string. It has no bearing on the handling of strings written to sys.stdout or sys.stderr.)

Body:
I am reading a word file using below code :

import win32com.client as win32

word = win32.dynamic.Dispatch("Word.Application")
word.Visible = 0
doc = word.Documents.Open(SigLexiconFilePath)

I get strings from the file which has lot of non-printable characters:

str = "\xa0keine\xa0freigäbü\xa0\x0b\r\x07"

I tried below codes to remove non-printable characters :

import string

str = "\xa0keine\xa0freigäbü\xa0\x0b\r\x07"
filtered_string = "".join(filter(lambda x:x in string.printable, str))

This gives me below output:

keinefreigb\x0b\r

Other piece of code which I tried :

str = str.split('\r')[0]
str = str.strip()

This gives me below output:

keine\xa0freigäbü

How can i remove all these non-printable characters to get below desired output using minimum code :

keine freigäbü

Body:
An elegant pythonic solution to stripping 'non printable' characters from a string in python is to use the isprintable() string method together with a generator expression or list comprehension depending on the use case ie. size of the string:

''.join(c for c in str if c.isprintable())

returns 'keinefreigäbü'

str.isprintable() Return True if all characters in the string are printable or the string is empty, False otherwise. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when repr() is invoked on a string. It has no bearing on the handling of strings written to sys.stdout or sys.stderr.)


问:
"PKIX path building failed" using Gradle with ZScaler
recently I'm facing some issues using gradle at our development department.
After our Department switched to ZScaler instead of our old VPN solution, I'm facing issues building our android app projects:

```<code>~ gradle clean

> Starting Daemon

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'com.example.app'.
> Could not resolve all artifacts for configuration ':classpath'.
   > Could not resolve com.android.tools.build:gradle:7.0.2.
     Required by:
         project :
      > Could not resolve com.android.tools.build:gradle:7.0.2.
         > Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/7.0.2/gradle-7.0.2.pom'.
            > Could not GET 'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/7.0.2/gradle-7.0.2.pom'.
               > PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
      > Could not resolve com.android.tools.build:gradle:7.0.2.
         > Could not get resource 'https://repo.maven.apache.org/maven2/com/android/tools/build/gradle/7.0.2/gradle-7.0.2.pom'.
            > Could not GET 'https://repo.maven.apache.org/maven2/com/android/tools/build/gradle/7.0.2/gradle-7.0.2.pom'.
               > PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
</code>```

I'm using a Windows 10 x64 machine
Gradle: 5.6.4
openjdk: 11.0.2 2019-01-15
Kotlin:       1.3.41

Does someone know about this issue?

Thanks in advance!

答:
This is a certificate issue. Get in touch with your it team to setup your VPN.

The issue in my case was it was not allowing to access the online gradle , google plugin repositories.

Maybe they did not whitelist them or it has not been set up in your device

Body:
recently I'm facing some issues using gradle at our development department.
After our Department switched to ZScaler instead of our old VPN solution, I'm facing issues building our android app projects:

~ gradle clean

> Starting Daemon

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'com.example.app'.
> Could not resolve all artifacts for configuration ':classpath'.
   > Could not resolve com.android.tools.build:gradle:7.0.2.
     Required by:
         project :
      > Could not resolve com.android.tools.build:gradle:7.0.2.
         > Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/7.0.2/gradle-7.0.2.pom'.
            > Could not GET 'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/7.0.2/gradle-7.0.2.pom'.
               > PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
      > Could not resolve com.android.tools.build:gradle:7.0.2.
         > Could not get resource 'https://repo.maven.apache.org/maven2/com/android/tools/build/gradle/7.0.2/gradle-7.0.2.pom'.
            > Could not GET 'https://repo.maven.apache.org/maven2/com/android/tools/build/gradle/7.0.2/gradle-7.0.2.pom'.
               > PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

I'm using a Windows 10 x64 machine
Gradle: 5.6.4
openjdk: 11.0.2 2019-01-15
Kotlin:       1.3.41

Does someone know about this issue?

Thanks in advance!


问:
Using a DataTrigger to set the properties of a ScaleTransform
A failed XAML attempt here - I'm obviously doing something stupid with the Style/Setter syntax. I just want to flip an element based on some bindings by setting the ScaleX and ScaleY properties of a ScaleTransform from a DataTrigger. Setter.Property obviously doesn't support a property path, but how can I get round this? I can't set the whole RenderTransform property because ScaleX and ScaleY are independent. Any ideas?

```<code><Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
   <StackPanel>
      <TextBlock FontSize="50" RenderTransformOrigin=".5,.5">
         <TextBlock.Style>
            <Style>
               <Style.Triggers>
                  <DataTrigger Binding="{Binding IsChecked, ElementName=FlipX}" Value="True">
                     <Setter Property="RenderTransform.ScaleX" Value="-1"/>
                  </DataTrigger>
                  <DataTrigger Binding="{Binding IsChecked, ElementName=FlipY}" Value="True">
                     <Setter Property="RenderTransform.ScaleY" Value="-1"/>
                  </DataTrigger>
               </Style.Triggers>
            </Style>
         </TextBlock.Style>
         <TextBlock.RenderTransform>
          <ScaleTransform/>
         </TextBlock.RenderTransform>
      Hello World
      </TextBlock>
      <CheckBox Name="FlipX">Flip x</CheckBox>
      <CheckBox Name="FlipY">Flip y</CheckBox>
   </StackPanel>
</Page>
</code>```

答:
You could use:</p>

```<code><Style.Triggers>
    <MultiDataTrigger>
        <MultiDataTrigger.Conditions>
            <Condition Binding="{Binding IsChecked, ElementName=FlipX}" Value="True" />
            <Condition Binding="{Binding IsChecked, ElementName=FlipY}" Value="True" />
         </MultiDataTrigger.Conditions>
         <Setter Property="RenderTransform">
             <Setter.Value>
                 <ScaleTransform ScaleX="-1" ScaleY="-1" />
             </Setter.Value>
         </Setter>
    </MultiDataTrigger>
    <MultiDataTrigger>
        <MultiDataTrigger.Conditions>
            <Condition Binding="{Binding IsChecked, ElementName=FlipX}" Value="True" />
            <Condition Binding="{Binding IsChecked, ElementName=FlipY}" Value="False" />
         </MultiDataTrigger.Conditions>
         <Setter Property="RenderTransform">
             <Setter.Value>
                 <ScaleTransform ScaleX="-1" ScaleY="1" />
             </Setter.Value>
         </Setter>
    </MultiDataTrigger>
    <MultiDataTrigger>
        <MultiDataTrigger.Conditions>
            <Condition Binding="{Binding IsChecked, ElementName=FlipX}" Value="False" />
            <Condition Binding="{Binding IsChecked, ElementName=FlipY}" Value="True" />
         </MultiDataTrigger.Conditions>
         <Setter Property="RenderTransform">
             <Setter.Value>
                 <ScaleTransform ScaleX="1" ScaleY="-1" />
             </Setter.Value>
         </Setter>
    </MultiDataTrigger>
</Style.Triggers>
</code>```

Body:
A failed XAML attempt here - I'm obviously doing something stupid with the Style/Setter syntax. I just want to flip an element based on some bindings by setting the ScaleX and ScaleY properties of a ScaleTransform from a DataTrigger. Setter.Property obviously doesn't support a property path, but how can I get round this? I can't set the whole RenderTransform property because ScaleX and ScaleY are independent. Any ideas?

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
   <StackPanel>
      <TextBlock FontSize="50" RenderTransformOrigin=".5,.5">
         <TextBlock.Style>

            </Style>
         </TextBlock.Style>
         <TextBlock.RenderTransform>
          <ScaleTransform/>
         </TextBlock.RenderTransform>
      Hello World
      </TextBlock>
      <CheckBox Name="FlipX">Flip x</CheckBox>
      <CheckBox Name="FlipY">Flip y</CheckBox>
   </StackPanel>
</Page>

Body:
You could use:

<Style.Triggers>
    <MultiDataTrigger>
        <MultiDataTrigger.Conditions>
            <Condition Binding="{Binding IsChecked, ElementName=FlipX}" Value="True" />
            <Condition Binding="{Binding IsChecked, ElementName=FlipY}" Value="True" />
         </MultiDataTrigger.Conditions>
         <Setter Property="RenderTransform">
             <Setter.Value>
                 <ScaleTransform ScaleX="-1" ScaleY="-1" />
             </Setter.Value>
         </Setter>
    </MultiDataTrigger>
    <MultiDataTrigger>
        <MultiDataTrigger.Conditions>
            <Condition Binding="{Binding IsChecked, ElementName=FlipX}" Value="True" />
            <Condition Binding="{Binding IsChecked, ElementName=FlipY}" Value="False" />
         </MultiDataTrigger.Conditions>
         <Setter Property="RenderTransform">
             <Setter.Value>
                 <ScaleTransform ScaleX="-1" ScaleY="1" />
             </Setter.Value>
         </Setter>
    </MultiDataTrigger>
    <MultiDataTrigger>
        <MultiDataTrigger.Conditions>
            <Condition Binding="{Binding IsChecked, ElementName=FlipX}" Value="False" />
            <Condition Binding="{Binding IsChecked, ElementName=FlipY}" Value="True" />
         </MultiDataTrigger.Conditions>
         <Setter Property="RenderTransform">
             <Setter.Value>
                 <ScaleTransform ScaleX="1" ScaleY="-1" />
             </Setter.Value>
         </Setter>
    </MultiDataTrigger>
</Style.Triggers>


问:
Git: Undo a commit after several good commits have been commited afterwards
I have a beginner question around git and GitHub i was hoping someone could help with.

I have accidentally committed a change in  piece of code that contains credentials on my local private repository on my local machine.

My pseudo commit history looks like the below and i am using the desktop application for GitHub to make these commits. I made the mistaken commit at id 3 but then all my other commits from four to seven are a big body of work and I do not wish to lose them.

Since this is my own repository the quick method might be to simply copy out the files i changed and revert back all my changes to id 3 and then copy in my good changed files. I was wondering if there was a better Git way

```<code>commit first change  id 1
commit second change id 2
commit third change  id 3 - here is where the password was committed
commit first change  id 4
commit second change id 5
commit first change  id 6
commit second change id 7
</code>```

Thank you very much for your time

答:
Since you tagged GitHub as well. Be sure to contact GitHub support to have them expunge the commit from their issue and PR links as well as the caches.

Do reset the password. Once pushed the password is out there.

The official process would be to:

Git clone --mirror a fresh copy of the repo. To be sure you have everything

git filter-repo to remove the password from all commits

Then run the garbage collector to remove all unreferenced commits:  git reflog expire --expire=now --all && git gc --prune=now --aggressive

Then force push the repo with the --mirror option.

Then contact GitHub support to remove the old commits from the caches.

Then contact all other contributors to get a fresh clone of to rebase their branches into the updated repository.

Body:
I have a beginner question around git and GitHub i was hoping someone could help with.

I have accidentally committed a change in  piece of code that contains credentials on my local private repository on my local machine.

My pseudo commit history looks like the below and i am using the desktop application for GitHub to make these commits. I made the mistaken commit at id 3 but then all my other commits from four to seven are a big body of work and I do not wish to lose them.

Since this is my own repository the quick method might be to simply copy out the files i changed and revert back all my changes to id 3 and then copy in my good changed files. I was wondering if there was a better Git way

commit first change  id 1
commit second change id 2
commit third change  id 3 - here is where the password was committed
commit first change  id 4
commit second change id 5
commit first change  id 6
commit second change id 7

Thank you very much for your time


问:
Plot value near point matplotlib
I have the following graph in in which there is the average bpm in relation to the listening day. I want to plot near the point the exact value of mean. How can I do it?

This is the image

What I expect in output is:

expected output

This is the code I wrote:

```<code>df = pd.read_csv(f, encoding = "ISO-8859-1", sep = ';')
bpmFriday= df.tempo

x = df .date.iloc[0]
bpmMean = bpmFriday.mean()

first= plt.figure(figsize=(10,5))
plt.title('BPM mean (Friday)')
plt.scatter(x, bpmMean )
plt.xticks(rotation=45)
</code>```

答:
You can use plt.text(x, y, s) where s is the text you want to display and x and y are the text coordinates.

```<code>import matplotlib.pyplot as plt

x = '2021-12-25'
bpmMean = 420

first= plt.figure(figsize=(10,5))
plt.title('BPM mean (Friday)')
plt.scatter(x, bpmMean )
plt.xticks(rotation=45)

# plt.annotate(s=bpmMean, xy=(x, bpmMean+.5))

plt.text(x=x, y=bpmMean+0.5, s=bpmMean) # y=bpmMean+0.5 for readibility
</code>```

Title: Plot value near point matplotlib

Body:
I have the following graph in in which there is the average bpm in relation to the listening day. I want to plot near the point the exact value of mean. How can I do it?

This is the image

What I expect in output is:

expected output

This is the code I wrote:

df = pd.read_csv(f, encoding = "ISO-8859-1", sep = ';')
bpmFriday= df.tempo

x = df .date.iloc[0]
bpmMean = bpmFriday.mean()

first= plt.figure(figsize=(10,5))
plt.title('BPM mean (Friday)')
plt.scatter(x, bpmMean )
plt.xticks(rotation=45)

Body:
You can use plt.text(x, y, s) where s is the text you want to display and x and y are the text coordinates.

import matplotlib.pyplot as plt

x = '2021-12-25'
bpmMean = 420

first= plt.figure(figsize=(10,5))
plt.title('BPM mean (Friday)')
plt.scatter(x, bpmMean )
plt.xticks(rotation=45)

# plt.annotate(s=bpmMean, xy=(x, bpmMean+.5))

plt.text(x=x, y=bpmMean+0.5, s=bpmMean) # y=bpmMean+0.5 for readibility


问:
How can I change the Python version in Visual Studio Code?
These are my settings:

User Settings

{
    "atomKeymap.promptV3Features": true,
    "editor.multiCursorModifier": "ctrlCmd",
    "editor.formatOnPaste": true,
    "python.pythonPath": "python3",
    "command": "python3",
}
```
</li>
<li><p>Workspace Settings</p>
<pre class="lang-json prettyprint-override"><code>{
    "python.pythonPath": "${workspaceFolder}/env/bin/python3.6",
    "git.ignoreLimitWarning": true
}
</code>```

tasks.json

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "0.1.0",
    "command": "python3",
    "isShellCommand": true,
    "args": ["${file}"],
    "showOutput": "always"
}
```

If I use the debug console, the version and path is right:

But the output always defaults to "python2.7", no matter what I do.

How can I fix this?

答: Windows: Use py -3.6 --version or to create virtual environment py -3.6 -m venv venv36

Body:
These are my settings:

User Settings

{
    "atomKeymap.promptV3Features": true,
    "editor.multiCursorModifier": "ctrlCmd",
    "editor.formatOnPaste": true,
    "python.pythonPath": "python3",
    "command": "python3",
}

Workspace Settings

{
    "python.pythonPath": "${workspaceFolder}/env/bin/python3.6",
    "git.ignoreLimitWarning": true
}

tasks.json

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "0.1.0",
    "command": "python3",
    "isShellCommand": true,
    "args": ["${file}"],
    "showOutput": "always"
}

If I use the debug console, the version and path is right:

But the output always defaults to "python2.7", no matter what I do.

How can I fix this?


问:
Regex to remove the character immediately after number
I want to remove a substring and number from the string.
For example:

AB1 Line 01B

CD12 Line 21

AE2 Line 12a

should return

AB

CD

AE  respectively

Currently, I'm using 'Line|[0-9]' regex, which can match everything except the character immediately after the string ('B' in 01B).
What changes should I make?
Your help is appreciated.

答:
```<code>var a = "AB1 Line 01B"
var b = a.replace(/\d.*/g, "")
console.log(b)
</code>```


问:
in-browser SSH - IP address range
One of the options to ssh into the instance is in-browser ssh. It only works if I allow SSH from 0.0.0.0/0 IP range.

Is there a way to get the range of specific IP address range(s) from where GCP will establish in-browser SSH?

P.S.: I am not talking about SSH from my laptop. I am talking about in-browser SSH.

答:
Why don't you run the command who on your ssh session, to see where the connection is originating from?

The search the excellent Cloud Platform documentation to see if an automation to allow this already exists. Otherwise write one.

This is not the best place to do your firewalling from, as its one more configuration to keep up to date. I would recommend an application firewall, or just adding a rate limit to your existing firewall. The chances of someone logging into your servers if you use keys, is virtually 0, even with a 14 character random password, and rate limited new connections. If you use keys or a password manager (as you should), use fail2ban.

Title: in-browser SSH - IP address range


问:
where after select using linq
I would like to add where condition  after my select but it wont let me. compiler complains and says a antonymous type for c inside the Where as it doesnt know if its clients or clientLogin

here is my code:

```<code>                    clientsLogin = (from c in db.Clients
                    join cl in db.clientLogin
                        on c.id equals cl.clientid
                    where c.active == true && cl.is_active == true
                    select new { cl, c }).ToList().
Where( c =>  DateTime.UtcNow < c.createdon.Value.AddHours(+48) && DateTime.UtcNow > c.createdon.Value.AddHours(+24)).ToList();
</code>```

答:
ended up doing the following:</p>
```<code>var clientsLoginAfter1Day = (from c in db.Clients
                            join cl in db.clientLogin
                                on c.id equals cl.clientid
                            where c.active == true && cl.is_active == true
                            select new { cl, c.createdon })
                        .ToList()
                        .Where(c => c.createdon >=  DateTime.UtcNow.AddHours(-48))
                        .Where(c => c.createdon < DateTime.UtcNow.AddHours(-24))
                        .ToList();
</code>```

Title: where after select using linq

Body:
I would like to add where condition  after my select but it wont let me. compiler complains and says a antonymous type for c inside the Where as it doesnt know if its clients or clientLogin

here is my code:

                    clientsLogin = (from c in db.Clients
                    join cl in db.clientLogin
                        on c.id equals cl.clientid
                    where c.active == true && cl.is_active == true
                    select new { cl, c }).ToList().
Where( c =>  DateTime.UtcNow < c.createdon.Value.AddHours(+48) && DateTime.UtcNow > c.createdon.Value.AddHours(+24)).ToList();

Body:
ended up doing the following:

var clientsLoginAfter1Day = (from c in db.Clients
                            join cl in db.clientLogin
                                on c.id equals cl.clientid
                            where c.active == true && cl.is_active == true
                            select new { cl, c.createdon })
                        .ToList()
                        .Where(c => c.createdon >=  DateTime.UtcNow.AddHours(-48))
                        .Where(c => c.createdon < DateTime.UtcNow.AddHours(-24))
                        .ToList();


问:
How to correctly add a systemd service to a cpack generated debian package?
I am trying to generate a debian package via cpack that respects the system configuration (as in don't start the service if the admin doesn't want it to) and that does not cause errors when being installed in a systemd free environment (as in some docker images).

My current setup consist out of a postinst and a prerm file that are simple given to cpack via CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA.
These call systemctl enable/start/stop/disable in both scripts.

From what I have gathered one should call dh_installsystemd --name=foo foo.service for starting services.

Replacing systemctl enable foo.service with that in my postinst file however causes an error:

```<code>dh_installsystemd: error: "debian/control" not found. Are you sure you are in the correct directory?
dpkg: error processing package foo (--configure):
 installed foo package post-installation script subprocess returned error exit status 255
Processing triggers for libc-bin (2.31-0ubuntu9.2) ...
Errors were encountered while processing:
 foo
</code>```

I must confess that I am somewhat lost as to how this should be handled.
How does one correctly add a systemd service to a debian package via CPack?

答:
The best solution that has come to mind is to dissect another package and use the same commands dh_installsystemd generates.

This results in a postinst file like:

```<code># End automatically added section
# Based on output by dh_installsystemd/13.5.2

if [ \"$1\" = \"configure\" ] || [ \"$1\" = \"abort-upgrade\" ] || [ \"$1\" = \"abort-deconfigure\" ] || [ \"$1\" = \"abort-remove\" ] ; then

    # was-enabled defaults to true, so new installations run enable.
    if deb-systemd-helper --quiet was-enabled 'foo.service'; then
        # Enables the unit on first installation, creates new
        # symlinks on upgrades if the unit file has changed.
        deb-systemd-helper enable 'foo.service' >/dev/null || true
    else
        # Update the statefile to add new symlinks (if any), which need to be
        # cleaned up on purge. Also remove old symlinks.
        deb-systemd-helper update-state 'foo.service' >/dev/null || true
    fi
fi
if [ \"$1\" = \"configure\" ] || [ \"$1\" = \"abort-upgrade\" ] || [ \"$1\" = \"abort-deconfigure\" ] || [ \"$1\" = \"abort-remove\" ] ; then
    if [ -z \"${DPKG_ROOT\:-}\" ] && [ -d /run/systemd/system ]; then
        systemctl --system daemon-reload >/dev/null || true
        deb-systemd-invoke restart 'foo.service' >/dev/null || true
    fi
fi

</code>```

Since these instructions are static updates in the macros have to be manually applied.

Body:
I am trying to generate a debian package via cpack that respects the system configuration (as in don't start the service if the admin doesn't want it to) and that does not cause errors when being installed in a systemd free environment (as in some docker images).

My current setup consist out of a postinst and a prerm file that are simple given to cpack via CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA.
These call systemctl enable/start/stop/disable in both scripts.

From what I have gathered one should call dh_installsystemd --name=foo foo.service for starting services.

Replacing systemctl enable foo.service with that in my postinst file however causes an error:

dh_installsystemd: error: "debian/control" not found. Are you sure you are in the correct directory?
dpkg: error processing package foo (--configure):
 installed foo package post-installation script subprocess returned error exit status 255
Processing triggers for libc-bin (2.31-0ubuntu9.2) ...
Errors were encountered while processing:
 foo

I must confess that I am somewhat lost as to how this should be handled.
How does one correctly add a systemd service to a debian package via CPack?

Body:
The best solution that has come to mind is to dissect another package and use the same commands dh_installsystemd generates.

This results in a postinst file like:

# End automatically added section
# Based on output by dh_installsystemd/13.5.2

if [ \"$1\" = \"configure\" ] || [ \"$1\" = \"abort-upgrade\" ] || [ \"$1\" = \"abort-deconfigure\" ] || [ \"$1\" = \"abort-remove\" ] ; then

    # was-enabled defaults to true, so new installations run enable.
    if deb-systemd-helper --quiet was-enabled 'foo.service'; then
        # Enables the unit on first installation, creates new
        # symlinks on upgrades if the unit file has changed.
        deb-systemd-helper enable 'foo.service' >/dev/null || true
    else
        # Update the statefile to add new symlinks (if any), which need to be
        # cleaned up on purge. Also remove old symlinks.
        deb-systemd-helper update-state 'foo.service' >/dev/null || true
    fi
fi
if [ \"$1\" = \"configure\" ] || [ \"$1\" = \"abort-upgrade\" ] || [ \"$1\" = \"abort-deconfigure\" ] || [ \"$1\" = \"abort-remove\" ] ; then
    if [ -z \"${DPKG_ROOT\:-}\" ] && [ -d /run/systemd/system ]; then
        systemctl --system daemon-reload >/dev/null || true
        deb-systemd-invoke restart 'foo.service' >/dev/null || true
    fi
fi

Since these instructions are static updates in the macros have to be manually applied.


问:
Adding a service reference to a website
I am trying to add a service reference to my website. When I add the service reference to a WPF application I get a reference.cs file that I can edit and add attributes to. When I try to do the same thing in a asp.net website there this file isn't present. I have also tried looking on the file system and the reference.cs isn't present. Can anyone provide some guidance?

EDIT:: Im using VS2010 and I need to edit the reference.cs to add [Webget] and [WebPost] attributes

答: If you want to manually edit a service stub, consider using svcutil.exe. </p>

Title: Adding a service reference to a website


问:
GDB: Ctrl+C doesn't interrupt process as it usually does but rather terminates the program
Normally when you run a program through GDB you can press Ctrl+C to interrupt it, e.g. if it gets stuck in an infinite loop and you want to get a backtrace.

I'm debugging a program (xmms2d as it happens) but in this program only, when I press Ctrl+C it gets treated as if GDB was not running - the program shuts down cleanly and then GDB tells me the program exited normally.

How do I get the usual GDB behaviour back, where Ctrl+C interrupts the program?  Or is there another way to produce the same reaction in GDB as a Ctrl+C normally does?

答:
I had a similar problem and I have solved it.

First, write a gdb script, the file name is sighhandler.gdb. The script file is in the project directory:

```<code>gdb_sigwait/src/sighandler.gdb
</code>```

Then, source the above script file in the gdb initialization file (~/.gdbinit), for example:

```<code>source ~/gdb_sigwait/src/sighandler.gdb
</code>```

The gdb script is too long.
So, I created a github project to introduce and store the related code:
https://github.com/fairyfar/gdb_sigwait

Body:
I had a similar problem and I have solved it.

First, write a gdb script, the file name is sighhandler.gdb. The script file is in the project directory:

gdb_sigwait/src/sighandler.gdb

Then, source the above script file in the gdb initialization file (~/.gdbinit), for example:

source ~/gdb_sigwait/src/sighandler.gdb

The gdb script is too long.
So, I created a github project to introduce and store the related code:
https://github.com/fairyfar/gdb_sigwait


问:
Network status retry callback
I have an API that returns the network status and I want to add retry and cancel function for the API call

```<code>@GET("{path1}/{path2}")
suspend fun status(
    @HeaderMap headers: Map<String, String>
): Status?
</code>```

This is the service class from where the API is called

```<code>override suspend fun status(): Status? =
    service.status(
        path1 = PATH_ONE,
        path2 = PATH_TWO,
        headers = mapOf(
            USER_AGENT to userAgent,
            ACCEPT to accept,
            ACCEPT_LANGUAGE to locale,
            X_APP_GUID to xAppGuid
        )
    )
</code>```

The issue that I am facing is that to use the retrofit2.enqueue() and retrofit2.cancel() functions I need to change the return type of the status() function to Call, but then I face the issue that I cannot return that to the user, because Call() is an interface and cannot instantiated, and I need to return the actual status.

Does anyone have any clue how to do it?

答:
When using Retrofit with Coroutines you do NOT need to use Call.

suspend functions (returned by Retrofit) are cancellable and will try to cancel the call when canceled. That means that:

```<code>myScope.launch { status(...) }
</code>```

will be canceled whenever myScope is canceled. You can alternately keep a reference to the returned Job and cancel that yourself.

For retrying you can take a look at this answer

```<code>retryIO(times = 3) { status(...) }
</code>```

Title: Network status retry callback

Body:
I have an API that returns the network status and I want to add retry and cancel function for the API call

@GET("{path1}/{path2}")
suspend fun status(
    @HeaderMap headers: Map<String, String>
): Status?

This is the service class from where the API is called

override suspend fun status(): Status? =
    service.status(
        path1 = PATH_ONE,
        path2 = PATH_TWO,
        headers = mapOf(
            USER_AGENT to userAgent,
            ACCEPT to accept,
            ACCEPT_LANGUAGE to locale,
            X_APP_GUID to xAppGuid
        )
    )

The issue that I am facing is that to use the retrofit2.enqueue() and retrofit2.cancel() functions I need to change the return type of the status() function to Call, but then I face the issue that I cannot return that to the user, because Call() is an interface and cannot instantiated, and I need to return the actual status.

Does anyone have any clue how to do it?

Body:
When using Retrofit with Coroutines you do NOT need to use Call.

suspend functions (returned by Retrofit) are cancellable and will try to cancel the call when canceled. That means that:

myScope.launch { status(...) }

will be canceled whenever myScope is canceled. You can alternately keep a reference to the returned Job and cancel that yourself.

For retrying you can take a look at this answer

retryIO(times = 3) { status(...) }


问:
Why is my listview not scrolling?
```<code><RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#dad4c8"
    android:gravity="center_horizontal">
    <include
        android:id="@+id/title_bar"
        layout="@layout/title_bar" />
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/title_bar"
        android:id="@+id/txt"
        android:hint="Song title" />

    <ListView
        android:cacheColorHint="#00000000"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/txt"
        android:id="@+id/list" />

</RelativeLayout>
</code>```

答:
The problem I was facing was I added a "ListView" in "ConstraintLayout". For that, my ListView was neither showing properly nor scrolling properly.

I found the solution by wrapping a LinearLayout with ListView.

Previously I was using:

Then The Solution was like:

Title: Why is my listview not scrolling?


问:
While using ng-select remove item on condition

```<code><div class="form-group profile-select">
                                <ng-select
                                [multiple]="true"
                                class= "custom-list"
                                formControlName="name"
                                placeholder="Please select"
                                [readonly]="isReadOnly"
                                [items]="catList"
                                bindLabel="name"
                                required="true"
                                (change)="changeFn($event)"
                                [clearable]='false'
                                >
                                <ng-template ng-option-tmp let-item="item" let-index="index" value="item">
                                    {{item?.name}}
                                </ng-template>
                                </ng-select>
                            </div>
</code>```

I want to remove an item using the above cross icon with each item only on condition.
How can we get an event or on click so that when I click on cross icon the item do not get removed from an input until we get a response of true?

答:
This solution is not ideal because it's kind of redundant. But I will listen when city is removed. If on some condition city is not allowed to be removed we quickly add it back to selectedCity[] - it's not a good solution because we're not preventing removal and selectedCity[] items index change may cause order changes on the template.

If we want to prevent remove action we would have to get deeper into the inner working of this library. Glancing over the docs no such default behaviour is available to disable or prevent removing the chip.

@Component({
  selector: 'my-app',
  template: `

Don't allow to remove item on condition

        Your first ng-select
        <ng-select [items]="cities"
                   bindLabel="name"
                   [multiple]="true"
                   (remove)="onRemove($event)"
                   placeholder="Select city"
                   [clearable]="false"
                   [(ngModel)]="selectedCity">
        </ng-select>
`,
})
export class AppComponent {
  selectedCity = [];

  constructor() {}

  someCondition = [1, 2, 3];

  onRemove(event: any) {
    console.log(event, this.selectedCity);
    if (this.someCondition.some((condition) => condition == event.value.id)) {
      console.log('adding back');
      this.selectedCity.push(event.value);
      this.selectedCity = [...this.selectedCity];
    }
  }

  cities = [
    { id: 1, name: 'Vilnius' },
    { id: 2, name: 'Kaunas' },
    { id: 3, name: 'Pavilnys', disabled: true },
    { id: 4, name: 'Pabradė' },
    { id: 5, name: 'Klaipėda' },
  ];
}
```

Here is a working example: https://stackblitz.com/edit/ng-select-example-pfxvpq?file=app%2Fapp.component.ts

Body:
                                <ng-select
                                [multiple]="true"
                                class= "custom-list"
                                formControlName="name"
                                placeholder="Please select"
                                [readonly]="isReadOnly"
                                [items]="catList"
                                bindLabel="name"
                                required="true"
                                (change)="changeFn($event)"
                                [clearable]='false'
                                >
                                <ng-template ng-option-tmp let-item="item" let-index="index" value="item">
                                    {{item?.name}}
                                </ng-template>
                                </ng-select>

I want to remove an item using the above cross icon with each item only on condition.
How can we get an event or on click so that when I click on cross icon the item do not get removed from an input until we get a response of true?

Body:
This solution is not ideal because it's kind of redundant. But I will listen when city is removed. If on some condition city is not allowed to be removed we quickly add it back to selectedCity[] - it's not a good solution because we're not preventing removal and selectedCity[] items index change may cause order changes on the template.

If we want to prevent remove action we would have to get deeper into the inner working of this library. Glancing over the docs no such default behaviour is available to disable or prevent removing the chip.

@Component({
  selector: 'my-app',
  template: `
        <h1>Don't allow to remove item on condition</h1>
        <label>Your first ng-select</label>
        <ng-select [items]="cities"
                   bindLabel="name"
                   [multiple]="true"
                   (remove)="onRemove($event)"
                   placeholder="Select city"
                   [clearable]="false"
                   [(ngModel)]="selectedCity">
        </ng-select>
`,
})
export class AppComponent {
  selectedCity = [];

  constructor() {}

  someCondition = [1, 2, 3];

  onRemove(event: any) {
    console.log(event, this.selectedCity);
    if (this.someCondition.some((condition) => condition == event.value.id)) {
      console.log('adding back');
      this.selectedCity.push(event.value);
      this.selectedCity = [...this.selectedCity];
    }
  }

  cities = [
    { id: 1, name: 'Vilnius' },
    { id: 2, name: 'Kaunas' },
    { id: 3, name: 'Pavilnys', disabled: true },
    { id: 4, name: 'Pabradė' },
    { id: 5, name: 'Klaipėda' },
  ];
}

Here is a working example: https://stackblitz.com/edit/ng-select-example-pfxvpq?file=app%2Fapp.component.ts


问:
How can I create an exception for a jquery mouseout event only if another mouseover event hasn't been triggered?
Basically my client wants hidden navigation to appear when mouseover an image.  I've solved the problem of the navigation not hiding when you mouseover the navigation and then hiding when you leave the navigation.  There are two problems I'm running into and I've tried a variety of different combinations that I thought would work, but of course didn't.  The two problems are:

When you mouseout the image without mouseover the navigation then the navigation needs to hide, as of right now it stays open until you either mouseover the image again or mouseleave the navigation.

Second problem is when you mouseleave the navigation directly to mouseover the image it loops the function and hides the nav then opens the nav again, I've tried changing slideToggle to show, but that causes a whole bunch of other issues.

Right now the code is behaving as close to how I want it and could be considered acceptable, but I'd love to know how to solve the problems above.  I thought about using the hoverIntent plugin to sense the mouse movements and only trigger the functions once the mouse has slowed, but couldn't get it working properly.  Clearly, I am a novice when it comes to javascript and jquery so please forgive me, but I'd really appreciate any help.

Here is my code

```<code>$(document).ready(function(){

$(".nav-body").hide();

$(".nav-head").mouseover(function(){
$(this).next(".nav-body").slideToggle(600);
$(".nav-body").mouseleave(function(){
$(this).hide(700);
});
});

});
</code>```

Here is my html:

```<code><p class="nav-head"><img src="/images/face-btn.jpg" /></p>
<div class="nav-body">
<ul><?php wp_list_pages('title_li=&child_of=12&depth=1'); ?></ul>
</div>
</code>```

答:
Markup change

```<code><div class="nav-container">
    <p class="nav-head"></p>
    <div class="nav-body"></div>
</div>
</code>```

Javascript

```<code>var eventHandler;

eventHandler = function(){$(".nav-head").one("mouseover",function(){
   $(this).next(".nav-body").slideToggle(600);
    $(".nav-container").one("mouseleave", function(){
        $(this).find(".nav-body").hide(700, eventHandler);
    });
});};

eventHandler();
</code>```

The first change is from mouseleave to mouseout. Inside the navigation, there are likely to be descendent elements that cover the actual nav-body. With mouse leave, the handler only triggers when the mouse leaves the bound element. If it goes over descend it elements, it is considered leaving. Mouseout only triggers if it is outside the bounds of the bound object.

The second thing I did was assign a delegate to the handler binding operation so that I could use it as a callback function for hide(). This way, the event handler won't be restored to the nav-head until the hide is completely done.

The last was to assign the mouseout handler to the containing div. This way, the so long as it leaves the nav-head (or the nav-body) since its contained, the body will hide.

Body:
Basically my client wants hidden navigation to appear when mouseover an image.  I've solved the problem of the navigation not hiding when you mouseover the navigation and then hiding when you leave the navigation.  There are two problems I'm running into and I've tried a variety of different combinations that I thought would work, but of course didn't.  The two problems are:

When you mouseout the image without mouseover the navigation then the navigation needs to hide, as of right now it stays open until you either mouseover the image again or mouseleave the navigation.

Second problem is when you mouseleave the navigation directly to mouseover the image it loops the function and hides the nav then opens the nav again, I've tried changing slideToggle to show, but that causes a whole bunch of other issues.

Right now the code is behaving as close to how I want it and could be considered acceptable, but I'd love to know how to solve the problems above.  I thought about using the hoverIntent plugin to sense the mouse movements and only trigger the functions once the mouse has slowed, but couldn't get it working properly.  Clearly, I am a novice when it comes to javascript and jquery so please forgive me, but I'd really appreciate any help.

Here is my code

$(document).ready(function(){

$(".nav-body").hide();

$(".nav-head").mouseover(function(){
$(this).next(".nav-body").slideToggle(600);
$(".nav-body").mouseleave(function(){
$(this).hide(700);
});
});

});

Here is my html:

<?php wp_list_pages('title_li=&child_of=12&depth=1'); ?>

Body:
Markup change

<div class="nav-container">
    <p class="nav-head"></p>
    <div class="nav-body"></div>
</div>

Javascript

var eventHandler;

eventHandler = function(){$(".nav-head").one("mouseover",function(){
   $(this).next(".nav-body").slideToggle(600);
    $(".nav-container").one("mouseleave", function(){
        $(this).find(".nav-body").hide(700, eventHandler);
    });
});};

eventHandler();

The first change is from mouseleave to mouseout. Inside the navigation, there are likely to be descendent elements that cover the actual nav-body. With mouse leave, the handler only triggers when the mouse leaves the bound element. If it goes over descend it elements, it is considered leaving. Mouseout only triggers if it is outside the bounds of the bound object.

The second thing I did was assign a delegate to the handler binding operation so that I could use it as a callback function for hide(). This way, the event handler won't be restored to the nav-head until the hide is completely done.

The last was to assign the mouseout handler to the containing div. This way, the so long as it leaves the nav-head (or the nav-body) since its contained, the body will hide.


问:
Why do the two grids react if you use focusin on one grid when using two grids?
I use blazor, syncfusion
The code below is an example of a syncfusion grid.
I want to know which grid was selected, or focused using the fuction  directly in onfocusin.
because, It's to decide whether to add a row to the master grid or a row to the detailed grid.
now it is only once called at initialized, is not work 'onclick', 'onfocusin'
What should I do?
I want the format below.
ex)</p>
```<code>@page "/counter"

@code {
    public aaa bbb { get; set; } = new();
}

<SfSplitter Height="100%" SeparatorSize="3" Orientation="Syncfusion.Blazor.Layouts.Orientation.Horizontal">
    <SplitterPanes>
        <SplitterPane Size="50%" Collapsible="true" CssClass="p-1">
            <ContentTemplate>
                <SfGrid ID="master" @onclick="@bbb.grid_onfocusin("master")"
                        DataSource="@Orders"
                        GridLines="GridLine.Both" Width="100%"
                        AllowSorting="false" AllowRowDragAndDrop="false" AllowGrouping="false">
                    <GridColumns>
                        <GridColumn Field=@nameof(Order.OrderID) HeaderText="Order ID" TextAlign="TextAlign.Right" Width="120"></GridColumn>
                        <GridColumn Field=@nameof(Order.CustomerID) HeaderText="Customer Name" Width="150"></GridColumn>
                        <GridColumn Field=@nameof(Order.OrderDate) HeaderText=" Order Date" Format="d" Type="ColumnType.Date" TextAlign="TextAlign.Right" Width="130"></GridColumn>
                        <GridColumn Field=@nameof(Order.Freight) HeaderText="Freight" Format="C2" TextAlign="TextAlign.Right" Width="120"></GridColumn>
                    </GridColumns>
                </SfGrid>
            </ContentTemplate>
        </SplitterPane>
        <SplitterPane Size="50%" Collapsible="true" CssClass="p-1">
            <ContentTemplate>
                <SfGrid ID="detail" @onclick="@bbb.grid_onfocusin("detail")"
                        DataSource="@Orders"
                        GridLines="GridLine.Both" Width="100%"
                        AllowSorting="false" AllowRowDragAndDrop="false" AllowGrouping="false">
                    <GridColumns>
                        <GridColumn Field=@nameof(Order.OrderID) HeaderText="Order ID" TextAlign="TextAlign.Right" Width="120"></GridColumn>
                        <GridColumn Field=@nameof(Order.CustomerID) HeaderText="Customer Name" Width="150"></GridColumn>
                        <GridColumn Field=@nameof(Order.OrderDate) HeaderText=" Order Date" Format="d" Type="ColumnType.Date" TextAlign="TextAlign.Right" Width="130"></GridColumn>
                        <GridColumn Field=@nameof(Order.Freight) HeaderText="Freight" Format="C2" TextAlign="TextAlign.Right" Width="120"></GridColumn>
                    </GridColumns>
                </SfGrid>
            </ContentTemplate>
        </SplitterPane>
    </SplitterPanes>
</SfSplitter>

@code {
    public List<Order> Orders { get; set; }

    public class aaa
    {
        public aaa()
        {

        }

        public string focusGrid { get; set; } = "";

        public EventCallback grid_onfocusin(string GridName)
        {
            focusGrid = GridName;
            Console.WriteLine("focusGrid: " + focusGrid);
            return EventCallback.Empty;
        }
    }

    protected override void OnInitialized()
    {
        Orders = Enumerable.Range(1, 75).Select(x => new Order()
            {
                OrderID = 1000 + x,
                CustomerID = (new string[] { "ALFKI", "ANANTR", "ANTON", "BLONP", "BOLID" })[new Random().Next(5)],
                Freight = 2.1 * x,
                OrderDate = DateTime.Now.AddDays(-x),
            }).ToList();
    }

    public class Order
    {
        public int? OrderID { get; set; }
        public string CustomerID { get; set; }
        public DateTime? OrderDate { get; set; }
        public double? Freight { get; set; }
    }
}

</code>```

答:
You have your syntax wrong - so the method is being called when the grid(s) render.

Change your onclick handlers like this:

@onclick="@( () => bbb.grid_onfocusin("master") )"

and

@onclick="@( () => bbb.grid_onfocusin("detail") )"

These will configure the grids to respond to being clicked as you expected.

Body:
I use blazor, syncfusion
The code below is an example of a syncfusion grid.
I want to know which grid was selected, or focused using the fuction  directly in onfocusin.
because, It's to decide whether to add a row to the master grid or a row to the detailed grid.
now it is only once called at initialized, is not work 'onclick', 'onfocusin'
What should I do?
I want the format below.
ex)

@page "/counter"

@code {
    public aaa bbb { get; set; } = new();
}

<SfSplitter Height="100%" SeparatorSize="3" Orientation="Syncfusion.Blazor.Layouts.Orientation.Horizontal">
    <SplitterPanes>
        <SplitterPane Size="50%" Collapsible="true" CssClass="p-1">
            <ContentTemplate>
                <SfGrid ID="master" @onclick="@bbb.grid_onfocusin("master")"
                        DataSource="@Orders"
                        GridLines="GridLine.Both" Width="100%"
                        AllowSorting="false" AllowRowDragAndDrop="false" AllowGrouping="false">
                    <GridColumns>
                        <GridColumn Field=@nameof(Order.OrderID) HeaderText="Order ID" TextAlign="TextAlign.Right" Width="120"></GridColumn>
                        <GridColumn Field=@nameof(Order.CustomerID) HeaderText="Customer Name" Width="150"></GridColumn>
                        <GridColumn Field=@nameof(Order.OrderDate) HeaderText=" Order Date" Format="d" Type="ColumnType.Date" TextAlign="TextAlign.Right" Width="130"></GridColumn>
                        <GridColumn Field=@nameof(Order.Freight) HeaderText="Freight" Format="C2" TextAlign="TextAlign.Right" Width="120"></GridColumn>
                    </GridColumns>
                </SfGrid>
            </ContentTemplate>
        </SplitterPane>
        <SplitterPane Size="50%" Collapsible="true" CssClass="p-1">
            <ContentTemplate>
                <SfGrid ID="detail" @onclick="@bbb.grid_onfocusin("detail")"
                        DataSource="@Orders"
                        GridLines="GridLine.Both" Width="100%"
                        AllowSorting="false" AllowRowDragAndDrop="false" AllowGrouping="false">
                    <GridColumns>
                        <GridColumn Field=@nameof(Order.OrderID) HeaderText="Order ID" TextAlign="TextAlign.Right" Width="120"></GridColumn>
                        <GridColumn Field=@nameof(Order.CustomerID) HeaderText="Customer Name" Width="150"></GridColumn>
                        <GridColumn Field=@nameof(Order.OrderDate) HeaderText=" Order Date" Format="d" Type="ColumnType.Date" TextAlign="TextAlign.Right" Width="130"></GridColumn>
                        <GridColumn Field=@nameof(Order.Freight) HeaderText="Freight" Format="C2" TextAlign="TextAlign.Right" Width="120"></GridColumn>
                    </GridColumns>
                </SfGrid>
            </ContentTemplate>
        </SplitterPane>
    </SplitterPanes>
</SfSplitter>

@code {
    public List<Order> Orders { get; set; }

    public class aaa
    {
        public aaa()
        {

        }

        public string focusGrid { get; set; } = "";

        public EventCallback grid_onfocusin(string GridName)
        {
            focusGrid = GridName;
            Console.WriteLine("focusGrid: " + focusGrid);
            return EventCallback.Empty;
        }
    }

    protected override void OnInitialized()
    {
        Orders = Enumerable.Range(1, 75).Select(x => new Order()
            {
                OrderID = 1000 + x,
                CustomerID = (new string[] { "ALFKI", "ANANTR", "ANTON", "BLONP", "BOLID" })[new Random().Next(5)],
                Freight = 2.1 * x,
                OrderDate = DateTime.Now.AddDays(-x),
            }).ToList();
    }

    public class Order
    {
        public int? OrderID { get; set; }
        public string CustomerID { get; set; }
        public DateTime? OrderDate { get; set; }
        public double? Freight { get; set; }
    }
}


问:
How do I assign a Converter from view class to Resource?
Here is part of my FooPage.xaml

<Page.Resources>

    <wpfCore:StringArrayToTextConverter
        x:Key="regionConverter" />
</Page.Resources>
```
<p>And somewhere also in this FooPage.xaml</p>
<pre class="lang-xml prettyprint-override"><code><ListViewItem>
    <DockPanel>
        <Label Content="Something" />
        <!-- I want to use regionToTextConverter from Page class here -->
        <TextBox
            Text="{Binding someValue, Mode=OneWay,
            Converter={StaticResource regionConverter}}" />
    </DockPanel>
</ListViewItem>
</code>```

Now part of my FooPage.cs:

```<code>public StringArrayToTextConverter regionToTextConverter { get; private set; }

//Somewhere else
// additionalValueMapping is a dictionary
    regionToTextConverter = new StringArrayToTextConverter()
    {
        additionalValueMapping = regionMapping
    };
</code>```

My question is, how do I use the regionToTextConverter from page instance in the xaml view? StaticResource may not be an option here because I need to some logic specifically in this case, I want to know how to correctly use it in this scenario.

答:
To create a converter in the code-behind of your FooPage and use it in XAML, just add it to the Resources of the page as you would do in XAML. However, you can only add it before the call to InitializeComponent, otherwise the resource is not available via the StaticResource extension. Using DynamicResource here is not applicable, because Converter is not a dependency property.

```<code>public partial class FooPage : Page
{
   public FooPage()
   {
      Resources.Add("regionConverter", new StringArrayToTextConverter()
      {
         additionalValueMapping = regionMapping
      });
      InitializeComponent();

      // ...other code.
   }

   // ...other code.
}
</code>```

Body:
Here is part of my FooPage.xaml

<Page.Resources>

    <wpfCore:StringArrayToTextConverter
        x:Key="regionConverter" />
</Page.Resources>

And somewhere also in this FooPage.xaml

<ListViewItem>
    <DockPanel>

        <TextBox
            Text="{Binding someValue, Mode=OneWay,
            Converter={StaticResource regionConverter}}" />
    </DockPanel>
</ListViewItem>

Now part of my FooPage.cs:

public StringArrayToTextConverter regionToTextConverter { get; private set; }

//Somewhere else
// additionalValueMapping is a dictionary
    regionToTextConverter = new StringArrayToTextConverter()
    {
        additionalValueMapping = regionMapping
    };

My question is, how do I use the regionToTextConverter from page instance in the xaml view? StaticResource may not be an option here because I need to some logic specifically in this case, I want to know how to correctly use it in this scenario.

Body:
To create a converter in the code-behind of your FooPage and use it in XAML, just add it to the Resources of the page as you would do in XAML. However, you can only add it before the call to InitializeComponent, otherwise the resource is not available via the StaticResource extension. Using DynamicResource here is not applicable, because Converter is not a dependency property.

public partial class FooPage : Page
{
   public FooPage()
   {
      Resources.Add("regionConverter", new StringArrayToTextConverter()
      {
         additionalValueMapping = regionMapping
      });
      InitializeComponent();

      // ...other code.
   }

   // ...other code.
}


问:
How to get java.sql.Types from mysql column define without creating the table?

goal

Get java.sql.Types without creating table.

detail

If I define a column like this "a JSON DEFAULT NULL"

How can I get java.sql.Types about column 'a'?

what I have tried

I use jdbc, so I use connection.getMetaData().getTypeInfo to get all types

```<code>    public static Map<String, Integer> load(final DatabaseMetaData databaseMetaData) throws SQLException {
    Map<String, Integer> result = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
    try (ResultSet resultSet = databaseMetaData.getTypeInfo()) {
        while (resultSet.next()) {
            result.put(resultSet.getString("TYPE_NAME"), resultSet.getInt("DATA_TYPE"));
        }
    }
    return result;
}
</code>```

Then I get this map like this

BIGINT -> {Integer@5274} -5

BIGINT UNSIGNED -> {Integer@5274} -5

And so on.

But there is no JSON.

what's more?

If I define like this

"id_card LONG CHAR VARYING"

Then how can I get the java.sql.Types?

答:
The code that you are using looks to be the correct way to get the supported column types.

One possible explanation for your not seeing JSON in the output is that your database does not support JSON as a column type.  For instance, although MySQL 8.x supports the JSON data type, according to the manual MySQL 5.6 does not support it.

It could also be the database driver.  For instance, I don't know what would happen vis a vis JSON support if you tried to use a Connector/J 5.1 driver with a MySQL 8.x database.

UPDATE

I had a look at the source code MySQL Connector/J 8.x (latest), and I think that the reason that you can't see JSON is ... it is a bug in the JDBC driver.

Looking at the implementation class for DatabaseMetadata, at line 4012 (or thereabouts) we see that the getTypeInfo() has code that assembles a ResultSet for a hard-wired list of types.  The JSON type is not there, and there is a comment that says:

```<code>  // TODO add missed types (aliases)
</code>```

(FWIW, I couldn't see any logic in the driver to check which data types are actually supported by the database.  That is potentially another bug.)

So, my "possible explanations" (see above) were not the actual explanation in your particular case.

Solution?  I don't think there is a good one in this case.  But I recommend that you submit a bug report.  (I couldn't find an existing bug report for this particular issue, though there were some old bugs about missing types in MySQL Connector/J 5.x)

Body:
goal

Get java.sql.Types without creating table.

detail

If I define a column like this "a JSON DEFAULT NULL"

How can I get java.sql.Types about column 'a'?

what I have tried

I use jdbc, so I use connection.getMetaData().getTypeInfo to get all types

    public static Map<String, Integer> load(final DatabaseMetaData databaseMetaData) throws SQLException {
    Map<String, Integer> result = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
    try (ResultSet resultSet = databaseMetaData.getTypeInfo()) {
        while (resultSet.next()) {
            result.put(resultSet.getString("TYPE_NAME"), resultSet.getInt("DATA_TYPE"));
        }
    }
    return result;
}

Then I get this map like this

BIGINT -> {Integer@5274} -5

BIGINT UNSIGNED -> {Integer@5274} -5

And so on.

But there is no JSON.

what's more?

If I define like this

"id_card LONG CHAR VARYING"

Then how can I get the java.sql.Types?

Body:
The code that you are using looks to be the correct way to get the supported column types.

One possible explanation for your not seeing JSON in the output is that your database does not support JSON as a column type.  For instance, although MySQL 8.x supports the JSON data type, according to the manual MySQL 5.6 does not support it.

It could also be the database driver.  For instance, I don't know what would happen vis a vis JSON support if you tried to use a Connector/J 5.1 driver with a MySQL 8.x database.

UPDATE

I had a look at the source code MySQL Connector/J 8.x (latest), and I think that the reason that you can't see JSON is ... it is a bug in the JDBC driver.

Looking at the implementation class for DatabaseMetadata, at line 4012 (or thereabouts) we see that the getTypeInfo() has code that assembles a ResultSet for a hard-wired list of types.  The JSON type is not there, and there is a comment that says:

  // TODO add missed types (aliases)

(FWIW, I couldn't see any logic in the driver to check which data types are actually supported by the database.  That is potentially another bug.)

So, my "possible explanations" (see above) were not the actual explanation in your particular case.

Solution?  I don't think there is a good one in this case.  But I recommend that you submit a bug report.  (I couldn't find an existing bug report for this particular issue, though there were some old bugs about missing types in MySQL Connector/J 5.x)


问:
How to find DIV inside div-structure by InnerText or Class
I have a div with multiple children which have a large div structure in them. Now I want to find an element with an specific innerText.
How can I do this?
I have heard something from document.evaluate but is this the right thing?

First Label

Second Label

Third Label

```

I have main and want to find the Label with the text Second Label without multiple Loops.

答:
var xpathResult = document.evaluate(
  "//label[contains(text(),'Second Label')]", // xpathExpression
  document.querySelector(".main"), // contextNode
  null, // namespaceResolver
  XPathResult.ANY_TYPE, // resultType
  null // result
).iterateNext();
console.log(xpathResult);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">
    <div class="child1">
        <div>
            <div><label class="text1">First Label</label></div>
        </div>
    </div>
    <div class="child2">
        <div>
            <div><label class="text2">Second Label</label></div>
        </div>
    </div>
    <div class="child3">
        <div>
            <div><label class="text3">Third Label</label></div>
        </div>
    </div>
</div></code>```

Body:
I have a div with multiple children which have a large div structure in them. Now I want to find an element with an specific innerText.
How can I do this?
I have heard something from document.evaluate but is this the right thing?

First Label

Second Label

Third Label

I have main and want to find the Label with the text Second Label without multiple Loops.

Body:
var xpathResult = document.evaluate(
  "//label[contains(text(),'Second Label')]", // xpathExpression
  document.querySelector(".main"), // contextNode
  null, // namespaceResolver
  XPathResult.ANY_TYPE, // resultType
  null // result
).iterateNext();
console.log(xpathResult);

<div class="main">
    <div class="child1">
        <div>
            <div><label class="text1">First Label</label></div>
        </div>
    </div>
    <div class="child2">
        <div>
            <div><label class="text2">Second Label</label></div>
        </div>
    </div>
    <div class="child3">
        <div>
            <div><label class="text3">Third Label</label></div>
        </div>
    </div>
</div>


问:
Referenced sniff "SlevomatCodingStandard.ControlStructures.RequireNullCoalesceOperator" does not exist
Just installed php_codesniffer and coder:

```<code>composer global require "squizlabs/php_codesniffer=*"
composer global require drupal/coder
</code>```

After installation, run phpcs -i and the result is as follows:

```<code>The installed coding standards are MySource, PEAR, Zend, PSR2, PSR1, Squiz, PSR12, PHPCompatibility, Drupal and DrupalPractice
</code>```

But when I use git commit, I get an error:

ERROR: Referenced sniff "SlevomatCodingStandard.ControlStructures.RequireNullCoalesceOperator" does not exist

My php version is 7.4.
Where am I going wrong?

答:
Excuting an order:

```<code> phpcs --config-set installed_paths /homeriverz/.config/composer/vendor/phpcompatibility/php-compatibility,/homeriverz/.config/composer/vendor/drupal/coder/coder_sniffer,/homeriverz/.config/composer/vendor/slevomat /coding-standard
</code>```

If not, reinstall php_codesniffer and drupal/coder.

Body:
Just installed php_codesniffer and coder:

composer global require "squizlabs/php_codesniffer=*"
composer global require drupal/coder

After installation, run phpcs -i and the result is as follows:

The installed coding standards are MySource, PEAR, Zend, PSR2, PSR1, Squiz, PSR12, PHPCompatibility, Drupal and DrupalPractice

But when I use git commit, I get an error:

ERROR: Referenced sniff "SlevomatCodingStandard.ControlStructures.RequireNullCoalesceOperator" does not exist

My php version is 7.4.
Where am I going wrong?

Body:
Excuting an order:

 phpcs --config-set installed_paths /homeriverz/.config/composer/vendor/phpcompatibility/php-compatibility,/homeriverz/.config/composer/vendor/drupal/coder/coder_sniffer,/homeriverz/.config/composer/vendor/slevomat /coding-standard

If not, reinstall php_codesniffer and drupal/coder.