问:
How to open mat-menu programmatically?
Im trying to trigger opening a menu when clicking mat-nav-list item.

HTML

```<code><mat-nav-list>
    <mat-list-item (click)="onOpenMenu(menu)" *ngFor="let i of data">
        <div mat-line>
            {{ i.name }}
        </div>
        <p mat-line>
            {{ i.email }}
        </p>
        <button mat-icon-button [matMenuTriggerFor]="menu">
            <mat-icon>more_vert</mat-icon>
        </button>
    </mat-list-item>
    <mat-menu #menu="matMenu">
        <button mat-menu-item>View profile</button>
        <button mat-menu-item>Add contact</button>
    </mat-menu>
</mat-nav-list>
</code>```

TS

```<code>onOpenMenu(menu: any): void {
   // menu doesn't have any openMenu() function
   // which is of course not a trigger object but a menu itself.
   console.log(menu);
}
</code>```

I have been trying to look at this issue on github which is closer to my situation. but in my case i have a dynamic list of items which i wanted to open a menu every click.

DEMO

答:
If you want to completely control it programmatically, without having an element on your website that also controls the menu, you can declare an element containing [matMenuTriggerFor], but hiding it via CSS.

Caveat: You will have to manually position the menu. You can do it roughly like that:

Template:

```<code><div #menuTrigger [matMenuTriggerFor]="menu" class="menu-trigger">I will be hidden</div>
<mat-menu #menu class="your-menu-class">
...
</mat-menu>
</code>```

CSS:

```<code>.menu-trigger {
  display: none;
}
</code>```

Component:

```<code>class YourComponent {
  @ViewChild(MatMenuTrigger) menuTrigger: MatMenuTrigger | undefined;

  constructor(private readonly viewRef: ViewContainerRef) { }

  someMethod() {
    this.menuTrigger?.menuOpened.pipe(take(1)).subscribe(() => {
      const menu = document.getElementsByClassName('your-menu-class')[0] as HTMLElement;
      const position: DOMRect = this.viewRef.element.nativeElement.getBoundingClientRect();

      menu.style.position = 'absolute';
      menu.style.top = `${position.top}px`;
      menu.style.left = `${position.width}px`;
    });

    this.menuTrigger?.openMenu();
  }
}
</code>```

Title: How to open mat-menu programmatically?

Body:
Im trying to trigger opening a menu when clicking mat-nav-list item.

HTML

<mat-nav-list>
    <mat-list-item (click)="onOpenMenu(menu)" *ngFor="let i of data">

            {{ i.name }}

            {{ i.email }}

        <button mat-icon-button [matMenuTriggerFor]="menu">
            <mat-icon>more_vert</mat-icon>
        </button>
    </mat-list-item>
    <mat-menu #menu="matMenu">
        <button mat-menu-item>View profile</button>
        <button mat-menu-item>Add contact</button>
    </mat-menu>
</mat-nav-list>

TS

onOpenMenu(menu: any): void {
   // menu doesn't have any openMenu() function
   // which is of course not a trigger object but a menu itself.
   console.log(menu);
}

I have been trying to look at this issue on github which is closer to my situation. but in my case i have a dynamic list of items which i wanted to open a menu every click.

DEMO

Body:
If you want to completely control it programmatically, without having an element on your website that also controls the menu, you can declare an element containing [matMenuTriggerFor], but hiding it via CSS.

Caveat: You will have to manually position the menu. You can do it roughly like that:

Template:

<div #menuTrigger [matMenuTriggerFor]="menu" class="menu-trigger">I will be hidden</div>
<mat-menu #menu class="your-menu-class">
...
</mat-menu>

CSS:

.menu-trigger {
  display: none;
}

Component:

class YourComponent {
  @ViewChild(MatMenuTrigger) menuTrigger: MatMenuTrigger | undefined;

  constructor(private readonly viewRef: ViewContainerRef) { }

  someMethod() {
    this.menuTrigger?.menuOpened.pipe(take(1)).subscribe(() => {
      const menu = document.getElementsByClassName('your-menu-class')[0] as HTMLElement;
      const position: DOMRect = this.viewRef.element.nativeElement.getBoundingClientRect();

      menu.style.position = 'absolute';
      menu.style.top = `${position.top}px`;
      menu.style.left = `${position.width}px`;
    });

    this.menuTrigger?.openMenu();
  }
}


来源: stackexchange

问:
Optional parameters, "index seek" plan
In my SELECT statement i use optional parameters in a way like this:

```<code>DECLARE @p1 INT = 1
DECLARE @p2 INT = 1
SELECT name FROM some_table WHERE (id = @p1 OR @p1 IS NULL) AND (name = @p2 OR @p2 IS NULL)
</code>```

In this case the optimizer generates "index scan" (not seek) operations for the entity which is not most effective when parameters are supplied with not null values.

If i add the RECOMPILE hint to the query the optimizer builds more effective plan which uses "seek". It works on my MSSQL 2008 R2 SP1 server and it also means that the optimizer CAN build a plan which consider only one logic branch of my query.

How can i make it to use that plan everywhere i want with no recompiling? The USE PLAN hint seemes not to work in this case.

Below is test code:

```<code>-- see plans
CREATE TABLE test_table(
    id INT IDENTITY(1,1) NOT NULL,
    name varchar(10),
    CONSTRAINT [pk_test_table] PRIMARY KEY CLUSTERED (id ASC))
GO
INSERT INTO test_table(name) VALUES ('a'),('b'),('c')
GO
DECLARE @p INT = 1
SELECT name FROM test_table WHERE id = @p OR @p IS NULL
SELECT name FROM test_table WHERE id = @p OR @p IS NULL OPTION(RECOMPILE)
GO
DROP TABLE test_table
GO
</code>```

Note that not all versions of SQL server will change the plan the way i shown.

答:
The reason you get a scan is because the predicate will not short-circuit and both statements will always be evaluated. As you have already stated it will not work well with the optimizer and force a scan. Even though with recompile appears to help sometimes, it's not consistent.

If you have a large table where seeks are a must then you have two options:

Dynamic sql.

If statements separating your queries and thus creating separate execution plans (when @p is null you will of course always get a scan).

ContentLicense: CC BY-SA 3.0

Title: Optional parameters, "index seek" plan

Body:
In my SELECT statement i use optional parameters in a way like this:

DECLARE @p1 INT = 1
DECLARE @p2 INT = 1
SELECT name FROM some_table WHERE (id = @p1 OR @p1 IS NULL) AND (name = @p2 OR @p2 IS NULL)

In this case the optimizer generates "index scan" (not seek) operations for the entity which is not most effective when parameters are supplied with not null values.

If i add the RECOMPILE hint to the query the optimizer builds more effective plan which uses "seek". It works on my MSSQL 2008 R2 SP1 server and it also means that the optimizer CAN build a plan which consider only one logic branch of my query.

How can i make it to use that plan everywhere i want with no recompiling? The USE PLAN hint seemes not to work in this case.

Below is test code:

-- see plans
CREATE TABLE test_table(
    id INT IDENTITY(1,1) NOT NULL,
    name varchar(10),
    CONSTRAINT [pk_test_table] PRIMARY KEY CLUSTERED (id ASC))
GO
INSERT INTO test_table(name) VALUES ('a'),('b'),('c')
GO
DECLARE @p INT = 1
SELECT name FROM test_table WHERE id = @p OR @p IS NULL
SELECT name FROM test_table WHERE id = @p OR @p IS NULL OPTION(RECOMPILE)
GO
DROP TABLE test_table
GO

Note that not all versions of SQL server will change the plan the way i shown.


问:
Cannot create SSPI context
I am working on a .NET application where I am trying to build the database scripts. While building the project, I am getting an error "Cannot create SSPI context.". This error is shown in the output window (inside VS2008 screen) and the building process failed. Please help on this. SQL Server is configured to work on Windows authentication & running as network service (these two things are must for my project).

Please help on this. This error is not seems to be consistent. It was fixed in the past by restarting the machine, changing the system time to match the domain time and some suggestions in the net. Please help on this.

答:
I am able to solve it by running the following commands.

Run CMD in admin mode

```<code>klist.exe -li 0x3e7 => if you see no output or error then continue and from last command try these commands once again.
klist.exe -li 0x3e7 purge
gpupdate /force
gpresult /r /scope computer
klist purge
runas /user:[your domain here]\[your user name here] cmd.exe
klist.exe sessions | findstr /i [your hostname here in the new opened cmd window]
</code>```

Try again these commands depending upon the condition specified, and then restart your PC.

Title: Cannot create SSPI context

Body:
I am able to solve it by running the following commands.

Run CMD in admin mode

klist.exe -li 0x3e7 => if you see no output or error then continue and from last command try these commands once again.
klist.exe -li 0x3e7 purge
gpupdate /force
gpresult /r /scope computer
klist purge
runas /user:[your domain here]\[your user name here] cmd.exe
klist.exe sessions | findstr /i [your hostname here in the new opened cmd window]

Try again these commands depending upon the condition specified, and then restart your PC.

ContentLicense: CC BY-SA 4.0


问:
Testing Django Models leads to TypeError: 'str' object is not callable
I am currently testing this model:

models.py

```<code>class Tag(models.Model):
    name = models.CharField(max_length=256)
    language = models.CharField(max_length=256)

    objects = models.Manager()

    def __str__(self):
        return self.name or ''

    @property
    def tags(self):
        tags = self.tagging.values('tag')
        return tags.values('tag_id', 'tag__name', 'tag__language')
</code>```

With these tests:

test_models.py

```<code>class TagTests(TestCase):
    def setUp(self):
        self.tag_name = "name of the tag"
        self.tag_language = "language of tag"
        self.tag = Tag.objects.create(name=self.tag_name, language=self.tag_language)

    def test_name_label(self):
        tag = Tag.objects.get(name=self.tag_name)
        field_label = tag._meta.get_field('name').verbose_name()
        self.assertEqual(field_label, 'name')

    def test_tag_size(self):
        tag = Tag.objects.get(name=self.tag_name)
        max_length = tag._meta.get_field('name').max_length
        self.assertEqual(max_length, 256)

    def test_str(self):
        """Test for string representation"""
        self.assertEqual(str(self.tag), self.tag.name)
</code>```

I currently get the following error for the method test_name_label(self):

```<code>FAILED frontend/tests/test_models.py::TagTests::test_name_label - TypeError: 'str' object is not callable

</code>```

How can I get rid of it? What am I doing wrong here?

答:
Field.verbose_name is a string, not a method. Just remove parenthesis from it:

```<code>field_label = tag._meta.get_field('name').verbose_name
</code>```

Body:
I am currently testing this model:

models.py

class Tag(models.Model):
    name = models.CharField(max_length=256)
    language = models.CharField(max_length=256)

    objects = models.Manager()

    def __str__(self):
        return self.name or ''

    @property
    def tags(self):
        tags = self.tagging.values('tag')
        return tags.values('tag_id', 'tag__name', 'tag__language')

With these tests:

test_models.py

class TagTests(TestCase):
    def setUp(self):
        self.tag_name = "name of the tag"
        self.tag_language = "language of tag"
        self.tag = Tag.objects.create(name=self.tag_name, language=self.tag_language)

    def test_name_label(self):
        tag = Tag.objects.get(name=self.tag_name)
        field_label = tag._meta.get_field('name').verbose_name()
        self.assertEqual(field_label, 'name')

    def test_tag_size(self):
        tag = Tag.objects.get(name=self.tag_name)
        max_length = tag._meta.get_field('name').max_length
        self.assertEqual(max_length, 256)

    def test_str(self):
        """Test for string representation"""
        self.assertEqual(str(self.tag), self.tag.name)

I currently get the following error for the method test_name_label(self):

FAILED frontend/tests/test_models.py::TagTests::test_name_label - TypeError: 'str' object is not callable

How can I get rid of it? What am I doing wrong here?

Body:
Field.verbose_name is a string, not a method. Just remove parenthesis from it:

field_label = tag._meta.get_field('name').verbose_name


问:
Creating a custom colorbar for battery levels
Using a simulation, I was able to construct a list of battery levels in percentage decreasing over time as you can see here :

I was already able to dispay the battery levels depending on the time using matplotlib pyplot.
This list has a size of 1944 elements and I would like to know if there is a possibility to display these battery levels depending on the time using a custom colorbar from green (100% of battery) to red (around 15% of battery) to black (below 15% of battery which is critical).

答:
You can use a LinearSegmentedColormap.from_list() using tuples of values and colors.  Here is an example using a seaborn heatmap to show how it works:

import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import seaborn as sns

cmap = LinearSegmentedColormap.from_list('', [(0, 'black'), (.15, 'black'), (.15, 'crimson'), (1, 'limegreen')])

fig, ax = plt.subplots(figsize=(5, 10))
sns.heatmap(np.linspace(100, 0, 30).reshape(-1, 1), annot=True, fmt='.2f', cmap=cmap, ax=ax)
```
<p><img src="https://i.stack.imgur.com/sSmpW.png" alt="using a LinearSegmentedColormap from list" /></p>
<p>PS: <code>plt.plot()</code> can't be used with a colormap. A curve has just one given color. You could use <code>plt.scatter(temps_total_simulation, pourcentage_total, c=pourcentage_total, cmap=cmap, vmin=0, vmax=100)</code> to individual points.</p>
<p>In matplotlib's tutorial, there is an example to split a curve into individual line segments, and then color these segments. Note that there is one segment less than there are points, as each segment connects two points.  The mean of the percentage values of the endpoints of a segment could define the segment's color:</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.collections import LineCollection
import numpy as np

cmap = LinearSegmentedColormap.from_list('', [(0, 'black'), (.15, 'black'), (.15, 'crimson'), (1, 'limegreen')])

fig, ax = plt.subplots(figsize=(12, 5))
temps_total_simulation = np.arange(1000)
pourcentage_total = np.random.randn(len(temps_total_simulation)).cumsum()
pourcentage_total -= pourcentage_total.min()
pourcentage_total = pourcentage_total / pourcentage_total.max() * 100
# ax.scatter(temps_total_simulation, pourcentage_total, s=3, c=pourcentage_total, cmap=cmap)

pnts = np.c_[temps_total_simulation, pourcentage_total]
segments = np.c_[pnts[:-1], pnts[1:]].reshape(-1, 2, 2)
linecol = LineCollection(segments, cmap=cmap, norm=plt.Normalize(0, 100))
linecol.set_array(
    (pourcentage_total[:-1] + pourcentage_total[1:]) / 2)  # use the mean percentage for colloring the segment
linecol.set_linewidth(1)
ax.add_collection(linecol)

ax.set_xlim(temps_total_simulation[0], temps_total_simulation[-1])
ax.set_ylim(0, 100)

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

Body:
You can use a LinearSegmentedColormap.from_list() using tuples of values and colors.  Here is an example using a seaborn heatmap to show how it works:

import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import seaborn as sns

cmap = LinearSegmentedColormap.from_list('', [(0, 'black'), (.15, 'black'), (.15, 'crimson'), (1, 'limegreen')])

fig, ax = plt.subplots(figsize=(5, 10))
sns.heatmap(np.linspace(100, 0, 30).reshape(-1, 1), annot=True, fmt='.2f', cmap=cmap, ax=ax)

PS: plt.plot() can't be used with a colormap. A curve has just one given color. You could use plt.scatter(temps_total_simulation, pourcentage_total, c=pourcentage_total, cmap=cmap, vmin=0, vmax=100) to individual points.

In matplotlib's tutorial, there is an example to split a curve into individual line segments, and then color these segments. Note that there is one segment less than there are points, as each segment connects two points.  The mean of the percentage values of the endpoints of a segment could define the segment's color:

import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.collections import LineCollection
import numpy as np

cmap = LinearSegmentedColormap.from_list('', [(0, 'black'), (.15, 'black'), (.15, 'crimson'), (1, 'limegreen')])

fig, ax = plt.subplots(figsize=(12, 5))
temps_total_simulation = np.arange(1000)
pourcentage_total = np.random.randn(len(temps_total_simulation)).cumsum()
pourcentage_total -= pourcentage_total.min()
pourcentage_total = pourcentage_total / pourcentage_total.max() * 100
# ax.scatter(temps_total_simulation, pourcentage_total, s=3, c=pourcentage_total, cmap=cmap)

pnts = np.c_[temps_total_simulation, pourcentage_total]
segments = np.c_[pnts[:-1], pnts[1:]].reshape(-1, 2, 2)
linecol = LineCollection(segments, cmap=cmap, norm=plt.Normalize(0, 100))
linecol.set_array(
    (pourcentage_total[:-1] + pourcentage_total[1:]) / 2)  # use the mean percentage for colloring the segment
linecol.set_linewidth(1)
ax.add_collection(linecol)

ax.set_xlim(temps_total_simulation[0], temps_total_simulation[-1])
ax.set_ylim(0, 100)

plt.show()


问:
Missing data in response body
I have a web service(FastAPI) deployed on AWS EC2.

In java client code, when I call the api, i got this error

```<code>org.apache.http.ConnectionClosedException: Premature end of Content-Length delimited message body (expected: 3,849,324; received: 1,834,837)
</code>```

In postman, when I call this api, the response is returned but not enough like this image

Seem the server (Fast API web service) do not return all data in response body.

I already check this question, the accepted answer said that this error is belong server-side.

So what is the problem here? What can I configure to solve this problem, on the AWS or my web service or any ?

Additional information, in the API implementation, business logic is connect to the AWS S3 and download some files. I don't know if this is the problem but when I looked for solution, a lot of people said it related to AWS S3

Thank you all guys!!!

答: After several investigating hours. My leader found the issue, it's out of memory issue. It is out of Hard disk driver instead of RAM. Lol</p>

Title: Missing data in response body

Body:
I have a web service(FastAPI) deployed on AWS EC2.

In java client code, when I call the api, i got this error

org.apache.http.ConnectionClosedException: Premature end of Content-Length delimited message body (expected: 3,849,324; received: 1,834,837)

In postman, when I call this api, the response is returned but not enough like this image

Seem the server (Fast API web service) do not return all data in response body.

I already check this question, the accepted answer said that this error is belong server-side.

So what is the problem here? What can I configure to solve this problem, on the AWS or my web service or any ?

Additional information, in the API implementation, business logic is connect to the AWS S3 and download some files. I don't know if this is the problem but when I looked for solution, a lot of people said it related to AWS S3

Thank you all guys!!!


问:
React component that shows the current weather in selected city (temperature, description and weather icon)
I would like to create a react component that shows the current weather in the selected city (temperature, description, and weather icon).

I'm using OpenWeatherMap, but I don't know where I should start..

I would like it to look like this:

```<code>function Weather() {
    const [weather, setWeather] = React.useState();

    const fetchWeather = () => {
        fetch(
            "api.openweathermap.org/data/2.5/weather?q=Helsinki &APPID=<APP-ID>"
        )
            .then(response => response.json())
            .then(data => {
                setWeather(data.results[0].weather);
            });
    };
}
</code>```

Help is needed! Thanks

答:
The issue was your fetch request is missing the protocol part at the start of URL(https://).

```<code>import "./styles.css";
import React from "react";

const cityList = ["Helsinki", "Tampere", "Turku", "Oulu"];

export default function Weather() {
  const [weather, setWeather] = React.useState();
  const [city, setCity] = React.useState("Helsinki");

  const fetchWeather = (city) => {
    fetch(
      `https://api.openweathermap.org/data/2.5/weather?q=${city}&APPID=dc6e198d710d27211ed68a445d1bb01e`
    )
      .then((response) => response.json())
      .then((data) => {
        setWeather(data);
      });
  };

  React.useEffect(() => {
    fetchWeather(city);
  }, [city]);

  return (
    <div className="App">
      <div>
        <select
          onChange={(e) => {
            setCity(e.target.value);
          }}
        >
          {cityList.map((city) => (
            <option value={city}>{city}</option>
          ))}
        </select>
      </div>
      <div style={{ marginTop: "20px" }}>
        <div>Temparature : {weather?.main?.temp}</div>
        <div>Weather : {weather?.weather?.[0]?.main}</div>
      </div>
    </div>
  );
}
</code>```

Body:
I would like to create a react component that shows the current weather in the selected city (temperature, description, and weather icon).

I'm using OpenWeatherMap, but I don't know where I should start..

I would like it to look like this:

function Weather() {
    const [weather, setWeather] = React.useState();

    const fetchWeather = () => {
        fetch(
            "api.openweathermap.org/data/2.5/weather?q=Helsinki &APPID=<APP-ID>"
        )
            .then(response => response.json())
            .then(data => {
                setWeather(data.results[0].weather);
            });
    };
}

Help is needed! Thanks

Body:
The issue was your fetch request is missing the protocol part at the start of URL(https://).

import "./styles.css";
import React from "react";

const cityList = ["Helsinki", "Tampere", "Turku", "Oulu"];

export default function Weather() {
  const [weather, setWeather] = React.useState();
  const [city, setCity] = React.useState("Helsinki");

  const fetchWeather = (city) => {
    fetch(
      `https://api.openweathermap.org/data/2.5/weather?q=${city}&APPID=dc6e198d710d27211ed68a445d1bb01e`
    )
      .then((response) => response.json())
      .then((data) => {
        setWeather(data);
      });
  };

  React.useEffect(() => {
    fetchWeather(city);
  }, [city]);

  return (
    <div className="App">
      <div>
        <select
          onChange={(e) => {
            setCity(e.target.value);
          }}
        >
          {cityList.map((city) => (
            <option value={city}>{city}</option>
          ))}
        </select>
      </div>
      <div style={{ marginTop: "20px" }}>
        <div>Temparature : {weather?.main?.temp}</div>
        <div>Weather : {weather?.weather?.[0]?.main}</div>
      </div>
    </div>
  );
}


问:
Can the unittest framework discover nested tests?
Is the following nested structure discoverable by unittest ?

```<code>class HerclTests(unittest.TestCase):

    def testJobs(self):
        def testJobSubmit():
            jid = "foobar"
            assert jid,'hercl job submit failed no job_id'
            return jid

        def testJobShow(jid):
            jid = "foobar"
            out,errout=bash(f"hercl job show --jid {jid} --form json")
            assert 'Job run has been accepted by airflow successfully' in out,'hercl job show failed'

</code>```

Here is the error when trying to run unittest :

```<code>============================= test session starts ==============================
platform darwin -- Python 3.6.7, pytest-5.4.3, py-1.10.0, pluggy-0.13.1 -- /Users/steve/git/hercl/.venv/bin/python
cachedir: .pytest_cache
rootdir: /Users/steve/git/hercl/tests
collecting ... collected 0 items
ERROR: not found: /Users/steve/git/hercl/tests/hercl_flow_test.py::HerclTests::testJobs::testJobSubmit
(no name '/Users/steve/git/hercl/tests/hercl_flow_test.py::HerclTests::testJobs::testJobSubmit' in any of [<TestCaseFunction testJobs>])

============================ no tests ran in 0.01s =============================
</code>```

Can this structure be tweaked to work with unittest or must each test method be elevated to the level of the HerclTests class?

答: This can't work - functions defined inside another function ("inner functions") only "exist" as variables inside the outer function's local scope. They're not accessible to any other code. The unittest discovery won't find them, and couldn't call them even if it knew about them.</p>

Body:
Is the following nested structure discoverable by unittest ?

class HerclTests(unittest.TestCase):

    def testJobs(self):
        def testJobSubmit():
            jid = "foobar"
            assert jid,'hercl job submit failed no job_id'
            return jid

        def testJobShow(jid):
            jid = "foobar"
            out,errout=bash(f"hercl job show --jid {jid} --form json")
            assert 'Job run has been accepted by airflow successfully' in out,'hercl job show failed'

Here is the error when trying to run unittest :

============================= test session starts ==============================
platform darwin -- Python 3.6.7, pytest-5.4.3, py-1.10.0, pluggy-0.13.1 -- /Users/steve/git/hercl/.venv/bin/python
cachedir: .pytest_cache
rootdir: /Users/steve/git/hercl/tests
collecting ... collected 0 items
ERROR: not found: /Users/steve/git/hercl/tests/hercl_flow_test.py::HerclTests::testJobs::testJobSubmit
(no name '/Users/steve/git/hercl/tests/hercl_flow_test.py::HerclTests::testJobs::testJobSubmit' in any of [<TestCaseFunction testJobs>])

============================ no tests ran in 0.01s =============================

Can this structure be tweaked to work with unittest or must each test method be elevated to the level of the HerclTests class?


问:
OpenCL Kernel working fine on intel but not on nvdia GPU?
My application uses OpenCL. I tested on my machine it was working fine but on a user's machine the kernels are just not working.

My Machine:

```<code>OpenCL Status : Using OpenCL Platform : Intel(R) OpenCL HD Graphics
OpenCL Status : Using GPU Device : Intel(R) HD Graphics 510
</code>```

Users Machine:

```<code>OpenCL Status : Using OpenCL Platform : NVIDIA CUDA
OpenCL Status : Using GPU Device : GeForce GT 730
</code>```

Code C++

```<code>kernels = new ComputeKernel();
std::string source = ReadShaderSourceFile(GetExecutableDir() + "\\Data\\kernels\\generators\\generators.cl", &tmp);
    kernels->AddSoruce(source);
    kernels->BuildProgram("-I" + appState->globals.kernelsIncludeDir + " -cl-fast-relaxed-math -cl-mad-enable");
    kernels->AddKernel("clear_mesh_terrain");
kernels->CreateBuffer("mesh", CL_MEM_READ_WRITE, appState->models.customBase->mesh->vertexCount * sizeof(Vert));
        kernels->WriteBuffer("mesh", true, appState->models.customBase->mesh->vertexCount * sizeof(Vert), appState->models.customBase->mesh->vert);
kernels->SetKernelArg("clear_mesh_terrain", 0, "mesh");

        kernels->ExecuteKernel("clear_mesh_terrain", cl::NDRange(1),

cl::NDRange(appState->models.coreTerrain->mesh->vertexCount));
</code>```

The ComputeKernel class:

```<code>void ComputeKernel::AddSoruce(std::string source)
{
    sources.push_back({source.c_str(), source.size()});
}

void ComputeKernel::BuildProgram(std::string options)
{
    program = cl::Program(context, sources);

    if (program.build({ device }, options.c_str()) != CL_SUCCESS)
    {
        onStatus("Error Building : " + program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device));
        return;
    }
}

void ComputeKernel::AddKernel(std::string name)
{
    kernels[name] = cl::Kernel(program, name.c_str());
}

void ComputeKernel::Clear()
{
    sources.clear();
    kernels.clear();
}

void ComputeKernel::ExecuteKernel(std::string name, cl::NDRange local, cl::NDRange global)
{
    queue.enqueueNDRangeKernel(kernels[name], cl::NullRange, global, local);
    queue.finish();
}

void ComputeKernel::CreateBuffer(std::string name, int type, size_t size)
{
    OpenCLBuffer buffer;
    buffer.size = size;
    buffer.buffer = cl::Buffer(context, type, size);
    buffers[name] = buffer;
}

void ComputeKernel::SetKernelArg(std::string name, int arg, std::string buffer)
{
    kernels[name].setArg(arg, buffers[buffer].buffer);
}

void ComputeKernel::ReadBuffer(std::string buffer, bool blocking, size_t size, void* data)
{
    queue.enqueueReadBuffer(buffers[buffer].buffer, blocking ? CL_TRUE : CL_FALSE, 0, size, data);
}

void ComputeKernel::WriteBuffer(std::string buffer, bool blocking, size_t size, void* data)
{
    queue.enqueueWriteBuffer(buffers[buffer].buffer, blocking ? CL_TRUE : CL_FALSE, 0, size, data);
}
</code>```

The Kernel:

```<code>__kernel void clear_mesh_terrain(__global Vert* mesh)
{
    int i = get_global_id(0);
    mesh[i].normal.x = 0.0f;
    mesh[i].normal.y = 0.0f;
    mesh[i].normal.z = 0.0f;
    mesh[i].normal.w = 0.0f;
    mesh[i].position.y = 0.0f;

}
</code>```

Now by not working i mean nothing is hapenning at all(kernels are not getting executed at all) but there are no errors no compile failure of kernels.

答:
The most likely explanation is that you are running out of memory on your Nvidia GT 730. Some of the Buffers fail to allocate, the Kernel runs through with 0 execution time and yet does nothing.

Keep track of how much memory you allocate in total. It should still work with smaller Buffers.

Body:
My application uses OpenCL. I tested on my machine it was working fine but on a user's machine the kernels are just not working.

My Machine:

OpenCL Status : Using OpenCL Platform : Intel(R) OpenCL HD Graphics
OpenCL Status : Using GPU Device : Intel(R) HD Graphics 510

Users Machine:

OpenCL Status : Using OpenCL Platform : NVIDIA CUDA
OpenCL Status : Using GPU Device : GeForce GT 730

Code C++

kernels = new ComputeKernel();
std::string source = ReadShaderSourceFile(GetExecutableDir() + "\\Data\\kernels\\generators\\generators.cl", &tmp);
    kernels->AddSoruce(source);
    kernels->BuildProgram("-I" + appState->globals.kernelsIncludeDir + " -cl-fast-relaxed-math -cl-mad-enable");
    kernels->AddKernel("clear_mesh_terrain");
kernels->CreateBuffer("mesh", CL_MEM_READ_WRITE, appState->models.customBase->mesh->vertexCount * sizeof(Vert));
        kernels->WriteBuffer("mesh", true, appState->models.customBase->mesh->vertexCount * sizeof(Vert), appState->models.customBase->mesh->vert);
kernels->SetKernelArg("clear_mesh_terrain", 0, "mesh");

        kernels->ExecuteKernel("clear_mesh_terrain", cl::NDRange(1),

cl::NDRange(appState->models.coreTerrain->mesh->vertexCount));

The ComputeKernel class:

void ComputeKernel::AddSoruce(std::string source)
{
    sources.push_back({source.c_str(), source.size()});
}

void ComputeKernel::BuildProgram(std::string options)
{
    program = cl::Program(context, sources);

    if (program.build({ device }, options.c_str()) != CL_SUCCESS)
    {
        onStatus("Error Building : " + program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device));
        return;
    }
}

void ComputeKernel::AddKernel(std::string name)
{
    kernels[name] = cl::Kernel(program, name.c_str());
}

void ComputeKernel::Clear()
{
    sources.clear();
    kernels.clear();
}

void ComputeKernel::ExecuteKernel(std::string name, cl::NDRange local, cl::NDRange global)
{
    queue.enqueueNDRangeKernel(kernels[name], cl::NullRange, global, local);
    queue.finish();
}

void ComputeKernel::CreateBuffer(std::string name, int type, size_t size)
{
    OpenCLBuffer buffer;
    buffer.size = size;
    buffer.buffer = cl::Buffer(context, type, size);
    buffers[name] = buffer;
}

void ComputeKernel::SetKernelArg(std::string name, int arg, std::string buffer)
{
    kernels[name].setArg(arg, buffers[buffer].buffer);
}

void ComputeKernel::ReadBuffer(std::string buffer, bool blocking, size_t size, void* data)
{
    queue.enqueueReadBuffer(buffers[buffer].buffer, blocking ? CL_TRUE : CL_FALSE, 0, size, data);
}

void ComputeKernel::WriteBuffer(std::string buffer, bool blocking, size_t size, void* data)
{
    queue.enqueueWriteBuffer(buffers[buffer].buffer, blocking ? CL_TRUE : CL_FALSE, 0, size, data);
}

The Kernel:

__kernel void clear_mesh_terrain(__global Vert* mesh)
{
    int i = get_global_id(0);
    mesh[i].normal.x = 0.0f;
    mesh[i].normal.y = 0.0f;
    mesh[i].normal.z = 0.0f;
    mesh[i].normal.w = 0.0f;
    mesh[i].position.y = 0.0f;

}

Now by not working i mean nothing is hapenning at all(kernels are not getting executed at all) but there are no errors no compile failure of kernels.


问:
Is there any way we can export the Antd table data into an excel sheet on button click with reactjs
I am new to reactjs. I got a scenario in which the Antd table data need to be exported to an excel sheet on a button click. Is there any default options available with Antd? or we need to do some custom development for same. Any pointers will be appreciated.

Thanks

答:
You can use library react-csv to convert the table data into an .csv file. You can refer to the docs for the onClick props.</p>
```<code>import { CSVLink } from "react-csv";

    <CSVLink
        data={data}
        onClick={() => {
        console.log("clicked")
        }}
    >
    Download me
    </CSVLink>

    <Table
       columns={columns}
       dataSource={data}
    />
</code>```

Body:
You can use library react-csv to convert the table data into an .csv file. You can refer to the docs for the onClick props.

import { CSVLink } from "react-csv";

    <CSVLink
        data={data}
        onClick={() => {
        console.log("clicked")
        }}
    >
    Download me
    </CSVLink>

    <Table
       columns={columns}
       dataSource={data}
    />


问:
Chrome: how to remove url from autocomplete list
For each project that i work on, I hit certain websites often.

When i'm done with that project, i would like those website URLs to not show up in my autocomplete any longer.

How do i do this on google chrome with a mac?

答:
I needed to remove it from
C:\Users\$USER%\AppData\Local\Google\Chrome\User Data\Default\Bookmarks
which is a plain-text file.

Many of the other, bigger files are sqlite3 databases..


问:
is there a way to use the behavior trick for IE6 when the image is set inline?
```<code><li><img alt="compra_segura" src="../../nImg/img_with_alpha.png" /></li>
</code>```

is there a way to use the behavior: url(/nJs/iepngfix.htc); trick for IE6 (when the image has alpha) when the image is set inline and not in the stylesheet?

thanks a lot

答:
Provided that it's all set up properly, you should just be able to add img to your "trigger the fix CSS":

```<code>img, div { behavior: url(iepngfix.htc) }
</code>```

http://www.twinhelix.com/css/iepngfix/demo/

Body:
Provided that it's all set up properly, you should just be able to add img to your "trigger the fix CSS":

img, div { behavior: url(iepngfix.htc) }

http://www.twinhelix.com/css/iepngfix/demo/


问:
Android custom permission vs app signature
I have gone through the available documentation and SO posts on both these topics (custom permissions and app signature), my understanding is:

Apps signed with same key can use signature-level permissions

A custom permission should only be defined in one place and the app declaring the permission needs to be installed first

A custom permission can be defined in multiple apps if the apps share same signature

Now I need to define some components in one app that I will be using in another app signed with the same key, but according to this I don't need to define a custom permission and can place a signature check

If the functionality is only available to apps signed with the same signature as the providing app, you may be able to avoid defining custom permissions by using signature checks. When one of your apps makes a request of another of your apps, the second app can verify that both apps are signed with the same certificate before complying with the request.

I don't understand what is meant by signature checks, is there a way to place a check in manifest on that component or do I have to check it programmatically? If latter, isn't it better to define a custom permission in both apps instead (to negate installation order issue)?

答:
is there a way to place a check in manifest on that component

No, sorry.

do I have to check it programmatically?

Yes. This pair of old projects demonstrate a bound service and a client that checks the signature of the service. Those projects are covered in a chapter in a chapter of this free old book. That sample has problems in modern Android, as an app can have multiple signatures. But, the SiganturesUtil class that it relies on shows how to get signatures from PackageManager for an installed app. You can then compare them with the expected value to determine if you are indeed talking to the app that you expect.

If latter, isn't it better to define a custom permission in both apps instead (to negate installation order issue)?

Signature checks are more flexible — they are not limited to two apps being signed by the same signing key. That, plus historical issues with custom permissions, may be why Google recommends signature checks over custom permissions on that page.


问:
Hide specific product from Woocommerce Shop page if the logged-in user has already been purchased
I am creating an LMS using LearnDash + WooCommerce. I am trying to find a way to hide specific product from the Woocommerce product table page. If the logged in user has already purchased said product a) prevent the user from purchasing it twice, and b) so that I can display a product grid for them without the already purchased item(s).

Another example: if a user who purchased Item B and D goes to the shop, Item B and D should not even be displayed for them.

```<code>
+--------+----------+
| Item A |   $116   |
+--------+----------+
| Item B |   $96    |
+--------+----------+
| Item C |   $41    |
+--------+----------+
| Item D |   $78    |
+--------+----------+

         ↓

+--------+----------+
| Item A |   $116   |
+--------+----------+
| Item C |   $41    |
+--------+----------+

</code>```

This is my code:

```<code>/* Avoid buying the same product again in WooCommerce by adding products to the cart by logged-in users before checkout */
function filter_woocommerce_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null) {
    // Retrieve the current user object
    $current_user = wp_get_current_user();
    // Check for variantions, if you don't want this, delete this code line
    $product_id = $variation_id > 0 ? $variation_id : $product_id;

    // Checks if a user (by email or ID or both) has bought an item
    if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product_id ) ) {
        // Display an error message
        wc_add_notice( __( 'You have already enrolled into the course. ' , 'woocommerce' ), 'error' );

        $passed = false;
    }

    return $passed;

}
add_filter( 'woocommerce_add_to_cart_validation', 'filter_woocommerce_add_to_cart_validation', 10, 5 );
</code>```

So any help would be appreciated.

答:
You can change the product query using the pre_get_posts action hook and then you can get current user products that they already purchased. pass all products id to post__not_in. check the below code. code will go active theme function.php file.

```<code>add_action( 'pre_get_posts', 'hide_product_from_shop_page_if_user_already_purchased', 20 );

function hide_product_from_shop_page_if_user_already_purchased( $query ) {

    if ( ! $query->is_main_query() ) return;

    if ( ! is_admin() && is_shop() ) {

        $current_user = wp_get_current_user();
        if ( 0 == $current_user->ID ) return;

        $customer_orders = get_posts( array(
            'numberposts' => -1,
            'meta_key'    => '_customer_user',
            'meta_value'  => $current_user->ID,
            'post_type'   => 'shop_order',
            'post_status' => array( 'wc-processing', 'wc-completed' ),
        ) );

        if ( ! $customer_orders ) return;

        $product_ids = array();

        foreach ( $customer_orders as $customer_order ) {
            $order = wc_get_order( $customer_order->ID );
            if( $order ){
                $items = $order->get_items();
                foreach ( $items as $item ) {
                    $product_id    = $item->get_product_id();
                    $product_ids[] = $product_id;
                }
            }
        }

        $product_ids = array_unique( $product_ids );

        $query->set( 'post__not_in', $product_ids );
    }

}
</code>```

Body:
I am creating an LMS using LearnDash + WooCommerce. I am trying to find a way to hide specific product from the Woocommerce product table page. If the logged in user has already purchased said product a) prevent the user from purchasing it twice, and b) so that I can display a product grid for them without the already purchased item(s).

Another example: if a user who purchased Item B and D goes to the shop, Item B and D should not even be displayed for them.

+--------+----------+
| Item A |   $116   |
+--------+----------+
| Item B |   $96    |
+--------+----------+
| Item C |   $41    |
+--------+----------+
| Item D |   $78    |
+--------+----------+

         ↓

+--------+----------+
| Item A |   $116   |
+--------+----------+
| Item C |   $41    |
+--------+----------+

This is my code:

/* Avoid buying the same product again in WooCommerce by adding products to the cart by logged-in users before checkout */
function filter_woocommerce_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null) {
    // Retrieve the current user object
    $current_user = wp_get_current_user();
    // Check for variantions, if you don't want this, delete this code line
    $product_id = $variation_id > 0 ? $variation_id : $product_id;

    // Checks if a user (by email or ID or both) has bought an item
    if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product_id ) ) {
        // Display an error message
        wc_add_notice( __( 'You have already enrolled into the course. ' , 'woocommerce' ), 'error' );

        $passed = false;
    }

    return $passed;

}
add_filter( 'woocommerce_add_to_cart_validation', 'filter_woocommerce_add_to_cart_validation', 10, 5 );

So any help would be appreciated.

Body:
You can change the product query using the pre_get_posts action hook and then you can get current user products that they already purchased. pass all products id to post__not_in. check the below code. code will go active theme function.php file.

add_action( 'pre_get_posts', 'hide_product_from_shop_page_if_user_already_purchased', 20 );

function hide_product_from_shop_page_if_user_already_purchased( $query ) {

    if ( ! $query->is_main_query() ) return;

    if ( ! is_admin() && is_shop() ) {

        $current_user = wp_get_current_user();
        if ( 0 == $current_user->ID ) return;

        $customer_orders = get_posts( array(
            'numberposts' => -1,
            'meta_key'    => '_customer_user',
            'meta_value'  => $current_user->ID,
            'post_type'   => 'shop_order',
            'post_status' => array( 'wc-processing', 'wc-completed' ),
        ) );

        if ( ! $customer_orders ) return;

        $product_ids = array();

        foreach ( $customer_orders as $customer_order ) {
            $order = wc_get_order( $customer_order->ID );
            if( $order ){
                $items = $order->get_items();
                foreach ( $items as $item ) {
                    $product_id    = $item->get_product_id();
                    $product_ids[] = $product_id;
                }
            }
        }

        $product_ids = array_unique( $product_ids );

        $query->set( 'post__not_in', $product_ids );
    }

}


问:
How to represent linear types in C#/.Net?
Is there a reasonable way to express the concept of a linear type in .Net (Compact Framework/desktop 3.5 common subset), in such a way that (a) the required syntax doesn't become overly verbose, convoluted, or otherwise painful and (b) the invariant can be either enforced at run time or validated by code analysis at compile time (so a maintenance programmer in an all-fired hurry can't just blithely ignore the invariant)?  The idea here is to avoid the need for defensive copying of command objects at subsystem boundaries.</p>

答:
Linear types, based on the theory of linear logic, and closely related to uniqueness types, are types assigned to values having the property that they have one and only one reference to them at all times. These are valuable for describing large immutable values such as files, strings, and so on.

An immutable type is one whose internal state cannot change after it has been instantiated.

A ‘deeply immutable’ type is one whose dependency graph contains reference types that are also ‘deeply immutable’.  If dependant reference types are not themselves ‘deeply immutable’, the type is termed ‘shallow immutable’.

In C# we work with reference types and value types.  Instances of reference types can be shared between disparate concurrently executing code, whereas value types are stack bound (unless boxed), copied on sharing and therefore autonomous, although not immutable (and may contain dependencies on other reference types which are then ‘copy shared’).

Although the ability to share a reference type is undoubtedly a powerful feature of object orientated frameworks, in the world of Enterprise development it should also be considered one of its main weaknesses and used with extreme caution.  Anything that cannot be executed atomically exposes fragility and an opportunity for interleaving bugs to intermittently wreak havoc.

In C# the best we can do is describe our intentions.  Immutability can be partially implemented by marking a types entire internal state as private and readonly.  Deep immutability cannot be enforced (nor for that matter can shallow) so it is up to the developer to stick to the intentions.  Changes to the state is through static methods that return new instances of the type containing the requested state.

```<code>public sealed class PersonImmutable {

    private readonly int _age;
    private readonly string _name;

    public PersonImmutable(int age, string name) {
        this._age = age;
        this._name = name;
    }

    public int Age {
        get { return this._age; }
    }

    public string Name {
        get { return this._name; }
    }

    public static PersonImmutable NotifyBirthday(PersonImmutable source) {
        return new PersonImmutable(1 + source.Age, source.Name);
    }
}
</code>```

Body:
Linear types, based on the theory of linear logic, and closely related to uniqueness types, are types assigned to values having the property that they have one and only one reference to them at all times. These are valuable for describing large immutable values such as files, strings, and so on.

An immutable type is one whose internal state cannot change after it has been instantiated.

A ‘deeply immutable’ type is one whose dependency graph contains reference types that are also ‘deeply immutable’.  If dependant reference types are not themselves ‘deeply immutable’, the type is termed ‘shallow immutable’.

In C# we work with reference types and value types.  Instances of reference types can be shared between disparate concurrently executing code, whereas value types are stack bound (unless boxed), copied on sharing and therefore autonomous, although not immutable (and may contain dependencies on other reference types which are then ‘copy shared’).

Although the ability to share a reference type is undoubtedly a powerful feature of object orientated frameworks, in the world of Enterprise development it should also be considered one of its main weaknesses and used with extreme caution.  Anything that cannot be executed atomically exposes fragility and an opportunity for interleaving bugs to intermittently wreak havoc.

In C# the best we can do is describe our intentions.  Immutability can be partially implemented by marking a types entire internal state as private and readonly.  Deep immutability cannot be enforced (nor for that matter can shallow) so it is up to the developer to stick to the intentions.  Changes to the state is through static methods that return new instances of the type containing the requested state.

public sealed class PersonImmutable {

    private readonly int _age;
    private readonly string _name;

    public PersonImmutable(int age, string name) {
        this._age = age;
        this._name = name;
    }

    public int Age {
        get { return this._age; }
    }

    public string Name {
        get { return this._name; }
    }

    public static PersonImmutable NotifyBirthday(PersonImmutable source) {
        return new PersonImmutable(1 + source.Age, source.Name);
    }
}


问:
Enable CORS on API Gateway with Python CDK
I have an API Gateway defined in the python cdk that will accept CURL Restful requests to upload / read / delete files from an S3 bucket:

```<code>api = api_gw.RestApi(self, "file-api",
                  rest_api_name="File REST Service")

        file = api.root.add_resource("{id}")

        get_files_integration = api_gw.LambdaIntegration(handler,
                request_templates={"application/json": '{ "statusCode": "200" }'})
        post_file_integration = api_gw.LambdaIntegration(handler)
        get_file_integration = api_gw.LambdaIntegration(handler)
        delete_file_integration = api_gw.LambdaIntegration(handler)

        api.root.add_method("GET", get_files_integration, authorization_type=api_gw.AuthorizationType.COGNITO, authorizer=auth)
        file.add_method("POST", post_file_integration);     # POST /{id}
        file.add_method("GET", get_file_integration);       # GET /{id}
        file.add_method("DELETE", delete_file_integration); # DELETE /{id}
</code>```

Is it possible to enable CORS on the API Gateway so that it will perform pre-flight checks and allow external access from a localhost on another machine?

I have attempted to use the existing add_core_preflight() method defined in the documentation I can find but believe this may no longer be valid as of CDK 2.0.

答:
Yes, IResource.add_cors_preflight() does exactly this.

You can also specify default CORS config with the default_cors_preflight_options attribute of RestApi.

Here are the examples from the docs. They're in Typescript, but it will work the same in Python.

The following example will enable CORS for all methods and all origins on all resources of the API:

new apigateway.RestApi(this, 'api', {
  defaultCorsPreflightOptions: {
    allowOrigins: apigateway.Cors.ALL_ORIGINS,
    allowMethods: apigateway.Cors.ALL_METHODS // this is also the default
  }
})
```
<blockquote>
<p>The following example will add an OPTIONS method to the myResource API resource, which only allows GET and PUT HTTP requests from the origin https://amazon.com.</p>
</blockquote>
<pre class="lang-typescript prettyprint-override"><code>declare const myResource: apigateway.Resource;

myResource.addCorsPreflight({
  allowOrigins: [ 'https://amazon.com' ],
  allowMethods: [ 'GET', 'PUT' ]
});
</code>```

Body:
I have an API Gateway defined in the python cdk that will accept CURL Restful requests to upload / read / delete files from an S3 bucket:

api = api_gw.RestApi(self, "file-api",
                  rest_api_name="File REST Service")

        file = api.root.add_resource("{id}")

        get_files_integration = api_gw.LambdaIntegration(handler,
                request_templates={"application/json": '{ "statusCode": "200" }'})
        post_file_integration = api_gw.LambdaIntegration(handler)
        get_file_integration = api_gw.LambdaIntegration(handler)
        delete_file_integration = api_gw.LambdaIntegration(handler)

        api.root.add_method("GET", get_files_integration, authorization_type=api_gw.AuthorizationType.COGNITO, authorizer=auth)
        file.add_method("POST", post_file_integration);     # POST /{id}
        file.add_method("GET", get_file_integration);       # GET /{id}
        file.add_method("DELETE", delete_file_integration); # DELETE /{id}

Is it possible to enable CORS on the API Gateway so that it will perform pre-flight checks and allow external access from a localhost on another machine?

I have attempted to use the existing add_core_preflight() method defined in the documentation I can find but believe this may no longer be valid as of CDK 2.0.

Body:
Yes, IResource.add_cors_preflight() does exactly this.

You can also specify default CORS config with the default_cors_preflight_options attribute of RestApi.

Here are the examples from the docs. They're in Typescript, but it will work the same in Python.

The following example will enable CORS for all methods and all origins on all resources of the API:

new apigateway.RestApi(this, 'api', {
  defaultCorsPreflightOptions: {
    allowOrigins: apigateway.Cors.ALL_ORIGINS,
    allowMethods: apigateway.Cors.ALL_METHODS // this is also the default
  }
})

The following example will add an OPTIONS method to the myResource API resource, which only allows GET and PUT HTTP requests from the origin https://amazon.com.

declare const myResource: apigateway.Resource;

myResource.addCorsPreflight({
  allowOrigins: [ 'https://amazon.com' ],
  allowMethods: [ 'GET', 'PUT' ]
});


问:
Show all street names when zooming out
I would like to print a map with all the street names with MapTiler or MapBox, especially Rue Robert Schuman:

Link to static map

Link to interactive map

But if I zoom out to zoom-level 18 (MapBox) or 16 (MapTiler) the names of some streets disappear, although there is enough space to display them.

I have tried to follow the instructions from MapBox, but I didn't manage to solve the problem.

Any ideas?

答:
the visibility of labels of map features (streets, buildings...)
is defined in the map style (style.json) which is editable via MapTiler Cloud map editor. If you change the visibility of road labels to corresponding levels, they will stay visible in your preferred zoom levels.

I am more than happy to help you set that up, just send me your MapTiler account email via support@maptiler.com and we can have a look at that together.

Thank you

Jiri
MapTiler Support

Title: Show all street names when zooming out


问:
HorizontalScroll Image on Android
I'm new at developing app and I'm trying to do my first app on Android Studio.

I have a problem: I would like that my horizontal scroll targets immediatly the next image (I will leave the photo)
This is the first image that we see

After that photo, there is another one:
Second Image

You can see that it shows both image 1 and image 2 together and I would like that it shows just 1 image at a time.

Tell me if the question is clear and if you need more information. Thanks

答:
You Can Set One Image At a Time After Time Click The Second Image Is Popup Using The Image Slider

For Image Slider You Use With ViewPager

Title: HorizontalScroll Image on Android


问:
Using a string as an index in typescript
I am trying to type the following

```<code>    interface IStudentType {
      [key: `${Students}`]: IStudent | IStudentMaths| IStudentPhysics
     }
</code>```

The issue I get is TS1268: An index signature parameter type must be 'string', 'number', 'symbol', or a template literal type.

Fair enough so I try

```<code>type StudentCategories = 'Mature' | 'Graduate' | 'Fresher' // these are the keys in the data

interface IStudentType {
  [key: `${StudentCategories}`]: IStudent | IStudentMaths| IStudentPhysics
}

TS1337: An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.
</code>```

Any ideas how to fix this?

答:
If you have a union of keys, you should use Record

type StudentCategories = 'Mature' | 'Graduate' | 'Fresher' // these are the keys in the data

type IStudent = {
    tag: 'IStudent '
}

type IStudentMaths = {
    tag: 'IStudentMaths'
}
type IStudentPhysics = {
    tag: 'IStudentPhysics'
}

type StudentType = Record<StudentCategories, IStudent | IStudentMaths | IStudentPhysics>
```
<p>Playground</p>
<p>It is possible to use Symbol and Template String Pattern Index Signatures and PR but then you need to add a prefix:</p>
<pre class="lang-js prettyprint-override"><code>
interface StudentType {
    [prop: `${string}-${StudentCategories}`]: IStudent | IStudentMaths | IStudentPhysics
}
</code>```

Body:
I am trying to type the following

    interface IStudentType {
      [key: `${Students}`]: IStudent | IStudentMaths| IStudentPhysics
     }

The issue I get is TS1268: An index signature parameter type must be 'string', 'number', 'symbol', or a template literal type.

Fair enough so I try

type StudentCategories = 'Mature' | 'Graduate' | 'Fresher' // these are the keys in the data

interface IStudentType {
  [key: `${StudentCategories}`]: IStudent | IStudentMaths| IStudentPhysics
}

TS1337: An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.

Any ideas how to fix this?

Body:
If you have a union of keys, you should use Record

type StudentCategories = 'Mature' | 'Graduate' | 'Fresher' // these are the keys in the data

type IStudent = {
    tag: 'IStudent '
}

type IStudentMaths = {
    tag: 'IStudentMaths'
}
type IStudentPhysics = {
    tag: 'IStudentPhysics'
}

type StudentType = Record<StudentCategories, IStudent | IStudentMaths | IStudentPhysics>

Playground

It is possible to use Symbol and Template String Pattern Index Signatures and PR but then you need to add a prefix:

interface StudentType {
    [prop: `${string}-${StudentCategories}`]: IStudent | IStudentMaths | IStudentPhysics
}


问:
How to fire keyboard events in Javascript using onClick?
I have an existing function that gets called when KeyD is pressed.

I want to trigger an KeyD event (without actually pressing keyD on keyboard) as soon as I click on some button.

Is it possible in Javascript?

答:
You have to implement dispatchEvent.

let element = document.querySelector('input');
element.onkeydown = e => alert(e.key);
changeValButton.onclick = () => element.value += "a";
dispatchButton.onclick = () => {
   element.dispatchEvent(new KeyboardEvent('keydown', {'key': 'd'}));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input/>
<button id="dispatchButton">Press to dispatch event </button>
<button id="changeValButton">Press to change value </button></code>```

Body:
You have to implement dispatchEvent.

let element = document.querySelector('input');
element.onkeydown = e => alert(e.key);
changeValButton.onclick = () => element.value += "a";
dispatchButton.onclick = () => {
   element.dispatchEvent(new KeyboardEvent('keydown', {'key': 'd'}));
}

<input/>
<button id="dispatchButton">Press to dispatch event </button>
<button id="changeValButton">Press to change value </button>


问:
node_modules/@types/node/index.d.ts(20,1): error TS1084: Invalid 'reference' directive syntax
I have a problem with typescript compilation. Has anybody else received this error?

node_modules/@types/node/index.d.ts(20,1): error TS1084: Invalid
'reference' directive syntax.

tsconfig.json:

```<code>{
    "compileOnSave": false,
    "compilerOptions": {
        "sourceMap": true,
        "outDir": "./dist",
        "rootDir": "./app",
        "target": "es6",
        "module": "commonjs",
        "declaration": false,
        "noImplicitAny": false,
        "removeComments": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "listFiles": false,
        "skipLibCheck": true
    },
    "include": [
        "./app/**/*.ts"
    ]
}
</code>```

typescript version in package.json: "typescript": "^2.6.1"

答:
Try downgrading the @type/node.

I had the same issue  with

```<code>"devDependencies": {
    "@types/node": "12.20.42",
}
</code>```

I downgraded it to lower version and it compiles successfully

```<code>"devDependencies": {
    "@types/node": "12.19.12",
}
</code>```

Body:
I have a problem with typescript compilation. Has anybody else received this error?

node_modules/@types/node/index.d.ts(20,1): error TS1084: Invalid
'reference' directive syntax.

tsconfig.json:

{
    "compileOnSave": false,
    "compilerOptions": {
        "sourceMap": true,
        "outDir": "./dist",
        "rootDir": "./app",
        "target": "es6",
        "module": "commonjs",
        "declaration": false,
        "noImplicitAny": false,
        "removeComments": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "listFiles": false,
        "skipLibCheck": true
    },
    "include": [
        "./app/**/*.ts"
    ]
}

typescript version in package.json: "typescript": "^2.6.1"

Body:
Try downgrading the @type/node.

I had the same issue  with

"devDependencies": {
    "@types/node": "12.20.42",
}

I downgraded it to lower version and it compiles successfully

"devDependencies": {
    "@types/node": "12.19.12",
}


问:
Which project files are relevant still for Visual Studio 2022?
After upgrading from VS-2015 and even earlier versions, I still have some project files in my folder which I might no longer need.

I am wondering, are there any of these files that I can delete (* = project name)?

```<code>*.VC.db -> 100+ MB
*.sdf -> ~100 MB
*.vcxproj.user
*.aps
*.filters
*.sln.docstates.suo
*.suo
*.user
*.vcxproj.filters
msvcp140.dll
vcruntime140.dll
</code>```

答:
Here's a breakdown of what those files are and whether or not you should delete them:

*.VC.db Project-level database for IntelliSense (since VS-2015) that replaces the old ".sdf" file. If you delete this, it will (at some point) get re-created, but your project will lose some of its 'remembered' information used by IntelliSense. You may like to delete this from time to time, if you notice it growing very large.

*.sdf Old (pre-VS-2015) database file (vide supra). Can readily be deleted, as it's no longer used.

*.vcxproj.user Per-user project options file; this is still used and is generally not large. Best not to delete it.

*.aps This is where your actions in the Visual Resource Editor are remembered. If you delete it, it will be re-created next time you use the resource editor. As with the first case, it can be useful to 'purge' these from time to time, as they can get very large. See also: What is app.aps file in Visual C++?

*.suo Old-style solution options database. No longer used and can be deleted.

*.user I'm not completely sure, but I think this is the old form of the .vcxproj.user settings file. None of my new project folders have this, so I can't see that VS-2015+ uses it. Maybe try removing it (but keeping it somewhere else) and see if any settings are lost or if it is re-created?

*.vcxproj.filters Still used. This tells VS where in the project tree to add any new files you create or add to the project (like ".cpp" files into "Source Files" and ".h" into "Header Files").

msvcp140.dll and vcruntime140.dll I have no idea why you have (copies of) these run-time libraries in your project folder. There will be the latest/appropriate versions of these files in your system folder, so you can delete them.

More information about the various file types used by Visual Studio can be found here.

Body:
After upgrading from VS-2015 and even earlier versions, I still have some project files in my folder which I might no longer need.

I am wondering, are there any of these files that I can delete (* = project name)?

*.VC.db -> 100+ MB
*.sdf -> ~100 MB
*.vcxproj.user
*.aps
*.filters
*.sln.docstates.suo
*.suo
*.user
*.vcxproj.filters
msvcp140.dll
vcruntime140.dll


问:
Difference between two codes and InputMismatchException
I am a newbie with java and the class scanners.
I have two Codes and I dont get the point why one of them throws a InputMismatchException.
I look forward to the answers.
Here both codes:

1st one with the Exception Error:

```<code>public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    String firstName, lastName, completeName;
    int age;

    System.out.println("Please enter your first name: ");

    firstName = sc.nextLine();

    System.out.println("Please enter your last name: ");

    lastName = sc.nextLine();

    System.out.println("Please enter your complete name and your age: ");

    completeName = sc.next();
    age = sc.nextInt();

    System.out.println("Your complete name is: " + completeName);
    System.out.println("Your age is: " + age);

}
</code>```

Console:

Please enter your first name:

Peter

Please enter your last name:

Henrik

Please enter your complete name and your age:

Peter Henrik 22

(InputMismatchException)

2nd one with no error:

```<code>public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    String firstName, lastName;
    int age;

    System.out.println("Please enter your first name: ");

    firstName = sc.nextLine();

    System.out.println("Please enter your last name: ");

    lastName = sc.nextLine();

    System.out.println("Please enter your age: ");

    age = sc.nextInt();

    System.out.println("Your complete name is: " + firstName + " " + lastName);
    System.out.println("Your age is: " + age);

}
</code>```

Console:

Please enter your first name:

Peter

Please enter your last name:

Henrik

Please enter your age:

22

Your complete name is: Peter Henrik

Your age is: 22

答:
Having a look at the Javadoc of Scanner#next() will tell you the following:

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.

The default delimiter for the Scanner is a whitespace.

Knowing this, you provide the following input

Peter Henrik 22
```
<p>and try to read this input via the following</p>
<pre class="lang-java prettyprint-override"><code>completeName = sc.next();
age = sc.nextInt();
</code>```

The call to sc.next() will read the first complete token up to the whitespace, which is "Peter".
So Henrik 22 is still available in the Scanner buffer.

Therefore sc.nextInt() will read Henrik and try to parse it to an int hence the InputMismatchException.

To read both tokens to get the complete name, simply change

completeName = sc.next();
```
<p>to</p>
<pre class="lang-java prettyprint-override"><code>completeName = sc.next() + " " + sc.next();
</code>```

However, names don't always consist of only two parts. Since there could be names that more than two single tokens, you should / could do it like the following (provided you still want to enter the complete name and age in one line):

String line = sc.nextLine(); // read the whole line
// everything up to the last token is the name
completeName = line.substring(0, line.lastIndexOf(" "));
// last token is the age
age = line.substring(line.lastIndexOf(" ") + 1);
```

Body:
I am a newbie with java and the class scanners.
I have two Codes and I dont get the point why one of them throws a InputMismatchException.
I look forward to the answers.
Here both codes:

1st one with the Exception Error:

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    String firstName, lastName, completeName;
    int age;

    System.out.println("Please enter your first name: ");

    firstName = sc.nextLine();

    System.out.println("Please enter your last name: ");

    lastName = sc.nextLine();

    System.out.println("Please enter your complete name and your age: ");

    completeName = sc.next();
    age = sc.nextInt();

    System.out.println("Your complete name is: " + completeName);
    System.out.println("Your age is: " + age);

}

Console:

Please enter your first name:

Peter

Please enter your last name:

Henrik

Please enter your complete name and your age:

Peter Henrik 22

(InputMismatchException)

2nd one with no error:

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    String firstName, lastName;
    int age;

    System.out.println("Please enter your first name: ");

    firstName = sc.nextLine();

    System.out.println("Please enter your last name: ");

    lastName = sc.nextLine();

    System.out.println("Please enter your age: ");

    age = sc.nextInt();

    System.out.println("Your complete name is: " + firstName + " " + lastName);
    System.out.println("Your age is: " + age);

}

Console:

Please enter your first name:

Peter

Please enter your last name:

Henrik

Please enter your age:

22

Your complete name is: Peter Henrik

Your age is: 22

Body:
Having a look at the Javadoc of Scanner#next() will tell you the following:

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.

The default delimiter for the Scanner is a whitespace.

Knowing this, you provide the following input

Peter Henrik 22

and try to read this input via the following

completeName = sc.next();
age = sc.nextInt();

The call to sc.next() will read the first complete token up to the whitespace, which is "Peter".
So Henrik 22 is still available in the Scanner buffer.

Therefore sc.nextInt() will read Henrik and try to parse it to an int hence the InputMismatchException.

To read both tokens to get the complete name, simply change

completeName = sc.next();

to

completeName = sc.next() + " " + sc.next();

However, names don't always consist of only two parts. Since there could be names that more than two single tokens, you should / could do it like the following (provided you still want to enter the complete name and age in one line):

String line = sc.nextLine(); // read the whole line
// everything up to the last token is the name
completeName = line.substring(0, line.lastIndexOf(" "));
// last token is the age
age = line.substring(line.lastIndexOf(" ") + 1);


问:
Airflow, avoid top level pull from SSM
I have the following DAG, which works just fine:

```<code>from airflow import DAG
from airflow.models import Variable
from airflow.operators.subdag import SubDagOperator
from subdags import my_subdag

data_sets = Variable.get("data_sets", deserialize_json=True).get("data")

default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'start_date': datetime(2020, 1, 1),
}

with DAG(
        'myDAG',
        default_args=default_args,
        schedule_interval='00 12 * * *'
) as dag:

    ...

    for data_set in data_sets:
        subdag = SubDagOperator(
            task_id=f'{data_set}_subdag',
            subdag=my_subdag(
                parent_dag_name='myDAG',
                child_dag_name=f'{data_set}_subdag',
            ),
            ...
            default_args=default_args,
        )
        start >> subdag >> end

</code>```

But as you can see, I am calling Variable at the top level, which is not best practice (the scheduler queries the secret backend every minute or so).

What can I do to make it so airflow is calling Variable.get only during execution? I was looking at best practices, I can't use another file ('Generating Python code with embedded meta-data') so I though maybe jinja templating could help but I am not sure how to proceed.

答:
No. You can't do it differently currently. If you want to have a dynamic DAG structure based on some external sources, then you cannot do it otherwise than using Top-Level code (and following best practices).

However If you want to have N identical tasks (with some variable index) that you want to dynamically start based on some dynamic data (which seems what you want to do) when the task is executed, there is a change coming in 2.3.0 that will allow you to do that.

https://cwiki.apache.org/confluence/display/AIRFLOW/AIP-42+Dynamic+Task+Mapping

Title: Airflow, avoid top level pull from SSM

Body:
I have the following DAG, which works just fine:

from airflow import DAG
from airflow.models import Variable
from airflow.operators.subdag import SubDagOperator
from subdags import my_subdag

data_sets = Variable.get("data_sets", deserialize_json=True).get("data")

default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'start_date': datetime(2020, 1, 1),
}

with DAG(
        'myDAG',
        default_args=default_args,
        schedule_interval='00 12 * * *'
) as dag:

    ...

    for data_set in data_sets:
        subdag = SubDagOperator(
            task_id=f'{data_set}_subdag',
            subdag=my_subdag(
                parent_dag_name='myDAG',
                child_dag_name=f'{data_set}_subdag',
            ),
            ...
            default_args=default_args,
        )
        start >> subdag >> end

But as you can see, I am calling Variable at the top level, which is not best practice (the scheduler queries the secret backend every minute or so).

What can I do to make it so airflow is calling Variable.get only during execution? I was looking at best practices, I can't use another file ('Generating Python code with embedded meta-data') so I though maybe jinja templating could help but I am not sure how to proceed.


问:
Take the mean of the top 10% values according to the date
I have a dataframe that consist of the day column and a score column. So per day, there are many values. So I need to get the mean of the top 10% values per day. Simply means I need the output as a day column and mean of the top 10% values of that day.

this is a example dataset screenshot

```<code>`{'Date':
 [
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1)],
 'value': [
  3.35,
  1.85,
  1.3,
  1.85,
  1.85,
  1.17,
  1.17,
  2.8,
  1.43,
  2.54,
  1.22,
  2.54,
  1.17,
  1.17,
  2.71,
  5.98,
  1.39,
  1.48,
  16.46,
  1.43,
  8.39,
  33.99,
  2.54,
  11.8,
  2.13,
  2.24,
  2.92,
  1.35,
  1.54,
  2.52]}`
</code>```

答:
df.nlargest is what you want.
First determine how many values correspond with 10% by running (df being your dataframe):

highest10p = 0.1*len(df)
```
<p>then you can select the 10 largest values in the <code>value</code> column by using</p>
<pre class="lang-py prettyprint-override"><code>df.nlargest(highest10p, 'value')
</code>```

So if you want the mean, you use .mean() function:

df.nlargest(highest10p, 'value').mean()
```

Body:
I have a dataframe that consist of the day column and a score column. So per day, there are many values. So I need to get the mean of the top 10% values per day. Simply means I need the output as a day column and mean of the top 10% values of that day.

this is a example dataset screenshot

`{'Date':
 [
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1),
  datetime.date(2021, 4, 1)],
 'value': [
  3.35,
  1.85,
  1.3,
  1.85,
  1.85,
  1.17,
  1.17,
  2.8,
  1.43,
  2.54,
  1.22,
  2.54,
  1.17,
  1.17,
  2.71,
  5.98,
  1.39,
  1.48,
  16.46,
  1.43,
  8.39,
  33.99,
  2.54,
  11.8,
  2.13,
  2.24,
  2.92,
  1.35,
  1.54,
  2.52]}`

Body:
df.nlargest is what you want.
First determine how many values correspond with 10% by running (df being your dataframe):

highest10p = 0.1*len(df)

then you can select the 10 largest values in the value column by using

df.nlargest(highest10p, 'value')

So if you want the mean, you use .mean() function:

df.nlargest(highest10p, 'value').mean()


问:
update pivot table in case of many to many relation laravel4
I have started working with Laravel4 recently. I am facing some problem while updating pivot table data, in case of many to many relation.

The situation is:
I have two table: Product, ProductType.
The relation between them is Many to many.
My Models are

```<code>class Product extends Eloquent {
    protected $table = 'products';
    protected $primaryKey = 'prd_id';

    public function tags() {
        return $this->belongsToMany('Tag', 'prd_tags', 'prta_prd_id', 'prta_tag_id');
    }
}

class Tag extends Eloquent {
    protected $table = 'tags';
    protected $primaryKey = 'tag_id';
        public function products()
    {
    return $this->belongsToMany('Product', 'prd_tags', 'prta_prd_id', 'prta_tag_id');
    }
}
</code>```

While inserting data to the pivot table prd_tags, I did:

```<code>$product->tags()->attach($tag->tagID);
</code>```

But now I want to update data in this pivot table, what is the best way to update data to the pivot table.
Let's say, I want to delete some tags and add new tags to a particular product.

答:
Since Laravel 6 you could also use newPivotQuery() if you would want to e.g. update() more than one pivot-model (database row) at the same time (using a Query\Builder::update() statement).

That would look something like this:

```<code>$someModel->someBelongsToManyRelation()
    ->wherePivotNotIn('some_column', [1, 2, 3])
    ->wherePivotNull('some_other_column')
    ->newPivotQuery()
    ->update(['some_other_column' => now()]);
</code>```

Or without the wherePivot methods:

```<code>$someModel->someBelongsToManyRelation()
    ->newPivotQuery()
    ->whereNotIn('some_column', [1, 2, 3])
    ->whereNull('some_other_column')
    ->update(['some_other_column' => now()]);
</code>```

Body:
I have started working with Laravel4 recently. I am facing some problem while updating pivot table data, in case of many to many relation.

The situation is:
I have two table: Product, ProductType.
The relation between them is Many to many.
My Models are

class Product extends Eloquent {
    protected $table = 'products';
    protected $primaryKey = 'prd_id';

    public function tags() {
        return $this->belongsToMany('Tag', 'prd_tags', 'prta_prd_id', 'prta_tag_id');
    }
}

class Tag extends Eloquent {
    protected $table = 'tags';
    protected $primaryKey = 'tag_id';
        public function products()
    {
    return $this->belongsToMany('Product', 'prd_tags', 'prta_prd_id', 'prta_tag_id');
    }
}

While inserting data to the pivot table prd_tags, I did:

$product->tags()->attach($tag->tagID);

But now I want to update data in this pivot table, what is the best way to update data to the pivot table.
Let's say, I want to delete some tags and add new tags to a particular product.

Body:
Since Laravel 6 you could also use newPivotQuery() if you would want to e.g. update() more than one pivot-model (database row) at the same time (using a Query\Builder::update() statement).

That would look something like this:

$someModel->someBelongsToManyRelation()
    ->wherePivotNotIn('some_column', [1, 2, 3])
    ->wherePivotNull('some_other_column')
    ->newPivotQuery()
    ->update(['some_other_column' => now()]);

Or without the wherePivot methods:

$someModel->someBelongsToManyRelation()
    ->newPivotQuery()
    ->whereNotIn('some_column', [1, 2, 3])
    ->whereNull('some_other_column')
    ->update(['some_other_column' => now()]);


问:
How to dynamically apply variables to the values of a dictionary using Python and/or RobotFramework
Say I have a list of dictionaries:

```<code>URL_LIST = [
    {'google': 'http://www.google.com/join'},
    {'yahoo':  'http://www.yahoo.com/{0}/join'},
    {'msn':    'http://www.msn.com/{0}/join'}
]
</code>```

Now, I want to pass this dictionary to a python function, along with two other variables, so that the two variables replaces the {0}s in the 'yahoo' and 'msn' variables:

```<code>def apply_arguments (url_list, yahoo_subpage, msn_subpage):
    #Do stuff
    return url_list
</code>```

So if the yahoo_suboage = 'aaa' and msn_subpage = 'bbb', I want the final result to be like this:

```<code>URL_LIST = [
    {'google': 'http://www.google.com/join'},
    {'yahoo':  'http://www.yahoo.com/aaa/join'},
    {'msn':    'http://www.msn.com/bbb/join'}
]
</code>```

I want to do it using either python or RobotFramework. Is that even possible?

答:
I think your URL_LIST is unnecessarily nested, so I use a list in this answer.

```<code>lst = [
    'http://www.google.com/join',
    'http://www.yahoo.com/{0}/join',
    'http://www.msn.com/{0}/join',
]

dct = {
    'yahoo': 'aaa',
    'msn': 'bbb',
}

def make_changes(lst, dct):

    for i, url in enumerate(lst):
        k = url.split('.')[1]

        try:
            lst[i] = url.replace('{0}', dct[k])
        except:
            pass

    return lst

print(make_changes(lst, dct))
</code>```

Output:

```<code>['http://www.google.com/join', 'http://www.yahoo.com/aaa/join', 'http://www.msn.com/bbb/join']
</code>```

Body:
Say I have a list of dictionaries:

URL_LIST = [
    {'google': 'http://www.google.com/join'},
    {'yahoo':  'http://www.yahoo.com/{0}/join'},
    {'msn':    'http://www.msn.com/{0}/join'}
]

Now, I want to pass this dictionary to a python function, along with two other variables, so that the two variables replaces the {0}s in the 'yahoo' and 'msn' variables:

def apply_arguments (url_list, yahoo_subpage, msn_subpage):
    #Do stuff
    return url_list

So if the yahoo_suboage = 'aaa' and msn_subpage = 'bbb', I want the final result to be like this:

URL_LIST = [
    {'google': 'http://www.google.com/join'},
    {'yahoo':  'http://www.yahoo.com/aaa/join'},
    {'msn':    'http://www.msn.com/bbb/join'}
]

I want to do it using either python or RobotFramework. Is that even possible?

Body:
I think your URL_LIST is unnecessarily nested, so I use a list in this answer.

lst = [
    'http://www.google.com/join',
    'http://www.yahoo.com/{0}/join',
    'http://www.msn.com/{0}/join',
]

dct = {
    'yahoo': 'aaa',
    'msn': 'bbb',
}

def make_changes(lst, dct):

    for i, url in enumerate(lst):
        k = url.split('.')[1]

        try:
            lst[i] = url.replace('{0}', dct[k])
        except:
            pass

    return lst

print(make_changes(lst, dct))

Output:

['http://www.google.com/join', 'http://www.yahoo.com/aaa/join', 'http://www.msn.com/bbb/join']


问:
Cron Expression confusion in the Spring Framework
My scheduler's application context defines this trgger:

```<code><bean id="myTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
   <property name="jobDetail" ref="myJob"/>
   <property name="cronExpression" value="0 0 ∗ ∗ ∗ ?"/>
</bean>
</code>```

Does it fire every day at 00:00? Or every hour?
I'd say the latter, but the documentation of this project says otherwise...
Can you help me out?
Are there different kind of expressions?

答:
Spring is using quartz for scheduling jobs so it is definitely every hour.
Please check:
http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/tutorial-lesson-06

ContentLicense: CC BY-SA 2.5

Body:
My scheduler's application context defines this trgger:

<bean id="myTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
   <property name="jobDetail" ref="myJob"/>
   <property name="cronExpression" value="0 0 ∗ ∗ ∗ ?"/>
</bean>

Does it fire every day at 00:00? Or every hour?
I'd say the latter, but the documentation of this project says otherwise...
Can you help me out?
Are there different kind of expressions?


问:
How can I get the text after one character in a String in Java
I have the next String:

```<code>com.microsoft.sqlserver.jdbc.SQLServerException: User not found
</code>```

I want to get the next String
starting from the previous:

```<code>User not found
</code>```

How can I get that using JDK 7?. The "com.microsoft.sqlserver.jdbc.SQLServerException:" its the same always

答:
```<code>String myString ="com.microsoft.sqlserver.jdbc.SQLServerException: User not found";

myString=myString.replace("com.microsoft.sqlserver.jdbc.SQLServerException:","");
</code>```

Body:
I have the next String:

com.microsoft.sqlserver.jdbc.SQLServerException: User not found

I want to get the next String
starting from the previous:

User not found

How can I get that using JDK 7?. The "com.microsoft.sqlserver.jdbc.SQLServerException:" its the same always


问:
making reference to file two by two in a bash command
I have this list of file that I have to analyse by pair (the a_1 with a_2, b_1 with b_2 and so on)

```<code>a_1.fq
a_2.fq
b_1.fq
b_2.fq
c_1.fq
...
</code>```

I want to set a for loop to make reference to these pairs of file in a command, bellow
this is just an example of what I want to do (with a false syntax) :

```<code>$ for File1 File2 in *1.fq *2.fq; do STAR --readFilein File1 File2 ; done
</code>```

Thank you a lot for your help

答:
Use a function to process pairs and iterate the glob expansion:

process_pair()
{
  while [ $# -gt 0 ]
  do
    f1=$1 # get 1st argument
    shift # shift to next argument
    f2=$1 # get 2nd argument
    shift # shift to next for the next round

    # Do stuffs with file1 and file2
    printf 'f1=%s\tf2=%s\n' "$f1" "$f2"
  done
}

# Submit pattern expansion as process_pair arguments
process_pair ./*_[12].fq
```

Body:
I have this list of file that I have to analyse by pair (the a_1 with a_2, b_1 with b_2 and so on)

a_1.fq
a_2.fq
b_1.fq
b_2.fq
c_1.fq
...

I want to set a for loop to make reference to these pairs of file in a command, bellow
this is just an example of what I want to do (with a false syntax) :

$ for File1 File2 in *1.fq *2.fq; do STAR --readFilein File1 File2 ; done

Thank you a lot for your help