问:
ReactJS - Add custom event listener to component
In plain old HTML I have the DIV

```<code><div class="movie" id="my_movie">
</code>```

and the following javascript code

var myMovie = document.getElementById('my_movie');
myMovie.addEventListener('nv-enter', function (event) {
     console.log('change scope');
});
```
<p>Now I have a React Component, inside this component, in the render method, I am returning my div. How can I add an event listener for my custom event? (I am using this library for TV apps - navigation )</p>
<pre class="lang-js prettyprint-override"><code>import React, { Component } from 'react';

class MovieItem extends Component {

  render() {

    if(this.props.index === 0) {
      return (
        <div aria-nv-el aria-nv-el-current className="menu_item nv-default">
            <div className="indicator selected"></div>
            <div className="category">
                <span className="title">{this.props.movieItem.caption.toUpperCase()}</span>
            </div>
        </div>
      );
    }
    else {
      return (
        <div aria-nv-el className="menu_item nv-default">
            <div className="indicator selected"></div>
            <div className="category">
                <span className="title">{this.props.movieItem.caption.toUpperCase()}</span>
            </div>
        </div>
      );
    }
  }

}

export default MovieItem;
</code>```

Update #1:

I applied all the ideas provided in the answers. I set the navigation library to debug mode and I am able to navigate on my menu items only based on the keyboard (as you can see in the screenshot I was able to navigate to Movies 4) but when I focus an item in the menu or press enter, I dont see anything in the console.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class MenuItem extends Component {

  constructor(props) {
    super(props);
    // Pre-bind your event handler, or define it as a fat arrow in ES7/TS
    this.handleNVFocus = this.handleNVFocus.bind(this);
    this.handleNVEnter = this.handleNVEnter.bind(this);
    this.handleNVRight = this.handleNVRight.bind(this);
  }

  handleNVFocus = event => {
      console.log('Focused: ' + this.props.menuItem.caption.toUpperCase());
  }

  handleNVEnter = event => {
      console.log('Enter: ' + this.props.menuItem.caption.toUpperCase());
  }

  handleNVRight = event => {
      console.log('Right: ' + this.props.menuItem.caption.toUpperCase());
  }

  componentDidMount() {
    ReactDOM.findDOMNode(this).addEventListener('nv-focus', this.handleNVFocus);
    ReactDOM.findDOMNode(this).addEventListener('nv-enter', this.handleNVEnter);
    ReactDOM.findDOMNode(this).addEventListener('nv-right', this.handleNVEnter);
    //this.refs.nv.addEventListener('nv-focus', this.handleNVFocus);
    //this.refs.nv.addEventListener('nv-enter', this.handleNVEnter);
    //this.refs.nv.addEventListener('nv-right', this.handleNVEnter);
  }

  componentWillUnmount() {
    ReactDOM.findDOMNode(this).removeEventListener('nv-focus', this.handleNVFocus);
    ReactDOM.findDOMNode(this).removeEventListener('nv-enter', this.handleNVEnter);
    ReactDOM.findDOMNode(this).removeEventListener('nv-right', this.handleNVRight);
    //this.refs.nv.removeEventListener('nv-focus', this.handleNVFocus);
    //this.refs.nv.removeEventListener('nv-enter', this.handleNVEnter);
    //this.refs.nv.removeEventListener('nv-right', this.handleNVEnter);
  }

  render() {
    var attrs = this.props.index === 0 ? {"aria-nv-el-current": true} : {};
    return (

              {this.props.menuItem.caption.toUpperCase()}

    )
  }

}

export default MenuItem;
```
<p>I left some lines commented because in both cases I am not able to get the console lines to be logged.</p>
<p>Update #2: This navigation library does not work well with React with its original Html Tags, so I had to set the options and rename the tags to use aria-* so it would not impact React.</p>
<pre class="lang-js prettyprint-override"><code>navigation.setOption('prefix','aria-nv-el');
navigation.setOption('attrScope','aria-nv-scope');
navigation.setOption('attrScopeFOV','aria-nv-scope-fov');
navigation.setOption('attrScopeCurrent','aria-nv-scope-current');
navigation.setOption('attrElement','aria-nv-el');
navigation.setOption('attrElementFOV','aria-nv-el-fov');
navigation.setOption('attrElementCurrent','aria-nv-el-current');
</code>```

答:
Here is a dannyjolie more detailed answer without need of component reference but using document.body reference.

First somewhere in your app, there is a component method that will create a new custom event and send it.
For example, your customer switch lang.
In this case, you can attach to the document body a new event :

```<code>setLang(newLang) {
    // lang business logic here
    // then throw a new custom event attached to the body :
    document.body.dispatchEvent(new CustomEvent("my-set-lang", {detail: { newLang }}));
  }
</code>```

Once that done, you have another component that will need to listen to the lang switch event. For example, your customer is on a given product, and you will refresh the product having new lang as argument.

First add/remove event listener for your target component :

```<code>  componentDidMount() {
    document.body.addEventListener('my-set-lang', this.handleLangChange.bind(this));
  }

  componentWillUnmount() {
    document.body.removeEventListener('my-set-lang', this.handleLangChange.bind(this));
  }

</code>```

then define your component my-set-langw handler

```<code>  handleLangChange(event) {
    console.log("lang has changed to", event.detail.newLang);
    // your business logic here .. this.setState({...});
  }
</code>```

Body:
In plain old HTML I have the DIV

and the following javascript code

var myMovie = document.getElementById('my_movie');
myMovie.addEventListener('nv-enter', function (event) {
     console.log('change scope');
});

Now I have a React Component, inside this component, in the render method, I am returning my div. How can I add an event listener for my custom event? (I am using this library for TV apps - navigation )

import React, { Component } from 'react';

class MovieItem extends Component {

  render() {

    if(this.props.index === 0) {
      return (

                {this.props.movieItem.caption.toUpperCase()}

      );
    }
    else {
      return (

                {this.props.movieItem.caption.toUpperCase()}

      );
    }
  }

}

export default MovieItem;

Update #1:

I applied all the ideas provided in the answers. I set the navigation library to debug mode and I am able to navigate on my menu items only based on the keyboard (as you can see in the screenshot I was able to navigate to Movies 4) but when I focus an item in the menu or press enter, I dont see anything in the console.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class MenuItem extends Component {

  constructor(props) {
    super(props);
    // Pre-bind your event handler, or define it as a fat arrow in ES7/TS
    this.handleNVFocus = this.handleNVFocus.bind(this);
    this.handleNVEnter = this.handleNVEnter.bind(this);
    this.handleNVRight = this.handleNVRight.bind(this);
  }

  handleNVFocus = event => {
      console.log('Focused: ' + this.props.menuItem.caption.toUpperCase());
  }

  handleNVEnter = event => {
      console.log('Enter: ' + this.props.menuItem.caption.toUpperCase());
  }

  handleNVRight = event => {
      console.log('Right: ' + this.props.menuItem.caption.toUpperCase());
  }

  componentDidMount() {
    ReactDOM.findDOMNode(this).addEventListener('nv-focus', this.handleNVFocus);
    ReactDOM.findDOMNode(this).addEventListener('nv-enter', this.handleNVEnter);
    ReactDOM.findDOMNode(this).addEventListener('nv-right', this.handleNVEnter);
    //this.refs.nv.addEventListener('nv-focus', this.handleNVFocus);
    //this.refs.nv.addEventListener('nv-enter', this.handleNVEnter);
    //this.refs.nv.addEventListener('nv-right', this.handleNVEnter);
  }

  componentWillUnmount() {
    ReactDOM.findDOMNode(this).removeEventListener('nv-focus', this.handleNVFocus);
    ReactDOM.findDOMNode(this).removeEventListener('nv-enter', this.handleNVEnter);
    ReactDOM.findDOMNode(this).removeEventListener('nv-right', this.handleNVRight);
    //this.refs.nv.removeEventListener('nv-focus', this.handleNVFocus);
    //this.refs.nv.removeEventListener('nv-enter', this.handleNVEnter);
    //this.refs.nv.removeEventListener('nv-right', this.handleNVEnter);
  }

  render() {
    var attrs = this.props.index === 0 ? {"aria-nv-el-current": true} : {};
    return (

              {this.props.menuItem.caption.toUpperCase()}

    )
  }

}

export default MenuItem;

I left some lines commented because in both cases I am not able to get the console lines to be logged.

Update #2: This navigation library does not work well with React with its original Html Tags, so I had to set the options and rename the tags to use aria-* so it would not impact React.

navigation.setOption('prefix','aria-nv-el');
navigation.setOption('attrScope','aria-nv-scope');
navigation.setOption('attrScopeFOV','aria-nv-scope-fov');
navigation.setOption('attrScopeCurrent','aria-nv-scope-current');
navigation.setOption('attrElement','aria-nv-el');
navigation.setOption('attrElementFOV','aria-nv-el-fov');
navigation.setOption('attrElementCurrent','aria-nv-el-current');

Body:
Here is a dannyjolie more detailed answer without need of component reference but using document.body reference.

First somewhere in your app, there is a component method that will create a new custom event and send it.
For example, your customer switch lang.
In this case, you can attach to the document body a new event :

setLang(newLang) {
    // lang business logic here
    // then throw a new custom event attached to the body :
    document.body.dispatchEvent(new CustomEvent("my-set-lang", {detail: { newLang }}));
  }

Once that done, you have another component that will need to listen to the lang switch event. For example, your customer is on a given product, and you will refresh the product having new lang as argument.

First add/remove event listener for your target component :

  componentDidMount() {
    document.body.addEventListener('my-set-lang', this.handleLangChange.bind(this));
  }

  componentWillUnmount() {
    document.body.removeEventListener('my-set-lang', this.handleLangChange.bind(this));
  }

then define your component my-set-langw handler

  handleLangChange(event) {
    console.log("lang has changed to", event.detail.newLang);
    // your business logic here .. this.setState({...});
  }


来源: stackexchange

问:
How to save the output of for loop to the same column?
In the for loop, I don't know why when I try to save the output to dataframe

```<code>Grid <- c("tt6483832/","tt5164196/","tt4052886/","tt1826940/")
BaseURL <- "http://www.imdb.com/title/"

for (i in 1:4){
FullURL <-paste(BaseURL,Grid[i], sep="")
Title <- read_html(FullURL)
title_contents <- html_element(Title,"selector")
storyline <- html_element(Title,"selector")
rating <- html_element(Title,"selector")
title_contents <- html_text(title_contents)
rating <- html_text(rating)
storyline <- html_text(storyline)
print(title_contents)
print(rating)
print(storyline)
df <- cbind(title_contents,rating,storyline)
}

df <- data.frame(df)
</code>```

The output will only have the fourth one which is enter image description here

How can I save all the output of for loop to the same column such as

```<code>    C1      C2      C3
R1  title1  rating1 storyline1
R2  title2  rating2 storyline2
R3  title3  rating3 storyline3
R4  title4  rating4 storyline4
</code>```

答:
The issue is you are overwriting the previous results thus you are getting result for only last one(fourth).

Create an empty vector df1 and store the results of each loop in it.

```<code>Grid <- c("tt6483832/","tt5164196/","tt4052886/","tt1826940/")
BaseURL <- "http://www.imdb.com/title/"

df1 = c()

for (i in 1:4){

  FullURL <-paste(BaseURL,Grid[i], sep="")

  title_contents <- FullURL %>% read_html() %>% html_nodes('.dxSWFG') %>% html_text()

  rating <- FullURL %>% read_html() %>% html_nodes('.iTLWoV') %>% html_text()
  rating = rating[1]

  storyline <- FullURL %>% read_html() %>% html_nodes('.eqlIrG') %>% html_text()

  df <- cbind(title_contents,rating,storyline)

  df1 = rbind(df, df1)
}

df1 <- data.frame(df1)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In the for loop, I don't know why when I try to save the output to dataframe

Grid <- c("tt6483832/","tt5164196/","tt4052886/","tt1826940/")
BaseURL <- "http://www.imdb.com/title/"

for (i in 1:4){
FullURL <-paste(BaseURL,Grid[i], sep="")
Title <- read_html(FullURL)
title_contents <- html_element(Title,"selector")
storyline <- html_element(Title,"selector")
rating <- html_element(Title,"selector")
title_contents <- html_text(title_contents)
rating <- html_text(rating)
storyline <- html_text(storyline)
print(title_contents)
print(rating)
print(storyline)
df <- cbind(title_contents,rating,storyline)
}

df <- data.frame(df)

The output will only have the fourth one which is enter image description here

How can I save all the output of for loop to the same column such as

    C1      C2      C3
R1  title1  rating1 storyline1
R2  title2  rating2 storyline2
R3  title3  rating3 storyline3
R4  title4  rating4 storyline4

Body:
The issue is you are overwriting the previous results thus you are getting result for only last one(fourth).

Create an empty vector df1 and store the results of each loop in it.

Grid <- c("tt6483832/","tt5164196/","tt4052886/","tt1826940/")
BaseURL <- "http://www.imdb.com/title/"

df1 = c()

for (i in 1:4){

  FullURL <-paste(BaseURL,Grid[i], sep="")

  title_contents <- FullURL %>% read_html() %>% html_nodes('.dxSWFG') %>% html_text()

  rating <- FullURL %>% read_html() %>% html_nodes('.iTLWoV') %>% html_text()
  rating = rating[1]

  storyline <- FullURL %>% read_html() %>% html_nodes('.eqlIrG') %>% html_text()

  df <- cbind(title_contents,rating,storyline)

  df1 = rbind(df, df1)
}

df1 <- data.frame(df1)


问:
How to achieve the following? C++ "advanced" map/list/array?
I am trying to create some sort of list, map or what ever may be suggested that does the following

```<code>something [] = {
        mainvalue1 = 2001 {
            value2 = 1905
            value3 = 2000
            result = 500

            value2 = 1910
            value3 = 2030
            result = 700
        }
        mainvalue2 = 2005 {
            value2 = 1635
            value3 = 2070
            result = 300

            value2 = 2310
            value3 = 5930
            result = 599
        }
}
</code>```

cout << "result: " << something[2001][1905][2000] << endl;

result: 500

cout << "result: " something[2001][1910][2030] << endl;

result: 700

cout << "result: " something[2005][2310][5930] << endl;

result: 599

Is this possible? I would appreciate if someone could guide me how to start my thought process or give me an example how this can be achievable in C++

答:
Use data-only structs or std::tuple for that kind of thing:
Tuple example:

```<code>std::vector<std::tuple<int, int, int>> dataVectorName;
</code>```

Struct example:

```<code>struct MyData
{
 int a;
 int b;
 int c;
 }
std::vector<MyData> dataVectorName;
</code>```

I always use and recommend std::tuple for data array. In such cases it is faster but does not seem user friendly. And to solve that problem, you can fake variables with typedef or using. And it's easy for nested datas.

Body:
I am trying to create some sort of list, map or what ever may be suggested that does the following

something [] = {
        mainvalue1 = 2001 {
            value2 = 1905
            value3 = 2000
            result = 500

            value2 = 1910
            value3 = 2030
            result = 700
        }
        mainvalue2 = 2005 {
            value2 = 1635
            value3 = 2070
            result = 300

            value2 = 2310
            value3 = 5930
            result = 599
        }
}

cout << "result: " << something[2001][1905][2000] << endl;

result: 500

cout << "result: " something[2001][1910][2030] << endl;

result: 700

cout << "result: " something[2005][2310][5930] << endl;

result: 599

Is this possible? I would appreciate if someone could guide me how to start my thought process or give me an example how this can be achievable in C++

Body:
Use data-only structs or std::tuple for that kind of thing:
Tuple example:

std::vector<std::tuple<int, int, int>> dataVectorName;

Struct example:

struct MyData
{
 int a;
 int b;
 int c;
 }
std::vector<MyData> dataVectorName;

I always use and recommend std::tuple for data array. In such cases it is faster but does not seem user friendly. And to solve that problem, you can fake variables with typedef or using. And it's easy for nested datas.


问:
Change values in np array Python
I am trying to change the value in np array if there is a match

For example, a np array a and its shape is (50,4)

```<code>a.shape#(50,4)
</code>```

I need to check if the np array a has this value [0,1,20,4] in the 1st axis, then I need to change that into [-1,-1,-1,-1].

I tried this format -

```<code>a[a==[0,1,20,4]]=[-1,-1,-1,-1]
</code>```

But, this is not working,

How to do this modification?

答:
This solves it for random array of shape (50,4)

```<code>b = np.random.randint(5,size=(50,4))
c = np.equal(b,[4,1,2,3])
ai = np.array(c.all(axis=1).nonzero())
np.put_along_axis(b,ai,[-1,-1,-1,-1],axis=0)
</code>```

change [4,1,2,3] to [0,1,20,4]

Title: Change values in np array Python

Body:
I am trying to change the value in np array if there is a match

For example, a np array a and its shape is (50,4)

a.shape#(50,4)

I need to check if the np array a has this value [0,1,20,4] in the 1st axis, then I need to change that into [-1,-1,-1,-1].

I tried this format -

a[a==[0,1,20,4]]=[-1,-1,-1,-1]

But, this is not working,

How to do this modification?

Body:
This solves it for random array of shape (50,4)

b = np.random.randint(5,size=(50,4))
c = np.equal(b,[4,1,2,3])
ai = np.array(c.all(axis=1).nonzero())
np.put_along_axis(b,ai,[-1,-1,-1,-1],axis=0)

change [4,1,2,3] to [0,1,20,4]


问:
Find and copy numbered paragraphs into individual cells in Excel
I want to copy numbered paragraphs from Word to Excel.

I want to copy below paragraphs into individual cells in Excel

heading

this is paragraph

heading 2

this is paragraph

heading 3

this is paragraph

this is itself a paragraph

I am able to count the number of numbered items via below function but stuck in copy and break till another numbered item.

count_observations = ActiveDocument.Content.ListFormat.CountNumberedItems(Level:=1)
```

答:
Thanks, I finaly figured it out by researching and searching the other posts. here's the below solution i've come up with.</p>
```<code>Sub AutoDatabase()

excel_path = "D:/test.xlm"

Dim obs_range1 As Word.Range
Dim obs_range2 As Word.Range
Dim response_range1 As Word.Range
Dim response_range2 As Word.Range

Dim obs As String
Dim response As String
Dim Z As Integer

Set obs_range1 = ActiveDocument.Range
Set obs_range2 = ActiveDocument.Range
Set response_range1 = ActiveDocument.Range
Set response_range2 = ActiveDocument.Range

x = ActiveDocument.Content.ListFormat _
    .CountNumberedItems(Level:=1)

For y = 1 To x

    If obs_range1.Find.Execute(FindText:="CopyThis") Then
        Set obs_range2 = ActiveDocument.Range(obs_range1.End, ActiveDocument.Range.End)
        If obs_range2.Find.Execute(FindText:="CopyThis") Then
            obs = ActiveDocument.Range(obs_range1.End, obs_range2.Start).Text

    If response_range1.Find.Execute(FindText:="Branch Comments") Then
        Set response_range2 = ActiveDocument.Range(response_range1.End, ActiveDocument.Range.End)
        If response_range2.Find.Execute(FindText:="CopyThis") Then
            response = ActiveDocument.Range(response_range1.End, response_range2.Start).Text
        'MsgBox (response)

    With ActiveDocument.Tables(1).Rows.Add
        With ActiveDocument.Tables(1).Cell(y, 1).Range
        .Text = obs
        End With
        With ActiveDocument.Tables(1).Cell(y, 2).Range
        .Text = response
        End With
    End With

        End If
        End If
    End If
    End If
    'MsgBox (obs)
Next y

' Remove ^p from table(1)
With ActiveDocument.Tables(1).Range
    .Find.Execute FindText:="^p", ReplaceWith:="", Replace:=wdReplaceAll
End With

End Sub
</code>```

Body:
Thanks, I finaly figured it out by researching and searching the other posts. here's the below solution i've come up with.

Sub AutoDatabase()

excel_path = "D:/test.xlm"

Dim obs_range1 As Word.Range
Dim obs_range2 As Word.Range
Dim response_range1 As Word.Range
Dim response_range2 As Word.Range

Dim obs As String
Dim response As String
Dim Z As Integer

Set obs_range1 = ActiveDocument.Range
Set obs_range2 = ActiveDocument.Range
Set response_range1 = ActiveDocument.Range
Set response_range2 = ActiveDocument.Range

x = ActiveDocument.Content.ListFormat _
    .CountNumberedItems(Level:=1)

For y = 1 To x

    If obs_range1.Find.Execute(FindText:="CopyThis") Then
        Set obs_range2 = ActiveDocument.Range(obs_range1.End, ActiveDocument.Range.End)
        If obs_range2.Find.Execute(FindText:="CopyThis") Then
            obs = ActiveDocument.Range(obs_range1.End, obs_range2.Start).Text

    If response_range1.Find.Execute(FindText:="Branch Comments") Then
        Set response_range2 = ActiveDocument.Range(response_range1.End, ActiveDocument.Range.End)
        If response_range2.Find.Execute(FindText:="CopyThis") Then
            response = ActiveDocument.Range(response_range1.End, response_range2.Start).Text
        'MsgBox (response)

    With ActiveDocument.Tables(1).Rows.Add
        With ActiveDocument.Tables(1).Cell(y, 1).Range
        .Text = obs
        End With
        With ActiveDocument.Tables(1).Cell(y, 2).Range
        .Text = response
        End With
    End With

        End If
        End If
    End If
    End If
    'MsgBox (obs)
Next y

' Remove ^p from table(1)
With ActiveDocument.Tables(1).Range
    .Find.Execute FindText:="^p", ReplaceWith:="", Replace:=wdReplaceAll
End With

End Sub


问:
how do I make a slideshow that has an animation
I'm trying to make a category and I want to make it as a slider so I want once the user click on any category it goes to the left and become bigger,
here is a link how the slide works : slideshow

答:
you want to add onClick event to all Categories

you already has array of categories

if not, you need to store all categories in array

and when user click on category you want to make [circular shift] for array
and then re-render it.

circular shift


问:
intermittent uninitialized constant error in ruby
In one of my application, there are three tabs and when any of the tab is pressed, it shows some information by making a post call to corresponding service.

The controller for tab1 is as follows (Only small part is shown)

```<code>def tab1_results
  response = tab1_service_wrapper.get_tab1_result(params)
</code>```

The controller for tab2 is as follows

```<code>def tab2_results
  search_params = JSON.parse(params[:searchParams])
  response = tab2_service_wrapper.get_tab2_result(search_params)
</code>```

In each of the service wrappers we convert the input provided into JSON format and make a call to the respective services.

But recently I have observed that pressing tab1 repeatedly triggers the following error.

```<code>uninitialized constant ServiceInitializerModule::Tab1ServiceWrapper
</code>```

This is observed only sometimes with tab1. This is not the case with tab2.

My question is can passing params directly to downstream be the cause for this issue?

答: The issue is not related to the above. I was missing the require statement of Tab1ServiceWrapper. Adding the require statement fixed the issue.</p>

Body:
In one of my application, there are three tabs and when any of the tab is pressed, it shows some information by making a post call to corresponding service.

The controller for tab1 is as follows (Only small part is shown)

def tab1_results
  response = tab1_service_wrapper.get_tab1_result(params)

The controller for tab2 is as follows

def tab2_results
  search_params = JSON.parse(params[:searchParams])
  response = tab2_service_wrapper.get_tab2_result(search_params)

In each of the service wrappers we convert the input provided into JSON format and make a call to the respective services.

But recently I have observed that pressing tab1 repeatedly triggers the following error.

uninitialized constant ServiceInitializerModule::Tab1ServiceWrapper

This is observed only sometimes with tab1. This is not the case with tab2.

My question is can passing params directly to downstream be the cause for this issue?


问:
How to check out actions available in OpenAI gym environment?
It seems like the list of actions for Open AI Gym environments are not available to check out even in the documentation. For example, let's say you want to play Atari Breakout. The available actions will be right, left, up, and down.

print(env.action_space.n) If I print the number of actions available in action space, it prints 4 as I have expected.
However, what I want to see is the list of actions such as right, up, punch(maybe, boxing-v1), jump etc... you name it.

Is there any way to check out?

答:
It is possible by game where Artati environment had Descrete 18 numbers that you may read from

```<code>print(env.env.get_action_meanings())
print(env.action_space.n)
</code>```

Result:

```<code>A.L.E: Arcade Learning Environment (version +978d2ce)
[Powered by Stella]
['NOOP', 'FIRE', 'UP', 'RIGHT', 'LEFT', 'DOWN', 'UPRIGHT', 'UPLEFT', 'DOWNRIGHT', 'DOWNLEFT', 'UPFIRE', 'RIGHTFIRE', 'LEFTFIRE', 'DOWNFIRE', 'UPRIGHTFIRE', 'UPLEFTFIRE', 'DOWNRIGHTFIRE', 'DOWNLEFTFIRE']
Discrete(18)
</code>```

Body:
It is possible by game where Artati environment had Descrete 18 numbers that you may read from

print(env.env.get_action_meanings())
print(env.action_space.n)

Result:

A.L.E: Arcade Learning Environment (version +978d2ce)
[Powered by Stella]
['NOOP', 'FIRE', 'UP', 'RIGHT', 'LEFT', 'DOWN', 'UPRIGHT', 'UPLEFT', 'DOWNRIGHT', 'DOWNLEFT', 'UPFIRE', 'RIGHTFIRE', 'LEFTFIRE', 'DOWNFIRE', 'UPRIGHTFIRE', 'UPLEFTFIRE', 'DOWNRIGHTFIRE', 'DOWNLEFTFIRE']
Discrete(18)


问:
Behavior of the 'return' statement in Bash functions
I'm having trouble understanding the behavior of the return built-in in Bash. Here is a sample script.

```<code>#!/bin/bash

dostuff() {
    date | while true; do
        echo returning 0
        return 0
        echo really-notreached
    done

    echo notreached
    return 3
}

dostuff
echo returncode: $?
</code>```

The output of this script is:

```<code>returning 0
notreached
returncode: 3
</code>```

If, however, the date |  is removed from line 4, the output is as I expected:

```<code>returning 0
returncode: 0
</code>```

It seems like the return statement as used above is acting the way I thought the break statement ought to behave, but only when the loop is on the right hand side of a pipe. Why is this the case? I couldn't find anything to explain this behavior in the Bash man page or online. The script acts the same way in Bash 4.1.5 and Dash 0.5.5.

答:
In the date | while ... scenario, that while loop is executed in a subshell due to the presence of the pipe. Thus, the return statement breaks the loop and the subshell ends, leaving your function to carry on.

You'll have to reconstruct the code to remove the pipeline so that no subshells are created:

```<code>dostuff() {
    # redirect from a process substitution instead of a pipeline
    while true; do
        echo returning 0
        return 0
        echo really-notreached
    done < <(date)

    echo notreached
    return 3
}
</code>```

Body:
I'm having trouble understanding the behavior of the return built-in in Bash. Here is a sample script.

#!/bin/bash

dostuff() {
    date | while true; do
        echo returning 0
        return 0
        echo really-notreached
    done

    echo notreached
    return 3
}

dostuff
echo returncode: $?

The output of this script is:

returning 0
notreached
returncode: 3

If, however, the date |  is removed from line 4, the output is as I expected:

returning 0
returncode: 0

It seems like the return statement as used above is acting the way I thought the break statement ought to behave, but only when the loop is on the right hand side of a pipe. Why is this the case? I couldn't find anything to explain this behavior in the Bash man page or online. The script acts the same way in Bash 4.1.5 and Dash 0.5.5.

Body:
In the date | while ... scenario, that while loop is executed in a subshell due to the presence of the pipe. Thus, the return statement breaks the loop and the subshell ends, leaving your function to carry on.

You'll have to reconstruct the code to remove the pipeline so that no subshells are created:

dostuff() {
    # redirect from a process substitution instead of a pipeline
    while true; do
        echo returning 0
        return 0
        echo really-notreached
    done < <(date)

    echo notreached
    return 3
}

ContentLicense: CC BY-SA 3.0


问:
Create another Widget when OnTap() is triggered
Does anyone know how to generate a new widget in Flutter when OnTap() is triggered?

In my case, I want to create a new column inside a container, when the column icon is pressed.

The icon is wrapped with an InkWell().

InkWell(
  onTap: () {
    print("Create Column in another Container");
  },
  child: Column(
    children: const [
      Icon(
        Icons.view_agenda,
        color: iconGreyColor,
        size: 20.0,
      ),
    ],
  ),
),

```
<p>The Goal shut look like this.</p>
<pre class="lang-dart prettyprint-override"><code>    Container(child: Column(children:[]),)
</code>```

答:
Main part:

...widget.widgets -> spread operator .whenever ontap pressed.the array will get new element and set state will update the widget.

```<code>InkWell(
              onTap: () {
                setState(() {
                  widget.widgets.add(Container(
                    height: 49,
                    child: new Column(
                      children: [
                        Text(
                          "hi",
                          style: TextStyle(fontSize: 40),
                        )
                      ],
                    ),
                  ));
                });
                print("Create Column in another Container");
              },
              child: Column(
                children: const [
                  Icon(
                    Icons.view_agenda,
                    size: 20.0,
                  ),
                ],
              ),
            )
</code>```

```<code> Container(
        margin: EdgeInsets.only(
          left: 10.0,
          right: 10.0,
        ),
        height: MediaQuery.of(context).size.height - 150,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [...widget.widgets],
        ),
      )
</code>```

sample code

```<code>void main() => runApp(MyHomePage());

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Page0(),
    );
  }
}

class Page0 extends StatefulWidget {
  final widgets = [];

  @override
  _Page0State createState() => _Page0State();
}

class _Page0State extends State<Page0> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: [
          SizedBox(
            height: 25.0,
          ),
          Center(
              child: Text(
            "macintosh_app",
            style: TextStyle(fontSize: 48),
          )),
          SizedBox(
            height: 50.0,
          ),
          Center(
            child: InkWell(
              onTap: () {
                setState(() {
                  widget.widgets.add(Container(
                    height: 49,
                    child: new Column(
                      children: [
                        Text(
                          "hi",
                          style: TextStyle(fontSize: 40),
                        )
                      ],
                    ),
                  ));
                });
                print("Create Column in another Container");
              },
              child: Column(
                children: const [
                  Icon(
                    Icons.view_agenda,
                    size: 20.0,
                  ),
                ],
              ),
            ),
          ),
          SizedBox(
            height: 25.0,
          ),
          Container(
            margin: EdgeInsets.only(
              left: 10.0,
              right: 10.0,
            ),
            height: MediaQuery.of(context).size.height - 150,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [...widget.widgets],
            ),
          ),
        ],
      ),
    );
  }
}
</code>```

Body:
Does anyone know how to generate a new widget in Flutter when OnTap() is triggered?

In my case, I want to create a new column inside a container, when the column icon is pressed.

The icon is wrapped with an InkWell().

InkWell(
  onTap: () {
    print("Create Column in another Container");
  },
  child: Column(
    children: const [
      Icon(
        Icons.view_agenda,
        color: iconGreyColor,
        size: 20.0,
      ),
    ],
  ),
),

The Goal shut look like this.

    Container(child: Column(children:[]),)

Body:
Main part:

...widget.widgets -> spread operator .whenever ontap pressed.the array will get new element and set state will update the widget.

InkWell(
              onTap: () {
                setState(() {
                  widget.widgets.add(Container(
                    height: 49,
                    child: new Column(
                      children: [
                        Text(
                          "hi",
                          style: TextStyle(fontSize: 40),
                        )
                      ],
                    ),
                  ));
                });
                print("Create Column in another Container");
              },
              child: Column(
                children: const [
                  Icon(
                    Icons.view_agenda,
                    size: 20.0,
                  ),
                ],
              ),
            )

 Container(
        margin: EdgeInsets.only(
          left: 10.0,
          right: 10.0,
        ),
        height: MediaQuery.of(context).size.height - 150,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [...widget.widgets],
        ),
      )

sample code

void main() => runApp(MyHomePage());

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Page0(),
    );
  }
}

class Page0 extends StatefulWidget {
  final widgets = [];

  @override
  _Page0State createState() => _Page0State();
}

class _Page0State extends State<Page0> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: [
          SizedBox(
            height: 25.0,
          ),
          Center(
              child: Text(
            "macintosh_app",
            style: TextStyle(fontSize: 48),
          )),
          SizedBox(
            height: 50.0,
          ),
          Center(
            child: InkWell(
              onTap: () {
                setState(() {
                  widget.widgets.add(Container(
                    height: 49,
                    child: new Column(
                      children: [
                        Text(
                          "hi",
                          style: TextStyle(fontSize: 40),
                        )
                      ],
                    ),
                  ));
                });
                print("Create Column in another Container");
              },
              child: Column(
                children: const [
                  Icon(
                    Icons.view_agenda,
                    size: 20.0,
                  ),
                ],
              ),
            ),
          ),
          SizedBox(
            height: 25.0,
          ),
          Container(
            margin: EdgeInsets.only(
              left: 10.0,
              right: 10.0,
            ),
            height: MediaQuery.of(context).size.height - 150,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [...widget.widgets],
            ),
          ),
        ],
      ),
    );
  }
}


问:
How to import module from other directory in python
I have a file tree like this:

```<code>app
|---src
|    |---vlep/config.py
|
|---tests
     |---conftest.py
</code>```

from conftest.py I am trying to import vlep.confi as config and I am getting the ModulenotFoundError: No module named 'vlep'. I am using venv and I added absolute paths for app, src and vlep directories to venv/bin/activate, so when I activate the virtualenv I can have these directories in the PYTHONPATH env. I thought that this would do the job, but no...and have no idea why. What am I doing wrong?

答:
You can insert the path to the src folder in sys.path like this:

import os
import sys

sys.path.insert(0, f'{os.path.dirname(os.path.abspath(__file__))}/../src')

from vlep import config
```

This way the absolute path to your src directory will be first when Python resolves where to import the module from. And it also does not matter what directory you run conftest.py from.

Body:
I have a file tree like this:

app
|---src
|    |---vlep/config.py
|
|---tests
     |---conftest.py

from conftest.py I am trying to import vlep.confi as config and I am getting the ModulenotFoundError: No module named 'vlep'. I am using venv and I added absolute paths for app, src and vlep directories to venv/bin/activate, so when I activate the virtualenv I can have these directories in the PYTHONPATH env. I thought that this would do the job, but no...and have no idea why. What am I doing wrong?

Body:
You can insert the path to the src folder in sys.path like this:

import os
import sys

sys.path.insert(0, f'{os.path.dirname(os.path.abspath(__file__))}/../src')

from vlep import config

This way the absolute path to your src directory will be first when Python resolves where to import the module from. And it also does not matter what directory you run conftest.py from.


问:
when I try to run a flutter app it shows error : FAILURE: Build failed with an exception. full error shown below
Invalid depfile: C:\Users\bhard\AndroidStudioProjects\true_weather.dart_tool\flutter_build\54ec25ea3e00199f07d81cf92fc10210\kernel_snapshot.d
Invalid depfile: C:\Users\bhard\AndroidStudioProjects\true_weather.dart_tool\flutter_build\54ec25ea3e00199f07d81cf92fc10210\kernel_snapshot.d

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:checkDebugAarMetadata'.

Multiple task action failures occurred:
A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction
> The minCompileSdk (31) specified in a
dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
is greater than this module's compileSdkVersion (android-30).
Dependency: androidx.window:window-java:1.0.0-beta04.
AAR metadata file: C:\Users\bhard.gradle\caches\transforms-2\files-2.1\5695d8d932d545af38bf66b725566d02\jetified-window-java-1.0.0-beta04\META-INF\com\android\build\gradle\aar-metadata.properties.
A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction
> The minCompileSdk (31) specified in a
dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
is greater than this module's compileSdkVersion (android-30).
Dependency: androidx.window:window:1.0.0-beta04.
AAR metadata file: C:\Users\bhard.gradle\caches\transforms-2\files-2.1\e4e324fde2799cc82a9b6d2e3e16efc2\jetified-window-1.0.0-beta04\META-INF\com\android\build\gradle\aar-metadata.properties.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 42s
Exception: Gradle task assembleDebug failed with exit code 1

答:
Go to app-level build.gradle file.

Change

compileSdkVersion to 31

targetSdkVersion 31


问:
can't compare password and confirm password strings and show a error message
hi I am new to react components, i cant pass a function with 2 values and compare the 2 password strings and show the error message. I could only get the error message from the first password text and no result from the 2nd confirm password error message.
i am hoping to get help in this.

thanks in advance!

import React, { useState } from "react";
import { View,Text ,StyleSheet, TouchableOpacity, TextInput, Keyboard, TouchableWithoutFeedback} from "react-native";
import { ScrollView } from "react-native-gesture-handler";

const SignUpPage= ({navigation}) => {
    const [email, setEmail] = useState('');
    const [emailValidError, setEmailValidError] = useState('');
    const [password, setPassword] = useState("")
    const [passwordErrorMessaage, setPasswordErrorMessage] = useState("")
    const [passwordConfirm, setConfirmPassword] = useState("")
    const [confirmPasswordErrorMessaage, setConfirmPasswordErrorMessage] = useState("")

    const handlePasswordError =(password,passwordConfirm) => {

        if (password.length === 0) {
          setPasswordErrorMessage('enter the password');
        } else if (password.length > 8 || password.length<20) {
          setPasswordErrorMessage('Min character 8 & maximum 20');
        } else if (password.length < 8 || password.length>20) {
            setPasswordErrorMessage('');
        }else if (password !== passwordConfirm) {
          setConfirmPasswordErrorMessage('The entered passwords doesnt match');
        } else if (passwordConfirm.length ==0){
         setConfirmPasswordErrorMessage('Fill all required fields');
        } else if (password === passwordConfirm) {
            setConfirmPasswordErrorMessage("")
        }

        };

    const handleValidEmail = val => {
        let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w\w+)+$/;
        if (val.length === 0) {
          setEmailValidError('email address must be enter');
        } else if (reg.test(val) === false) {
          setEmailValidError('enter valid email address');
        } else if (reg.test(val) === true) {
          setEmailValidError('');
        }
        };

    return (
        <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
        <ScrollView style={styles.cont}>
            <View style={styles.container}>
            <Text style={styles.welcome}>Sign Up to my app</Text>
            <TextInput  style={styles.input}
            title='Email'
            placeholder="E-mail"
            onChangeText={value => {
            setEmail(value);
            handleValidEmail(value);
            }}>
            </TextInput>
            {emailValidError ? <Text>{emailValidError}</Text> : null}
            <TextInput style={styles.input}
            title='Password'
            placeholder="password"
            secureTextEntry
            onChangeText={value1 => {
            setPassword(value1);
            handlePasswordError(password,passwordConfirm);
            }} >
            </TextInput>
            {passwordErrorMessaage ? <Text>{passwordErrorMessaage}</Text> : null}
            <TextInput style={styles.input}
            title='Confirm Password'
            placeholder=" Confirm password"
            secureTextEntry
            onChangeText={value2 => {
                setConfirmPassword(value2);
                handlePasswordError(password,passwordConfirm);
                }} >
            </TextInput>
            {confirmPasswordErrorMessaage ? <Text>{confirmPasswordErrorMessaage}</Text> : null}
            <TextInput style={styles.input}  title='Educational Qualification' placeholder="Educational Qualification" ></TextInput>
            <TextInput style={styles.input}  title='Current Postion' placeholder="Current Postion" ></TextInput>
            <View style={styles.btncont}>
                <TouchableOpacity style={styles.Usrbtn} onPress={()=> alert('Sign Up Successfull')} >
                    <Text style={styles.Usrtxt}> Sign Up</Text>
                </TouchableOpacity>
                <TouchableOpacity style={styles.Usrbtn} onPress={()=>navigation.navigate('Login')}>
                    <Text style={styles.Usrtxt}> Login Page</Text>
                </TouchableOpacity>
            </View>
            </View>
            </ScrollView>
            </TouchableWithoutFeedback>
    )
}

const styles =StyleSheet.create({
    container:{
        flex:1,
        justifyContent:'center',
        alignItems:'center',
        backgroundColor: '#A83EE1',
    },
    welcome:{
        fontSize:30,
        textAlign: 'center',
        margin: 15,
        color:'#fff',
        fontFamily: 'DancingScript-Bold'
    },
    input:{
        width:'90%',
        backgroundColor: '#fff',
        padding: 15,
        marginBottom: 10,
    },
    Usrbtn:{
        backgroundColor: "#FFD7FF",
        padding:15,
        width:"45%"
    },
    Usrtxt:{
        fontSize:18,
        textAlign:'center'
    },
    btncont:{
        flexDirection:'row',
        justifyContent:'space-between',
        width:"90%"
    },
    textDanger: {
        color: "#dc3545"
    },
    cont:{
        flex:1,
        backgroundColor: '#A83EE1'
    }
});

export default SignUpPage;```

答:
Once the state is being set the component will rerender so once you have one of the if's satisfied its not getting to last else if.

So once the password.length is being satisfied the state is being set and the else if doesn't come into play.

Maybe try a condition if the passwordconfirm is "" then review the password - if its not then continue on to the next part.

```<code>   const handlePasswordError =(password,passwordConfirm) => {

if(passwordConfirm === ""){

        if (password.length === 0) {
          setPasswordErrorMessage('enter the password');
        } else if (password.length > 8 || password.length<20) {
          setPasswordErrorMessage('Min character 8 & maximum 20');
        } else if (password.length < 8 || password.length>20) {
            setPasswordErrorMessage('');
        }
} else {
if (password !== passwordConfirm) {
          setConfirmPasswordErrorMessage('The entered passwords doesnt match');
        } else if (passwordConfirm.length ==0){
         setConfirmPasswordErrorMessage('Fill all required fields');
        } else if (password === passwordConfirm) {
            setConfirmPasswordErrorMessage("")
        }
}
</code>```

or something like that so the if statement considers the passwordconfirm before it stops at the password length

Body:
Once the state is being set the component will rerender so once you have one of the if's satisfied its not getting to last else if.

So once the password.length is being satisfied the state is being set and the else if doesn't come into play.

Maybe try a condition if the passwordconfirm is "" then review the password - if its not then continue on to the next part.

   const handlePasswordError =(password,passwordConfirm) => {

if(passwordConfirm === ""){

        if (password.length === 0) {
          setPasswordErrorMessage('enter the password');
        } else if (password.length > 8 || password.length<20) {
          setPasswordErrorMessage('Min character 8 & maximum 20');
        } else if (password.length < 8 || password.length>20) {
            setPasswordErrorMessage('');
        }
} else {
if (password !== passwordConfirm) {
          setConfirmPasswordErrorMessage('The entered passwords doesnt match');
        } else if (passwordConfirm.length ==0){
         setConfirmPasswordErrorMessage('Fill all required fields');
        } else if (password === passwordConfirm) {
            setConfirmPasswordErrorMessage("")
        }
}

or something like that so the if statement considers the passwordconfirm before it stops at the password length


问:
ansible cannot access key from included task
I have a playbook to connect to a network device and parse the interfaces. Genie gives me a nice JSON from the command output:

- name: "Reading interfaces from ASA and update Netbox"
  connection: ansible.netcommon.network_cli
  gather_facts: false
  hosts: vm

  tasks:
    - name: Include Parse Genie Role
      include_role:
        name: clay584.parse_genie

    - name: Gather facts (asa)
      cisco.asa.asa_command:
        commands:
          - show interface summary
      register: asa_int

    - name: Set asa facts
      set_fact:
         interface_items: "{{ asa_int['stdout'][0] | parse_genie(command='show interface summary', os='asa') }}"

- name: Populate NetBox DataBase with asa interfaces
  connection: local
  hosts: localhost
  gather_facts: False
  vars:
    ansible_python_interpreter: /usr/bin/python3
    ansible_connection: local

  tasks:
    - name: netbox interfaces
      include_tasks: vm-interface_nb.yml
      loop: "{{ hostvars['localhost']['groups']['vm']|flatten(levels=1) }}"
      loop_control:
         loop_var: host
```
<p>In this last task I am looping thru the devices and include another task to actually update my inventory DB by looping thru the dict of interfaces.</p>
<pre class="lang-yaml prettyprint-override"><code>- name: update asa interface in netbox
  netbox.netbox.netbox_vm_interface:
    netbox_url: 'https://blabla'
    netbox_token: '111111111111111111111111111111'
    validate_certs: False
    data:
      virtual_machine: "{{ host| from_json }}"
      name: "{{ item| from_json }}"
      mtu: "{{ hostvars[host]['interface_items']['interfaces'][item]['mtu'] | default(omit) }}"
      mac_address: "{{ hostvars[host]['interface_items']['interfaces'][item]['mac_address'] | default(omit) }}"
      enabled: "{{ hostvars[host]['interface_items']['interfaces'][item]['config_status'] | default(omit) }}"
      description: "{{ hostvars[host]['interface_items']['interfaces'][item]['name'] | default(omit) }}"
    state: present
  loop: "{{ hostvars[host]['interface_items']['interfaces']|flatten(levels=1) }}"
```yaml

The host and the item variable work fine in the loop statement and when I assign the values.
Except for those two lines:
```yaml
      virtual_machine: "{{ host| from_json }}"
      name: "{{ item| from_json }}"
</code>```

I have also tried:

      virtual_machine: host
      name: item
```
<p>But I see in the verbose output that the item/host variable from the first loop is ok(item=batman1-admin) as well as the item variable from the 2nd loop (item=Management0/0). But in the API call I just see 'host' and 'item' as string, not as value:</p>
<pre class="lang-none prettyprint-override"><code>TASK [netbox interfaces] ***************************************************************************************
included: /home/lulli/vm-interface_nb.yml for localhost => (item=batman1-admin)

TASK [update asa interface in netbox] **************************************************************************************
failed: [localhost] (item=Management0/0) => {
    "ansible_loop_var": "item",
    "changed": false,
    "invocation": {
        "module_args": {
            "cert": null,
            "data": {
                "custom_fields": null,
                "description": "management",
                "enabled": true,
                "mac_address": "a00e.3000.0010",
                "mode": null,
                "mtu": 1500,
                "name": "item",
                "parent_vm_interface": null,
                "tagged_vlans": null,
                "tags": null,
                "untagged_vlan": null,
                "virtual_machine": "host"
            },
            "netbox_token": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
            "netbox_url": "https://1.1.1.1",
            "query_params": null,
            "state": "present",
            "validate_certs": false
        }
    },
    "item": "Management0/0",
}
</code>```

And I have tried

      virtual_machine: host.key
      name: item.key
```
<p>But throws an error that <code>'str object' has no attribute 'key'</code></p>
<p>Those two attempts did not work either as I get a "Expecting value" error:</p>
<pre class="lang-yaml prettyprint-override"><code>      virtual_machine: "{{ host.key }}"
      name: "{{ item.key }}"

      virtual_machine: "{{ host }}"
      name: "{{ item }}"
</code>```

If I include a debug task in the 2nd file to print the host variable I get this error

 debug:
   var: "{{ host }}"
```
<blockquote>
<p>"template error while templating string: expected token 'end of print statement', got 'integer'. String: {{batman1-admin}}"</p>
</blockquote>
<p>When I remove the brackets from the debug it looks like a dict, but it is not as I cannot access the key or value.</p>
<pre class="lang-yaml prettyprint-override"><code> debug:
   var: host
</code>```

ok: [localhost] => {
    "host": "batman1-admin"
}
```

答:
There are two problems I see with your code: you seem to be calling from_json in places where it shouldn't be necessary, which I think may be the source of your problem, and you also seem to be calling flatten where it shouldn't be necessary (I don't think that's a problem, but it suggests that either I'm wrong about what your data looks like or you've got a more general problem with unnecessary filters in your expressions).

You haven't provided a runnable example that reproduces the problem, which makes it a little hard to diagnose, so I've tried to put together something that I think reflects what you're trying to do.

If I start with this dummy inventory file:

all:
  vars:
    ansible_host: localhost
  children:
    vm:
      hosts:
        host0:
          interface_items:
            interfaces:
              eth0:
                mtu: 1500
                name: uplink
        host1:
          interface_items:
            interfaces:
              eth0:
                mtu: 1500
                name: storage
```
<p>And apply that to this playbook:</p>
<pre class="lang-yaml prettyprint-override"><code>- hosts: localhost
  gather_facts: false
  tasks:
    - name: netbox interfaces
      include_tasks: vm-interface-nb.yml
      loop: "{{ groups.vm }}"
      loop_control:
        loop_var: host
</code>```

And this vm-interface-nb.yml task, in which I've wrapped your call
to netbox.netbox.netbox_vm_interface in a debug task:

- name: update asa interface in netbox
  debug:
    msg:
      netbox.netbox.netbox_vm_interface:
        netbox_url: 'https://blabla'
        netbox_token: '111111111111111111111111111111'
        validate_certs: false
        data:
          virtual_machine: "{{ host|from_json }}"
          name: "{{ item|from_json }}"
          mtu: "{{ hostvars[host]['interface_items']['interfaces'][item]['mtu'] | default(omit) }}"
          mac_address: "{{ hostvars[host]['interface_items']['interfaces'][item]['mac_address'] | default(omit) }}"
          enabled: "{{ hostvars[host]['interface_items']['interfaces'][item]['config_status'] | default(omit) }}"
          description: "{{ hostvars[host]['interface_items']['interfaces'][item]['name'] | default(omit) }}"
        state: present
  loop: "{{ hostvars[host]['interface_items']['interfaces']|flatten(levels=1) }}"
```
<p>And then run it like this:</p>
<pre class="lang-none prettyprint-override"><code>ansible-playbook -i hosts.yml playbook.yml
</code>```

It will fail with this error:

fatal: [localhost]: FAILED! => {"msg": "the field 'args' has an invalid value ({'msg': {'netbox.netbox.netbox_vm_interface': {'netbox_url': 'https://blabla', 'netbox_token': '111111111111111111111111111111', 'validate_certs': False, 'data': {'virtual_machine': '{{ host|from_json }}', 'name': '{{ item|from_json }}', 'mtu': "{{ hostvars[host]['interface_items']['interfaces'][item]['mtu'] | default(omit) }}", 'mac_address': "{{ hostvars[host]['interface_items']['interfaces'][item]['mac_address'] | default(omit) }}", 'enabled': "{{ hostvars[host]['interface_items']['interfaces'][item]['config_status'] | default(omit) }}", 'description': "{{ hostvars[host]['interface_items']['interfaces'][item]['name'] | default(omit) }}"}, 'state': 'present'}}}), and could not be converted to an dict.The error was: Expecting value: line 1 column 1 (char 0)\n\nThe error appears to be in '/home/lars/tmp/ansible/vm-interface-nb.yml': line 1, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: update asa interface in netbox\n  ^ here\n"}

The problem with the above is that -- at least in my model -- both
host and item are simple strings, not JSON representations of a
more complex data structure, and can't meaningfully be passed to
from_json.

If I remove the from_json filters from that task (and flatten,
which at least in this case is a no-op ):

- name: update asa interface in netbox
  debug:
    msg:
      netbox.netbox.netbox_vm_interface:
        netbox_url: 'https://blabla'
        netbox_token: '111111111111111111111111111111'
        validate_certs: false
        data:
          virtual_machine: "{{ host }}"
          name: "{{ item }}"
          mtu: "{{ hostvars[host]['interface_items']['interfaces'][item]['mtu'] | default(omit) }}"
          mac_address: "{{ hostvars[host]['interface_items']['interfaces'][item]['mac_address'] | default(omit) }}"
          enabled: "{{ hostvars[host]['interface_items']['interfaces'][item]['config_status'] | default(omit) }}"
          description: "{{ hostvars[host]['interface_items']['interfaces'][item]['name'] | default(omit) }}"
        state: present
  loop: "{{ hostvars[host]['interface_items']['interfaces'] }}"
```
<p>And run it again, it seems to work as expected:</p>
<pre class="lang-none prettyprint-override"><code>PLAY [localhost] ***************************************************************

TASK [netbox interfaces] *******************************************************
included: /home/lars/tmp/ansible/vm-interface-nb.yml for localhost => (item=host0)
included: /home/lars/tmp/ansible/vm-interface-nb.yml for localhost => (item=host1)

TASK [update asa interface in netbox] ******************************************
ok: [localhost] => (item=eth0) => {
    "msg": {
        "netbox.netbox.netbox_vm_interface": {
            "data": {
                "description": "uplink",
                "mtu": "1500",
                "name": "eth0",
                "virtual_machine": "host0"
            },
            "netbox_token": "111111111111111111111111111111",
            "netbox_url": "https://blabla",
            "state": "present",
            "validate_certs": false
        }
    }
}

TASK [update asa interface in netbox] ******************************************
ok: [localhost] => (item=eth0) => {
    "msg": {
        "netbox.netbox.netbox_vm_interface": {
            "data": {
                "description": "storage",
                "mtu": "1500",
                "name": "eth0",
                "virtual_machine": "host1"
            },
            "netbox_token": "111111111111111111111111111111",
            "netbox_url": "https://blabla",
            "state": "present",
            "validate_certs": false
        }
    }
}

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

</code>```

If I've made mistakes in inferring the format of your input data,
please feel free to update your question to show some explicit
examples and I would be happy to revisit this answer.

Body:
I have a playbook to connect to a network device and parse the interfaces. Genie gives me a nice JSON from the command output:

- name: "Reading interfaces from ASA and update Netbox"
  connection: ansible.netcommon.network_cli
  gather_facts: false
  hosts: vm

  tasks:
    - name: Include Parse Genie Role
      include_role:
        name: clay584.parse_genie

    - name: Gather facts (asa)
      cisco.asa.asa_command:
        commands:
          - show interface summary
      register: asa_int

    - name: Set asa facts
      set_fact:
         interface_items: "{{ asa_int['stdout'][0] | parse_genie(command='show interface summary', os='asa') }}"

- name: Populate NetBox DataBase with asa interfaces
  connection: local
  hosts: localhost
  gather_facts: False
  vars:
    ansible_python_interpreter: /usr/bin/python3
    ansible_connection: local

  tasks:
    - name: netbox interfaces
      include_tasks: vm-interface_nb.yml
      loop: "{{ hostvars['localhost']['groups']['vm']|flatten(levels=1) }}"
      loop_control:
         loop_var: host

In this last task I am looping thru the devices and include another task to actually update my inventory DB by looping thru the dict of interfaces.

- name: update asa interface in netbox
  netbox.netbox.netbox_vm_interface:
    netbox_url: 'https://blabla'
    netbox_token: '111111111111111111111111111111'
    validate_certs: False
    data:
      virtual_machine: "{{ host| from_json }}"
      name: "{{ item| from_json }}"
      mtu: "{{ hostvars[host]['interface_items']['interfaces'][item]['mtu'] | default(omit) }}"
      mac_address: "{{ hostvars[host]['interface_items']['interfaces'][item]['mac_address'] | default(omit) }}"
      enabled: "{{ hostvars[host]['interface_items']['interfaces'][item]['config_status'] | default(omit) }}"
      description: "{{ hostvars[host]['interface_items']['interfaces'][item]['name'] | default(omit) }}"
    state: present
  loop: "{{ hostvars[host]['interface_items']['interfaces']|flatten(levels=1) }}"
```yaml

The host and the item variable work fine in the loop statement and when I assign the values.
Except for those two lines:
```yaml
      virtual_machine: "{{ host| from_json }}"
      name: "{{ item| from_json }}"

I have also tried:

      virtual_machine: host
      name: item

But I see in the verbose output that the item/host variable from the first loop is ok(item=batman1-admin) as well as the item variable from the 2nd loop (item=Management0/0). But in the API call I just see 'host' and 'item' as string, not as value:

TASK [netbox interfaces] ***************************************************************************************
included: /home/lulli/vm-interface_nb.yml for localhost => (item=batman1-admin)

TASK [update asa interface in netbox] **************************************************************************************
failed: [localhost] (item=Management0/0) => {
    "ansible_loop_var": "item",
    "changed": false,
    "invocation": {
        "module_args": {
            "cert": null,
            "data": {
                "custom_fields": null,
                "description": "management",
                "enabled": true,
                "mac_address": "a00e.3000.0010",
                "mode": null,
                "mtu": 1500,
                "name": "item",
                "parent_vm_interface": null,
                "tagged_vlans": null,
                "tags": null,
                "untagged_vlan": null,
                "virtual_machine": "host"
            },
            "netbox_token": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
            "netbox_url": "https://1.1.1.1",
            "query_params": null,
            "state": "present",
            "validate_certs": false
        }
    },
    "item": "Management0/0",
}

And I have tried

      virtual_machine: host.key
      name: item.key

But throws an error that 'str object' has no attribute 'key'

Those two attempts did not work either as I get a "Expecting value" error:

      virtual_machine: "{{ host.key }}"
      name: "{{ item.key }}"

      virtual_machine: "{{ host }}"
      name: "{{ item }}"

If I include a debug task in the 2nd file to print the host variable I get this error

 debug:
   var: "{{ host }}"

"template error while templating string: expected token 'end of print statement', got 'integer'. String: {{batman1-admin}}"

When I remove the brackets from the debug it looks like a dict, but it is not as I cannot access the key or value.

 debug:
   var: host

ok: [localhost] => {
    "host": "batman1-admin"
}

Body:
There are two problems I see with your code: you seem to be calling from_json in places where it shouldn't be necessary, which I think may be the source of your problem, and you also seem to be calling flatten where it shouldn't be necessary (I don't think that's a problem, but it suggests that either I'm wrong about what your data looks like or you've got a more general problem with unnecessary filters in your expressions).

You haven't provided a runnable example that reproduces the problem, which makes it a little hard to diagnose, so I've tried to put together something that I think reflects what you're trying to do.

If I start with this dummy inventory file:

all:
  vars:
    ansible_host: localhost
  children:
    vm:
      hosts:
        host0:
          interface_items:
            interfaces:
              eth0:
                mtu: 1500
                name: uplink
        host1:
          interface_items:
            interfaces:
              eth0:
                mtu: 1500
                name: storage

And apply that to this playbook:

- hosts: localhost
  gather_facts: false
  tasks:
    - name: netbox interfaces
      include_tasks: vm-interface-nb.yml
      loop: "{{ groups.vm }}"
      loop_control:
        loop_var: host

And this vm-interface-nb.yml task, in which I've wrapped your call
to netbox.netbox.netbox_vm_interface in a debug task:

- name: update asa interface in netbox
  debug:
    msg:
      netbox.netbox.netbox_vm_interface:
        netbox_url: 'https://blabla'
        netbox_token: '111111111111111111111111111111'
        validate_certs: false
        data:
          virtual_machine: "{{ host|from_json }}"
          name: "{{ item|from_json }}"
          mtu: "{{ hostvars[host]['interface_items']['interfaces'][item]['mtu'] | default(omit) }}"
          mac_address: "{{ hostvars[host]['interface_items']['interfaces'][item]['mac_address'] | default(omit) }}"
          enabled: "{{ hostvars[host]['interface_items']['interfaces'][item]['config_status'] | default(omit) }}"
          description: "{{ hostvars[host]['interface_items']['interfaces'][item]['name'] | default(omit) }}"
        state: present
  loop: "{{ hostvars[host]['interface_items']['interfaces']|flatten(levels=1) }}"

And then run it like this:

ansible-playbook -i hosts.yml playbook.yml

It will fail with this error:

fatal: [localhost]: FAILED! => {"msg": "the field 'args' has an invalid value ({'msg': {'netbox.netbox.netbox_vm_interface': {'netbox_url': 'https://blabla', 'netbox_token': '111111111111111111111111111111', 'validate_certs': False, 'data': {'virtual_machine': '{{ host|from_json }}', 'name': '{{ item|from_json }}', 'mtu': "{{ hostvars[host]['interface_items']['interfaces'][item]['mtu'] | default(omit) }}", 'mac_address': "{{ hostvars[host]['interface_items']['interfaces'][item]['mac_address'] | default(omit) }}", 'enabled': "{{ hostvars[host]['interface_items']['interfaces'][item]['config_status'] | default(omit) }}", 'description': "{{ hostvars[host]['interface_items']['interfaces'][item]['name'] | default(omit) }}"}, 'state': 'present'}}}), and could not be converted to an dict.The error was: Expecting value: line 1 column 1 (char 0)\n\nThe error appears to be in '/home/lars/tmp/ansible/vm-interface-nb.yml': line 1, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: update asa interface in netbox\n  ^ here\n"}

The problem with the above is that -- at least in my model -- both
host and item are simple strings, not JSON representations of a
more complex data structure, and can't meaningfully be passed to
from_json.

If I remove the from_json filters from that task (and flatten,
which at least in this case is a no-op ):

- name: update asa interface in netbox
  debug:
    msg:
      netbox.netbox.netbox_vm_interface:
        netbox_url: 'https://blabla'
        netbox_token: '111111111111111111111111111111'
        validate_certs: false
        data:
          virtual_machine: "{{ host }}"
          name: "{{ item }}"
          mtu: "{{ hostvars[host]['interface_items']['interfaces'][item]['mtu'] | default(omit) }}"
          mac_address: "{{ hostvars[host]['interface_items']['interfaces'][item]['mac_address'] | default(omit) }}"
          enabled: "{{ hostvars[host]['interface_items']['interfaces'][item]['config_status'] | default(omit) }}"
          description: "{{ hostvars[host]['interface_items']['interfaces'][item]['name'] | default(omit) }}"
        state: present
  loop: "{{ hostvars[host]['interface_items']['interfaces'] }}"

And run it again, it seems to work as expected:

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

TASK [netbox interfaces] *******************************************************
included: /home/lars/tmp/ansible/vm-interface-nb.yml for localhost => (item=host0)
included: /home/lars/tmp/ansible/vm-interface-nb.yml for localhost => (item=host1)

TASK [update asa interface in netbox] ******************************************
ok: [localhost] => (item=eth0) => {
    "msg": {
        "netbox.netbox.netbox_vm_interface": {
            "data": {
                "description": "uplink",
                "mtu": "1500",
                "name": "eth0",
                "virtual_machine": "host0"
            },
            "netbox_token": "111111111111111111111111111111",
            "netbox_url": "https://blabla",
            "state": "present",
            "validate_certs": false
        }
    }
}

TASK [update asa interface in netbox] ******************************************
ok: [localhost] => (item=eth0) => {
    "msg": {
        "netbox.netbox.netbox_vm_interface": {
            "data": {
                "description": "storage",
                "mtu": "1500",
                "name": "eth0",
                "virtual_machine": "host1"
            },
            "netbox_token": "111111111111111111111111111111",
            "netbox_url": "https://blabla",
            "state": "present",
            "validate_certs": false
        }
    }
}

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

If I've made mistakes in inferring the format of your input data,
please feel free to update your question to show some explicit
examples and I would be happy to revisit this answer.


问:
How to sendkeys ctrl and Mouse wheel?
Use WebBrowser to browse folder paths.

And I want to make a zoom.

Really do this with the ctrl and mouse wheel.

I would like to do that with the code:

```<code>WebBrowser_Folder_Failes.Focus()
SendKeys.Send("^{+}")
</code>```

Unfortunately, I failed.

How to sendkeys ctrl and Mouse wheel?

答:
You can use this code.

```<code> [DllImport("user32.dll")]
        private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);
</code>```

It create method mouse_event in class. Then just use this method.

```<code>uint perSent = 10;
mouse_event(0x0800, 0,0,perSent ,0);//it will zoom 10 per sent
</code>```

If you want understand more, check this: https://www.pinvoke.net/default.aspx/user32.mouse_event
or just google mouseeventflags and use mouse_event.

Title: How to sendkeys ctrl and Mouse wheel?

Body:
Use WebBrowser to browse folder paths.

And I want to make a zoom.

Really do this with the ctrl and mouse wheel.

I would like to do that with the code:

WebBrowser_Folder_Failes.Focus()
SendKeys.Send("^{+}")

Unfortunately, I failed.

How to sendkeys ctrl and Mouse wheel?

Body:
You can use this code.

 [DllImport("user32.dll")]
        private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);

It create method mouse_event in class. Then just use this method.

uint perSent = 10;
mouse_event(0x0800, 0,0,perSent ,0);//it will zoom 10 per sent

If you want understand more, check this: https://www.pinvoke.net/default.aspx/user32.mouse_event
or just google mouseeventflags and use mouse_event.


问:
HMR's publicHost option not taken into account

For the background

I was writting a .NET Core 2.2/Angular 7 app for a while, with HMR set and working.
I wanted to profile that app using the Angular DevTools plugin and, to do so, needed to update to Angular 9.

The problem is, that broke my HMR config. HMR was activated and effectively reloading the page when a change was made (the diff even looked correct in DevTools), but was not reflected to the app.

I read that Angular 9 droped HMR support with ivy and was activated again on V11. So I updated to Angular 11 and still no HMR, it's now even totally broken, no more reloading, the sockjs-node calls are facing 404 errors.

Again, I read that HMR support was greatly improved on V12, so, again, I updated to V12 but without imrovement regarding HMR.

Implementation details

The angular app is served by .NET Core using spa.UseAngularCliServer(npmScript: "hmr"); (in developement). The app is split into 2 parts, one in ASP.NET MVC and the other is the actual Angular app, on a special virtual subfolder /app, captured using:

```<code>app.Map("/app", angular =>
{
    angular.UseHttpsRedirection();
    angular.UseSpaStaticFiles();
    angular.UseSpa(spa =>
    {
        spa.Options.SourcePath = "ClientApp";

        if (env.IsDevelopment())
        {
            spa.Options.StartupTimeout = TimeSpan.FromSeconds(120);
            spa.UseAngularCliServer(npmScript: "hmr");
        }
    });
});
</code>```

My HMR script is "hmr": "ng serve --configuration hmr" and the HMR configuration as follows:

```<code>"hmr": {
  "hmr": true,
  "browserTarget": "ClientApp:build:hmr",
  "publicHost": "https://localhost.com:44369/app",
  "servePath": "/"
}
</code>```

So, when sockjs tries to reach https://localhost.com:44369/sockjs-node/info?t=xxxxx

He is obviously not captured by .NET Core's Angular proxy and goes to the MVC app hence the 404 error;

HMR seems to ignore the publicHost options which wasn't the case with V7.

I've also tried the launch script "hmr": "ng serve --hmr" with the same result (how can hmr know the publicHost option in that case anyway?).

How can I set my publicHost option properly agiain?

Edit

As a workaround, I've tried to add an MVC action that catches the /sockjs-node/... requests and redirect them to /app/sockjs-node/..., but unfortunately that does not work for the websocket one...

Edit 2

Well well well... my mistake...

As sockjs is a pollyfill to websocket, even if websocket doesn't work, it will be emulated by another plain http method. So, even if the websocket connection fails, this method (while not perfect) works. See my answer.

答:
It looks like, unlike previously, Angular sends all websocket requests to the root.

The only workaround I've found for this issue until now is to use an MVC action to redirect all the /sockjs-node/... requests to their correct /app/sockjs-node/... form. This will not redirect the websocket call but sockjs will pollyfill it to http requests.

So, I've added this action in one of my controllers:

```<code>/// <summary>Redirects sockjs-node requests to the app subdirectory to fix HMR issues</summary>
[HttpGet("/sockjs-node/{**path}")]
[HttpPost("/sockjs-node/{**path}")]
public IActionResult AngularHmr(string path)
{
    return RedirectPermanentPreserveMethod("/app/sockjs-node/" + path);
}
</code>```

This solution is far from ideal, but this is only for developpement so it's not so much of a big deal...

Body:
For the background

I was writting a .NET Core 2.2/Angular 7 app for a while, with HMR set and working.
I wanted to profile that app using the Angular DevTools plugin and, to do so, needed to update to Angular 9.

The problem is, that broke my HMR config. HMR was activated and effectively reloading the page when a change was made (the diff even looked correct in DevTools), but was not reflected to the app.

I read that Angular 9 droped HMR support with ivy and was activated again on V11. So I updated to Angular 11 and still no HMR, it's now even totally broken, no more reloading, the sockjs-node calls are facing 404 errors.

Again, I read that HMR support was greatly improved on V12, so, again, I updated to V12 but without imrovement regarding HMR.

Implementation details

The angular app is served by .NET Core using spa.UseAngularCliServer(npmScript: "hmr"); (in developement). The app is split into 2 parts, one in ASP.NET MVC and the other is the actual Angular app, on a special virtual subfolder /app, captured using:

app.Map("/app", angular =>
{
    angular.UseHttpsRedirection();
    angular.UseSpaStaticFiles();
    angular.UseSpa(spa =>
    {
        spa.Options.SourcePath = "ClientApp";

        if (env.IsDevelopment())
        {
            spa.Options.StartupTimeout = TimeSpan.FromSeconds(120);
            spa.UseAngularCliServer(npmScript: "hmr");
        }
    });
});

My HMR script is "hmr": "ng serve --configuration hmr" and the HMR configuration as follows:

"hmr": {
  "hmr": true,
  "browserTarget": "ClientApp:build:hmr",
  "publicHost": "https://localhost.com:44369/app",
  "servePath": "/"
}

So, when sockjs tries to reach https://localhost.com:44369/sockjs-node/info?t=xxxxx

He is obviously not captured by .NET Core's Angular proxy and goes to the MVC app hence the 404 error;

HMR seems to ignore the publicHost options which wasn't the case with V7.

I've also tried the launch script "hmr": "ng serve --hmr" with the same result (how can hmr know the publicHost option in that case anyway?).

How can I set my publicHost option properly agiain?

Edit

As a workaround, I've tried to add an MVC action that catches the /sockjs-node/... requests and redirect them to /app/sockjs-node/..., but unfortunately that does not work for the websocket one...

Edit 2

Well well well... my mistake...

As sockjs is a pollyfill to websocket, even if websocket doesn't work, it will be emulated by another plain http method. So, even if the websocket connection fails, this method (while not perfect) works. See my answer.

Body:
It looks like, unlike previously, Angular sends all websocket requests to the root.

The only workaround I've found for this issue until now is to use an MVC action to redirect all the /sockjs-node/... requests to their correct /app/sockjs-node/... form. This will not redirect the websocket call but sockjs will pollyfill it to http requests.

So, I've added this action in one of my controllers:

/// <summary>Redirects sockjs-node requests to the app subdirectory to fix HMR issues</summary>
[HttpGet("/sockjs-node/{**path}")]
[HttpPost("/sockjs-node/{**path}")]
public IActionResult AngularHmr(string path)
{
    return RedirectPermanentPreserveMethod("/app/sockjs-node/" + path);
}

This solution is far from ideal, but this is only for developpement so it's not so much of a big deal...


问:
how to download files via rselenium
I'm trying to download files via Rselium and it has been 4 days without any success. All I want to do is get Rselium to click on the download link and save it to a local file on disk.

I am using Docker on a windows 10 machine.

In this page https://www.rba.gov.au/mkt-operations/resources/tech-notes/eligible-securities.html

I want to download the List of eligible securities

Based on feed back from @Nad pat below, I have now updated my code. I am still not able to download the files to the specified directory!

Updated code

```<code>library(tidyverse)
library(lubridate)
library(XML)
library(readxl)
library(janitor)

library(RSelenium)

fprof <- makeFirefoxProfile(list(

    browser.download.manager.showWhenStarting = FALSE,

    browser.download.dir = str_replace_all("c:/users/joe/downloads/", "/", "\\\\\\\\"),
    # browser.download.dir = "c:/users/joe/downloads",
    # browser.download.useDownloadDir = str_replace_all("c:/users/joe/downloads/", "/", "\\\\\\\\"),

    rowser.helperApps.neverAsk.openFile = "text/csv",

    browser.helperApps.neverAsk.saveToDisk = "text/plain,application/octet-stream,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    # browser.helperApps.neverAsk.saveToDisk="text/csv",

    browser.download.folderList = 2L
                                 )
)

link_to_chart <- "https://www.rba.gov.au/mkt-operations/resources/tech-notes/eligible-securities.html"

remDr <- remoteDriver(remoteServerAddr = "localhost",
                      port = 4445L, browserName = "firefox",
                      extraCapabilities = fprof)

remDr$open(silent = TRUE)
remDr$navigate(link_to_chart)
remDr$screenshot(display = TRUE) #This will take a screenshot and display it in the RStudio viewer

#download file - 2 options
remDr$findElement(using ="class", "anchor-xls")$clickElement()
remDr$findElement(using ="xpath", '//*[@id="content"]/section/div[2]/table/tbody/tr[1]/th/a')$clickElement()

remDr$closeWindow()
</code>```

Old Code

This is the best code I could come-up with:

```<code>library(tidyverse)
library(lubridate)

library(XML)
library(readxl)
library(janitor)
library(platus)

library(RSelenium)

firefor_exemptions <- c("application/vnd.openxmlformats-officedocument.presentationml.presentation",
  "application/vnd.openxmlformats-officedocument.presentationml.slide",
  "application/vnd.openxmlformats-officedocument.presentationml.slideshw",
  "application/vnd.openxmlformats-officedocument.presentationml.template",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.template",
  "application/vnd.openxmformats-officedocument.wordprocessingml.document",
  "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
  "application/x-msbinder",
  "application/vnd.ms-officetheme",
  "application/onenote",
  "audio/vnd.ms-playready.media.pya",
  "vdeo/vnd.ms-playready.media.pyv",
  "application/vnd.ms-powerpoint",
  "application/vnd.ms-powerpoint.addin.macroenabled.12",
  "application/vnd.ms-powerpoint.slide.macroenabled.12",
  "application/vnd.ms-powerpoint.presentation.macroenabled.12",
  "appliation/vnd.ms-powerpoint.slideshow.macroenabled.12",
  "application/vnd.ms-project",
  "application/x-mspublisher",
  "application/x-msschedule",
  "application/x-silverlight-app"
)

fprof <- makeFirefoxProfile(list(browser.helperApps.neverAsk.saveToDisk = firefor_exemptions,
                                 browser.download.dir = str_replace_all("c:/users/john_doe/downloads", "/", "\\\\\\\\"))
)

link_to_chart <- "https://www.rba.gov.au/mkt-operations/resources/tech-notes/eligible-securities.html"

remDr <- remoteDriver(remoteServerAddr = "localhost",
                      port = 4445L, browserName = "firefox",
                      extraCapabilities = fprof)

remDr$open(silent = FALSE)
remDr$navigate(link_to_chart)

#I'm not sure what I should be selecting
remDr$findElement("class", "js-no-cache anchor-to-file anchor-xls")$clickElement()

remDr$findElement("link", "List of eligible securities")$clickElement()

remDr$closeWindow()
</code>```

Any ideas on how to make this work?

答:
For chrome to download in working directory we can use,

```<code>file_path <- getwd() %>% str_replace_all("/", "\\\\\\")

eCaps <- list(
  chromeOptions =
    list(prefs = list('download.default_directory' = file_path))
)

driver <- rsDriver(browser = "chrome",port = 9995L, extraCapabilities = eCaps)

remDr<-driver[["client"]]
remDr$navigate(link_to_chart)
</code>```

Using the xpath I was able to download the file,

```<code>remDr$findElement(using ="xpath", '//*[@id="content"]/section/div[2]/table/tbody/tr[1]/th/a')$clickElement()
</code>```

using class

```<code>remDr$findElement(using ="class", 'anchor-xls')$clickElement()
</code>```

Title: how to download files via rselenium

Body:
I'm trying to download files via Rselium and it has been 4 days without any success. All I want to do is get Rselium to click on the download link and save it to a local file on disk.

I am using Docker on a windows 10 machine.

In this page https://www.rba.gov.au/mkt-operations/resources/tech-notes/eligible-securities.html

I want to download the List of eligible securities

Based on feed back from @Nad pat below, I have now updated my code. I am still not able to download the files to the specified directory!

Updated code

library(tidyverse)
library(lubridate)
library(XML)
library(readxl)
library(janitor)

library(RSelenium)

fprof <- makeFirefoxProfile(list(

    browser.download.manager.showWhenStarting = FALSE,

    browser.download.dir = str_replace_all("c:/users/joe/downloads/", "/", "\\\\\\\\"),
    # browser.download.dir = "c:/users/joe/downloads",
    # browser.download.useDownloadDir = str_replace_all("c:/users/joe/downloads/", "/", "\\\\\\\\"),

    rowser.helperApps.neverAsk.openFile = "text/csv",

    browser.helperApps.neverAsk.saveToDisk = "text/plain,application/octet-stream,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    # browser.helperApps.neverAsk.saveToDisk="text/csv",

    browser.download.folderList = 2L
                                 )
)

link_to_chart <- "https://www.rba.gov.au/mkt-operations/resources/tech-notes/eligible-securities.html"

remDr <- remoteDriver(remoteServerAddr = "localhost",
                      port = 4445L, browserName = "firefox",
                      extraCapabilities = fprof)

remDr$open(silent = TRUE)
remDr$navigate(link_to_chart)
remDr$screenshot(display = TRUE) #This will take a screenshot and display it in the RStudio viewer

#download file - 2 options
remDr$findElement(using ="class", "anchor-xls")$clickElement()
remDr$findElement(using ="xpath", '//*[@id="content"]/section/div[2]/table/tbody/tr[1]/th/a')$clickElement()

remDr$closeWindow()

Old Code

This is the best code I could come-up with:

library(tidyverse)
library(lubridate)

library(XML)
library(readxl)
library(janitor)
library(platus)

library(RSelenium)

firefor_exemptions <- c("application/vnd.openxmlformats-officedocument.presentationml.presentation",
  "application/vnd.openxmlformats-officedocument.presentationml.slide",
  "application/vnd.openxmlformats-officedocument.presentationml.slideshw",
  "application/vnd.openxmlformats-officedocument.presentationml.template",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.template",
  "application/vnd.openxmformats-officedocument.wordprocessingml.document",
  "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
  "application/x-msbinder",
  "application/vnd.ms-officetheme",
  "application/onenote",
  "audio/vnd.ms-playready.media.pya",
  "vdeo/vnd.ms-playready.media.pyv",
  "application/vnd.ms-powerpoint",
  "application/vnd.ms-powerpoint.addin.macroenabled.12",
  "application/vnd.ms-powerpoint.slide.macroenabled.12",
  "application/vnd.ms-powerpoint.presentation.macroenabled.12",
  "appliation/vnd.ms-powerpoint.slideshow.macroenabled.12",
  "application/vnd.ms-project",
  "application/x-mspublisher",
  "application/x-msschedule",
  "application/x-silverlight-app"
)

fprof <- makeFirefoxProfile(list(browser.helperApps.neverAsk.saveToDisk = firefor_exemptions,
                                 browser.download.dir = str_replace_all("c:/users/john_doe/downloads", "/", "\\\\\\\\"))
)

link_to_chart <- "https://www.rba.gov.au/mkt-operations/resources/tech-notes/eligible-securities.html"

remDr <- remoteDriver(remoteServerAddr = "localhost",
                      port = 4445L, browserName = "firefox",
                      extraCapabilities = fprof)

remDr$open(silent = FALSE)
remDr$navigate(link_to_chart)

#I'm not sure what I should be selecting
remDr$findElement("class", "js-no-cache anchor-to-file anchor-xls")$clickElement()

remDr$findElement("link", "List of eligible securities")$clickElement()

remDr$closeWindow()

Any ideas on how to make this work?

Body:
For chrome to download in working directory we can use,

file_path <- getwd() %>% str_replace_all("/", "\\\\\\")

eCaps <- list(
  chromeOptions =
    list(prefs = list('download.default_directory' = file_path))
)

driver <- rsDriver(browser = "chrome",port = 9995L, extraCapabilities = eCaps)

remDr<-driver[["client"]]
remDr$navigate(link_to_chart)

Using the xpath I was able to download the file,

remDr$findElement(using ="xpath", '//*[@id="content"]/section/div[2]/table/tbody/tr[1]/th/a')$clickElement()

using class

remDr$findElement(using ="class", 'anchor-xls')$clickElement()


问:
Synchronous Requests in Node.js
How could I make the 'request' module in Node.js load things in a synchronous fashion? The best advice I've seen is to somehow use the callback to get the function to not return itself until it is done. I am trying to use the 'request' function inline in code (things need to be processed based on that data that can't be placed in callbacks).

So how could I use the callback of the 'request' module to keep it from returning itself until it is finished with loading the resource?

What I'm doing is running a loop that downloads two values from an API, and then has to do some math based on those values. While the math could be done in callbacks... the loop would advance without the values it needs to perform the next operation. (So stopping the loop from advancing until the data is ready would solve the issue)

```<code>    /* loop */ {
         /* URL Generation */

    request( {url: base + u_ext}, function( err, res, body ) {
        var split1 = body.split("\n");
        var split2 = split1[1].split(", ");
        ucomp = split2[1];
    });

    request( {url: base + v_ext}, function( err, res, body ) {
        var split1 = body.split("\n");
        var split2 = split1[1].split(", ");
        vcomp = split2[1];
    });

    /* math which needs to be after functions get variables and before loop advances */
    }
</code>```

答:
As of this writing all answers are either:

Sync but with a control flow (such as using async library)

Sync, but blocking [which means that all other threads on Node are stopped, which is bad performance wise], such as retus or sync-request.

Out of date, such as http-request.

Check out the non-blocking sync-request, based on deasync.

Or see some of the answers in this thread, such as this, which use deasync directly.

Title: Synchronous Requests in Node.js

Body:
How could I make the 'request' module in Node.js load things in a synchronous fashion? The best advice I've seen is to somehow use the callback to get the function to not return itself until it is done. I am trying to use the 'request' function inline in code (things need to be processed based on that data that can't be placed in callbacks).

So how could I use the callback of the 'request' module to keep it from returning itself until it is finished with loading the resource?

What I'm doing is running a loop that downloads two values from an API, and then has to do some math based on those values. While the math could be done in callbacks... the loop would advance without the values it needs to perform the next operation. (So stopping the loop from advancing until the data is ready would solve the issue)

    /* loop */ {
         /* URL Generation */

    request( {url: base + u_ext}, function( err, res, body ) {
        var split1 = body.split("\n");
        var split2 = split1[1].split(", ");
        ucomp = split2[1];
    });

    request( {url: base + v_ext}, function( err, res, body ) {
        var split1 = body.split("\n");
        var split2 = split1[1].split(", ");
        vcomp = split2[1];
    });

    /* math which needs to be after functions get variables and before loop advances */
    }