问:
How to override class from package as a ObservableObject?
I want to have few classes in package and depending on implementation i wish to make it useful in fe. iPhone app. Is there anyway to something like override package class with ObservableObject?

Package

```<code>class Team{
var name = ""
}
</code>```

App

```<code>override Team: ObservableObject // or sth like that

@EnvironmentObject team1: Team
</code>```

答:
You can wrap your package class(es) into one new class, that publishes all of them for the UI:</p>
```<code>class Team {
    var name: String = "Test"

}

class PublishedPackages: ObservableObject {
    @Published var team = Team()
    // ... other package classes
}

struct ContentView: View {

    @StateObject var publishedPackages = PublishedPackages()

    var body: some View {
        VStack {
            Text(publishedPackages.team.name)
                .padding()

            Button("change") {
                publishedPackages.objectWillChange.send()
                publishedPackages.team.name = "other Name"
            }
        }
    }
}
</code>```

Body:
I want to have few classes in package and depending on implementation i wish to make it useful in fe. iPhone app. Is there anyway to something like override package class with ObservableObject?

Package

class Team{
var name = ""
}

App

override Team: ObservableObject // or sth like that

@EnvironmentObject team1: Team

Body:
You can wrap your package class(es) into one new class, that publishes all of them for the UI:

class Team {
    var name: String = "Test"

}

class PublishedPackages: ObservableObject {
    @Published var team = Team()
    // ... other package classes
}

struct ContentView: View {

    @StateObject var publishedPackages = PublishedPackages()

    var body: some View {
        VStack {
            Text(publishedPackages.team.name)
                .padding()

            Button("change") {
                publishedPackages.objectWillChange.send()
                publishedPackages.team.name = "other Name"
            }
        }
    }
}


来源: stackexchange

问:
How do I notice that a file executed from AWS StepFunctions has stopped?
SendCommand is executed in AWS StepFunctions.

I am executing a file in EC2 from SendCommand.

If the file stops in the middle, I want StepFunctions to exit with Fail Status.

How can I achieve this?

答: You have to use Callback with the Task Token. Your application on ec2 has to "know" when it succeeds or fails, and send SendTaskSuccess or SendTaskFailure to Step Functions.

ContentLicense: CC BY-SA 4.0


问:
how to merge two arrays of objects in javascript?
here is a sample example where there are two arrays and we have a merge() to which we pass the arrays. the merge() should return the merged array such that it should merge the objects which have same name.</p>
```<code>let arr1 = [
  {
    name: "Person1",
    age: 20
  },
  {
    name: "Person2",
    age: 30
  }
]

let arr2 = [
  {
    name: "Person1",
    email: "person1@mail.com"
  },
  {
    name: "Person3",
    age: 25
  }
]

arr3 = merge(arr1, arr2)

output :
arr3 should be :
[
 {
    name: "Person1",
    age: 20,
    email: "person1@mail.com"
  },
   {
    name: "Person2",
    age: 30
  },
   {
    name: "Person3",
    age: 25
  }
]
</code>```

答:
You could take an object as hash table for keeping track of merged objects with same name and return only the values from the hash table.

const
    merge = (...arrays) => {
        const merged = {};

        arrays.forEach(data =>
            data.forEach(o => Object.assign(merged[o.name] ??= {}, o))
        );

        return Object.values(merged);
    },
    array1 = [{ name: "Person1", age: 20 }, { name: "Person2", age: 30 }],
    array2 = [{name: "Person1", email: "person1@mail.com" }, { name: "Person3", age: 25 }],
    result = merge(array1, array2);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
here is a sample example where there are two arrays and we have a merge() to which we pass the arrays. the merge() should return the merged array such that it should merge the objects which have same name.

let arr1 = [
  {
    name: "Person1",
    age: 20
  },
  {
    name: "Person2",
    age: 30
  }
]

let arr2 = [
  {
    name: "Person1",
    email: "person1@mail.com"
  },
  {
    name: "Person3",
    age: 25
  }
]

arr3 = merge(arr1, arr2)

output :
arr3 should be :
[
 {
    name: "Person1",
    age: 20,
    email: "person1@mail.com"
  },
   {
    name: "Person2",
    age: 30
  },
   {
    name: "Person3",
    age: 25
  }
]

Body:
You could take an object as hash table for keeping track of merged objects with same name and return only the values from the hash table.

const
    merge = (...arrays) => {
        const merged = {};

        arrays.forEach(data =>
            data.forEach(o => Object.assign(merged[o.name] ??= {}, o))
        );

        return Object.values(merged);
    },
    array1 = [{ name: "Person1", age: 20 }, { name: "Person2", age: 30 }],
    array2 = [{name: "Person1", email: "person1@mail.com" }, { name: "Person3", age: 25 }],
    result = merge(array1, array2);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Is there a way to enumerate interfaces using NI Daqmx
I have a C++ application interfacing with a NI DAQ card, however the name of the device is hard coded and if changed in the NI Max app it would stop working, so is there a way to enumerate connected devices to know the name of the cards that are connected ?</p>

答:
List of all devices can be retrieved with DAQmxGetSysDevNames(). The names are separated by commas.

Once you have the list of all names, you can use the product type to find the correct device.

```<code>const std::string expectedProductType = "1234";
constexpr size_t bufferSize = 1000;
char buffer[bufferSize] = {};
if (!DAQmxFailed(DAQmxGetSysDevNames(buffer, bufferSize))) {
    std::string allNames(buffer);
    std::vector<std::string> names;
    boost::split(names, allNames, boost::is_any_of(","));
    for (auto name : names) {
        char buffer2[bufferSize] = {};
        if (!DAQmxFailed(DAQmxGetDevProductType(name.c_str(), buffer2, bufferSize))) {
            if (expectedProductType == std::string(buffer2)) {
                // match found
            }
        }
    }
}
</code>```

Body:
List of all devices can be retrieved with DAQmxGetSysDevNames(). The names are separated by commas.

Once you have the list of all names, you can use the product type to find the correct device.

const std::string expectedProductType = "1234";
constexpr size_t bufferSize = 1000;
char buffer[bufferSize] = {};
if (!DAQmxFailed(DAQmxGetSysDevNames(buffer, bufferSize))) {
    std::string allNames(buffer);
    std::vector<std::string> names;
    boost::split(names, allNames, boost::is_any_of(","));
    for (auto name : names) {
        char buffer2[bufferSize] = {};
        if (!DAQmxFailed(DAQmxGetDevProductType(name.c_str(), buffer2, bufferSize))) {
            if (expectedProductType == std::string(buffer2)) {
                // match found
            }
        }
    }
}


问:
Android and authenticated HttpPut with JSON body
How do you do write an HttpPut request with authentication on Android?

(I'm trying to work around using HttpURLConnection, which seems to serious have bugs (at least in Android 2.2) but GET works fine. I'd like to send a JSON representation of an array, and I have correct credentials already set using PasswordAuthentication.)

答:
First you need to have an authentication token. And then just add this line.</p>

```<code>httpGet.setHeader("Authorization", "Bearer " + yourToken);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
First you need to have an authentication token. And then just add this line.

httpGet.setHeader("Authorization", "Bearer " + yourToken);


问:
How to impose order on fixtures in pytest?
I am trying to use pytest-dependency to make fixtures happen in order, regardless of how they are named, and regardless of the order in which they appear in a test's argument list.

The reason I need this, is to create fixtures that require initializations, that depend on other fixtures that require initializations, and they must happen in order. I have quite a few of these, and I don't want to rely on naming or on order in the argument list.

I also don't want to use pytest_sessionstart, because it can't take fixture inputs, which causes very unclean code.

The trivial example in the doc shows how to create programmed dependencies for tests:

```<code>import pytest

@pytest.mark.dependency()
@pytest.mark.xfail(reason="deliberate fail")
def test_a():
    assert False

@pytest.mark.dependency()
def test_b():
    pass

@pytest.mark.dependency(depends=["test_a"])
def test_c():
    pass

@pytest.mark.dependency(depends=["test_b"])
def test_d():
    pass

@pytest.mark.dependency(depends=["test_b", "test_c"])
def test_e():
    pass
</code>```

This works with output:

```<code>============================= test session starts =============================
collecting ... collected 5 items

test_sanity.py::test_z XFAIL (deliberate fail)                           [ 20%]
@pytest.mark.dependency()
    @pytest.mark.xfail(reason="deliberate fail")
    def test_z():
>       assert False
E       assert False

test_sanity.py:6: AssertionError

test_sanity.py::test_x PASSED                                            [ 40%]
test_sanity.py::test_c SKIPPED (test_c depends on test_z)                [ 60%]
Skipped: test_c depends on test_z

test_sanity.py::test_d PASSED                                            [ 80%]
test_sanity.py::test_w SKIPPED (test_w depends on test_c)                [100%]
Skipped: test_w depends on test_c

=================== 2 passed, 2 skipped, 1 xfailed in 0.05s ===================
</code>```

Now I want to do the same for fixtures.

My attempt:

conftest.py:

```<code>import pytest

pytest_plugins = ["dependency"]

@pytest.mark.dependency()
@pytest.fixture(autouse=True)
def zzzshould_happen_first():
    assert False

@pytest.mark.dependency(depends=["zzzshould_happen_first"])
@pytest.fixture(autouse=True)
def should_happen_last():
    assert False
</code>```

and test_sanity.py:

```<code>def test_nothing():
    assert True
</code>```

Outputs

```<code>test_sanity.py::test_nothing ERROR                                       [100%]
test setup failed
@pytest.mark.dependency(depends=["zzzshould_happen_first"])
    @pytest.fixture(autouse=True)
    def should_happen_last():
>       assert False
E       assert False

conftest.py:15: AssertionError
</code>```

I expected the error on zzzshould_happen_first.

Is there a way to impose ordering on fixtures, such that

Their name is ignored

Their order in the argument list is ignored

Other pytest features such as autouse can still be applied

答:
You can give a fixture as a dependency directly with pytest. Something like this:

import pytest

@pytest.fixture(autouse=True)
def zzzshould_happen_first():
    assert False

@pytest.fixture(autouse=True)
def should_happen_last(zzzshould_happen_first):
    assert False

def test_nothing():
    assert True
```
<p>It gives what you want:</p>
```test setup failed
@pytest.fixture(autouse=True)
    def zzzshould_happen_first():
>       assert False
E       assert False

answer.py:7: AssertionError
```

Body:
I am trying to use pytest-dependency to make fixtures happen in order, regardless of how they are named, and regardless of the order in which they appear in a test's argument list.

The reason I need this, is to create fixtures that require initializations, that depend on other fixtures that require initializations, and they must happen in order. I have quite a few of these, and I don't want to rely on naming or on order in the argument list.

I also don't want to use pytest_sessionstart, because it can't take fixture inputs, which causes very unclean code.

The trivial example in the doc shows how to create programmed dependencies for tests:

import pytest

@pytest.mark.dependency()
@pytest.mark.xfail(reason="deliberate fail")
def test_a():
    assert False

@pytest.mark.dependency()
def test_b():
    pass

@pytest.mark.dependency(depends=["test_a"])
def test_c():
    pass

@pytest.mark.dependency(depends=["test_b"])
def test_d():
    pass

@pytest.mark.dependency(depends=["test_b", "test_c"])
def test_e():
    pass

This works with output:

============================= test session starts =============================
collecting ... collected 5 items

test_sanity.py::test_z XFAIL (deliberate fail)                           [ 20%]
@pytest.mark.dependency()
    @pytest.mark.xfail(reason="deliberate fail")
    def test_z():
>       assert False
E       assert False

test_sanity.py:6: AssertionError

test_sanity.py::test_x PASSED                                            [ 40%]
test_sanity.py::test_c SKIPPED (test_c depends on test_z)                [ 60%]
Skipped: test_c depends on test_z

test_sanity.py::test_d PASSED                                            [ 80%]
test_sanity.py::test_w SKIPPED (test_w depends on test_c)                [100%]
Skipped: test_w depends on test_c

=================== 2 passed, 2 skipped, 1 xfailed in 0.05s ===================

Now I want to do the same for fixtures.

My attempt:

conftest.py:

import pytest

pytest_plugins = ["dependency"]

@pytest.mark.dependency()
@pytest.fixture(autouse=True)
def zzzshould_happen_first():
    assert False

@pytest.mark.dependency(depends=["zzzshould_happen_first"])
@pytest.fixture(autouse=True)
def should_happen_last():
    assert False

and test_sanity.py:

def test_nothing():
    assert True

Outputs

test_sanity.py::test_nothing ERROR                                       [100%]
test setup failed
@pytest.mark.dependency(depends=["zzzshould_happen_first"])
    @pytest.fixture(autouse=True)
    def should_happen_last():
>       assert False
E       assert False

conftest.py:15: AssertionError

I expected the error on zzzshould_happen_first.

Is there a way to impose ordering on fixtures, such that

Their name is ignored

Their order in the argument list is ignored

Other pytest features such as autouse can still be applied

Body:
You can give a fixture as a dependency directly with pytest. Something like this:

import pytest

@pytest.fixture(autouse=True)
def zzzshould_happen_first():
    assert False

@pytest.fixture(autouse=True)
def should_happen_last(zzzshould_happen_first):
    assert False

def test_nothing():
    assert True

It gives what you want:

test setup failed
@pytest.fixture(autouse=True)
    def zzzshould_happen_first():
>       assert False
E       assert False

answer.py:7: AssertionError


问:
How to assign or return generic T that is constrained by union?
In other words, how do I implement type-specific solutions for different types in a union type set?

Given the following code...

type FieldType interface {
    string | int
}

type Field[T FieldType] struct {
    name         string
    defaultValue T
}

func NewField[T FieldType](name string, defaultValue T) *Field[T] {
    return &Field[T]{
        name:         name,
        defaultValue: defaultValue,
    }
}

func (f *Field[T]) Name() string {
    return f.name
}

func (f *Field[T]) Get() (T, error) {
    value, ok := os.LookupEnv(f.name)
    if !ok {
        return f.defaultValue, nil
    }
    return value, nil
}
```
<p>the compiler shows the error:</p>
```field.go:37:9: cannot use value (variable of type string) as type T in return statement
```
<p>Is there a way to provide implementations for all possible <code>FieldType</code>s?</p>
<p>Like...</p>
<pre class="lang-golang prettyprint-override"><code>func (f *Field[string]) Get() (string, error) {
    value, ok := os.LookupEnv(f.name)
    if !ok {
        return f.defaultValue, nil
    }
    return value, nil
}

func (f *Field[int]) Get() (int, error) {
    raw, ok := os.LookupEnv(f.name)
    if !ok {
        return f.defaultValue, nil
    }
    value, err := strconv.ParseInt(raw, 10, 64)
    if err != nil {
        return *new(T), err
    }
    return int(value), nil
}
</code>```

Any hint would be welcome.

答:
The error occurs because operations that involve a type parameter (including assignments and returns) must be valid for all types in its type set.
In case of string | int, there isn't a common operation to initialize their value from a string.

However you still have a couple options:

Type-switch on T

You use the field with the generic type T in a type-switch, and temporarily set the values with concrete types into an interface{}/any. Then type-assert the interface back to T in order to return it. Beware that this assertion is unchecked, so it may panic if for some reason ret holds something that isn't in the type set of T. Of course you can check it with comma-ok but it's still a run-time assertion:

```<code>func (f *Field[T]) Get() (T, error) {
    value, ok := os.LookupEnv(f.name)
    if !ok {
        return f.defaultValue, nil
    }
    var ret any
    switch any(f.defaultValue).(type) {
    case string:
        ret = value

    case int:
        // don't actually ignore errors
        i, _ := strconv.ParseInt(value, 10, 64)
        ret = int(i)
    }
    return ret.(T), nil
}
</code>```

Type-switch on *T

You can further simplify the code above and get rid of the empty interface. In this case you take the address of the T-type variable and switch on the pointer types. This is fully type-checked at compile time:

```<code>func (f *Field[T]) Get() (T, error) {
    value, ok := env[f.name]
    if !ok {
        return f.defaultValue, nil
    }

    var ret T
    switch p := any(&ret).(type) {
    case *string:
        *p = value

    case *int:
        i, _ := strconv.ParseInt(value, 10, 64)
        *p = int(i)
    }
    // ret has the zero value if no case matches
    return ret, nil
}
</code>```

Note that in both cases you must convert the T value to an interface{}/any in order to use it in a type switch. You can't type-switch directly on T.

Playground with map to simulate os.LookupEnv: https://go.dev/play/p/JVBEZwCXRMW

Body:
In other words, how do I implement type-specific solutions for different types in a union type set?

Given the following code...

type FieldType interface {
    string | int
}

type Field[T FieldType] struct {
    name         string
    defaultValue T
}

func NewField[T FieldType](name string, defaultValue T) *Field[T] {
    return &Field[T]{
        name:         name,
        defaultValue: defaultValue,
    }
}

func (f *Field[T]) Name() string {
    return f.name
}

func (f *Field[T]) Get() (T, error) {
    value, ok := os.LookupEnv(f.name)
    if !ok {
        return f.defaultValue, nil
    }
    return value, nil
}

the compiler shows the error:

field.go:37:9: cannot use value (variable of type string) as type T in return statement

Is there a way to provide implementations for all possible FieldTypes?

Like...

func (f *Field[string]) Get() (string, error) {
    value, ok := os.LookupEnv(f.name)
    if !ok {
        return f.defaultValue, nil
    }
    return value, nil
}

func (f *Field[int]) Get() (int, error) {
    raw, ok := os.LookupEnv(f.name)
    if !ok {
        return f.defaultValue, nil
    }
    value, err := strconv.ParseInt(raw, 10, 64)
    if err != nil {
        return *new(T), err
    }
    return int(value), nil
}

Any hint would be welcome.

Body:
The error occurs because operations that involve a type parameter (including assignments and returns) must be valid for all types in its type set.
In case of string | int, there isn't a common operation to initialize their value from a string.

However you still have a couple options:

Type-switch on T

You use the field with the generic type T in a type-switch, and temporarily set the values with concrete types into an interface{}/any. Then type-assert the interface back to T in order to return it. Beware that this assertion is unchecked, so it may panic if for some reason ret holds something that isn't in the type set of T. Of course you can check it with comma-ok but it's still a run-time assertion:

func (f *Field[T]) Get() (T, error) {
    value, ok := os.LookupEnv(f.name)
    if !ok {
        return f.defaultValue, nil
    }
    var ret any
    switch any(f.defaultValue).(type) {
    case string:
        ret = value

    case int:
        // don't actually ignore errors
        i, _ := strconv.ParseInt(value, 10, 64)
        ret = int(i)
    }
    return ret.(T), nil
}

Type-switch on *T

You can further simplify the code above and get rid of the empty interface. In this case you take the address of the T-type variable and switch on the pointer types. This is fully type-checked at compile time:

func (f *Field[T]) Get() (T, error) {
    value, ok := env[f.name]
    if !ok {
        return f.defaultValue, nil
    }

    var ret T
    switch p := any(&ret).(type) {
    case *string:
        *p = value

    case *int:
        i, _ := strconv.ParseInt(value, 10, 64)
        *p = int(i)
    }
    // ret has the zero value if no case matches
    return ret, nil
}

Note that in both cases you must convert the T value to an interface{}/any in order to use it in a type switch. You can't type-switch directly on T.

Playground with map to simulate os.LookupEnv: https://go.dev/play/p/JVBEZwCXRMW


问:
Sending messages in the on_ready? Python discord bot
I want my bot to send a message when going online in the on_ready event. The line work in (on_message) but I haven't been able to make it send something in the (on_ready) </p>

```<code>@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))
    await message.channel.send('The bot is online ')
</code>```

答:
copy your user_id and paste without quotes</p>
```<code>    @client.event
    async def on_ready():
        print("The bot is ready")
        print("------------------------")
        user = await client.fetch_user("User id")
        await user.send("hello")

</code>```

Body:
I want my bot to send a message when going online in the on_ready event. The line work in (on_message) but I haven't been able to make it send something in the (on_ready)

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))
    await message.channel.send('The bot is online ')

Body:
copy your user_id and paste without quotes

    @client.event
    async def on_ready():
        print("The bot is ready")
        print("------------------------")
        user = await client.fetch_user("User id")
        await user.send("hello")


问:
Selenium test in Internet Explorer always times out?
I'm trying to run a basic test in Internet Explorer via Selenium-RC/PHPUnit, and it always returns with

```<code># phpunit c:\googletest.php
PHPUnit 3.4.15 by Sebastian Bergmann.

E

Time: 35 seconds, Memory: 4.75Mb

There was 1 error:

1) Example::testMyTestCase
PHPUnit_Framework_Exception: Response from Selenium RC server for testComplete()
.
Timed out after 30000ms.

C:\googletest.php:17

FAILURES!
Tests: 1, Assertions: 0, Errors: 1.

Paul@PAUL-TS-LAPTOP C:\xampp
#
</code>```

The last command in command history is waitForPageToLoad(30000).  The same test runs fine and completes in firefox.  How can I get this test to run and complete in internet explorer?

Thanks

答:
There's an open bug in selenium that causes waitForPageToLoad to sometimes timeout on IE.

http://jira.openqa.org/browse/SRC-552

It's marked as occurring on IE6, but I'm experiencing the same error in at least IE9.

A workaround is to wait for e.g. a specific DOM-element on the page that is loading instead of using waitForPageToLoad. For example: waitForVisible('css=#header')

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to run a basic test in Internet Explorer via Selenium-RC/PHPUnit, and it always returns with

# phpunit c:\googletest.php
PHPUnit 3.4.15 by Sebastian Bergmann.

E

Time: 35 seconds, Memory: 4.75Mb

There was 1 error:

1) Example::testMyTestCase
PHPUnit_Framework_Exception: Response from Selenium RC server for testComplete()
.
Timed out after 30000ms.

C:\googletest.php:17

FAILURES!
Tests: 1, Assertions: 0, Errors: 1.

Paul@PAUL-TS-LAPTOP C:\xampp
#

The last command in command history is waitForPageToLoad(30000).  The same test runs fine and completes in firefox.  How can I get this test to run and complete in internet explorer?

Thanks


问:
How to wirte a part of <fo:table> in a function
I have to create many <fo:table-row> in a  <fo:table-body>. I think it's not nice if I write almost 5 lines of code several times (Maybe 50 times) to create the rows.

Like this:

```<code><fo:table-body>
<fo:table-row>
   <fo:table-cell padding-bottom="6pt">
       <fo:value-of select="row1"/>
   </fo:table-cell>
</fo:table-row>
<fo:table-row>
   <fo:table-cell padding-bottom="6pt">
       <fo:value-of select="row2"/>
   </fo:table-cell>
</fo:table-row>
<fo:table-row>
   <fo:table-cell padding-bottom="6pt">
       <fo:value-of select="row3"/>
   </fo:table-cell>
</fo:table-row>
....
</fo:table-body>
</code>```

I tried to write a function that writes the <fo:table-row> for me. And I have to call the function every time and pass a parameter.

```<code><xsl:function name="fn:createRow">
    <xsl:param name="string1"/>

    <fo:table-row>
       <fo:table-cell padding-bottom="6pt">
           <fo:value-of select="$string1"/>
       </fo:table-cell>
    </fo:table-row>

  </xsl:function>
</code>```

And now my XSLT look like this.

```<code><fo:table-body>
    <fo:block>
           <fo:value-of select="fn:createRow('row1')"/>
           <fo:value-of select="fn:createRow('row2')"/>
   </fo:block>
</fo:table-body>
</code>```

But I get the error:

"fo:block" is not a valid child of "fo:table-body"!

But when I work without <fo:block> I get nothing in the PDF:

```<code><fo:table-body>
       <fo:value-of select="fn:createRow('row1')"/>
       <fo:value-of select="fn:createRow('row2')"/>
</fo:table-body>
</code>```

Is there any opportunity to do it?

Thanks!

答:
fo:table-cell can contain one or more block-level FOs, including fo:block. (See https://www.w3.org/TR/xsl11/#fo_table-cell)

You don't show your XML, but if all of the row* elements are contained by one element, then in the template for that element, you could do something like:

```<code><fo:table>
  <fo:table-body>
    <xsl:for-each select="*">
      <fo:table-row>
        <fo:table-cell padding-bottom="6pt">
          <fo:block>
            <!-- The row* element is the current element here. -->
            <xsl:apply-templates />
          </fo:block>
        </fo:table-cell>
      </fo:table-row>
    </fo:for-each>
  </fo:table-body>
</fo:table>
</code>```

Alternatively, you could make a template for all of the row* elements:

```<code><xsl:template match="*[starts-with(local-name(), 'row')]">
  <fo:table-row>
  ...
</code>```

(From this distance, it's not clear why the row elements need separate element names.)

When you know the names of the elements that you want to format, you can do:

```<code><xsl:apply-templates select="row1, row2, row3" />
</code>```

and:

```<code><xsl:template match="row1 | row2 | row3">
  <fo:table-row>
  ...
</code>```

Body:
I have to create many <fo:table-row> in a  <fo:table-body>. I think it's not nice if I write almost 5 lines of code several times (Maybe 50 times) to create the rows.

Like this:

<fo:table-body>
<fo:table-row>
   <fo:table-cell padding-bottom="6pt">
       <fo:value-of select="row1"/>
   </fo:table-cell>
</fo:table-row>
<fo:table-row>
   <fo:table-cell padding-bottom="6pt">
       <fo:value-of select="row2"/>
   </fo:table-cell>
</fo:table-row>
<fo:table-row>
   <fo:table-cell padding-bottom="6pt">
       <fo:value-of select="row3"/>
   </fo:table-cell>
</fo:table-row>
....
</fo:table-body>

I tried to write a function that writes the <fo:table-row> for me. And I have to call the function every time and pass a parameter.

<xsl:function name="fn:createRow">
    <xsl:param name="string1"/>

    <fo:table-row>
       <fo:table-cell padding-bottom="6pt">
           <fo:value-of select="$string1"/>
       </fo:table-cell>
    </fo:table-row>

  </xsl:function>

And now my XSLT look like this.

<fo:table-body>
    <fo:block>
           <fo:value-of select="fn:createRow('row1')"/>
           <fo:value-of select="fn:createRow('row2')"/>
   </fo:block>
</fo:table-body>

But I get the error:

"fo:block" is not a valid child of "fo:table-body"!

But when I work without <fo:block> I get nothing in the PDF:

<fo:table-body>
       <fo:value-of select="fn:createRow('row1')"/>
       <fo:value-of select="fn:createRow('row2')"/>
</fo:table-body>

Is there any opportunity to do it?

Thanks!

Body:
fo:table-cell can contain one or more block-level FOs, including fo:block. (See https://www.w3.org/TR/xsl11/#fo_table-cell)

You don't show your XML, but if all of the row* elements are contained by one element, then in the template for that element, you could do something like:

<fo:table>
  <fo:table-body>
    <xsl:for-each select="*">
      <fo:table-row>
        <fo:table-cell padding-bottom="6pt">
          <fo:block>
            <!-- The row* element is the current element here. -->
            <xsl:apply-templates />
          </fo:block>
        </fo:table-cell>
      </fo:table-row>
    </fo:for-each>
  </fo:table-body>
</fo:table>

Alternatively, you could make a template for all of the row* elements:

<xsl:template match="*[starts-with(local-name(), 'row')]">
  <fo:table-row>
  ...

(From this distance, it's not clear why the row elements need separate element names.)

When you know the names of the elements that you want to format, you can do:

<xsl:apply-templates select="row1, row2, row3" />

and:

<xsl:template match="row1 | row2 | row3">
  <fo:table-row>
  ...


问:
How to make this shape with border radius?
I have trouble reproducing this shape using the border-radius:

Right now I obtain this:

Here is my css code (it's inside a grid):

```<code> .container-11-1 {
    grid-column: 1;
    grid-row: 1 / 3;
    background: #e4cab6;
    border-bottom-left-radius: 50%;
    border-bottom-right-radius: 50%;
    margin-bottom: 30px; //otherwise the bottom stick to the section below and it's even worse
}
</code>```

答:
You could just change the percent to pixels or rem or other units.
See if this fits your requirement - https://codepen.io/alstonchan/pen/eYevKZq.</p>
```<code>border-bottom-left-radius: 10rem;
border-bottom-right-radius: 10rem;
/*or*/
border-bottom-left-radius: 160px;
border-bottom-right-radius: 160px;
</code>```

Body:
I have trouble reproducing this shape using the border-radius:

Right now I obtain this:

Here is my css code (it's inside a grid):

 .container-11-1 {
    grid-column: 1;
    grid-row: 1 / 3;
    background: #e4cab6;
    border-bottom-left-radius: 50%;
    border-bottom-right-radius: 50%;
    margin-bottom: 30px; //otherwise the bottom stick to the section below and it's even worse
}

Body:
You could just change the percent to pixels or rem or other units.
See if this fits your requirement - https://codepen.io/alstonchan/pen/eYevKZq.

border-bottom-left-radius: 10rem;
border-bottom-right-radius: 10rem;
/*or*/
border-bottom-left-radius: 160px;
border-bottom-right-radius: 160px;


问:
How to center scrollable content with header?
I'm trying to center some content. The content is larger than the parent and therefore requires scrolling. There is also a header at top. For some reason, the scroll height clips the scrollable content. Thoughts on how I should fix the issue?

Here's the fiddle: https://jsfiddle.net/xgsqyu45/

.app {
  height: 400px;
}

.header {
  width: 100%;
  height: 44px;
  background-color: grey;
  border: 2px solid;
}

.container {
  border: 1px solid red;
  height: 100%;
}

.scroll {
  overflow: scroll;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.content {
  height: 600px;
  width: 300px;
  margin: 12px;
  border: 2px solid blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="app">
  <div class="header">
  </div>
  <div class="container">
    <div class="scroll">
      <div class="content">
      </div>
    </div>
  </div>
</div></code>```

答:
Just use display:grid instead of display:flex in .scroll class:

.app {
  height: 400px;
}

.header {
  width: 100%;
  height: 44px;
  background-color: grey;
  border: 2px solid;
}

.container {
  marign-top: 60px;
  border: 1px solid red;
  height: 100%;
}

.scroll {
  overflow: scroll;
  height: 100%;
  display: grid;
  justify-content: center;
  align-items: center;
}

.content {
  height: 600px;
  width: 300px;
  margin: 12px;
  border: 2px solid blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="app">
  <div class="header">
  </div>
  <div class="container">
    <div class="scroll">
      <div class="content">
      </div>
    </div>
  </div>
</div></code>```

Body:
Just use display:grid instead of display:flex in .scroll class:

.app {
  height: 400px;
}

.header {
  width: 100%;
  height: 44px;
  background-color: grey;
  border: 2px solid;
}

.container {
  marign-top: 60px;
  border: 1px solid red;
  height: 100%;
}

.scroll {
  overflow: scroll;
  height: 100%;
  display: grid;
  justify-content: center;
  align-items: center;
}

.content {
  height: 600px;
  width: 300px;
  margin: 12px;
  border: 2px solid blue;
}

<div class="app">
  <div class="header">
  </div>
  <div class="container">
    <div class="scroll">
      <div class="content">
      </div>
    </div>
  </div>
</div>


问:
how to do right click and after that select copy option from the right click menu using down arrow keys in selenium python
as the subject says, i want to open web page, double click on word, after that once the word is selected to do mouse right click and select copy from the menu. till now i have the following code which do everything, open google, click on word, invoke the mouse right click but i have no idea how to do/use down arrow key to select copy. here is the code:

```<code>import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Firefox()

driver.get("https://www.google.com/?hl=en")

codeID = driver.find_element(By.XPATH, '//*[@id="SIvCob"]')

ActionChains = ActionChains(driver)
ActionChains.double_click(codeID).perform()

ActionChains.context_click(codeID).perform();
</code>```

i found some solutions in java and tried to implement those in python, but non of those worked, for example as this one (which I tried to use as a replacement for the last line of my code):

```<code>from selenium.webdriver.common.keys import Keys
ActionChains.context_click(codeID).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN).perform();
</code>```

please if someone can help me how to do this. thanks!

答:
so in case anyone have the problem, this worked for me

```<code>codeID = driver.find_element(By.XPATH, '//*[@id="message-htmlpart1"]/div/table/tbody/tr/td[2]/div/table/tbody/tr/td/table/tbody/tr/td/h2').text
pyperclip.copy(codeID)
</code>```

and the code was copied in the clipboard.

Body:
as the subject says, i want to open web page, double click on word, after that once the word is selected to do mouse right click and select copy from the menu. till now i have the following code which do everything, open google, click on word, invoke the mouse right click but i have no idea how to do/use down arrow key to select copy. here is the code:

import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Firefox()

driver.get("https://www.google.com/?hl=en")

codeID = driver.find_element(By.XPATH, '//*[@id="SIvCob"]')

ActionChains = ActionChains(driver)
ActionChains.double_click(codeID).perform()

ActionChains.context_click(codeID).perform();

i found some solutions in java and tried to implement those in python, but non of those worked, for example as this one (which I tried to use as a replacement for the last line of my code):

from selenium.webdriver.common.keys import Keys
ActionChains.context_click(codeID).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN).perform();

please if someone can help me how to do this. thanks!

Body:
so in case anyone have the problem, this worked for me

codeID = driver.find_element(By.XPATH, '//*[@id="message-htmlpart1"]/div/table/tbody/tr/td[2]/div/table/tbody/tr/td/table/tbody/tr/td/h2').text
pyperclip.copy(codeID)

and the code was copied in the clipboard.


问:
Android Ad failed to load 3
I am using Rewarded Ads with test ids, however still I am getting error 3.
This looks strange.
Below is the code:

```<code>implementation "com.google.android.gms:play-services-ads:20.5.0"

<string name="google_admob_id">ca-app-pub-3940256099942544~3347511713</string>

val rewardedCallback = object:RewardedAdLoadCallback(){

}
MobileAds.initialize(this){
   // test id
   RewardedAd.load(this, "ca-app-pub-3940256099942544/5224354917",    AdRequest.Builder().build(), rewardedCallback)
}
</code>```

This is the error I received when Ads are initialized, no matter what version I use:

```<code>2022-02-03 00:45:12.766 2778-2778/com.doppelmate.development I/zygote:     at void com.google.android.gms.internal.ads.zzcne.<init>(com.google.android.gms.internal.ads.zzcoa, com.google.android.gms.internal.ads.zzcob, java.lang.String, boolean, boolean, com.google.android.gms.internal.ads.zzaas, com.google.android.gms.internal.ads.zzbkk, com.google.android.gms.internal.ads.zzcgz, com.google.android.gms.internal.ads.zzbka, com.google.android.gms.ads.internal.zzl, com.google.android.gms.ads.internal.zza, com.google.android.gms.internal.ads.zzazb, com.google.android.gms.internal.ads.zzezz, com.google.android.gms.internal.ads.zzfac) (com.google.android.gms:play-services-ads@@20.5.0:1)
2022-02-03 00:45:12.766 2778-2778/com.doppelmate.development I/zygote:     at java.lang.Object com.google.android.gms.internal.ads.zzcmu.zza() (com.google.android.gms:play-services-ads@@20.5.0:4)
2022-02-03 00:45:12.766 2778-2778/com.doppelmate.development I/zygote:     at com.google.android.gms.internal.ads.zzcml com.google.android.gms.internal.ads.zzcmx.zza(android.content.Context, com.google.android.gms.internal.ads.zzcob, java.lang.String, boolean, boolean, com.google.android.gms.internal.ads.zzaas, com.google.android.gms.internal.ads.zzbkk, com.google.android.gms.internal.ads.zzcgz, com.google.android.gms.internal.ads.zzbka, com.google.android.gms.ads.internal.zzl, com.google.android.gms.ads.internal.zza, com.google.android.gms.internal.ads.zzazb, com.google.android.gms.internal.ads.zzezz, com.google.android.gms.internal.ads.zzfac) (com.google.android.gms:play-services-ads@@20.5.0:9)
2022-02-03 00:45:12.766 2778-2778/com.doppelmate.development I/zygote:     at void com.google.android.gms.internal.ads.zzbsv.<init>(android.content.Context, com.google.android.gms.internal.ads.zzcgz, com.google.android.gms.internal.ads.zzaas, com.google.android.gms.ads.internal.zza) (com.google.android.gms:play-services-ads@@20.5.0:3)
2022-02-03 00:45:12.766 2778-2778/com.doppelmate.development I/zygote:     at void com.google.android.gms.internal.ads.zzbts.zzi(com.google.android.gms.internal.ads.zzaas, com.google.android.gms.internal.ads.zzbtr) (com.google.android.gms:play-services-ads@@20.5.0:1)
2022-02-03 00:45:12.766 2778-2778/com.doppelmate.development I/zygote:     at void com.google.android.gms.internal.ads.zzbsx.run() (com.google.android.gms:play-services-ads@@20.5.0:1)
2022-02-03 00:45:12.766 2778-2778/com.doppelmate.development I/zygote:     at void com.google.android.gms.internal.ads.zzchd.execute(java.lang.Runnable) (com.google.android.gms:play-services-ads@@20.5.0:2)
2022-02-03 00:45:12.766 2778-2778/com.doppelmate.development I/zygote:     at void com.google.android.gms.internal.ads.zzche.execute(java.lang.Runnable) (com.google.android.gms:play-services-ads@@20.5.0:1)
2022-02-03 00:45:12.766 2778-2778/com.doppelmate.development I/zygote:     at com.google.android.gms.internal.ads.zzbtr com.google.android.gms.internal.ads.zzbts.zzf(com.google.android.gms.internal.ads.zzaas) (com.google.android.gms:play-services-ads@@20.5.0:2)
2022-02-03 00:45:12.766 2778-2778/com.doppelmate.development I/zygote:     at com.google.android.gms.internal.ads.zzbtm com.google.android.gms.internal.ads.zzbts.zzg(com.google.android.gms.internal.ads.zzaas) (com.google.android.gms:play-services-ads@@20.5.0:4)
2022-02-03 00:45:12.766 2778-2778/com.doppelmate.development I/zygote:     at com.google.android.gms.internal.ads.zzfsm com.google.android.gms.internal.ads.zzbuk.zzb(java.lang.Object) (com.google.android.gms:play-services-ads@@20.5.0:2)
</code>```

答: I have also this problem. Recently my ads was showing, but suddenly it disappear... :/ Without any code changes.</p>

Title: Android Ad failed to load 3

Body:
I am using Rewarded Ads with test ids, however still I am getting error 3.
This looks strange.
Below is the code:

implementation "com.google.android.gms:play-services-ads:20.5.0"

<string name="google_admob_id">ca-app-pub-3940256099942544~3347511713</string>

val rewardedCallback = object:RewardedAdLoadCallback(){

}
MobileAds.initialize(this){
   // test id
   RewardedAd.load(this, "ca-app-pub-3940256099942544/5224354917",    AdRequest.Builder().build(), rewardedCallback)
}

This is the error I received when Ads are initialized, no matter what version I use:

2022-02-03 00:45:12.766 2778-2778/com.doppelmate.development I/zygote:     at void com.google.android.gms.internal.ads.zzcne.<init>(com.google.android.gms.internal.ads.zzcoa, com.google.android.gms.internal.ads.zzcob, java.lang.String, boolean, boolean, com.google.android.gms.internal.ads.zzaas, com.google.android.gms.internal.ads.zzbkk, com.google.android.gms.internal.ads.zzcgz, com.google.android.gms.internal.ads.zzbka, com.google.android.gms.ads.internal.zzl, com.google.android.gms.ads.internal.zza, com.google.android.gms.internal.ads.zzazb, com.google.android.gms.internal.ads.zzezz, com.google.android.gms.internal.ads.zzfac) (com.google.android.gms:play-services-ads@@20.5.0:1)
2022-02-03 00:45:12.766 2778-2778/com.doppelmate.development I/zygote:     at java.lang.Object com.google.android.gms.internal.ads.zzcmu.zza() (com.google.android.gms:play-services-ads@@20.5.0:4)
2022-02-03 00:45:12.766 2778-2778/com.doppelmate.development I/zygote:     at com.google.android.gms.internal.ads.zzcml com.google.android.gms.internal.ads.zzcmx.zza(android.content.Context, com.google.android.gms.internal.ads.zzcob, java.lang.String, boolean, boolean, com.google.android.gms.internal.ads.zzaas, com.google.android.gms.internal.ads.zzbkk, com.google.android.gms.internal.ads.zzcgz, com.google.android.gms.internal.ads.zzbka, com.google.android.gms.ads.internal.zzl, com.google.android.gms.ads.internal.zza, com.google.android.gms.internal.ads.zzazb, com.google.android.gms.internal.ads.zzezz, com.google.android.gms.internal.ads.zzfac) (com.google.android.gms:play-services-ads@@20.5.0:9)
2022-02-03 00:45:12.766 2778-2778/com.doppelmate.development I/zygote:     at void com.google.android.gms.internal.ads.zzbsv.<init>(android.content.Context, com.google.android.gms.internal.ads.zzcgz, com.google.android.gms.internal.ads.zzaas, com.google.android.gms.ads.internal.zza) (com.google.android.gms:play-services-ads@@20.5.0:3)
2022-02-03 00:45:12.766 2778-2778/com.doppelmate.development I/zygote:     at void com.google.android.gms.internal.ads.zzbts.zzi(com.google.android.gms.internal.ads.zzaas, com.google.android.gms.internal.ads.zzbtr) (com.google.android.gms:play-services-ads@@20.5.0:1)
2022-02-03 00:45:12.766 2778-2778/com.doppelmate.development I/zygote:     at void com.google.android.gms.internal.ads.zzbsx.run() (com.google.android.gms:play-services-ads@@20.5.0:1)
2022-02-03 00:45:12.766 2778-2778/com.doppelmate.development I/zygote:     at void com.google.android.gms.internal.ads.zzchd.execute(java.lang.Runnable) (com.google.android.gms:play-services-ads@@20.5.0:2)
2022-02-03 00:45:12.766 2778-2778/com.doppelmate.development I/zygote:     at void com.google.android.gms.internal.ads.zzche.execute(java.lang.Runnable) (com.google.android.gms:play-services-ads@@20.5.0:1)
2022-02-03 00:45:12.766 2778-2778/com.doppelmate.development I/zygote:     at com.google.android.gms.internal.ads.zzbtr com.google.android.gms.internal.ads.zzbts.zzf(com.google.android.gms.internal.ads.zzaas) (com.google.android.gms:play-services-ads@@20.5.0:2)
2022-02-03 00:45:12.766 2778-2778/com.doppelmate.development I/zygote:     at com.google.android.gms.internal.ads.zzbtm com.google.android.gms.internal.ads.zzbts.zzg(com.google.android.gms.internal.ads.zzaas) (com.google.android.gms:play-services-ads@@20.5.0:4)
2022-02-03 00:45:12.766 2778-2778/com.doppelmate.development I/zygote:     at com.google.android.gms.internal.ads.zzfsm com.google.android.gms.internal.ads.zzbuk.zzb(java.lang.Object) (com.google.android.gms:play-services-ads@@20.5.0:2)


问:
Where should i handle sort in redux-saga?
I want to sort the data received from an api. Should I sort in the saga function and then save it to reducer? or Sort the data just before updating the store in reducer? or Should I sort in UI before rendering?</p>

答:
Depends.

Lot's of it comes to personal preference, some people prefer to do as much as they can in a saga and have reducers as simple as possible, others prefer to use sagas only for side effects and keep most data transformations to the reducers.

Most of the time it doesn't matter much, but in some cases there are things to consider. For example, if you know an action is going to get dispatched from multiple places and you will want to sort the data in each case, it might make more sense to do the sorting in the reducer, rather than doing it multiple times at those different places where the actions are being dispatched.

I found that for such data transformations it is best to have an utility function that will do the job. You can then call this function in either saga or reducer - it will be nicely "hidden" in whichever place you decided to put it to and it will also be easy to switch it to the other place if needed.

You also mentioned components and you are right, often times you will want to do transformations such as sorting during render and not when the data are stored, especially when e.g. the sorting depends on another application state like selected sort option. If you have a connected component, use reselect selectors to memoize such result so you are not sorting the same data again and again on every render. If it is some transformation done deeper in the react tree you can't handle with reselect, use something like memoize-one (class components) or use useMemo (function components) for the same effect.


问:
Extract motion fields from the nvidia Visionworks Motion estimator example
I am trying to extract the motion field from the visionworks example. i saw the post in the nvidia forum here but i still do not understand how to get the motion field.

The documentation says that the motion fiels is  a vx_image with type NVX_DF_IMAGE2F32, this means there are two channels.

Someone know the meaning of each channel? I even realize that the size of the image is the half of the input images used to detect the movement.

In the nvidia post the moderator said " that value(x, y) is the motion of the point (x, y)", but i do not understand what this means.

I understand the concept explained "More precisely, for point(x, y) with field value(mx, my) in frame N. The matched point in the frame N-1 is (x+mx, y+my)."

but i could not match the result i get in the vx_image with these parameters.

答:
After some research i found the meaning. I write the solution in case is useful for someone else:

Here my understanding using cv::Mat that can be easily used to draw the result.

```<code>// get the motion in vx_image format
vx_image MotionImage = ime.getMotionField();

//convert to cv::Mat (or GpuMat as you like...)
nvx_cv::VXImageToCVMatMapper map(MotionImage);
//cv::cuda::GpuMat MotionImageGpuMat = map.getGpuMat();
cv::Mat MotionImageMatMap = map.getMat();

//resize the motion map as it is the half of the original image used to compute the motion
cv::Mat MotionImageMat;
cv::resize(MotionImageMatMap,MotionImageMat,cv::Size(),2.0,2.0,cv::INTER_NEAREST);

//split in two channels
cv::Mat MotionImageMat_split[2];
cv::split(MotionImageMat, MotionImageMat_split);

//MotionImageMat_split[0](x,y) -> contains the increment for the pixel (x,y) in width (columns) direction between the current and previous frame.
//   Example: if MotionImageMat_split[0] at pixel (x,y) is 5 means that the difference between the current and previous frame in the width (columns) direction is 5

//MotionImageMat_split[1](x,y) -> contains the increment for the pixel (x,y) in height (rows) direction between the current and previous frame.
//   Example: if MotionImageMat_split[0] at pixel (x,y) is 5 means that the difference between the current and previous frame in the height (rows) direction is 5
</code>```

Body:
After some research i found the meaning. I write the solution in case is useful for someone else:

Here my understanding using cv::Mat that can be easily used to draw the result.

// get the motion in vx_image format
vx_image MotionImage = ime.getMotionField();

//convert to cv::Mat (or GpuMat as you like...)
nvx_cv::VXImageToCVMatMapper map(MotionImage);
//cv::cuda::GpuMat MotionImageGpuMat = map.getGpuMat();
cv::Mat MotionImageMatMap = map.getMat();

//resize the motion map as it is the half of the original image used to compute the motion
cv::Mat MotionImageMat;
cv::resize(MotionImageMatMap,MotionImageMat,cv::Size(),2.0,2.0,cv::INTER_NEAREST);

//split in two channels
cv::Mat MotionImageMat_split[2];
cv::split(MotionImageMat, MotionImageMat_split);

//MotionImageMat_split[0](x,y) -> contains the increment for the pixel (x,y) in width (columns) direction between the current and previous frame.
//   Example: if MotionImageMat_split[0] at pixel (x,y) is 5 means that the difference between the current and previous frame in the width (columns) direction is 5

//MotionImageMat_split[1](x,y) -> contains the increment for the pixel (x,y) in height (rows) direction between the current and previous frame.
//   Example: if MotionImageMat_split[0] at pixel (x,y) is 5 means that the difference between the current and previous frame in the height (rows) direction is 5


问:
Difference between the calculation of the training loss and validation loss using pytorch
I wanna use the following code of this traditional image classification problem for my regression problem. The code can be found here:

GeeksforGeeks-Training Neural Networks with Validation using Pytorch

```<code>class Network(nn.Module):
    def __init__(self):
        super(Network,self).__init__()
        self.fc1 = nn.Linear(28*28, 256)
        self.fc2 = nn.Linear(256, 128)
        self.fc3 = nn.Linear(128, 10)

    def forward(self, x):
        x = x.view(1,-1)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

model = Network()

criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr = 0.01)

epochs = 5

for e in range(epochs):
    train_loss = 0.0
    model.train()     # Optional when not using Model Specific layer
    for data, labels in trainloader:
        if torch.cuda.is_available():
            data, labels = data.cuda(), labels.cuda()

        optimizer.zero_grad()
        target = model(data)
        loss = criterion(target,labels)
        loss.backward()
        optimizer.step()
        train_loss += loss.item()

    valid_loss = 0.0
    model.eval()     # Optional when not using Model Specific layer
    for data, labels in validloader:
        if torch.cuda.is_available():
            data, labels = data.cuda(), labels.cuda()

        target = model(data)
        loss = criterion(target,labels)
        valid_loss = loss.item() * data.size(0)

print(f'Epoch {e+1} \t\t Training Loss: {train_loss / len(trainloader)} \t\t Validation Loss: {valid_loss / len(validloader)}')

</code>```

I can understand why the training loss is summed up and then divided by the length of the training data in this example, but I can't get why the validation loss is also not summed up and divided by the length. If I understand correctly, the validation loss will be calculated here by using the validation loss of the last batch and then it is multiplied by the length of the batch size.

Is the calulation of the validation loss the correct way to do it? Can I use the code for my regression problem assuming I use regression-specific metrics (e.g. MSE instead of CrossEntropyLoss etc.)?

答:
Yes, you can use the code for your regression task. The targets of the code example are one-hot vectors or in the MNIST example the numbers 0 to 9, which symbolize the classes. You would make a scalar out of that in the regression case. The loss function, which is the cross-entropy in the example, can be replaced by the MSE in your case.

I assume that the validation loss in this example is only estimated by extrapolating from a single data point to all other data points.
Since data.size represents the batch size, even averaging would only come out with the loss of that single data point.

However, on the web page, the validation loss is calculated over all data points in the validation set, as it should be done.

Body:
I wanna use the following code of this traditional image classification problem for my regression problem. The code can be found here:

GeeksforGeeks-Training Neural Networks with Validation using Pytorch

class Network(nn.Module):
    def __init__(self):
        super(Network,self).__init__()
        self.fc1 = nn.Linear(28*28, 256)
        self.fc2 = nn.Linear(256, 128)
        self.fc3 = nn.Linear(128, 10)

    def forward(self, x):
        x = x.view(1,-1)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

model = Network()

criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr = 0.01)

epochs = 5

for e in range(epochs):
    train_loss = 0.0
    model.train()     # Optional when not using Model Specific layer
    for data, labels in trainloader:
        if torch.cuda.is_available():
            data, labels = data.cuda(), labels.cuda()

        optimizer.zero_grad()
        target = model(data)
        loss = criterion(target,labels)
        loss.backward()
        optimizer.step()
        train_loss += loss.item()

    valid_loss = 0.0
    model.eval()     # Optional when not using Model Specific layer
    for data, labels in validloader:
        if torch.cuda.is_available():
            data, labels = data.cuda(), labels.cuda()

        target = model(data)
        loss = criterion(target,labels)
        valid_loss = loss.item() * data.size(0)

print(f'Epoch {e+1} \t\t Training Loss: {train_loss / len(trainloader)} \t\t Validation Loss: {valid_loss / len(validloader)}')

I can understand why the training loss is summed up and then divided by the length of the training data in this example, but I can't get why the validation loss is also not summed up and divided by the length. If I understand correctly, the validation loss will be calculated here by using the validation loss of the last batch and then it is multiplied by the length of the batch size.

Is the calulation of the validation loss the correct way to do it? Can I use the code for my regression problem assuming I use regression-specific metrics (e.g. MSE instead of CrossEntropyLoss etc.)?


问:
How to fill NA's when you have enough information to calculate what the NA should be in R
I've got a dataset where there are some NA's but I can manually work out what the values should be as the df is a column for name and the rest of the columns are just numbers followed by a final column with total. Only one NA appears per row at most so I can work out what the value should be by using the total column and the sum of all the other columns. Just wondering what would be the best way to fill these NA's without having to hardcode one by one as the df I'm using is pretty big

example df:

```<code>df = structure(list(city = c("sydney", "new york", "london", "beijing", "paris", "madrid"),
                    year = c(2005:2010),
                    A = c(1, 4, 5 , NA, 2, 1),
                    B = c(3, NA, 4 , 9, 0, 6),
                    C = c(3, 4 , 6, 1, 8, NA),
                    total = c(NA, 10, 15, 14, NA, 15)),
               class = "data.frame", row.names = c(NA, -6L))

df
</code>```

答:
You need to replace the NA in total column first and then you can simply calculate the rest. You can also make a function for the A, B, C columns so you don't repeat the code, but with only 3 columns that shouldn't be the problem.

df = structure(list(city = c("sydney", "new york", "london", "beijing", "paris", "madrid"),
                    year = c(2005:2010),
                    A = c(1, 4, 5 , NA, 2, 1),
                    B = c(3, NA, 4 , 9, 0, 6),
                    C = c(3, 4 , 6, 1, 8, NA),
                    total = c(NA, 10, 15, 14, NA, 15)),
               class = "data.frame", row.names = c(NA, -6L))

df
#>       city year  A  B  C total
#> 1   sydney 2005  1  3  3    NA
#> 2 new york 2006  4 NA  4    10
#> 3   london 2007  5  4  6    15
#> 4  beijing 2008 NA  9  1    14
#> 5    paris 2009  2  0  8    NA
#> 6   madrid 2010  1  6 NA    15

df$total <- ifelse(is.na(df$total), rowSums(df[, c("A", "B", "C")]), df$total)
df$A <- ifelse(is.na(df$A), df$total - rowSums(df[, c("A", "B", "C")], na.rm = TRUE), df$A)
df$B <- ifelse(is.na(df$B), df$total - rowSums(df[, c("A", "B", "C")], na.rm = TRUE), df$B)
df$C <- ifelse(is.na(df$C), df$total - rowSums(df[, c("A", "B", "C")], na.rm = TRUE), df$C)

df
#>       city year A B C total
#> 1   sydney 2005 1 3 3     7
#> 2 new york 2006 4 2 4    10
#> 3   london 2007 5 4 6    15
#> 4  beijing 2008 4 9 1    14
#> 5    paris 2009 2 0 8    10
#> 6   madrid 2010 1 6 8    15
```
<p><sup>Created on 2022-02-09 by the reprex package (v2.0.1)</sup></p>
<p>UPDATE: After replacing <code>NA</code> in total column, you can use the <code>na.aprox</code> function from <code>zoo</code> package to interpolate the rest of values.</p>
```library(zoo)

df$total <- ifelse(is.na(df$total), rowSums(df[, c("A", "B", "C")]), df$total)   # first totals
df[, c("A", "B", "C")] <- na.approx(df[, c("A", "B", "C", "total")], rule = 2)   # then rest
df
      city year   A   B C total
1   sydney 2005 1.0 3.0 3     7
2 new york 2006 4.0 3.5 4    10
3   london 2007 5.0 4.0 6    15
4  beijing 2008 3.5 9.0 1    14
5    paris 2009 2.0 0.0 8    10
6   madrid 2010 1.0 6.0 8    15
```

Body:
I've got a dataset where there are some NA's but I can manually work out what the values should be as the df is a column for name and the rest of the columns are just numbers followed by a final column with total. Only one NA appears per row at most so I can work out what the value should be by using the total column and the sum of all the other columns. Just wondering what would be the best way to fill these NA's without having to hardcode one by one as the df I'm using is pretty big

example df:

df = structure(list(city = c("sydney", "new york", "london", "beijing", "paris", "madrid"),
                    year = c(2005:2010),
                    A = c(1, 4, 5 , NA, 2, 1),
                    B = c(3, NA, 4 , 9, 0, 6),
                    C = c(3, 4 , 6, 1, 8, NA),
                    total = c(NA, 10, 15, 14, NA, 15)),
               class = "data.frame", row.names = c(NA, -6L))

df

Body:
You need to replace the NA in total column first and then you can simply calculate the rest. You can also make a function for the A, B, C columns so you don't repeat the code, but with only 3 columns that shouldn't be the problem.

df = structure(list(city = c("sydney", "new york", "london", "beijing", "paris", "madrid"),
                    year = c(2005:2010),
                    A = c(1, 4, 5 , NA, 2, 1),
                    B = c(3, NA, 4 , 9, 0, 6),
                    C = c(3, 4 , 6, 1, 8, NA),
                    total = c(NA, 10, 15, 14, NA, 15)),
               class = "data.frame", row.names = c(NA, -6L))

df
#>       city year  A  B  C total
#> 1   sydney 2005  1  3  3    NA
#> 2 new york 2006  4 NA  4    10
#> 3   london 2007  5  4  6    15
#> 4  beijing 2008 NA  9  1    14
#> 5    paris 2009  2  0  8    NA
#> 6   madrid 2010  1  6 NA    15

df$total <- ifelse(is.na(df$total), rowSums(df[, c("A", "B", "C")]), df$total)
df$A <- ifelse(is.na(df$A), df$total - rowSums(df[, c("A", "B", "C")], na.rm = TRUE), df$A)
df$B <- ifelse(is.na(df$B), df$total - rowSums(df[, c("A", "B", "C")], na.rm = TRUE), df$B)
df$C <- ifelse(is.na(df$C), df$total - rowSums(df[, c("A", "B", "C")], na.rm = TRUE), df$C)

df
#>       city year A B C total
#> 1   sydney 2005 1 3 3     7
#> 2 new york 2006 4 2 4    10
#> 3   london 2007 5 4 6    15
#> 4  beijing 2008 4 9 1    14
#> 5    paris 2009 2 0 8    10
#> 6   madrid 2010 1 6 8    15

Created on 2022-02-09 by the reprex package (v2.0.1)

UPDATE: After replacing NA in total column, you can use the na.aprox function from zoo package to interpolate the rest of values.

library(zoo)

df$total <- ifelse(is.na(df$total), rowSums(df[, c("A", "B", "C")]), df$total)   # first totals
df[, c("A", "B", "C")] <- na.approx(df[, c("A", "B", "C", "total")], rule = 2)   # then rest
df
      city year   A   B C total
1   sydney 2005 1.0 3.0 3     7
2 new york 2006 4.0 3.5 4    10
3   london 2007 5.0 4.0 6    15
4  beijing 2008 3.5 9.0 1    14
5    paris 2009 2.0 0.0 8    10
6   madrid 2010 1.0 6.0 8    15


问:
iframe not loading HTML Page I want to perform onClick operation on it but instead HTML is working on its own

The question I have is I don't want my HTML pages to work in the iframe instead want them to just display and when someone click on them a new page gets open.

Right now Top Row Middle Iframe has an audio and it is being played on clicking
similarly in Bottom row first iframe has a dropdown which is working but I want if anyone clicks anywhere it should open a corresponding page

pointer-events none is disabling the onclick event as well.

答:
First of all, you must add some sort of a container over the iframe to block any interactions with the iframe. Additionally, that container must be bound to a mouse click event that would take you to the page displayed in the iframe.

Here is a working example:

// Here is an event listner to bind a click event to the container
// that covers the iframe.
// All it does is take you to the page that the iframe is displaying
document.getElementById("cover-iframe").addEventListener('click', () => {
  document.location.href = 'test.html'
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Set the size of this container (width, height)
to change the size of the iframe */
.container {
  position: relative;
  width: 50rem;
}

.iframe {
  width: 100%;
}

/* This is to make the container cover the iframe */
#cover-iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0);
  cursor: pointer;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

```

I added comments to the code above to make it self explanatory.

Body:
First of all, you must add some sort of a container over the iframe to block any interactions with the iframe. Additionally, that container must be bound to a mouse click event that would take you to the page displayed in the iframe.

Here is a working example:

// Here is an event listner to bind a click event to the container
// that covers the iframe.
// All it does is take you to the page that the iframe is displaying
document.getElementById("cover-iframe").addEventListener('click', () => {
  document.location.href = 'test.html'
})

/* Set the size of this container (width, height)
to change the size of the iframe */
.container {
  position: relative;
  width: 50rem;
}

.iframe {
  width: 100%;
}

/* This is to make the container cover the iframe */
#cover-iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0);
  cursor: pointer;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
  <!-- This container is to hold the iframe and the container that will cover the iframe  -->
  <div class="container">
    <!-- "test.html" can be changed to the page you want to display -->
    <iframe src="test.html" frameborder="1" class="iframe"></iframe>
    <span id="cover-iframe"></span>
  </div>
</body>

</html>

I added comments to the code above to make it self explanatory.


问:
Interceptor is not triggered when bonded annotation has parameters
I have the following annotation bounded with the following interceptor

```<code>@Target( AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
@InterceptorBinding
annotation class NamesAllowed(vararg val values: String)
</code>```
```<code>@ScopesAllowed("")
@Priority(9)
@Interceptor
class NamesAllowedInterceptor {

    @Inject
    var jwt: JsonWebToken? = null

    @AroundInvoke
    fun intercept(ic: InvocationContext): Any {
        // some logic
        return ic.proceed()
    }
}
</code>```

The annotation is used to extract a custom claim and check a list of names from an incoming JWT

```<code>@GET
    @Path("/identifier")
    @Produces(MediaType.APPLICATION_JSON)
    @RequestScoped
    @ScopesAllowed("some_scope")  <---
    fun getMyCoolResource(): Response {
        // some logic executed
       return Response.ok()
        }
</code>```

Problem

The NamesAllowedInterceptor#intercept is never triggered.

When I define my annotation without parameters:

```<code>@Target( AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
@InterceptorBinding
annotation class NamesAllowed
</code>```

The NamesAllowedInterceptor#intercept is triggered. =s

Any help?

答:
Your interceptor only applies to @ScopesAllowed(""). It doesn't apply to @ScopesAllowed("anything-else").

It looks like you need the annotation member's value to be ignored during interceptor resolution. For that, you need to annotate the annotation member with @Nonbinding.

Not sure if this is the correct Kotlin syntax, but it should look like this:

@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
@InterceptorBinding
annotation class ScopesAllowed(@Nonbinding vararg val values: String)
```

Body:
I have the following annotation bounded with the following interceptor

@Target( AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
@InterceptorBinding
annotation class NamesAllowed(vararg val values: String)

@ScopesAllowed("")
@Priority(9)
@Interceptor
class NamesAllowedInterceptor {

    @Inject
    var jwt: JsonWebToken? = null

    @AroundInvoke
    fun intercept(ic: InvocationContext): Any {
        // some logic
        return ic.proceed()
    }
}

The annotation is used to extract a custom claim and check a list of names from an incoming JWT

@GET
    @Path("/identifier")
    @Produces(MediaType.APPLICATION_JSON)
    @RequestScoped
    @ScopesAllowed("some_scope")  <---
    fun getMyCoolResource(): Response {
        // some logic executed
       return Response.ok()
        }

Problem

The NamesAllowedInterceptor#intercept is never triggered.

When I define my annotation without parameters:

@Target( AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
@InterceptorBinding
annotation class NamesAllowed

The NamesAllowedInterceptor#intercept is triggered. =s

Any help?


问:
Printing a specific dimension of a tensor in tensorflow
I have a tensor x of shape (4,64,5,5). How can I print (or just visualize) the content of a specific dimension?

What I'm trying to do is

```<code>with tf.Session() as sess: print(x[0,:,:,:].eval())
</code>```

but I got the following error:

```<code>FailedPreconditionError: Error while reading resource variable dense_2/kernel from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/dense_2/kernel)
</code>```

I'm using Tensorflow

```<code>1.14
</code>```

答:
I tried the same in colab in Tensorflow version 1.14 using tf.ones(shape=(4,64,5,5)). It is working fine. Here's the code:

```<code>! pip install tensorflow==1.14
import tensorflow as tf
print(tf.__version__)

x=tf.ones(shape=(4,64,5,5))
with tf.Session() as sess: print(x[:,0,0,0].eval())
</code>```

Output:

```<code>1.14.0
[1. 1. 1. 1.]
</code>```

Let us know if the issue still persists. Thanks!

Body:
I have a tensor x of shape (4,64,5,5). How can I print (or just visualize) the content of a specific dimension?

What I'm trying to do is

with tf.Session() as sess: print(x[0,:,:,:].eval())

but I got the following error:

FailedPreconditionError: Error while reading resource variable dense_2/kernel from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/dense_2/kernel)

I'm using Tensorflow

1.14

Body:
I tried the same in colab in Tensorflow version 1.14 using tf.ones(shape=(4,64,5,5)). It is working fine. Here's the code:

! pip install tensorflow==1.14
import tensorflow as tf
print(tf.__version__)

x=tf.ones(shape=(4,64,5,5))
with tf.Session() as sess: print(x[:,0,0,0].eval())

Output:

1.14.0
[1. 1. 1. 1.]

Let us know if the issue still persists. Thanks!


问:
segregate duplicates and non duplicates from a list of objects based on property on multiple property in java 8
I want to segregate duplicates and non duplicates from a list of objects based on property customerId and customerRegistration using java 8

segregate meaning

if I have 3 record with same customerId and customerRegistration, first record should add into nonduplicate list and 2 nd 3 record should be add in to duplicate list.

I have below pojo class created hashcode and equals method based on customerId and customerRegistration.

```<code>public class Asset {

private String customerName;
private int customerId;
private String Type;
private String customerRegistration;
private int assetTagList;
private String rso;
private String active;
private int billableUser;
private int billableAsset;

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Asset asset = (Asset) o;
    return customerId == asset.customerId && Objects.equals(customerRegistration, asset.customerRegistration);
}

@Override
public int hashCode() {
    return Objects.hash(customerId, customerRegistration);
}
</code>```

}

I have written below logic in java7 which will work fine ,is there any way I can write using stream(convert forloop logic in the below code to stream)?

```<code>public  Map<String ,List<Asset>> execute1() throws IOException {

    List<Asset> assetList=new ArrayList<>();
    Set<Asset> set=new HashSet<>();
    List<Asset> duplicateList=new ArrayList<>();
    List<Asset> nonDuplicateList=new ArrayList<>();
    Map<String ,List<Asset>> map = new HashMap<>();
    Asset asset1 = new Asset("French Customer1", 673, "Vehicle", "KNH 9009", 175, "FR", "Yes", 0, 0);
    Asset asset2 = new Asset("French Customer2", 673, "Vehicle", "KNH 9009", 175, "FR", "Yes", 0, 0);

    Asset asset3 = new Asset("French Customer3", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
    Asset asset4= new Asset("French Customer4", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
    Asset asset5= new Asset("French Customer4", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);

    Asset asset6 = new Asset("French Customer5", 674, "Vehicle", "KNH 9008", 175, "FR", "Yes", 0, 0);

    assetList.add(asset1);
    assetList.add(asset2);
    assetList.add(asset3);
    assetList.add(asset4);
    assetList.add(asset5);
    assetList.add(asset6);

    for (Asset assetTemp:assetList){
        if(set.add(assetTemp)){
            nonDuplicateList.add(assetTemp);
        }
        else {
            duplicateList.add(assetTemp);
        }
    }

    map.put("duplicate",duplicateList);
    map.put("nonDuplicateList",nonDuplicateList);

   return map
}
</code>```

expecting output like below(from input assetList which is defined in the above execute1 function)

nonDuplicateList should have (asset1,asset3,asset6):

```<code>Asset asset1 = new Asset("French Customer1", 673, "Vehicle", "KNH 9009", 175, "FR", "Yes", 0, 0);
Asset asset3 = new Asset("French Customer3", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
Asset asset6 = new Asset("French Customer5", 674, "Vehicle", "KNH 9008", 175, "FR", "Yes", 0, 0);
</code>```

duplicateList should have:(asset2,asset4,asset5)

```<code>Asset asset2 = new Asset("French Customer2", 673, "Vehicle", "KNH 9009", 175, "FR", "Yes", 0, 0);
Asset asset4= new Asset("French Customer4", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
Asset asset5= new Asset("French Customer4", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
</code>```

答:
You can group the elements depending on adding to your set returns true or false:</p>
```<code>public  static Map<String ,List<Asset>> execute2() throws IOException {

    List<Asset> assetList=new ArrayList<>();
    Asset asset1 = new Asset("French Customer1", 673, "Vehicle", "KNH 9009", 175, "FR", "Yes", 0, 0);
    Asset asset2 = new Asset("French Customer2", 673, "Vehicle", "KNH 9009", 175, "FR", "Yes", 0, 0);

    Asset asset3 = new Asset("French Customer3", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
    Asset asset4= new Asset("French Customer4", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
    Asset asset5= new Asset("French Customer4", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);

    Asset asset6 = new Asset("French Customer5", 674, "Vehicle", "KNH 9008", 175, "FR", "Yes", 0, 0);

    assetList.add(asset1);
    assetList.add(asset2);
    assetList.add(asset3);
    assetList.add(asset4);
    assetList.add(asset5);
    assetList.add(asset6);

    Set<Asset> set=new HashSet<>();
    return assetList.stream().collect(Collectors.groupingBy(x -> set.add(x) ? "nonDuplicateList" : "duplicate"));
}
</code>```

Body:
I want to segregate duplicates and non duplicates from a list of objects based on property customerId and customerRegistration using java 8

segregate meaning

if I have 3 record with same customerId and customerRegistration, first record should add into nonduplicate list and 2 nd 3 record should be add in to duplicate list.

I have below pojo class created hashcode and equals method based on customerId and customerRegistration.

public class Asset {

private String customerName;
private int customerId;
private String Type;
private String customerRegistration;
private int assetTagList;
private String rso;
private String active;
private int billableUser;
private int billableAsset;

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Asset asset = (Asset) o;
    return customerId == asset.customerId && Objects.equals(customerRegistration, asset.customerRegistration);
}

@Override
public int hashCode() {
    return Objects.hash(customerId, customerRegistration);
}

}

I have written below logic in java7 which will work fine ,is there any way I can write using stream(convert forloop logic in the below code to stream)?

public  Map<String ,List<Asset>> execute1() throws IOException {

    List<Asset> assetList=new ArrayList<>();
    Set<Asset> set=new HashSet<>();
    List<Asset> duplicateList=new ArrayList<>();
    List<Asset> nonDuplicateList=new ArrayList<>();
    Map<String ,List<Asset>> map = new HashMap<>();
    Asset asset1 = new Asset("French Customer1", 673, "Vehicle", "KNH 9009", 175, "FR", "Yes", 0, 0);
    Asset asset2 = new Asset("French Customer2", 673, "Vehicle", "KNH 9009", 175, "FR", "Yes", 0, 0);

    Asset asset3 = new Asset("French Customer3", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
    Asset asset4= new Asset("French Customer4", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
    Asset asset5= new Asset("French Customer4", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);

    Asset asset6 = new Asset("French Customer5", 674, "Vehicle", "KNH 9008", 175, "FR", "Yes", 0, 0);

    assetList.add(asset1);
    assetList.add(asset2);
    assetList.add(asset3);
    assetList.add(asset4);
    assetList.add(asset5);
    assetList.add(asset6);

    for (Asset assetTemp:assetList){
        if(set.add(assetTemp)){
            nonDuplicateList.add(assetTemp);
        }
        else {
            duplicateList.add(assetTemp);
        }
    }

    map.put("duplicate",duplicateList);
    map.put("nonDuplicateList",nonDuplicateList);

   return map
}

expecting output like below(from input assetList which is defined in the above execute1 function)

nonDuplicateList should have (asset1,asset3,asset6):

Asset asset1 = new Asset("French Customer1", 673, "Vehicle", "KNH 9009", 175, "FR", "Yes", 0, 0);
Asset asset3 = new Asset("French Customer3", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
Asset asset6 = new Asset("French Customer5", 674, "Vehicle", "KNH 9008", 175, "FR", "Yes", 0, 0);

duplicateList should have:(asset2,asset4,asset5)

Asset asset2 = new Asset("French Customer2", 673, "Vehicle", "KNH 9009", 175, "FR", "Yes", 0, 0);
Asset asset4= new Asset("French Customer4", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
Asset asset5= new Asset("French Customer4", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);

Body:
You can group the elements depending on adding to your set returns true or false:

public  static Map<String ,List<Asset>> execute2() throws IOException {

    List<Asset> assetList=new ArrayList<>();
    Asset asset1 = new Asset("French Customer1", 673, "Vehicle", "KNH 9009", 175, "FR", "Yes", 0, 0);
    Asset asset2 = new Asset("French Customer2", 673, "Vehicle", "KNH 9009", 175, "FR", "Yes", 0, 0);

    Asset asset3 = new Asset("French Customer3", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
    Asset asset4= new Asset("French Customer4", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);
    Asset asset5= new Asset("French Customer4", 673, "Vehicle", null, 175, "FR", "Yes", 0, 0);

    Asset asset6 = new Asset("French Customer5", 674, "Vehicle", "KNH 9008", 175, "FR", "Yes", 0, 0);

    assetList.add(asset1);
    assetList.add(asset2);
    assetList.add(asset3);
    assetList.add(asset4);
    assetList.add(asset5);
    assetList.add(asset6);

    Set<Asset> set=new HashSet<>();
    return assetList.stream().collect(Collectors.groupingBy(x -> set.add(x) ? "nonDuplicateList" : "duplicate"));
}


问:
Will an If statement stop checking if the first OR condition is met?
Does SystemVerilog evaluate the whole if statement or the minimum to get the result?

For example:

```<code>if (condition1 && condition2) begin
  ...
end

if (condition1 || condition2) begin
  ...
end
</code>```

In the first case, will condition2 be evaluated if condition1 is False?
In the second case, will condition2 be evaluated if condition1 is True?

答:
This behavior is also known as short-circuit evaluation.

Refer to IEEE 1800-2017, section 11.4.7 Logical operators.

```<code>The && and || operators shall use short circuit evaluation as follows:
    — The first operand expression shall always be evaluated.
    — For &&, if the first operand value is logically false then the second
      operand shall not be evaluated.
    — For ||, if the first operand value is logically true then the second
      operand shall not be evaluated.
</code>```

Therefore, for the operators in your if statements, all the expressions may not be evaluated.

To see which operators have similar behavior, and which do not, refer to section 11.3.5 Operator expression short circuiting.

Body:
Does SystemVerilog evaluate the whole if statement or the minimum to get the result?

For example:

if (condition1 && condition2) begin
  ...
end

if (condition1 || condition2) begin
  ...
end

In the first case, will condition2 be evaluated if condition1 is False?
In the second case, will condition2 be evaluated if condition1 is True?

Body:
This behavior is also known as short-circuit evaluation.

Refer to IEEE 1800-2017, section 11.4.7 Logical operators.

The && and || operators shall use short circuit evaluation as follows:
    — The first operand expression shall always be evaluated.
    — For &&, if the first operand value is logically false then the second
      operand shall not be evaluated.
    — For ||, if the first operand value is logically true then the second
      operand shall not be evaluated.

Therefore, for the operators in your if statements, all the expressions may not be evaluated.

To see which operators have similar behavior, and which do not, refer to section 11.3.5 Operator expression short circuiting.


问:
FLASK, How to redirect Google autentication to a local html.file
Hi everyone I have implemented the Google Authentication with API.
I would like that once the user is authenticated the page redirect to a local html/Javascript application.
I am trying the following code which is not working because it is not finding the correct url.

from flask import Flask, redirect, url_for, session, request, render_template
from authlib.integrations.flask_client import OAuth
import os
from datetime import timedelta

```<code># App config
app = Flask(__name__)
app.secret_key = "random secret"

# oAuth Setup
oauth = OAuth(app)
google = oauth.register(
    name='google',
    client_id='',
    client_secret='',
    access_token_url='https://accounts.google.com/o/oauth2/token',
    access_token_params=None,
    authorize_url='https://accounts.google.com/o/oauth2/auth',
    authorize_params=None,
    api_base_url='https://www.googleapis.com/oauth2/v1/',
    client_kwargs={'scope': 'openid email profile'},
)

@app.route('/')
def hello_world():
    email = dict(session).get('email',None)
    return f'Hello, {email}!'

@app.route('/login')
def login():
    google = oauth.create_client('google')
    redirect_uri = url_for('authorize', _external=True)
    return google.authorize_redirect(redirect_uri)

@app.route('/authorize')
def authorize():
    google = oauth.create_client('google')
    token = google.authorize_access_token()
    resp = google.get('userinfo')
    user_info = resp.json()
    session['email'] = user_info['email']
    return redirect('file:///home/luca/Desktop/ft_userdata/ProvaLogIn/prova.htm')

if __name__ == "__main__":
    app.run(debug=True)
</code>```

Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

THe html that i am trying to render is simply an html local file with wrote  hello

答:
you need to create folder called templates inside your project in this folder you will add your html file in your case it will be prova.html

and change the return statement to

```<code>    return render_template('prova.html')
</code>```

this how should your directory tree should look like (general view)

```<code>├── app.py
├── static
└── templates
    └── status.html
</code>```

hope this solve your issue

Body:
Hi everyone I have implemented the Google Authentication with API.
I would like that once the user is authenticated the page redirect to a local html/Javascript application.
I am trying the following code which is not working because it is not finding the correct url.

from flask import Flask, redirect, url_for, session, request, render_template
from authlib.integrations.flask_client import OAuth
import os
from datetime import timedelta

# App config
app = Flask(__name__)
app.secret_key = "random secret"

# oAuth Setup
oauth = OAuth(app)
google = oauth.register(
    name='google',
    client_id='',
    client_secret='',
    access_token_url='https://accounts.google.com/o/oauth2/token',
    access_token_params=None,
    authorize_url='https://accounts.google.com/o/oauth2/auth',
    authorize_params=None,
    api_base_url='https://www.googleapis.com/oauth2/v1/',
    client_kwargs={'scope': 'openid email profile'},
)

@app.route('/')
def hello_world():
    email = dict(session).get('email',None)
    return f'Hello, {email}!'

@app.route('/login')
def login():
    google = oauth.create_client('google')
    redirect_uri = url_for('authorize', _external=True)
    return google.authorize_redirect(redirect_uri)

@app.route('/authorize')
def authorize():
    google = oauth.create_client('google')
    token = google.authorize_access_token()
    resp = google.get('userinfo')
    user_info = resp.json()
    session['email'] = user_info['email']
    return redirect('file:///home/luca/Desktop/ft_userdata/ProvaLogIn/prova.htm')

if __name__ == "__main__":
    app.run(debug=True)

Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

THe html that i am trying to render is simply an html local file with wrote  hello

Body:
you need to create folder called templates inside your project in this folder you will add your html file in your case it will be prova.html

and change the return statement to

    return render_template('prova.html')

this how should your directory tree should look like (general view)

├── app.py
├── static
└── templates
    └── status.html

hope this solve your issue


问:
Issue in angular updating version 12 to 13 in angular core
export 'ɵcoerceToBoolean' (imported as 'ɵcoerceToBoolean') was not found in '@angular/core'

When i tried to update the project from angular 12 to 13,I got this error on the terminal.

答: Probably an issue of mixed versions from upgrade. Remove local version of folder node_modules and remove package-lock.json and reinstall using npm i. If that does not resolve your issue then follow the steps again using upgrade guide: https://update.angular.io/?l=3&v=12.0-13.0


问:
Jmeter result file is not getting generated when executed test on slave from java code
I am running Jmeter performance test from java application in distributed mode (2 slaves + master). In my test script I have configured Summary Report to store result data to csv file. This file location is configured with fixed name "result/summary.csv" value but the csv result file is not getting generated.

Result file is created when the test is run only on one master but not when using master + slave combination

```<code>public static void main(String[] argv) throws Exception {

    File jmeterHome = new File(System.getProperty("jmeter.home"));
    String slash = System.getProperty("file.separator");

    if (jmeterHome.exists()) {
        File jmeterProperties = new File(jmeterHome.getPath() + slash + "bin" + slash + "jmeter.properties");
        if (jmeterProperties.exists()) {
            //JMeter Engine
            DistributedRunner distributedRunner = new DistributedRunner();

            //JMeter initialization (properties, log levels, locale, etc)
            JMeterUtils.setJMeterHome(jmeterHome.getPath());
            JMeterUtils.loadJMeterProperties(jmeterProperties.getPath());
            JMeterUtils.initLogging();// you can comment this line out to see extra log messages of i.e. DEBUG level
            JMeterUtils.initLocale();

            // JMeter Test Plan, basically JOrphan HashTree
            HashTree testPlanTree = new HashTree();

            // First HTTP Sampler - open example.com
            HTTPSamplerProxy examplecomSampler = new HTTPSamplerProxy();
            examplecomSampler.setDomain("example.com");
            examplecomSampler.setPort(80);
            examplecomSampler.setPath("/");
            examplecomSampler.setMethod("GET");
            examplecomSampler.setName("Open example.com");
            examplecomSampler.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName());
            examplecomSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());

            // Second HTTP Sampler - open blazemeter.com
            HTTPSamplerProxy blazemetercomSampler = new HTTPSamplerProxy();
            blazemetercomSampler.setDomain("blazemeter.com");
            blazemetercomSampler.setPort(80);
            blazemetercomSampler.setPath("/");
            blazemetercomSampler.setMethod("GET");
            blazemetercomSampler.setName("Open blazemeter.com");
            blazemetercomSampler.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName());
            blazemetercomSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());

            // Loop Controller
            LoopController loopController = new LoopController();
            loopController.setLoops(1);
            loopController.setFirst(true);
            loopController.setProperty(TestElement.TEST_CLASS, LoopController.class.getName());
            loopController.setProperty(TestElement.GUI_CLASS, LoopControlPanel.class.getName());
            loopController.initialize();

            // Thread Group
            ThreadGroup threadGroup = new ThreadGroup();
            threadGroup.setName("Example Thread Group");
            threadGroup.setNumThreads(1);
            threadGroup.setRampUp(1);
            threadGroup.setSamplerController(loopController);
            threadGroup.setProperty(TestElement.TEST_CLASS, ThreadGroup.class.getName());
            threadGroup.setProperty(TestElement.GUI_CLASS, ThreadGroupGui.class.getName());

            // Test Plan
            TestPlan testPlan = new TestPlan("Create JMeter Script From Java Code");
            testPlan.setProperty(TestElement.TEST_CLASS, TestPlan.class.getName());
            testPlan.setProperty(TestElement.GUI_CLASS, TestPlanGui.class.getName());
            testPlan.setUserDefinedVariables((Arguments) new ArgumentsPanel().createTestElement());

            // Construct Test Plan from previously initialized elements
            testPlanTree.add(testPlan);
            HashTree threadGroupHashTree = testPlanTree.add(testPlan, threadGroup);
            threadGroupHashTree.add(blazemetercomSampler);
            threadGroupHashTree.add(examplecomSampler);

            // save generated test plan to JMeter's .jmx file format
            SaveService.saveTree(testPlanTree, new FileOutputStream(jmeterHome + slash + "example.jmx"));

            //add Summarizer output to get test progress in stdout like:
            // summary =      2 in   1.3s =    1.5/s Avg:   631 Min:   290 Max:   973 Err:     0 (0.00%)
            Summariser summer = null;
            String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");
            if (summariserName.length() > 0) {
                summer = new Summariser(summariserName);
            }

            // Store execution results into a .jtl file
            String logFile = jmeterHome + slash + "example.jtl";

            // Store execution results into a .csv file
            //String logFile = jmeterHome + slash + "csv.jtl";

            ResultCollector logger = new ResultCollector(summer);
            logger.setFilename(logFile);
            testPlanTree.add(testPlanTree.getArray()[0], logger);

            ArrayList<String> remoteHostList = new ArrayList<String>();
            remoteHostList.add("0.0.0.127");
            remoteHostList.add("0.0.0.128");

            List<JMeterEngine> engines = new LinkedList<JMeterEngine>();
            distributedRunner.setStdout(System.out);
            distributedRunner.setStdErr(System.err);
            distributedRunner.init(remoteHostList, testPlanTree);
            engines.addAll(distributedRunner.getEngines());
            distributedRunner.start();

            System.out.println("Test completed. See " + jmeterHome + slash + "example.jtl file for results");
            System.out.println("JMeter .jmx script is available at " + jmeterHome + slash + "example.jmx");
            System.exit(0);

        }
    }
    System.exit(1);
}
</code>```

答:
When you're running JMeter in distributed mode the master node:

Sends .jmx test plan to the slaves

Collects results from the slaves and merges then into a single .jtl results file

It's hard to say what's wrong without seeing your code, but my expectation is that you need to use ClientJMeterEngine instead of StandardJMeterEngine

Body:
I am running Jmeter performance test from java application in distributed mode (2 slaves + master). In my test script I have configured Summary Report to store result data to csv file. This file location is configured with fixed name "result/summary.csv" value but the csv result file is not getting generated.

Result file is created when the test is run only on one master but not when using master + slave combination

public static void main(String[] argv) throws Exception {

    File jmeterHome = new File(System.getProperty("jmeter.home"));
    String slash = System.getProperty("file.separator");

    if (jmeterHome.exists()) {
        File jmeterProperties = new File(jmeterHome.getPath() + slash + "bin" + slash + "jmeter.properties");
        if (jmeterProperties.exists()) {
            //JMeter Engine
            DistributedRunner distributedRunner = new DistributedRunner();

            //JMeter initialization (properties, log levels, locale, etc)
            JMeterUtils.setJMeterHome(jmeterHome.getPath());
            JMeterUtils.loadJMeterProperties(jmeterProperties.getPath());
            JMeterUtils.initLogging();// you can comment this line out to see extra log messages of i.e. DEBUG level
            JMeterUtils.initLocale();

            // JMeter Test Plan, basically JOrphan HashTree
            HashTree testPlanTree = new HashTree();

            // First HTTP Sampler - open example.com
            HTTPSamplerProxy examplecomSampler = new HTTPSamplerProxy();
            examplecomSampler.setDomain("example.com");
            examplecomSampler.setPort(80);
            examplecomSampler.setPath("/");
            examplecomSampler.setMethod("GET");
            examplecomSampler.setName("Open example.com");
            examplecomSampler.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName());
            examplecomSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());

            // Second HTTP Sampler - open blazemeter.com
            HTTPSamplerProxy blazemetercomSampler = new HTTPSamplerProxy();
            blazemetercomSampler.setDomain("blazemeter.com");
            blazemetercomSampler.setPort(80);
            blazemetercomSampler.setPath("/");
            blazemetercomSampler.setMethod("GET");
            blazemetercomSampler.setName("Open blazemeter.com");
            blazemetercomSampler.setProperty(TestElement.TEST_CLASS, HTTPSamplerProxy.class.getName());
            blazemetercomSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());

            // Loop Controller
            LoopController loopController = new LoopController();
            loopController.setLoops(1);
            loopController.setFirst(true);
            loopController.setProperty(TestElement.TEST_CLASS, LoopController.class.getName());
            loopController.setProperty(TestElement.GUI_CLASS, LoopControlPanel.class.getName());
            loopController.initialize();

            // Thread Group
            ThreadGroup threadGroup = new ThreadGroup();
            threadGroup.setName("Example Thread Group");
            threadGroup.setNumThreads(1);
            threadGroup.setRampUp(1);
            threadGroup.setSamplerController(loopController);
            threadGroup.setProperty(TestElement.TEST_CLASS, ThreadGroup.class.getName());
            threadGroup.setProperty(TestElement.GUI_CLASS, ThreadGroupGui.class.getName());

            // Test Plan
            TestPlan testPlan = new TestPlan("Create JMeter Script From Java Code");
            testPlan.setProperty(TestElement.TEST_CLASS, TestPlan.class.getName());
            testPlan.setProperty(TestElement.GUI_CLASS, TestPlanGui.class.getName());
            testPlan.setUserDefinedVariables((Arguments) new ArgumentsPanel().createTestElement());

            // Construct Test Plan from previously initialized elements
            testPlanTree.add(testPlan);
            HashTree threadGroupHashTree = testPlanTree.add(testPlan, threadGroup);
            threadGroupHashTree.add(blazemetercomSampler);
            threadGroupHashTree.add(examplecomSampler);

            // save generated test plan to JMeter's .jmx file format
            SaveService.saveTree(testPlanTree, new FileOutputStream(jmeterHome + slash + "example.jmx"));

            //add Summarizer output to get test progress in stdout like:
            // summary =      2 in   1.3s =    1.5/s Avg:   631 Min:   290 Max:   973 Err:     0 (0.00%)
            Summariser summer = null;
            String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");
            if (summariserName.length() > 0) {
                summer = new Summariser(summariserName);
            }

            // Store execution results into a .jtl file
            String logFile = jmeterHome + slash + "example.jtl";

            // Store execution results into a .csv file
            //String logFile = jmeterHome + slash + "csv.jtl";

            ResultCollector logger = new ResultCollector(summer);
            logger.setFilename(logFile);
            testPlanTree.add(testPlanTree.getArray()[0], logger);

            ArrayList<String> remoteHostList = new ArrayList<String>();
            remoteHostList.add("0.0.0.127");
            remoteHostList.add("0.0.0.128");

            List<JMeterEngine> engines = new LinkedList<JMeterEngine>();
            distributedRunner.setStdout(System.out);
            distributedRunner.setStdErr(System.err);
            distributedRunner.init(remoteHostList, testPlanTree);
            engines.addAll(distributedRunner.getEngines());
            distributedRunner.start();

            System.out.println("Test completed. See " + jmeterHome + slash + "example.jtl file for results");
            System.out.println("JMeter .jmx script is available at " + jmeterHome + slash + "example.jmx");
            System.exit(0);

        }
    }
    System.exit(1);
}