问:
How the html table's editable cell data will be selected when moved from one cell to another cell using Tab key
I just want to do the next cell data will be selected when I move from one cell to another cell by pressing Tab. Suppose I move from Firstname cell to Lastname cell, Then Lastname cell data will be selected automatically. In the following I have given my code and my need's image.Please help me to solve the problem.

$(document).ready(function() {

  $("#btn").click(function() {
    var ary = [];
    $(function() {
      $('#tbl tbody tr').each(function(a, b) {
        var id = $('.id', b).text();
        var fname = $('.fname', b).text();
        var lname = $('.lname', b).text();
        var email = $('.email', b).text();
        ary.push({
          ID: id,
          fname: fname,
          lname: lname,
          email: email
        });

      });

      alert(JSON.stringify(ary));

    });

  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tdstyle {
  background: white;
  color: #060606;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

Editable Table

        ID
        Firstname
        Lastname
        Email

        101
        John
        Doe
        john@example.com

        102
        Mary
        Moe
        mary@example.com

        103
        July
        Dooley
        july@example.com

  <input type="submit" class="btn btn-success btn-block" id="btn" value="Show Edit data">

```

My need is given in the following image.

答:
Use this (found here https://stackoverflow.com/a/987376/9487478):

```<code>function selectText(event) {
  node = event.target;

  if (document.body.createTextRange) {
    const range = document.body.createTextRange();
    range.moveToElementText(node);
    range.select();
  } else if (window.getSelection) {
    const selection = window.getSelection();
    const range = document.createRange();
    range.selectNodeContents(node);
    selection.removeAllRanges();
    selection.addRange(range);
  } else {
    console.warn("Could not select text in node: Unsupported browser.");
  }
}
</code>```

And trigger it on focus (this will also mark all the text on click):

```<code>$("td[contenteditable]").focus(selectText);
</code>```

Body:
I just want to do the next cell data will be selected when I move from one cell to another cell by pressing Tab. Suppose I move from Firstname cell to Lastname cell, Then Lastname cell data will be selected automatically. In the following I have given my code and my need's image.Please help me to solve the problem.

$(document).ready(function() {

  $("#btn").click(function() {
    var ary = [];
    $(function() {
      $('#tbl tbody tr').each(function(a, b) {
        var id = $('.id', b).text();
        var fname = $('.fname', b).text();
        var lname = $('.lname', b).text();
        var email = $('.email', b).text();
        ary.push({
          ID: id,
          fname: fname,
          lname: lname,
          email: email
        });

      });

      alert(JSON.stringify(ary));

    });

  });

});

.tdstyle {
  background: white;
  color: #060606;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

Editable Table

        ID
        Firstname
        Lastname
        Email

        101
        John
        Doe
        john@example.com

        102
        Mary
        Moe
        mary@example.com

        103
        July
        Dooley
        july@example.com

  <input type="submit" class="btn btn-success btn-block" id="btn" value="Show Edit data">

My need is given in the following image.

Body:
Use this (found here https://stackoverflow.com/a/987376/9487478):

function selectText(event) {
  node = event.target;

  if (document.body.createTextRange) {
    const range = document.body.createTextRange();
    range.moveToElementText(node);
    range.select();
  } else if (window.getSelection) {
    const selection = window.getSelection();
    const range = document.createRange();
    range.selectNodeContents(node);
    selection.removeAllRanges();
    selection.addRange(range);
  } else {
    console.warn("Could not select text in node: Unsupported browser.");
  }
}

And trigger it on focus (this will also mark all the text on click):

$("td[contenteditable]").focus(selectText);


来源: stackexchange

问:
React.js: problem with passing variable from select
In GetTariffs.js file, I get the tariff values from the GET-request.
In the AddForm.js file there is a POST-request for sending data. There was a problem with the transfer of values from the GET-request (drop-down list) from GetTariffs.js file to AddForm.js file.

The values in the drop-down list are not displayed on the page:

But in the source code values are present:

GetTariffs.js:

```<code>import React, { Component } from 'react'

class GetTariffs extends Component {

    constructor(props) {
        super(props);
        this.state = {
            tariffs: [],
            isLoaded: false,
        }
    }

    componentDidMount() {
        fetch('/api/v1/tariff/all')
            .then(res => res.json())
            .then(json => {
                this.setState({
                    isLoaded: true,
                    tariffs: json,
                })
            })
    }

    render() {

        var {isLoaded, tariffs} = this.state;

        if (!isLoaded) {
            return <div>loading</div>
        }

        else {
            return (

                <div>
                    {tariffs.map(tariff => {
                        return <option name="tariff" key={tariff.id} value={tariff.name}>
                            {tariff.name}
                        </option>
                    })}
                </div>

            )
        }
    }
}

export default GetTariffs

</code>```

AddForm.js:

```<code>...
import GetTariffs from "./GetTariffs";
...
                <form onSubmit={this.submitHandler}>
...
                    <div className="form-container">
                        <h5>Тариф</h5>
                        <div className="form-row">
                            <div className="form-group col-md-12">
                                <select id="inputState" className="form-control" onChange={this.changeGetTariffHandler}>
                                    <GetTariffs/>
                                </select>
                            </div>
                        </div>
                    </div>
</code>```

答:
Они не отображаются, потому что ты обернул их в div.
They don’t appear because you wrapped them in div.

Use:

```<code> <>
   <option></option>
   <option></option>
 </>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In GetTariffs.js file, I get the tariff values from the GET-request.
In the AddForm.js file there is a POST-request for sending data. There was a problem with the transfer of values from the GET-request (drop-down list) from GetTariffs.js file to AddForm.js file.

The values in the drop-down list are not displayed on the page:

But in the source code values are present:

GetTariffs.js:

import React, { Component } from 'react'

class GetTariffs extends Component {

    constructor(props) {
        super(props);
        this.state = {
            tariffs: [],
            isLoaded: false,
        }
    }

    componentDidMount() {
        fetch('/api/v1/tariff/all')
            .then(res => res.json())
            .then(json => {
                this.setState({
                    isLoaded: true,
                    tariffs: json,
                })
            })
    }

    render() {

        var {isLoaded, tariffs} = this.state;

        if (!isLoaded) {
            return
loading

        }

        else {
            return (

                    {tariffs.map(tariff => {
                        return <option name="tariff" key={tariff.id} value={tariff.name}>
                            {tariff.name}
                        </option>
                    })}

            )
        }
    }
}

export default GetTariffs

AddForm.js:

...
import GetTariffs from "./GetTariffs";
...
                <form onSubmit={this.submitHandler}>
...

Тариф

                                <select id="inputState" className="form-control" onChange={this.changeGetTariffHandler}>
                                    <GetTariffs/>
                                </select>

Body:
Они не отображаются, потому что ты обернул их в div.
They don’t appear because you wrapped them in div.

Use:

 <>
   <option></option>
   <option></option>
 </>


问:
Getting 400 BAD Request when using Spring RestTemplate to POST
Can someone please help me figure out what is wrong with the code below?

I am using Spring 3.1.1 RestTemplate to try to call a REST WS on Box.com to get a new access token from a refresh token.

The code below is returning a 400 (BAD REQUEST). I am able to successfully call the same method using the FireFox POST plugin. I've compared output from the writeForm method on the FormHttpMessageConverter class and it is exactly as I am sending it from FireFox.

Does anyone have any ideas?

```<code>public static void main(String[] args) throws InterruptedException {
    try {
        String apiUrl = "https://www.box.com/api/oauth2/token";
        String clientSecret = "[MY SECRET]";
        String clientId = "[MY ID]";
        String currentRefreshToken = "[MY CURRENT VALID REFRESHTOKEN]";

        RestTemplate restTemplate = new RestTemplate();

        List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();

        messageConverters.add(new FormHttpMessageConverter());
        restTemplate.setMessageConverters(messageConverters);

        MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();

        body.add("grant_type", "refresh_token");
        body.add("refresh_token", currentRefreshToken);
        body.add("client_id", clientId);
        body.add("client_secret", clientSecret);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,application/json");
        headers.add("Accept-Encoding", "gzip, deflate");

        HttpEntity<?> entity = new HttpEntity<Object>(body, headers);

        restTemplate.exchange(apiUrl, HttpMethod.POST, entity, String.class);
    } catch (Exception ex) {
        System.out.println("ex = " + ex.getMessage());
    }
  }
}
</code>```

答: double check the HttpHeaders properly !!</p>

ContentLicense: CC BY-SA 3.0

Body:
Can someone please help me figure out what is wrong with the code below?

I am using Spring 3.1.1 RestTemplate to try to call a REST WS on Box.com to get a new access token from a refresh token.

The code below is returning a 400 (BAD REQUEST). I am able to successfully call the same method using the FireFox POST plugin. I've compared output from the writeForm method on the FormHttpMessageConverter class and it is exactly as I am sending it from FireFox.

Does anyone have any ideas?

public static void main(String[] args) throws InterruptedException {
    try {
        String apiUrl = "https://www.box.com/api/oauth2/token";
        String clientSecret = "[MY SECRET]";
        String clientId = "[MY ID]";
        String currentRefreshToken = "[MY CURRENT VALID REFRESHTOKEN]";

        RestTemplate restTemplate = new RestTemplate();

        List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();

        messageConverters.add(new FormHttpMessageConverter());
        restTemplate.setMessageConverters(messageConverters);

        MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();

        body.add("grant_type", "refresh_token");
        body.add("refresh_token", currentRefreshToken);
        body.add("client_id", clientId);
        body.add("client_secret", clientSecret);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,application/json");
        headers.add("Accept-Encoding", "gzip, deflate");

        HttpEntity<?> entity = new HttpEntity<Object>(body, headers);

        restTemplate.exchange(apiUrl, HttpMethod.POST, entity, String.class);
    } catch (Exception ex) {
        System.out.println("ex = " + ex.getMessage());
    }
  }
}


答:
I think it is because the options are bounded by div.
You want the options to be the children of the select tag.

Try bound the options with React.Fragment instead of bounding the options in div. React Fragment exists exactly for situations like these :)

React Fragment

The render should look something like that:

```<code>render() {

    var {isLoaded, tariffs} = this.state;

    if (!isLoaded) {
        return <div>loading</div>
    }

    else {
        return (

            <React.Fragment>
                {tariffs.map(tariff => {
                    return <option name="tariff" key={tariff.id} value={tariff.name}>
                        {tariff.name}
                    </option>
                })}
            </React.Fragment>

        )
    }
}
</code>```

Title: React.js: problem with passing variable from select

Body:
I think it is because the options are bounded by div.
You want the options to be the children of the select tag.

Try bound the options with React.Fragment instead of bounding the options in div. React Fragment exists exactly for situations like these :)

React Fragment

The render should look something like that:

render() {

    var {isLoaded, tariffs} = this.state;

    if (!isLoaded) {
        return <div>loading</div>
    }

    else {
        return (

            <React.Fragment>
                {tariffs.map(tariff => {
                    return <option name="tariff" key={tariff.id} value={tariff.name}>
                        {tariff.name}
                    </option>
                })}
            </React.Fragment>

        )
    }
}


问:
Why is my Log4j logging not displaying to the console?
I have a web app built in Eclipse/STS with Spring MVC and Maven.

I want to add logging, so I added SLF4 and Log4J to the pom.xml like this ..

```<code>     <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.30</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.30</version>
        <scope>test</scope>
    </dependency>

     <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.30</version>
        <scope>test</scope>
    </dependency>
</code>```

I have a simple log4j.properties file in the project/src/main/resources folder, like this ...

```<code># Root logger option
log4j.rootLogger=DEBUG, stdout, file

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
</code>```

I created a Logger class in my main WebController, like this ...

```<code>private static Logger logger = LoggerFactory.getLogger(WebController.class);
</code>```

And in my "showMain" method I'm doing some logging stuff, like this ...

```<code>@RequestMapping(value={"", "/", "showhome"}, method={RequestMethod.POST,RequestMethod.GET})
public ModelAndView showHome(Model model) {

    logger.info("########### TEST LOG INFO");
    logger.error("########### TEST LOG ERROR");
    logger.warn("########### TEST LOG WARN");
    logger.debug("########### TEST LOG DEBUG");

    /* ... */
}
</code>```

But when I run the application, I don't see any logging output in the console.

I also don't see anything in the console output to indicate that it is even using the logging framework.  And there's no "can't find log4j.properties" message or anything.

I tried putting the log4j.properties in different places in the project, but nothing.

I must be missing something simple?  What have I missed?

答:
You stated that you added log4j in your pom.xml but I do not see it, are you sure this is your newest version of pom.xml?</p>

```<code>    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
</code>```

Body:
I have a web app built in Eclipse/STS with Spring MVC and Maven.

I want to add logging, so I added SLF4 and Log4J to the pom.xml like this ..

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.30</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.30</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.30</version>
        <scope>test</scope>
    </dependency>

I have a simple log4j.properties file in the project/src/main/resources folder, like this ...

# Root logger option
log4j.rootLogger=DEBUG, stdout, file

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

I created a Logger class in my main WebController, like this ...

private static Logger logger = LoggerFactory.getLogger(WebController.class);

And in my "showMain" method I'm doing some logging stuff, like this ...

@RequestMapping(value={"", "/", "showhome"}, method={RequestMethod.POST,RequestMethod.GET})
public ModelAndView showHome(Model model) {

    logger.info("########### TEST LOG INFO");
    logger.error("########### TEST LOG ERROR");
    logger.warn("########### TEST LOG WARN");
    logger.debug("########### TEST LOG DEBUG");

    /* ... */
}

But when I run the application, I don't see any logging output in the console.

I also don't see anything in the console output to indicate that it is even using the logging framework.  And there's no "can't find log4j.properties" message or anything.

I tried putting the log4j.properties in different places in the project, but nothing.

I must be missing something simple?  What have I missed?

Body:
You stated that you added log4j in your pom.xml but I do not see it, are you sure this is your newest version of pom.xml?

    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>


问:
Angular Input vs RxJS for 30+ components
My app's performance is drastically deteriorating as soon as there is some data to handle (a set of 60+ objects). Which is insane, because there is really not much going on.

I have an array of objects, which then needs to get filtered through and displayed in a calendar-like layout. For now every "day" of that calendar is a component, which extends a base "day" component which in turn subscribes to a globally held subject holding the aforementioned array of objects. Which means for 5 weeks in a month view I have 35 subscriptions on one page (that's not counting subscriptions for other parts of UI). I suspect the number of subscriptions makes it so less responsive to user actions.

Which alternative approach could boost performance if I have one "source of truth" which needs to be filtered 35 times on one page depending on several filters (like, mode, layout, date)?

I know @Input could theoretically do the trick, but when I tried it, it seemed like even worse of an option. Any ideas?

答:
Try to change the Change Detection Strategy to OnPush, with that, angular will check for changes only when the values of the @Input variables changes, reducing processing.

@Component({
  template: `...`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
```

You can get more info about that config here.

Body:
Try to change the Change Detection Strategy to OnPush, with that, angular will check for changes only when the values of the @Input variables changes, reducing processing.

@Component({
  template: `...`,
  changeDetection: ChangeDetectionStrategy.OnPush
})

You can get more info about that config here.


问:
R - Find if characters of a vector are in another vector
I have a doubt very similar to this topic here: Find matches of a vector of strings in another vector of strings.

I have a vector of clients, and if the name indicates that is a commercial client, I need to change the type in my data.frame.

So, suppose that:

```<code>commercial_names <- c("BAKERY","MARKET", "SCHOOL", "CINEMA")
clients <- c("JOHN XX","REESE YY","BAKERY ZZ","SAMANTHA WW")
</code>```

I tried the code in the topic cited before, but I had an error:

```<code>> grepl(paste(commercial_names, collape="|"),clients)
[1] TRUE TRUE TRUE TRUE
Warning message:
In grepl(paste(commercial_names, collape = "|"), clients) :
  argument 'pattern' has length > 1 and only the first element will be used
</code>```

What am I doing wrong? I would thank any help.

答:
Not sure how to do this with a one-liner but a loop seems to do the trick.    </p>

```<code>sapply(clients, function(client) {
  any(str_detect(client, commercial_names))
})
> JOHN XX    REESE YY   BAKERY ZZ SAMANTHA WW
> FALSE       FALSE        TRUE       FALSE

</code>```

Body:
I have a doubt very similar to this topic here: Find matches of a vector of strings in another vector of strings.

I have a vector of clients, and if the name indicates that is a commercial client, I need to change the type in my data.frame.

So, suppose that:

commercial_names <- c("BAKERY","MARKET", "SCHOOL", "CINEMA")
clients <- c("JOHN XX","REESE YY","BAKERY ZZ","SAMANTHA WW")

I tried the code in the topic cited before, but I had an error:

> grepl(paste(commercial_names, collape="|"),clients)
[1] TRUE TRUE TRUE TRUE
Warning message:
In grepl(paste(commercial_names, collape = "|"), clients) :
  argument 'pattern' has length > 1 and only the first element will be used

What am I doing wrong? I would thank any help.

Body:
Not sure how to do this with a one-liner but a loop seems to do the trick.

sapply(clients, function(client) {
  any(str_detect(client, commercial_names))
})
> JOHN XX    REESE YY   BAKERY ZZ SAMANTHA WW
> FALSE       FALSE        TRUE       FALSE


问:
How to get specific text information with no unique elements in Python Beautiful Soup?
I would like to just get the open positions text from this website: https://www.praeses.com/careers/.  I copy and pasted the class and it pulls the text from most of the site because almost everything uses this class, but there's no other unique data to pull from.  How do I just get the open positions?  I basically get everything with an "a class".

Senior National Accounts Manager
```

<pre class="lang-py prettyprint-override"><code>import requests
from bs4 import BeautifulSoup

print("Praeses jobs:")
praeses_url = "https://www.praeses.com/careers/"
praeses_html_text = requests.get(praeses_url).text
praeses_soup = BeautifulSoup(praeses_html_text, 'html.parser')
# print(praeses_soup)
for job in praeses_soup.find_all('et_pb_button et_pb_custom_button_icon et_pb_button_1 et_hover_enabled et_pb_bg_layout_dark'):
    print(praeses_soup.text)
</code>```

答:
You can use CSS selector for the task.

For example:

```<code>import requests
from bs4 import BeautifulSoup

url = 'https://www.praeses.com/careers/'

soup = BeautifulSoup(requests.get(url).content, 'html.parser')

for a in soup.select('div:contains("Open Positions") ~ div > a'):
    print('{:<40}{}'.format(a.get_text(strip=True), a['href']))
</code>```

Prints:

```<code>Senior National Accounts Manager        https://www.praeses.com/senior-national-accounts-manager/
National Accounts Manager               https://www.praeses.com/national-accounts-manager/
Cloud Architect                         https://www.praeses.com/cloud-architect/
Front-End Developer                     https://www.praeses.com/front-end-developer/
Senior Project Manager (GOV)            https://www.praeses.com/senior-project-manager-gov/
</code>```

Body:
I would like to just get the open positions text from this website: https://www.praeses.com/careers/.  I copy and pasted the class and it pulls the text from most of the site because almost everything uses this class, but there's no other unique data to pull from.  How do I just get the open positions?  I basically get everything with an "a class".

Senior National Accounts Manager

import requests
from bs4 import BeautifulSoup

print("Praeses jobs:")
praeses_url = "https://www.praeses.com/careers/"
praeses_html_text = requests.get(praeses_url).text
praeses_soup = BeautifulSoup(praeses_html_text, 'html.parser')
# print(praeses_soup)
for job in praeses_soup.find_all('et_pb_button et_pb_custom_button_icon et_pb_button_1 et_hover_enabled et_pb_bg_layout_dark'):
    print(praeses_soup.text)

Body:
You can use CSS selector for the task.

For example:

import requests
from bs4 import BeautifulSoup

url = 'https://www.praeses.com/careers/'

soup = BeautifulSoup(requests.get(url).content, 'html.parser')

for a in soup.select('div:contains("Open Positions") ~ div > a'):
    print('{:<40}{}'.format(a.get_text(strip=True), a['href']))

Prints:

Senior National Accounts Manager        https://www.praeses.com/senior-national-accounts-manager/
National Accounts Manager               https://www.praeses.com/national-accounts-manager/
Cloud Architect                         https://www.praeses.com/cloud-architect/
Front-End Developer                     https://www.praeses.com/front-end-developer/
Senior Project Manager (GOV)            https://www.praeses.com/senior-project-manager-gov/


问:
removing an object of a list from a persisted entity JPA
I have two entities Order and Item with one to many relationship.

Order.java

```<code>@Id
@Column(name="id")
private Long id;

@OneToMany(mappedBy = "order",  cascade = CascadeType.ALL, orphanRemoval = true)
private List<Item> items;
</code>```

Item.java

```<code>@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "order_id", referencedColumnName = "id")
private Order order;
</code>```

During update flow, user can add or remove items to the order. I am using spring boot crud repository to update the order as shown below. OrderRequest is the request json for update flow. I have written the code to implement that. But code is sure as hell messy. How can this code be improved. Any suggestions?

```<code>Optional<Order> orderFromDb = orderRepo.findById(id);

    if(CollectionUtils.isNotEmpty(orderRequest.getItems()))

    {
        // if there are less items in update request than database
        if (orderRequest.getItems().size() < orderFromDb.getItems().size()) {
            Set<Long> itemIds = orderRequest.getItems().stream().map(id -> id.getId()).collect(Collectors.toSet());
            for (ItemRequest itemRequest : orderRequest.getItems()) {
                Iterator<Item> item = orderFromDb.getItems().iterator();
                Item i;
                while (item.hasNext()) {
                    i = item.next();
                    if (!itemIds.contains(i.getId())) {
                        item.remove();
                        continue;
                    }
                    if (i.getId() == itemRequest.getId()) {
                        i.setName(itemRequest.getName());
                    }
                }
            }
        } else {
            // if there are more or same items in update request and database
            for (ItemRequest itemRequest : orderRequest.getItems()) {
                // assuming for newly added items id will not be there(db should generate)
                if (itemRequest.getId() == null) {
                    Item item = new Item();
                    item.setName(itemRequest.getName());
                    item.setOrder(orderFromDb);
                    orderFromDb.getItems().add(item);
                    continue;
                }
                for (Item item : orderFromDb.getItems()) {
                    if (item.getId() == itemRequest.getId()) {
                        item.setName(request.getName());
                    }
                }
            }
        }
    }
</code>```

答:
You are not persisting removed item.

you could implement ItemRepository object (extends from CrudRepository) and then delete the item. If you delete item, next time you query Order, your item won't be there.

https://www.baeldung.com/spring-data-jpa-delete

Body:
I have two entities Order and Item with one to many relationship.

Order.java

@Id
@Column(name="id")
private Long id;

@OneToMany(mappedBy = "order",  cascade = CascadeType.ALL, orphanRemoval = true)
private List<Item> items;

Item.java

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "order_id", referencedColumnName = "id")
private Order order;

During update flow, user can add or remove items to the order. I am using spring boot crud repository to update the order as shown below. OrderRequest is the request json for update flow. I have written the code to implement that. But code is sure as hell messy. How can this code be improved. Any suggestions?

Optional<Order> orderFromDb = orderRepo.findById(id);

    if(CollectionUtils.isNotEmpty(orderRequest.getItems()))

    {
        // if there are less items in update request than database
        if (orderRequest.getItems().size() < orderFromDb.getItems().size()) {
            Set<Long> itemIds = orderRequest.getItems().stream().map(id -> id.getId()).collect(Collectors.toSet());
            for (ItemRequest itemRequest : orderRequest.getItems()) {
                Iterator<Item> item = orderFromDb.getItems().iterator();
                Item i;
                while (item.hasNext()) {
                    i = item.next();
                    if (!itemIds.contains(i.getId())) {
                        item.remove();
                        continue;
                    }
                    if (i.getId() == itemRequest.getId()) {
                        i.setName(itemRequest.getName());
                    }
                }
            }
        } else {
            // if there are more or same items in update request and database
            for (ItemRequest itemRequest : orderRequest.getItems()) {
                // assuming for newly added items id will not be there(db should generate)
                if (itemRequest.getId() == null) {
                    Item item = new Item();
                    item.setName(itemRequest.getName());
                    item.setOrder(orderFromDb);
                    orderFromDb.getItems().add(item);
                    continue;
                }
                for (Item item : orderFromDb.getItems()) {
                    if (item.getId() == itemRequest.getId()) {
                        item.setName(request.getName());
                    }
                }
            }
        }
    }


问:
Visual Studio Code - Unused Import Warning - Python
When importing the Tkinter module, VS Code gives me a 100+ warning messages about unused imports. Is there a way to turn this off? Or should I be doing something different to avoid this?<img src="https://i.stack.imgur.com/7Wazo.png" alt="enter image description here"> </p>

答: Becuase you're using from tkinter import * python is importing everything in the tkinter module. You then get a warning for each class in tkinter that you aren't using. You can either just import the classes you need (from tkinter import Tk), or turn off the warnings in visual studio settings (Tools > Options > Python).


问:
A little confused with Big O
So I have a quick question on how to verify the big O of a function.

for example: a quicksort algorithm sorting an array of 5000000 element yields a time interval of 0.008524 seconds, running the same algorithm with 1000000 element yields 0.017909.  How would I check the big O if my quicksort is/is not big O of n*log(n)??

What I think I understand: n increased by 2  thus the runtime should increase by 2*log(2)?

f(n) = 0.008524 -> n log (n)

f(2n) = 0.017909 ->2n*log(2n)

答: With this code you are looking at, it is dependent on how long it takes for the method to run through the 50 elements compared to 100, not the timing itself. Like if I was iterating through an array, that would be linear time O(n), because the array would has to go through each index to the end. N represents how large the array would be. Besides, Big O notation is meant for the overall scheme of things, in the long run. If you averaged the timing for 50, 100, 1000, 100000, 1000000, you would see on average it would have a O(nlog(n)).

Title: A little confused with Big O


问:
Reverse Proxy with pgadmin and apache
I would like to setup the local pgadmin in server mode behind the reverse proxy. The reverse proxy and the pgadmin could be on the same machine. I tried to set up but it always fails.
Here is mypgadmin conf:

```<code>Listen 8080
<VirtualHost *:8080>
  SSLEngine on
  SSLCertificateFile /etc/pki/tls/certs/pgadmin.crt
  SSLCertificateKeyFile /etc/pki/tls/private/pgadmin.key

  LoadModule wsgi_module modules/mod_wsgi.so
  LoadModule ssl_module modules/mod_ssl.so
  WSGIDaemonProcess pgadmin processes=1 threads=25
  WSGIScriptAlias /pgadmin /usr/lib/python2.7/site-packages/pgadmin4-web/pgAdmin4.wsgi

  <Directory /usr/lib/python2.7/site-packages/pgadmin4-web/>
          WSGIProcessGroup pgadmin
          WSGIApplicationGroup %{GLOBAL}
          <IfModule mod_authz_core.c>
                  # Apache 2.4
                  Require all granted
          </IfModule>
          <IfModule !mod_authz_core.c>
                  # Apache 2.2
                  Order Deny,Allow
                  Deny from All
                  Allow from 127.0.0.1
                  Allow from ::1
          </IfModule>
  </Directory>
</VirtualHost>
</code>```

and my reverse proxy conf

```<code>Listen 443

<VirtualHost *:443>

        SSLEngine on
    SSLCertificateFile /etc/pki/tls/certs/localhost.crt
    SSLCertificateKeyFile /etc/pki/tls/private/localhost.key

    ErrorLog /var/log/httpd/reverse_proxy_error.log
    CustomLog /var/log/httpd/reverse_proxy_access.log combined

    SSLProxyEngine on
    SSLProxyVerify require
    SSLProxyCheckPeerCN off
    SSLProxyCheckPeerName off
    SSLProxyCACertificateFile "/etc/pki/tls/certs/ca-bundle.crt"

    ProxyPreserveHost On

    ProxyPass   /   https://localhost:8080/pgadmin
    ProxyPassReverse    /   https://localhost:8080/pgadmin

</VirtualHost>
</code>```

The httpd start but when I want to test it with

```<code>wget --no-check-certificate https://localhost/
</code>```

it give me error 400

but the

```<code>wget --no-check-certificate https://localhost:8080/pgadmin

</code>```

is working. Where is the problem in my config?

答:
This config works,
use 0.0.0.0 for pgadmin docker, else use your ip

change port 5050 with your pgadmin port

```<code><VirtualHost *:80>
 ServerName pgadmin.yourdomain.com
 RedirectMatch permanent ^/pgadmin4$ /pgadmin4/
 ProxyPreserveHost On
 ProxyPass / http://0.0.0.0:5050/
 ProxyPassReverse / http://0.0.0.0:5050/
 Header edit Location ^/ /pgadmin4/
 Header always set X-Script-Name /pgadmin4
</VirtualHost>
</code>```

Cofigure with SSL, replace yourdomain.com with valid SSL for your domain

```<code><VirtualHost *:80>
    ServerName pgadmin.yourdomain.com
    RedirectMatch permanent ^/(.*)$ https://pgadmin.yourdomain.com/$1
</VirtualHost>

<VirtualHost *:443>
 ServerName pgadmin.yourdomain.com

 SSLEngine on
 SSLCertificateFile /etc/letsencrypt/live/yourdomain.com/fullchain.pem
 SSLCertificateKeyFile /etc/letsencrypt/live/yourdomain.com/privkey.pem

 RedirectMatch permanent ^/pgadmin4$ /pgadmin4/
 ProxyPreserveHost On
 ProxyPass / http://0.0.0.0:5050/
 ProxyPassReverse / http://0.0.0.0:5050/
 Header edit Location ^/ /pgadmin4/
 Header always set X-Script-Name /pgadmin4

</VirtualHost>
</code>```

Title: Reverse Proxy with pgadmin and apache

Body:
I would like to setup the local pgadmin in server mode behind the reverse proxy. The reverse proxy and the pgadmin could be on the same machine. I tried to set up but it always fails.
Here is mypgadmin conf:

Listen 8080
<VirtualHost *:8080>
  SSLEngine on
  SSLCertificateFile /etc/pki/tls/certs/pgadmin.crt
  SSLCertificateKeyFile /etc/pki/tls/private/pgadmin.key

  LoadModule wsgi_module modules/mod_wsgi.so
  LoadModule ssl_module modules/mod_ssl.so
  WSGIDaemonProcess pgadmin processes=1 threads=25
  WSGIScriptAlias /pgadmin /usr/lib/python2.7/site-packages/pgadmin4-web/pgAdmin4.wsgi

  <Directory /usr/lib/python2.7/site-packages/pgadmin4-web/>
          WSGIProcessGroup pgadmin
          WSGIApplicationGroup %{GLOBAL}
          <IfModule mod_authz_core.c>
                  # Apache 2.4
                  Require all granted
          </IfModule>
          <IfModule !mod_authz_core.c>
                  # Apache 2.2
                  Order Deny,Allow
                  Deny from All
                  Allow from 127.0.0.1
                  Allow from ::1
          </IfModule>
  </Directory>
</VirtualHost>

and my reverse proxy conf

Listen 443

<VirtualHost *:443>

        SSLEngine on
    SSLCertificateFile /etc/pki/tls/certs/localhost.crt
    SSLCertificateKeyFile /etc/pki/tls/private/localhost.key

    ErrorLog /var/log/httpd/reverse_proxy_error.log
    CustomLog /var/log/httpd/reverse_proxy_access.log combined

    SSLProxyEngine on
    SSLProxyVerify require
    SSLProxyCheckPeerCN off
    SSLProxyCheckPeerName off
    SSLProxyCACertificateFile "/etc/pki/tls/certs/ca-bundle.crt"

    ProxyPreserveHost On

    ProxyPass   /   https://localhost:8080/pgadmin
    ProxyPassReverse    /   https://localhost:8080/pgadmin

</VirtualHost>

The httpd start but when I want to test it with

wget --no-check-certificate https://localhost/

it give me error 400

but the

wget --no-check-certificate https://localhost:8080/pgadmin

is working. Where is the problem in my config?

Body:
This config works,
use 0.0.0.0 for pgadmin docker, else use your ip

change port 5050 with your pgadmin port

<VirtualHost *:80>
 ServerName pgadmin.yourdomain.com
 RedirectMatch permanent ^/pgadmin4$ /pgadmin4/
 ProxyPreserveHost On
 ProxyPass / http://0.0.0.0:5050/
 ProxyPassReverse / http://0.0.0.0:5050/
 Header edit Location ^/ /pgadmin4/
 Header always set X-Script-Name /pgadmin4
</VirtualHost>

Cofigure with SSL, replace yourdomain.com with valid SSL for your domain

<VirtualHost *:80>
    ServerName pgadmin.yourdomain.com
    RedirectMatch permanent ^/(.*)$ https://pgadmin.yourdomain.com/$1
</VirtualHost>

<VirtualHost *:443>
 ServerName pgadmin.yourdomain.com

 SSLEngine on
 SSLCertificateFile /etc/letsencrypt/live/yourdomain.com/fullchain.pem
 SSLCertificateKeyFile /etc/letsencrypt/live/yourdomain.com/privkey.pem

 RedirectMatch permanent ^/pgadmin4$ /pgadmin4/
 ProxyPreserveHost On
 ProxyPass / http://0.0.0.0:5050/
 ProxyPassReverse / http://0.0.0.0:5050/
 Header edit Location ^/ /pgadmin4/
 Header always set X-Script-Name /pgadmin4

</VirtualHost>


问:
I can't fill card data in selenium python

Hi guess, today I struggled with a problem I cant fill card data.https://i.stack.imgur.com/VzN22.png
As I understood it appears cuz of nested html(html in html I'm not good in eng). So what do u supposed to do?

I tried to fill it by id, full xpath, selector etc...

Nothing works.

Some code what I used

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "cardCvc-input"))).send_keys("1234")
</code>```

data.https://i.stack.imgur.com/VzN22.png

答:
You need to switch to iframe first to access the element.The input element present inside an iframe.

Induce WebDriverWait() and frame_to_be_available_and_switch_to_it() and following css selector.

```<code>WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[title='payment']")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "cardCvc-input"))).send_keys("1234")
</code>```

To come out from iframe you need to switch to default_content.

```<code>driver.switch_to.default_content()
</code>```

Body:
Hi guess, today I struggled with a problem I cant fill card data.https://i.stack.imgur.com/VzN22.png
As I understood it appears cuz of nested html(html in html I'm not good in eng). So what do u supposed to do?

I tried to fill it by id, full xpath, selector etc...

Nothing works.

Some code what I used

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "cardCvc-input"))).send_keys("1234")

data.https://i.stack.imgur.com/VzN22.png

Body:
You need to switch to iframe first to access the element.The input element present inside an iframe.

Induce WebDriverWait() and frame_to_be_available_and_switch_to_it() and following css selector.

WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[title='payment']")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "cardCvc-input"))).send_keys("1234")

To come out from iframe you need to switch to default_content.

driver.switch_to.default_content()


问:
ffmpeg NVENC Encoding with -flags:v +ildct shows "No NVENC capable devices found"
So far I use NVENC with ffmpeg for all my encoding successfully. Today I got a new Zotac nVidia GEForce GTX 1660 6GB card.

I get "No NVENC capable devices found" error from ffmpeg. Only if I use -flags:v +ildct flag. Without ildct flag no issues except the output is progressive.

I 100% need Interlaced output and I tried most of the Interlaced flags like, -vf tinterlace=interleave_top,fieldorder=tff -x264opts tff=1 Nothing is giving me Interlaced output except -flags +ildct But with "Zotac nVidia GEForce GTX 1660" ffmpeg shows:

```<code>No NVENC capable devices found
</code>```

I even tried all latest nVidia drivers. Nothing helped me.

My pseudo ffmpeg command line is as below:

```<code>ffmpeg -i SourceFile.mkv -codec:v h264_nvenc -preset:v slow -flags:v +ildct+cgop -s:v 1920x1080 -ac 2 -ar 48000 -codec:a mp2 -b:a 384k -r 25 -f mp4 -y NewFile.mp4
</code>```

Is it a bug with nVidia driver or ffmpeg ? Is latest nVidia Turing technology doesn't support Interlaced (very Bad) ?

Could some one help me ?

答:
nVidia inexplicably disabled interlaced encoding on Turing GPU's. See here and here.
I'm waiting for fix, too.</p>

Body:
So far I use NVENC with ffmpeg for all my encoding successfully. Today I got a new Zotac nVidia GEForce GTX 1660 6GB card.

I get "No NVENC capable devices found" error from ffmpeg. Only if I use -flags:v +ildct flag. Without ildct flag no issues except the output is progressive.

I 100% need Interlaced output and I tried most of the Interlaced flags like, -vf tinterlace=interleave_top,fieldorder=tff -x264opts tff=1 Nothing is giving me Interlaced output except -flags +ildct But with "Zotac nVidia GEForce GTX 1660" ffmpeg shows:

No NVENC capable devices found

I even tried all latest nVidia drivers. Nothing helped me.

My pseudo ffmpeg command line is as below:

ffmpeg -i SourceFile.mkv -codec:v h264_nvenc -preset:v slow -flags:v +ildct+cgop -s:v 1920x1080 -ac 2 -ar 48000 -codec:a mp2 -b:a 384k -r 25 -f mp4 -y NewFile.mp4

Is it a bug with nVidia driver or ffmpeg ? Is latest nVidia Turing technology doesn't support Interlaced (very Bad) ?

Could some one help me ?


问:
Plotting confidence interval around predicted line plot
I am trying to plot confidence intervals around a line plot, similar to this: https://scikit-learn.org/0.17/_images/plot_gp_regression_001.png

I am fitting a gaussian process and when predicting values, for each, it returns a mean and a std (standard deviation). Using this, I should be able to able to plot different ranges of the confidence interval. For my case, I am trying to have ranges for 10%, 20%, ... 90%.

Currently I am doing something like this

```<code>y_pred, std = reg.predict(x, return_std=True)

std_z = 1.96 # from z-table for 95%
confidence_interval = std * std_z

plt.plot(x, y_pred)
plt.fill_between(x, y_pred - confidence_interval, y_pred + confidence_interval)
</code>```

That works. According to the z-table (http://www.z-table.com/uploads/2/1/7/9/21795380/8573955.png?759), you can see that the z value is 1.96 for 95%. However, take for example 25% and 75%. The z values for those would be - and + 0.67 respective, which would just overlap in the confidence interval when plotting. This seems intuitively incorrect to me. I would expect expect shrinking bands for lower confidence ranges and expanding ones for increasing, right?

Any help would be appreciated.

答: Wrong.  The percentages associated with confidence intervals (95%, 75%, 25% in your examples) are coverage probabilities.  They're the chance that the true value of quantity you're estimating (the predicted value in this case) lies within the CI..  Given that the CI's you're talking about are central confidence intervals (that is, they are centred on the predicted value) it stands to reason that for a higher confidence, you need a wider interval.  This is exactly what you are seeing.  If a narrower confidence interval had a higher coverage probabiulity than a wider one, then that would imply that there was a region that somehow had a negative coverage probability associated with it.  Probabilities can't be negative, so that's impossible.</p>

Body:
I am trying to plot confidence intervals around a line plot, similar to this: https://scikit-learn.org/0.17/_images/plot_gp_regression_001.png

I am fitting a gaussian process and when predicting values, for each, it returns a mean and a std (standard deviation). Using this, I should be able to able to plot different ranges of the confidence interval. For my case, I am trying to have ranges for 10%, 20%, ... 90%.

Currently I am doing something like this

y_pred, std = reg.predict(x, return_std=True)

std_z = 1.96 # from z-table for 95%
confidence_interval = std * std_z

plt.plot(x, y_pred)
plt.fill_between(x, y_pred - confidence_interval, y_pred + confidence_interval)

That works. According to the z-table (http://www.z-table.com/uploads/2/1/7/9/21795380/8573955.png?759), you can see that the z value is 1.96 for 95%. However, take for example 25% and 75%. The z values for those would be - and + 0.67 respective, which would just overlap in the confidence interval when plotting. This seems intuitively incorrect to me. I would expect expect shrinking bands for lower confidence ranges and expanding ones for increasing, right?

Any help would be appreciated.


问:
Can't make a POST request using axios
The error message I get is

"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/user/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."

http-header.js

```<code>"import axios from 'axios';

export default axios.create({
  baseURL: "http://localhost:5000",
  headers: {
    'Content-type': 'application/json',
    'Access-Control-Allow-Origin': '*'
  }
})
</code>```

AuthService.js

```<code>import axios from '../http-header.js'

export default {
  login : user => {
    return axios.post('/user/login', user)
    .then(res => {
      if(res.status !== 401)
        return res.json().then(data => data)
      else {
        return {isAuthenticated: false, user: {username: "", role: ""}}
      }
    })
  }
}
</code>```

答: You have to add 'Access-Control-Allow-Origin': '*' to your backend.

Title: Can't make a POST request using axios

Body:
The error message I get is

"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/user/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."

http-header.js

"import axios from 'axios';

export default axios.create({
  baseURL: "http://localhost:5000",
  headers: {
    'Content-type': 'application/json',
    'Access-Control-Allow-Origin': '*'
  }
})

AuthService.js

import axios from '../http-header.js'

export default {
  login : user => {
    return axios.post('/user/login', user)
    .then(res => {
      if(res.status !== 401)
        return res.json().then(data => data)
      else {
        return {isAuthenticated: false, user: {username: "", role: ""}}
      }
    })
  }
}


问:
what is the time complexity of array.splice(...array.splice())
I was solving one of the leetcode question which is rotating array. I solve with O(N) by using two for loop but then my runtime was lower then this solution.

My solution: runtime 80ms

```<code>var rotate = function(nums, k) {

    let a = Array.from({length:nums.length})

    for (let i = 0; i < nums.length; i++) {
      a[(i + k) % nums.length] = nums[i];
    }
    for (let i = 0; i < nums.length; i++) {
      nums[i] = a[i];
    }

};
</code>```

Other Solution : runtime 52ms

```<code>var rotate = function(nums, k) {
      return nums.splice(0,0,...nums.splice(nums.length - k))
};
</code>```

how this is possible. As I know splice  is O(N) and in this solution splice also is being used in the splice again. So this solution should be O(N2) and my solution should be faster then this?

答:
Array#splice is O(n) because it can shift up to each array element per call. See: What's the time complexity of array.splice in Google Chrome?

In determining the time complexity of an algorithm, as long as each O(n) operation is in series and the number of O(n) operations is a constant factor (which are the case here), it's still O(n). O(n2) is the consequence of nested loops; that is, for each n we perform another O(n) operation.

This code uses only two sequential calls to Array#splice along with an O(n) spread for a total of O(3n) which is equivalent to O(n).

"My runtime was slower" -- Time complexity and runtime are totally distinct things. Much of runtime rests on implementation details, fixed overhead expenses (constant factors) that are ignored by big O, how large LC's test cases are, the composition of the test cases, inaccuracies LC's test case measurement, etc. Use a benchmark under your own control on very large random inputs to be more certain. Two O(n) codes rarely exhibit identical performance characteristics--time complexity is only concerned with the rate of growth of an algorithm.

As for this particular comparison, keep in mind that builtin functions are highly optimized. I'm assuming this runs in NodeJS (V8), so many builtins are written in C++ (or Torque) (and V8 is not unique in this).

Implementing builtins natively at a lower-level means the memory is likely to be compact and regular so cache accesses benefit from locality, less pointer chasing, opportunities for stack allocation, etc. for loops in high-level code are harder to optimize. They involve index variables, performing comparisons, branching and so forth, all of which needs to be effectively translated to bytecode in a way that may be sub-optimal. In cases when the builtin implementation is in JS, the designers have done much work to make them as efficient as possible.

In Array#splice's case, it's written in Torque which is translated to efficient assembly.

In your code, let a = Array.from({length:nums.length}). Incurs allocation overhead for two objects.

In short: benchmark fairly, don't conflate complexity and speed, and use builtins whenever possible (use a profiler to determine rare cases when not to).

Body:
I was solving one of the leetcode question which is rotating array. I solve with O(N) by using two for loop but then my runtime was lower then this solution.

My solution: runtime 80ms

var rotate = function(nums, k) {

    let a = Array.from({length:nums.length})

    for (let i = 0; i < nums.length; i++) {
      a[(i + k) % nums.length] = nums[i];
    }
    for (let i = 0; i < nums.length; i++) {
      nums[i] = a[i];
    }

};

Other Solution : runtime 52ms

var rotate = function(nums, k) {
      return nums.splice(0,0,...nums.splice(nums.length - k))
};

how this is possible. As I know splice  is O(N) and in this solution splice also is being used in the splice again. So this solution should be O(N2) and my solution should be faster then this?


问:
Vertical scroll is not working with HammerJS and Angular2
I'm having a problem using the HammerJS with Angular2.
I have a carousel (based on the bootstrap carousel with Angular2 event handlers) where I'm listening to the swipe left and swipe right events.
The swipe itself works perfectly.
The problem is that since I use the HammerJS I can not scroll up/down over my carousel component and since it's a full viewport sized item it's a huge issue.

How can this issue be solved?

Platform:
 Angular2 2.1.2
 Samsung Galaxy S2 with Android
  5.1.1
 Google Chrome for Android: 54.0.2840.85

答:
<b>ionic with angular 9 </b> do not forget to add
in app.module.ts</p>

```

import { HammerModule } from '@angular/platform-browser';
imports: [
    ...,
    HammerModule,
  ],
```

Body:
ionic with angular 9  do not forget to add
in app.module.ts

import { HammerModule } from '@angular/platform-browser';
imports: [
    ...,
    HammerModule,
  ],


问:
iOS XML parsing on main or background thread
When parsing XML in Objective-C on an iOS app, when can the main thread be used and when should the parsing happen on a background thread? Can the main thread handle SAX parsing on small documents, or should all XML parsing happen in the background?

答:
Anything that does not call into UIKit (UIView & it's subclasses) or even suggests that it might render to the screen is completely safe to do off the main thread.

I've got several apps that process XML on a background thread. I would suggest using a NSOperation that you pass the entire XML document to, allow it to process it completely or provide a series of delegate methods that notify the main thread about it's progress. If you plan on using core data, might i suggest my own NSOperation abstract class for doing background imports.

In fact you can do some rendering on a background thread, but you must pick your API's very carefully.


问:
Remove parent JSON element depending on child value
I have a JSON with lots of empty content:

```<code>{
    "items": [
        {
            "category": "login",
            "fields": [
                {
                    "label": "Name",
                    "value": "",
                },
                {
                    "label": "E-Mail",
                    "value": "",
                },
                {
                    "label": "Password",
                    "value": "123456",
                },
                {
                    "label": "Website",
                    "fields": [
                        {
                            "label": "Name X",
                            "value": ""
                        },
                        {
                            "label": "Name Y",
                            "value": "another one"
                        },…
                    ]
                },…
            ]
        },…
    ]
}
</code>```

The nesting goes several levels deeper. This shows only the first level. I want to delete all elements of "fields" (or whatever the array's key in deeper levels is), where their "value" is empty.

```<code>{
    "items": [
        {
            "category": "login",
            "fields": [
                {
                    "label": "Password",
                    "value": "123456",
                },
                {
                    "label": "Website",
                    "fields": [
                        {
                            "label": "Name Y",
                            "value": "another one"
                        },…
                    ]
                },…
            ]
        },…
    ]
}
</code>```

How can I do this in Javascript?

答:
Well, I found a way to iterate through the JSON object:

```<code>function remove(jsondata) {
  for (let i in jsondata) {
    if (jsondata[i].value != undefined && jsondata[i].value == '') {
       delete jsondata[i];
    }
    else if (typeof jsondata[i] === "object") remove(jsondata[i]);
  }
}
</code>```

Not sure, if it's the most elegant way, but it works so far.

Body:
I have a JSON with lots of empty content:

{
    "items": [
        {
            "category": "login",
            "fields": [
                {
                    "label": "Name",
                    "value": "",
                },
                {
                    "label": "E-Mail",
                    "value": "",
                },
                {
                    "label": "Password",
                    "value": "123456",
                },
                {
                    "label": "Website",
                    "fields": [
                        {
                            "label": "Name X",
                            "value": ""
                        },
                        {
                            "label": "Name Y",
                            "value": "another one"
                        },…
                    ]
                },…
            ]
        },…
    ]
}

The nesting goes several levels deeper. This shows only the first level. I want to delete all elements of "fields" (or whatever the array's key in deeper levels is), where their "value" is empty.

{
    "items": [
        {
            "category": "login",
            "fields": [
                {
                    "label": "Password",
                    "value": "123456",
                },
                {
                    "label": "Website",
                    "fields": [
                        {
                            "label": "Name Y",
                            "value": "another one"
                        },…
                    ]
                },…
            ]
        },…
    ]
}

How can I do this in Javascript?

Body:
Well, I found a way to iterate through the JSON object:

function remove(jsondata) {
  for (let i in jsondata) {
    if (jsondata[i].value != undefined && jsondata[i].value == '') {
       delete jsondata[i];
    }
    else if (typeof jsondata[i] === "object") remove(jsondata[i]);
  }
}

Not sure, if it's the most elegant way, but it works so far.


问:
Error ELIFECYCLE 3228369023 on attempted connection to SQL Server database using Node.js MSSQL
I'm working on setting up an API for a SQL Server Express database, I'm planning on using mssql in Node.js with express to receive requests and interact with the database. I have tried several approaches to connecting to the DB via node, and believe that the server (running locally) is found, but my node app is unable to connect with it.

The approaches I've made include various different forms of connection strings (some just strings as displayed below, and some attempts using a JSON object). Also, at first I only used the mssql package, but I later added in msnodesqlv8.

```<code>function connect(){
var sql = require("mssql/msnodesqlv8");

// config for your database
var connString = 'Driver={SQL Server Native Client 11.0};Server={DESKTOP-RJH9ERF\\SQLEXPRESS};Uid={DESKTOP-RJH9ERF\\Jake};Database={MAIC};Trusted_Connection={yes};'

// connect to your database
sql.connect(connString, function (err) {

    if (err) console.log(err);

    // create Request object
    var request = new sql.Request();

    // query to the database and get the records
    request.query('select * from Events', function (err, recordset) {

        if (err) console.log(err)

        // send records as a response
        res.send(recordset);

    });
});
};
</code>```

At first, there appeared to be an issue with a user not being recognized. On my more recent approaches to connecting, however, I am getting this error repeatedly.

20 error code ELIFECYCLE
21 error errno 3228369023
22 error maic-api@1.0.0 start: node server.js
22 error Exit status 3228369023

I have seen no additional information regarding what this error means and after some searches online it remains unclear what is causing this. Is anyone familiar with this error and what it might have to do with MSSQL in node?

答:
Sorry for being late to the party, I just fixed the same error right now. What was happening on my side was that I was using a .env file to provide variables for the database connection configuration and since it is bad practice to commit your .env, I had it stored locally. When I switched to my laptop, the .env file was gone, and so were my DB_USER and DB_PASS environment variables (they were actually undefined).

For some reason, I could only make the tedious logs appear by placing console.log('OK') right after the require which was causing the error, like below. My guess is that for some reason the error buffer was not getting flushed.

db-conn.js

```<code>require('dotenv').config
var Connection = require('tedious').Connection

var config = {
  server: process.env.DB_SERVER,
  options: {
    database: process.env.DB_NAME,
    trustServerCertificate: true,
    encrypt: true,
  },
  authentication: {
    type: "default",
    options: {
      userName: process.env.DB_USERNAME,
      password: process.env.DB_PASSWORD,
    },
  },
};

const connection = new Connection(config);

module.exports = connection;
</code>```

server.js

```<code>const connection = require("./server/db-conn");
console.log('OK');
</code>```

Body:
I'm working on setting up an API for a SQL Server Express database, I'm planning on using mssql in Node.js with express to receive requests and interact with the database. I have tried several approaches to connecting to the DB via node, and believe that the server (running locally) is found, but my node app is unable to connect with it.

The approaches I've made include various different forms of connection strings (some just strings as displayed below, and some attempts using a JSON object). Also, at first I only used the mssql package, but I later added in msnodesqlv8.

function connect(){
var sql = require("mssql/msnodesqlv8");

// config for your database
var connString = 'Driver={SQL Server Native Client 11.0};Server={DESKTOP-RJH9ERF\\SQLEXPRESS};Uid={DESKTOP-RJH9ERF\\Jake};Database={MAIC};Trusted_Connection={yes};'

// connect to your database
sql.connect(connString, function (err) {

    if (err) console.log(err);

    // create Request object
    var request = new sql.Request();

    // query to the database and get the records
    request.query('select * from Events', function (err, recordset) {

        if (err) console.log(err)

        // send records as a response
        res.send(recordset);

    });
});
};

At first, there appeared to be an issue with a user not being recognized. On my more recent approaches to connecting, however, I am getting this error repeatedly.

20 error code ELIFECYCLE
21 error errno 3228369023
22 error maic-api@1.0.0 start: node server.js
22 error Exit status 3228369023

I have seen no additional information regarding what this error means and after some searches online it remains unclear what is causing this. Is anyone familiar with this error and what it might have to do with MSSQL in node?

Body:
Sorry for being late to the party, I just fixed the same error right now. What was happening on my side was that I was using a .env file to provide variables for the database connection configuration and since it is bad practice to commit your .env, I had it stored locally. When I switched to my laptop, the .env file was gone, and so were my DB_USER and DB_PASS environment variables (they were actually undefined).

For some reason, I could only make the tedious logs appear by placing console.log('OK') right after the require which was causing the error, like below. My guess is that for some reason the error buffer was not getting flushed.

db-conn.js

require('dotenv').config
var Connection = require('tedious').Connection

var config = {
  server: process.env.DB_SERVER,
  options: {
    database: process.env.DB_NAME,
    trustServerCertificate: true,
    encrypt: true,
  },
  authentication: {
    type: "default",
    options: {
      userName: process.env.DB_USERNAME,
      password: process.env.DB_PASSWORD,
    },
  },
};

const connection = new Connection(config);

module.exports = connection;

server.js

const connection = require("./server/db-conn");
console.log('OK');


问:
Azure CI Pipeline fails to build Java / Maven solution with 2 projects
Summary:

I've taken a basic Java / Maven solution from a course and I'm trying to get it to work within an Azure CI pipeline. The Java solution contains 2 projects; each one has it's own pom file.
I'm able to build and execute the tests from within Eclipse.
But when I try to use the solution in an Azure CI pipeline I've created it generates an error each time.

What do I need to change in the Azure pipeline file to get things to work? Thanks.

Error Message:

```<code>2020-05-15T15:31:58.1123350Z Downloaded from central: https://repo.maven.apache.org/maven2/junit/junit/4.12/junit-4.12.jar (315 kB at 3.6 MB/s)
2020-05-15T15:31:58.1124631Z [INFO] ------------------------------------------------------------------------
2020-05-15T15:31:58.1125092Z [INFO] BUILD FAILURE
2020-05-15T15:31:58.1125891Z [INFO] ------------------------------------------------------------------------
2020-05-15T15:31:58.1126382Z [INFO] Total time:  1.621 s
2020-05-15T15:31:58.1127089Z [INFO] Finished at: 2020-05-15T15:31:57Z
2020-05-15T15:31:58.1127980Z [INFO] ------------------------------------------------------------------------
2020-05-15T15:31:58.1129910Z [ERROR] Failed to execute goal on project Tests: Could not resolve dependencies for project com.pluralsight:Tests:jar:0.0.1-SNAPSHOT: Could not find artifact com.pluralsight:TestFramework:jar:0.0.1-SNAPSHOT -> [Help 1]
2020-05-15T15:31:58.1130901Z [ERROR]
2020-05-15T15:31:58.1131330Z [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
2020-05-15T15:31:58.1132008Z [ERROR] Re-run Maven using the -X switch to enable full debug logging.
2020-05-15T15:31:58.1132234Z [ERROR]
2020-05-15T15:31:58.1132574Z [ERROR] For more information about the errors and possible solutions, please read the following articles:
2020-05-15T15:31:58.1133037Z [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException
2020-05-15T15:31:58.1149156Z No test result files matching /home/vsts/work/1/s/**/surefire-reports/TEST-*.xml were found, so publishing JUnit test results is being skipped.
2020-05-15T15:31:58.1177703Z ##[error]Build failed.
2020-05-15T15:31:58.1207997Z ##[section]Finishing: Maven
</code>```

Java solution information:

This screenshot shows the overall Java solution structure and the location of the Azure pipeline file:

This screenshot shows how the two Java projects are structured:

This is the Azure pipeline file that I've created so far:

# Maven
# Build your Java project and run tests with Apache Maven.
# Add steps that analyze code, save build artifacts, deploy, and more:
# https://learn.microsoft.com/azure/devops/pipelines/languages/java

trigger:
- master

pool:
  vmImage: 'ubuntu-latest'

steps:
- task: Maven@3
  inputs:
    mavenPomFile: './Tests/pom.xml'
    mavenOptions: '-Xmx3072m'
    javaHomeOption: 'JDKVersion'
    jdkVersionOption: '1.8'
    jdkArchitectureOption: 'x64'
    publishJUnitResults: true
    testResultsFiles: '**/surefire-reports/TEST-*.xml'
    goals: 'test'```
</div>
</div>
</p>

<p>The Maven pom file for the Tests project is:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.pluralsight</groupId>
  <artifactId>Tests</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <dependencies>
   <dependency>
   <groupId>com.pluralsight</groupId>
   <artifactId>TestFramework</artifactId>
   <version>0.0.1-SNAPSHOT</version>
  </dependency>

  <dependency>
   <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.6.1</version>
    <configuration>
     <source>1.8</source>
     <target>1.8</target>
    </configuration>
   </plugin>
  </plugins>
 </build>

</project></code>```

The Maven pom file for the TestFramework project is:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.pluralsight</groupId>
  <artifactId>TestFramework</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <dependencies>
  <dependency>
   <groupId>org.seleniumhq.selenium</groupId>
   <artifactId>selenium-java</artifactId>
   <version>3.4.0</version>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.6.1</version>
    <configuration>
     <source>1.8</source>
     <target>1.8</target>
    </configuration>
   </plugin>
  </plugins>
 </build>

</project>```

答:
Error is obviously related to TestFramework. You have to upload your TestFramework to custom repository or maven repository.

Other choice is to build your TestFramework and put it your m2 repository of the container.
Then you can access TestFramework project

Body:
Summary:

I've taken a basic Java / Maven solution from a course and I'm trying to get it to work within an Azure CI pipeline. The Java solution contains 2 projects; each one has it's own pom file.
I'm able to build and execute the tests from within Eclipse.
But when I try to use the solution in an Azure CI pipeline I've created it generates an error each time.

What do I need to change in the Azure pipeline file to get things to work? Thanks.

Error Message:

2020-05-15T15:31:58.1123350Z Downloaded from central: https://repo.maven.apache.org/maven2/junit/junit/4.12/junit-4.12.jar (315 kB at 3.6 MB/s)
2020-05-15T15:31:58.1124631Z [INFO] ------------------------------------------------------------------------
2020-05-15T15:31:58.1125092Z [INFO] BUILD FAILURE
2020-05-15T15:31:58.1125891Z [INFO] ------------------------------------------------------------------------
2020-05-15T15:31:58.1126382Z [INFO] Total time:  1.621 s
2020-05-15T15:31:58.1127089Z [INFO] Finished at: 2020-05-15T15:31:57Z
2020-05-15T15:31:58.1127980Z [INFO] ------------------------------------------------------------------------
2020-05-15T15:31:58.1129910Z [ERROR] Failed to execute goal on project Tests: Could not resolve dependencies for project com.pluralsight:Tests:jar:0.0.1-SNAPSHOT: Could not find artifact com.pluralsight:TestFramework:jar:0.0.1-SNAPSHOT -> [Help 1]
2020-05-15T15:31:58.1130901Z [ERROR]
2020-05-15T15:31:58.1131330Z [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
2020-05-15T15:31:58.1132008Z [ERROR] Re-run Maven using the -X switch to enable full debug logging.
2020-05-15T15:31:58.1132234Z [ERROR]
2020-05-15T15:31:58.1132574Z [ERROR] For more information about the errors and possible solutions, please read the following articles:
2020-05-15T15:31:58.1133037Z [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException
2020-05-15T15:31:58.1149156Z No test result files matching /home/vsts/work/1/s/**/surefire-reports/TEST-*.xml were found, so publishing JUnit test results is being skipped.
2020-05-15T15:31:58.1177703Z ##[error]Build failed.
2020-05-15T15:31:58.1207997Z ##[section]Finishing: Maven

Java solution information:

This screenshot shows the overall Java solution structure and the location of the Azure pipeline file:

This screenshot shows how the two Java projects are structured:

This is the Azure pipeline file that I've created so far:

# Maven
# Build your Java project and run tests with Apache Maven.
# Add steps that analyze code, save build artifacts, deploy, and more:
# https://learn.microsoft.com/azure/devops/pipelines/languages/java

trigger:
- master

pool:
  vmImage: 'ubuntu-latest'

steps:
- task: Maven@3
  inputs:
    mavenPomFile: './Tests/pom.xml'
    mavenOptions: '-Xmx3072m'
    javaHomeOption: 'JDKVersion'
    jdkVersionOption: '1.8'
    jdkArchitectureOption: 'x64'
    publishJUnitResults: true
    testResultsFiles: '**/surefire-reports/TEST-*.xml'
    goals: 'test'

The Maven pom file for the Tests project is:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.pluralsight</groupId>
  <artifactId>Tests</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <dependencies>
   <dependency>
   <groupId>com.pluralsight</groupId>
   <artifactId>TestFramework</artifactId>
   <version>0.0.1-SNAPSHOT</version>
  </dependency>

  <dependency>
   <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.6.1</version>
    <configuration>
     <source>1.8</source>
     <target>1.8</target>
    </configuration>
   </plugin>
  </plugins>
 </build>

</project>

The Maven pom file for the TestFramework project is:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.pluralsight</groupId>
  <artifactId>TestFramework</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <dependencies>
  <dependency>
   <groupId>org.seleniumhq.selenium</groupId>
   <artifactId>selenium-java</artifactId>
   <version>3.4.0</version>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.6.1</version>
    <configuration>
     <source>1.8</source>
     <target>1.8</target>
    </configuration>
   </plugin>
  </plugins>
 </build>

</project>


问:
How can I get a modified copy of a immutable object?
How can I get a modified copy of a immutable object?

I.e. how could some_magical_method look like in this snipped?

import attr

@attr.s(frozen=True, slots=True)
class Config:
    param1: int = attr.ib()
    param2: str = attr.ib()

my_base_config = Config(param1=1, param2="2")
my_derived_config = my_base_config.some_magical_method(param2="two")

print(my_derived_config.param1) # output: 1
print(my_derived_config.param2) # output: two
```

Background: I want to use immutable objects for my configuration. But I also want to avoid code duplication when dealing with very similar configurations, e.g. for unit tests

答:
Here's a method that does what you want! Add it to your object, here's my code and output:

```<code>@attr.s(frozen=True, slots=True)
class Config:
    param1: int = attr.ib()
    param2: str = attr.ib()

    def some_magical_method(self, **kwargs):
        params_to_use = {"param1": self.param1, "param2": self.param2}
        params_to_use.update(kwargs)
        new_obj = Config(**params_to_use)
        return new_obj

my_base_config = Config(param1=1, param2="2")
my_derived_config = my_base_config.some_magical_method(param2="two")

>>> print(my_derived_config.param1) # output: 1
1
>>>print(my_derived_config.param2) # output: two
two
</code>```

The key here is that the method creates the new Config object,  using its own values first, and then overwriting with any that are passed into the method using params_to_use.update(kwargs). The updated values are then passed to the constructor/init of the new object, which is returned.

Hope that helps, Happy Coding!

Body:
How can I get a modified copy of a immutable object?

I.e. how could some_magical_method look like in this snipped?

import attr

@attr.s(frozen=True, slots=True)
class Config:
    param1: int = attr.ib()
    param2: str = attr.ib()

my_base_config = Config(param1=1, param2="2")
my_derived_config = my_base_config.some_magical_method(param2="two")

print(my_derived_config.param1) # output: 1
print(my_derived_config.param2) # output: two

Background: I want to use immutable objects for my configuration. But I also want to avoid code duplication when dealing with very similar configurations, e.g. for unit tests

Body:
Here's a method that does what you want! Add it to your object, here's my code and output:

@attr.s(frozen=True, slots=True)
class Config:
    param1: int = attr.ib()
    param2: str = attr.ib()

    def some_magical_method(self, **kwargs):
        params_to_use = {"param1": self.param1, "param2": self.param2}
        params_to_use.update(kwargs)
        new_obj = Config(**params_to_use)
        return new_obj

my_base_config = Config(param1=1, param2="2")
my_derived_config = my_base_config.some_magical_method(param2="two")

>>> print(my_derived_config.param1) # output: 1
1
>>>print(my_derived_config.param2) # output: two
two

The key here is that the method creates the new Config object,  using its own values first, and then overwriting with any that are passed into the method using params_to_use.update(kwargs). The updated values are then passed to the constructor/init of the new object, which is returned.

Hope that helps, Happy Coding!


问:
How do I change a Django Template based on the User's Group?
Right now I have two different groups of users on my site: customers and businesses.

Right now I am only using one login that allows both user groups to see their profile page.

However, there are portions of the profile page I only want the Customer to see and portions I only want the business to see. How can I go about limiting what each group sees on this page?

Should I do it in the template with some sort of if statement? or is there some other solution anyone can let me know about?

答:
This is probably too old for you to care any more, but I stumbled here myself before figuring it out on my own.  For posterity, I found the following solution:

In your view, add something like this:

```<code>is_customer = request.user.groups.filter(name='Customers').exists()
</code>```

In your template:

{% if is_customer %} customer stuff here {% endif %}

It relies on the fact that an if clause in a template will be evaluate to false for an empty list.

ContentLicense: CC BY-SA 2.5

Body:
This is probably too old for you to care any more, but I stumbled here myself before figuring it out on my own.  For posterity, I found the following solution:

In your view, add something like this:

is_customer = request.user.groups.filter(name='Customers').exists()

In your template:

{% if is_customer %} customer stuff here {% endif %}

It relies on the fact that an if clause in a template will be evaluate to false for an empty list.


问:
How to pass a property as a method parameter then set it to nil in a block in Objective-C?
I have the following situation where I'm sending in the property self.view, which holds some view, as a parameter to the below method:

```<code>- (void) someMethod:(UIView *)view
{
    [UIView animateWithDuration:.25 delay:0 options: UIViewAnimationOptionAllowUserInteraction animations:^
     {
        //blablabla
     }
    completion:^(BOOL finished)
     {
        [view removeFromSuperview];
        view = nil;
     }];
}
</code>```

Where the compiler is telling me:

Variable is not assignable (missing __block type specifier)

I do try adding the block type specifier to the parameter and that doesn't work. I'm wanting it so that when I set view to nil, it will also set the property self.view to nil. I am having trouble wrapping my head around this situation especially when you throw the block into it, I think normally I would need a double pointer?

I'm wondering what is the best way to approach this where I can self.view to nil using the parameter in the method block.

答:
What’s in your question is a linguistic issue, and linguistically what you are asking for is impossible and wouldn’t work even if it were possible. The code in the completion handler cannot magically reach out and nilify your reference to something.

To see why, imagine if this were possible! No one could write any code, our apps would always be mysteriously failing or crashing, because we could never be sure whether our reference to something had been magically destroyed by someone else.

Body:
I have the following situation where I'm sending in the property self.view, which holds some view, as a parameter to the below method:

- (void) someMethod:(UIView *)view
{
    [UIView animateWithDuration:.25 delay:0 options: UIViewAnimationOptionAllowUserInteraction animations:^
     {
        //blablabla
     }
    completion:^(BOOL finished)
     {
        [view removeFromSuperview];
        view = nil;
     }];
}

Where the compiler is telling me:

Variable is not assignable (missing __block type specifier)

I do try adding the block type specifier to the parameter and that doesn't work. I'm wanting it so that when I set view to nil, it will also set the property self.view to nil. I am having trouble wrapping my head around this situation especially when you throw the block into it, I think normally I would need a double pointer?

I'm wondering what is the best way to approach this where I can self.view to nil using the parameter in the method block.


问:
Python loop through list of csv and check for value?
I have five .csv's that have the same fields in the same order that need to be processed as such:

Get list of files

Make each file into a dataframe

Check if a column of letter-number combinations has a specific value (different for each file) eg: check if the number PT333 is in column1 for the file name data1:

```<code>column1   column2    column3
PT389     LA       image.jpg
PT372     NY       image2.jpg
</code>```

If the column has a specific value, print which value it has and the filename/variable name that i've assigned to that file, and then rename that dataframe to output1

I tried to do this, but I don't know how to make it loop and do the same thing for each file.
At the moment it returns the number, but I also want it to return the data frame name, and I also want it to loop through all the files (a to e) to check for all the values in the numbers list.

This is what I have:

```<code>import os
import glob
import pandas as pd
from glob import glob
from os.path import expanduser

home = expanduser("~")
os.chdir(home + f'/files/')

data = glob.glob('data*.csv')
data

# If you have tips on how to loop through these rather than
# have a line for each one, open to feedback
a = pd.read_csv(data[0], encoding='ISO-8859-1', error_bad_lines=False)
b = pd.read_csv(data[1], encoding='ISO-8859-1', error_bad_lines=False)
c = pd.read_csv(data[2], encoding='ISO-8859-1', error_bad_lines=False)
d = pd.read_csv(data[3], encoding='ISO-8859-1', error_bad_lines=False)
e = pd.read_csv(data[4], encoding='ISO-8859-1', error_bad_lines=False)
filenames = [a,b,c,d,e]
filelist= ['a','b','c','d','e']

# I am aware that this part is repetitive. Unsure how to fix this,
# I keep getting errors
# Any help appreciated
numbers = ['PT333', 'PT121', 'PT111', 'PT211', 'PT222']
def type():
    for i in a.column1:
        if i == numbers[0]:
            print(numbers[0])
        elif i == numbers[1]:
            print(numbers[1])
        elif i == numbers[2]:
            print(numbers[2])
        elif i == numbers[3]:
            print(numbers[3])
        elif i == numbers[4]:
            print(numbers[4])
type()
</code>```

Also happy to take any constructive criticism as to how to repeat less code and make things smoother. TIA

答:
Give this a try

```<code>for file in glob.glob('data*.csv'):       # loop through each file
    df = pd.read_csv(file,                # create the DataFrame of the file
             encoding='ISO-8859-1',
             error_bad_lines=False)
    result = df.where( \                  # Check where the DF contains these numbers
                 df.isin(numbers)) \
                .melt()['value'] \        # melt the DF to be a series of 'value'
                .dropna() \               # Remove any nans (non match)
                .unique().tolist()        # Return the unique values as a list.
    if result:                            # If there are any results
        print(file, ', '.join(result)     # print the file name, and the results
</code>```

Remove the comments and trailing spaces if you are copying and pasting the code. for the result line, in case you run into SyntaxError.

As mentioned you should be able to do the same without DataFrame as well:

```<code>for file in glob.glob('data*.csv'):
    data = file.read()
    for num in numbers:
        if num in data:
            print(file, num)
</code>```

Body:
I have five .csv's that have the same fields in the same order that need to be processed as such:

Get list of files

Make each file into a dataframe

Check if a column of letter-number combinations has a specific value (different for each file) eg: check if the number PT333 is in column1 for the file name data1:

column1   column2    column3
PT389     LA       image.jpg
PT372     NY       image2.jpg

If the column has a specific value, print which value it has and the filename/variable name that i've assigned to that file, and then rename that dataframe to output1

I tried to do this, but I don't know how to make it loop and do the same thing for each file.
At the moment it returns the number, but I also want it to return the data frame name, and I also want it to loop through all the files (a to e) to check for all the values in the numbers list.

This is what I have:

import os
import glob
import pandas as pd
from glob import glob
from os.path import expanduser

home = expanduser("~")
os.chdir(home + f'/files/')

data = glob.glob('data*.csv')
data

# If you have tips on how to loop through these rather than
# have a line for each one, open to feedback
a = pd.read_csv(data[0], encoding='ISO-8859-1', error_bad_lines=False)
b = pd.read_csv(data[1], encoding='ISO-8859-1', error_bad_lines=False)
c = pd.read_csv(data[2], encoding='ISO-8859-1', error_bad_lines=False)
d = pd.read_csv(data[3], encoding='ISO-8859-1', error_bad_lines=False)
e = pd.read_csv(data[4], encoding='ISO-8859-1', error_bad_lines=False)
filenames = [a,b,c,d,e]
filelist= ['a','b','c','d','e']

# I am aware that this part is repetitive. Unsure how to fix this,
# I keep getting errors
# Any help appreciated
numbers = ['PT333', 'PT121', 'PT111', 'PT211', 'PT222']
def type():
    for i in a.column1:
        if i == numbers[0]:
            print(numbers[0])
        elif i == numbers[1]:
            print(numbers[1])
        elif i == numbers[2]:
            print(numbers[2])
        elif i == numbers[3]:
            print(numbers[3])
        elif i == numbers[4]:
            print(numbers[4])
type()

Also happy to take any constructive criticism as to how to repeat less code and make things smoother. TIA

Body:
Give this a try

for file in glob.glob('data*.csv'):       # loop through each file
    df = pd.read_csv(file,                # create the DataFrame of the file
             encoding='ISO-8859-1',
             error_bad_lines=False)
    result = df.where( \                  # Check where the DF contains these numbers
                 df.isin(numbers)) \
                .melt()['value'] \        # melt the DF to be a series of 'value'
                .dropna() \               # Remove any nans (non match)
                .unique().tolist()        # Return the unique values as a list.
    if result:                            # If there are any results
        print(file, ', '.join(result)     # print the file name, and the results

Remove the comments and trailing spaces if you are copying and pasting the code. for the result line, in case you run into SyntaxError.

As mentioned you should be able to do the same without DataFrame as well:

for file in glob.glob('data*.csv'):
    data = file.read()
    for num in numbers:
        if num in data:
            print(file, num)


问:
problem with install and creat my first react app
here is the img description of the error

first it creates the folder (my-app), but after a few seconds it will be removed automatically. Either I installed the latest version of node.js.

$ npx create-react-app my-app
npx : 98 installé(s) en 23.154s

Creating a new React app in D:\Mon-Travail-Personnel\my-work-with-REACT\my-app.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

until know it's good but after :
**
npm ERR! Unexpected end of JSON input while parsing near '...rg\r\n\r\nwsFcBAEBCAA'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\khith\AppData\Roaming\npm-cache_logs\2020-05-29T16_51_36_753Z-debug.log

Aborting installation.
  npm install --save --save-exact --loglevel error react react-dom react-scripts cra-template has failed.

Deleting generated file... package.json
Deleting my-app/ from D:\Mon-Travail-Personnel\my-work-with-REACT
Done.
**

答:
Could you try this,

Clear cache: npm cache clean --force

Install create-react-app globally: npm i create-react-app -g

Create your React project: create-react-app my-app

The problem should mostly be resolved with Step 1.


问:
How to get specific text information with no unique elements in Python Beautiful Soup?
I would like to just get the open positions text from this website: https://www.praeses.com/careers/.  I copy and pasted the class and it pulls the text from most of the site because almost everything uses this class, but there's no other unique data to pull from.  How do I just get the open positions?  I basically get everything with an "a class".

Senior National Accounts Manager
```

<pre class="lang-py prettyprint-override"><code>import requests
from bs4 import BeautifulSoup

print("Praeses jobs:")
praeses_url = "https://www.praeses.com/careers/"
praeses_html_text = requests.get(praeses_url).text
praeses_soup = BeautifulSoup(praeses_html_text, 'html.parser')
# print(praeses_soup)
for job in praeses_soup.find_all('et_pb_button et_pb_custom_button_icon et_pb_button_1 et_hover_enabled et_pb_bg_layout_dark'):
    print(praeses_soup.text)
</code>```

答:
Try with this:</p>

```<code>import requests
from bs4 import BeautifulSoup

print("Praeses jobs:")
praeses_url = "https://www.praeses.com/careers/"
praeses_html_text = requests.get(praeses_url).text
praeses_soup = BeautifulSoup(praeses_html_text, 'html.parser')
# print(praeses_soup)
for j in range(1,10):
    try:
        clase = "et_pb_button et_pb_custom_button_icon et_pb_button_"+str(j)+" et_hover_enabled et_pb_bg_layout_dark"
        hola = praeses_soup.findAll("a", {"class": clase})
        print(hola[0].text)
    except:
        print("Its over")
        break
</code>```

Body:
I would like to just get the open positions text from this website: https://www.praeses.com/careers/.  I copy and pasted the class and it pulls the text from most of the site because almost everything uses this class, but there's no other unique data to pull from.  How do I just get the open positions?  I basically get everything with an "a class".

Senior National Accounts Manager

import requests
from bs4 import BeautifulSoup

print("Praeses jobs:")
praeses_url = "https://www.praeses.com/careers/"
praeses_html_text = requests.get(praeses_url).text
praeses_soup = BeautifulSoup(praeses_html_text, 'html.parser')
# print(praeses_soup)
for job in praeses_soup.find_all('et_pb_button et_pb_custom_button_icon et_pb_button_1 et_hover_enabled et_pb_bg_layout_dark'):
    print(praeses_soup.text)

Body:
Try with this:

import requests
from bs4 import BeautifulSoup

print("Praeses jobs:")
praeses_url = "https://www.praeses.com/careers/"
praeses_html_text = requests.get(praeses_url).text
praeses_soup = BeautifulSoup(praeses_html_text, 'html.parser')
# print(praeses_soup)
for j in range(1,10):
    try:
        clase = "et_pb_button et_pb_custom_button_icon et_pb_button_"+str(j)+" et_hover_enabled et_pb_bg_layout_dark"
        hola = praeses_soup.findAll("a", {"class": clase})
        print(hola[0].text)
    except:
        print("Its over")
        break