问:
Change fill color on vector asset in Android Studio
Android Studio now supports vector assets on 21+ and will generate pngs for lower versions at compile time.  I have a vector asset (from the Material Icons) that I want to change the fill color.  This works on 21+, but the generated pngs do not change color.  Is there a way to do this?

```<code><vector android:height="48dp" android:viewportHeight="24.0"
android:viewportWidth="24.0" android:width="48dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="@color/primary" android:pathData="M9,16.17L4.83,12l-1.42,1.41L9,19 21,7l-1.41,-1.41z"/>
</code>```

答:
For those not using an ImageView, the following worked for me on a plain View (and hence the behaviour should replicate on any kind of view)

```<code><View
    android:background="@drawable/ic_reset"
    android:backgroundTint="@color/colorLightText" />
</code>```

Body:
Android Studio now supports vector assets on 21+ and will generate pngs for lower versions at compile time.  I have a vector asset (from the Material Icons) that I want to change the fill color.  This works on 21+, but the generated pngs do not change color.  Is there a way to do this?

<vector android:height="48dp" android:viewportHeight="24.0"
android:viewportWidth="24.0" android:width="48dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="@color/primary" android:pathData="M9,16.17L4.83,12l-1.42,1.41L9,19 21,7l-1.41,-1.41z"/>

Body:
For those not using an ImageView, the following worked for me on a plain View (and hence the behaviour should replicate on any kind of view)

<View
    android:background="@drawable/ic_reset"
    android:backgroundTint="@color/colorLightText" />


来源: stackexchange

问:
How do I create a class with the specified characteristics?
What I want to do is to create a class that I will call a Cluster that I can use to store representations of multivariable data points. Like a bunch of people's heights, weights, and ages. I want to make it so when I create an instance of Cluster, it returns an empty dictionary. I then want to be able to add key value pairs. I want each value paired with each key to only be a list. I want each list to only contain only 1 data type.

However, they don't have to be the same data type for every list. What I mean is that one list can only consists of integers, and the other list is only full of strings. I even allow a list of tuples or lists or dictionaries. They don't even have to have the same data type for each value in itself. But, the overall list must then contain all dictionaries, tuples, etc.

Example of a Cluster:

```<code>{'Hobbies': [(3, 's', {'name': 'Sam'}), (4, 5), (), (True)], 'Weights': [1, 34, 3, 90]}
</code>```

Notice how the above 'Hobbies' value pair is a list of only tuples and the 'Weights' value pair is a list of only integers. This is what I mean by what I am trying to say above.

I created a function that generates what a Cluster full of values should look like, but I want it to be a class. It gives you what I want to happen, but I want make a class, not a function that generates it. Other methods such as getting the length of the Cluster I can figure out, I just want everything that I said above to be true.

```<code>from random import randint

def create_cluster(a, b, c, *d):
    cluster = {}
    for key in d:
        point = []
        for integer in range(0, a):
            point.append(randint(b, c))
        cluster[key] = point
    return cluster

print(create_cluster(4, 2, 9, 'Height', 'Weight', 'Age'))
</code>```

Output:

{'Height': [5, 3, 3, 6], 'Weight': [7, 3, 5, 7], 'Age': [9, 5, 3, 6]}

```

答:
If I'm understanding what you need, we can actually make a dict object that will type check for you!
No imports needed.

We just have to subclass the dict class, and override the functions for adding items to the dictionary, so we can type check before allowing any additions.

Here is the code below.

```<code>class ClusterDict(dict):
    key_type = str  # we want all of our keys to be str type
    value_type = list  # same for our value as a list

    # lets override the function for dictionary assignment so we can type check before we add to our dictionary
    def __setitem__(self, key, value):
        self.type_check_and_add(key, value)

    # Lets override update as well
    def update(self, **kwargs) -> None:
        for key, value in kwargs.items():
            self.type_check_and_add(key, value)

    def type_check_and_add(self, key: str, value: list) -> None:
        assert type(key) == self.key_type, f"Expected {self.key_type} for key, got {type(key)} instead."
        if type(value) is not list:
            value = [value]  # Make it a list if its isn't, remove this if you know it will always come as a list, even if its a single entry, like [5], or [(2, 6)]
        assert type(value) == self.value_type, f"Expected {self.value_type} for key, got {type(value)} instead."
        val_type = type(value[0])  # type of first item in list, lets make sure they all match this one
        for val in value:
            assert type(val) == val_type, f"Items do not have matching types for key {key}."
        super().__setitem__(key, value)  # this then passes assignment as usual to the base class dict
</code>```

Lets do some tests now!

```<code>if __name__ == '__main__':
    clust = ClusterDict()
    input_data = {
        'Height': [4, 3, 5],
        'Age': [(4, 9), (4, 6, 8)]
    }
    clust.update(**input_data)
    print(clust)
</code>```

```<code>{'Height': [4, 3, 5], 'Age': [(4, 9), (4, 6, 8)]}
</code>```

Looks good so far, we can add whole dictionaries using update as usual

```<code>    input_data = {'Weights': [1, 34, 3, 90]}
    clust.update(**input_data)
    print(clust)
</code>```

```<code>{'Height': [4, 3, 5], 'Age': [(4, 9), (4, 6, 8)], 'Weights': [1, 34, 3, 90]}
</code>```

Or just one entry at a time.

Lets try the usual way, dict[key] = value

```<code>    clust['Hobbies'] = [(3, 's', {'name': 'Sam'}), (4, 5), (), (True,)]
    print(clust)
</code>```

```<code>{'Height': [4, 3, 5], 'Age': [(4, 9), (4, 6, 8)], 'Weights': [1, 34, 3, 90], 'Hobbies': [(3, 's', {'name': 'Sam'}), (4, 5), (), (True,)]}
</code>```

Looking good. But now lets try adding a list with types that don't match.

```<code>    clust['My Favorite Number'] = [7, '7', (1, 1, 1, 1, 1, 1, 1)]
    print(clust)
</code>```

```<code>    assert type(val) == val_type, f"Items do not have matching types for key {key}."
AssertionError: Items do not have matching types for key My Favorite Number.
</code>```

Which throws an AssertionError and prevents us from doing so, like we wanted.

Bonus though, because we subclassed dict, we get all of its methods for free!

```<code>>>>len(clust)
4

for k, v in clust.items():
...     print(k, v)
...
Height [4, 3, 5]
Age [(4, 9), (4, 6, 8)]
Weights [1, 34, 3, 90]
Hobbies [(3, 's', {'name': 'Sam'}), (4, 5), (), (True,)]
</code>```

Hopefully this is what you were looking for and it helps!

ContentLicense: CC BY-SA 4.0

Body:
What I want to do is to create a class that I will call a Cluster that I can use to store representations of multivariable data points. Like a bunch of people's heights, weights, and ages. I want to make it so when I create an instance of Cluster, it returns an empty dictionary. I then want to be able to add key value pairs. I want each value paired with each key to only be a list. I want each list to only contain only 1 data type.

However, they don't have to be the same data type for every list. What I mean is that one list can only consists of integers, and the other list is only full of strings. I even allow a list of tuples or lists or dictionaries. They don't even have to have the same data type for each value in itself. But, the overall list must then contain all dictionaries, tuples, etc.

Example of a Cluster:

{'Hobbies': [(3, 's', {'name': 'Sam'}), (4, 5), (), (True)], 'Weights': [1, 34, 3, 90]}

Notice how the above 'Hobbies' value pair is a list of only tuples and the 'Weights' value pair is a list of only integers. This is what I mean by what I am trying to say above.

I created a function that generates what a Cluster full of values should look like, but I want it to be a class. It gives you what I want to happen, but I want make a class, not a function that generates it. Other methods such as getting the length of the Cluster I can figure out, I just want everything that I said above to be true.

from random import randint

def create_cluster(a, b, c, *d):
    cluster = {}
    for key in d:
        point = []
        for integer in range(0, a):
            point.append(randint(b, c))
        cluster[key] = point
    return cluster

print(create_cluster(4, 2, 9, 'Height', 'Weight', 'Age'))

Output:

{'Height': [5, 3, 3, 6], 'Weight': [7, 3, 5, 7], 'Age': [9, 5, 3, 6]}

Body:
If I'm understanding what you need, we can actually make a dict object that will type check for you!
No imports needed.

We just have to subclass the dict class, and override the functions for adding items to the dictionary, so we can type check before allowing any additions.

Here is the code below.

class ClusterDict(dict):
    key_type = str  # we want all of our keys to be str type
    value_type = list  # same for our value as a list

    # lets override the function for dictionary assignment so we can type check before we add to our dictionary
    def __setitem__(self, key, value):
        self.type_check_and_add(key, value)

    # Lets override update as well
    def update(self, **kwargs) -> None:
        for key, value in kwargs.items():
            self.type_check_and_add(key, value)

    def type_check_and_add(self, key: str, value: list) -> None:
        assert type(key) == self.key_type, f"Expected {self.key_type} for key, got {type(key)} instead."
        if type(value) is not list:
            value = [value]  # Make it a list if its isn't, remove this if you know it will always come as a list, even if its a single entry, like [5], or [(2, 6)]
        assert type(value) == self.value_type, f"Expected {self.value_type} for key, got {type(value)} instead."
        val_type = type(value[0])  # type of first item in list, lets make sure they all match this one
        for val in value:
            assert type(val) == val_type, f"Items do not have matching types for key {key}."
        super().__setitem__(key, value)  # this then passes assignment as usual to the base class dict

Lets do some tests now!

if __name__ == '__main__':
    clust = ClusterDict()
    input_data = {
        'Height': [4, 3, 5],
        'Age': [(4, 9), (4, 6, 8)]
    }
    clust.update(**input_data)
    print(clust)

{'Height': [4, 3, 5], 'Age': [(4, 9), (4, 6, 8)]}

Looks good so far, we can add whole dictionaries using update as usual

    input_data = {'Weights': [1, 34, 3, 90]}
    clust.update(**input_data)
    print(clust)

{'Height': [4, 3, 5], 'Age': [(4, 9), (4, 6, 8)], 'Weights': [1, 34, 3, 90]}

Or just one entry at a time.

Lets try the usual way, dict[key] = value

    clust['Hobbies'] = [(3, 's', {'name': 'Sam'}), (4, 5), (), (True,)]
    print(clust)

{'Height': [4, 3, 5], 'Age': [(4, 9), (4, 6, 8)], 'Weights': [1, 34, 3, 90], 'Hobbies': [(3, 's', {'name': 'Sam'}), (4, 5), (), (True,)]}

Looking good. But now lets try adding a list with types that don't match.

    clust['My Favorite Number'] = [7, '7', (1, 1, 1, 1, 1, 1, 1)]
    print(clust)

    assert type(val) == val_type, f"Items do not have matching types for key {key}."
AssertionError: Items do not have matching types for key My Favorite Number.

Which throws an AssertionError and prevents us from doing so, like we wanted.

Bonus though, because we subclassed dict, we get all of its methods for free!

>>>len(clust)
4

for k, v in clust.items():
...     print(k, v)
...
Height [4, 3, 5]
Age [(4, 9), (4, 6, 8)]
Weights [1, 34, 3, 90]
Hobbies [(3, 's', {'name': 'Sam'}), (4, 5), (), (True,)]

Hopefully this is what you were looking for and it helps!


问:
Limit number of characters allowed in form input text field
How do I limit or restrict the user to only enter a maximum of five characters in the textbox?

Below is the input field as part of my form:

```<code><input type="text" id="sessionNo" name="sessionNum" />
</code>```

Is it using something like maxSize or something like that?

答:
```<code><input type="text" name="MobileNumber" id="MobileNumber" maxlength="10" onkeypress="checkNumber(event);"  placeholder="MobileNumber">

<script>
function checkNumber(key) {
  console.log(key);
  var inputNumber = document.querySelector("#MobileNumber").value;
  if(key.key >= 0 && key.key <= 9) {
    inputNumber += key.key;
  }
  else {
    key.preventDefault();
  }
}
</script>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How do I limit or restrict the user to only enter a maximum of five characters in the textbox?

Below is the input field as part of my form:

<input type="text" id="sessionNo" name="sessionNum" />

Is it using something like maxSize or something like that?


问:
React component run error.Uncaught Error: Minified React error #31
I am trying to return some html label when write render in my component. Code like this:

```<code> import React, {Component} from 'react';
import Request from 'react-http-request';

class NameForm extends React.Component {
constructor() {
    super();
    this.state = {value: '', result: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
}

handleChange(event) {
    this.setState({value: event.target.value});
}

handleSubmit(event) {
    var content = this.state.value;

    var split = content.split(/\s+/);

    var queryObject = new Object();

    queryObject.law = null;
    queryObject.character = null;
    queryObject.lawRule = null;
    if (split.length == 1) {
        queryObject.law = split[0];
    }
    else if (split.length == 2) {
        queryObject.law = split[0];
        queryObject.character = split[1];
    }
    else if (split.length > 2) {
        queryObject.law = split[0];
        queryObject.character = split[1];
        queryObject.lawRule = split[2];
    }
    // var json = JSON.stringify(queryObject);
    var json = "{\"law\":\"军工企业股份制改造实施暂行办法\",\"character\":\"第二章\"}";

    var test = JSON.stringify(<Fetchs args={json}/>);

    var request = new XMLHttpRequest();
    request.open('POST', 'http://localhost:8080/path', false);
    request.setRequestHeader('Content-Type', 'application/json');
    var resp = '';
    request.onreadystatechange = function (e) {
        if (this.status == 200) {
            resp = this.response;
        }
    }

    request.send(json);

    // console.info("XMLHttpRequest test is " + JSON.stringify(resp));

    // console.info("test is " + resp);

    this.setState({result: resp});

    event.preventDefault();
}

render() {

    // console.log("prite"+this.state.result.queryResults);
    // console.log("100"+this.strToJson(this.state.result));
    // console.log("200"+this.strToJson(this.state.result.queryResults));
    // alert(this.state.result);

    var parse = JSON.parse(this.state.result ? this.state.result : null);
    var out = parse ? parse.queryResults : null;
    for (var i = 0; out != null && i < out.length; i++) {
        if (out[i].keyword == null) {
            out[i].keyword = "{}";
            console.info("keyword is null");
        }
        else {
            // this.state.result.queryResults.keyword
            console.info("keword is not null");
            out[i].keyword = JSON.stringify(out[i].keyword);
        }
    }

    return (
        <div>
            <form onSubmit={this.handleSubmit}>
                <label>
                    Name:
                    <input type="text" value={this.state.value} onChange={this.handleChange}/>
                </label>
                <input type="submit" value="Submit"/>
            </form>
            <table border="10" >
                <tr>
                    <thead>
                    <th>GraphName</th>
                    <th>Relation</th>
                    <th>Content</th>
                    <th>KeyWord</th>
                    </thead>
                </tr>
                <tbody>

                {out}
                </tbody>
            </table>

        </div>
    );
 }
}

ReactDOM.render(<NameForm/>, document.getElementById('react'))
</code>```

out is a array parsed from json data, like this:

My problem is that I want show out on page by table label, But use {out} I get a error, like this:

What troubled me is how to show out array in a table.

答:
When i encountered this error, my first gaze of was that the difference themes and styling components i was using were conflicting. But latter own i discovered i was rendering wrong data format from my database.
The React Form field expected to receive a string but i was supplying an Object

Body:
I am trying to return some html label when write render in my component. Code like this:

 import React, {Component} from 'react';
import Request from 'react-http-request';

class NameForm extends React.Component {
constructor() {
    super();
    this.state = {value: '', result: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
}

handleChange(event) {
    this.setState({value: event.target.value});
}

handleSubmit(event) {
    var content = this.state.value;

    var split = content.split(/\s+/);

    var queryObject = new Object();

    queryObject.law = null;
    queryObject.character = null;
    queryObject.lawRule = null;
    if (split.length == 1) {
        queryObject.law = split[0];
    }
    else if (split.length == 2) {
        queryObject.law = split[0];
        queryObject.character = split[1];
    }
    else if (split.length > 2) {
        queryObject.law = split[0];
        queryObject.character = split[1];
        queryObject.lawRule = split[2];
    }
    // var json = JSON.stringify(queryObject);
    var json = "{\"law\":\"军工企业股份制改造实施暂行办法\",\"character\":\"第二章\"}";

    var test = JSON.stringify(<Fetchs args={json}/>);

    var request = new XMLHttpRequest();
    request.open('POST', 'http://localhost:8080/path', false);
    request.setRequestHeader('Content-Type', 'application/json');
    var resp = '';
    request.onreadystatechange = function (e) {
        if (this.status == 200) {
            resp = this.response;
        }
    }

    request.send(json);

    // console.info("XMLHttpRequest test is " + JSON.stringify(resp));

    // console.info("test is " + resp);

    this.setState({result: resp});

    event.preventDefault();
}

render() {

    // console.log("prite"+this.state.result.queryResults);
    // console.log("100"+this.strToJson(this.state.result));
    // console.log("200"+this.strToJson(this.state.result.queryResults));
    // alert(this.state.result);

    var parse = JSON.parse(this.state.result ? this.state.result : null);
    var out = parse ? parse.queryResults : null;
    for (var i = 0; out != null && i < out.length; i++) {
        if (out[i].keyword == null) {
            out[i].keyword = "{}";
            console.info("keyword is null");
        }
        else {
            // this.state.result.queryResults.keyword
            console.info("keword is not null");
            out[i].keyword = JSON.stringify(out[i].keyword);
        }
    }

    return (

            <form onSubmit={this.handleSubmit}>

                    Name:
                    <input type="text" value={this.state.value} onChange={this.handleChange}/>

                <input type="submit" value="Submit"/>
            </form>

                    GraphName
                    Relation
                    Content
                    KeyWord

                {out}

    );
 }
}

ReactDOM.render(<NameForm/>, document.getElementById('react'))

out is a array parsed from json data, like this:

My problem is that I want show out on page by table label, But use {out} I get a error, like this:

What troubled me is how to show out array in a table.


问:
How to compare row by row in a dataframe
I have a data frame that has a name and the URL ID of the name. For example:

```<code>Abc           123
Abc.com       123
Def           345
Pqr           123
PQR.com       123
</code>```

Here due to data extraction error, at times different names have same ID. I want to clean the table such that if the names are different and ID is same, then the record should remain the same. If the names are similar and ID is also same, the name should be changed to one. To be clear,

The expected output should be:

```<code>Abc.com     123
Abc.com     123
Def         354
PQR.com     123
PQR.com     123
</code>```

That is, the last one was data entry error..and both were the same name(The first word of the string was the same). So they are changed to one name looking at ID.
But first and second records even though they had a similar ID to the last ones their names did not match and were completely different.

I am not able to understand how to achieve this.

Request some guidance here. Thanks in advance.

Note: The size of the dataset is almost 16 million of such records.

答:
Idea is use fuzzy matching lib fuzzywuzzy for ratio of all combinations of Names by cross join by DataFrame.merge and removed rows with same names in both columns by DataFrame.query, also was added new column by lengths of data by Series.str.len:

```<code>from fuzzywuzzy import fuzz

df1 = df.merge(df, on='ID').query('Name_x != Name_y')
df1['ratio'] = df1.apply(lambda x:  fuzz.ratio(x['Name_x'], x['Name_y']), axis=1)
df1['len'] = df1['Name_x'].str.len()
print (df1)
    Name_x   ID   Name_y  ratio  len
1      Abc  123      BCD      0    3
2      BCD  123      Abc      0    3
6      Pqr  789  PQR.com     20    3
7  PQR.com  789      Pqr     20    7
</code>```

Then filter rows by treshold and boolean indexing. Then is necessary choose which value is necessary, one possible solution is get longer text. So is uses DataFrameGroupBy.idxmax with DataFrame.loc and then DataFrame.set_index for Series:

```<code>N = 15
df2 = df1[df1['ratio'].gt(N)]
s = df2.loc[df2.groupby('ID')['len'].idxmax()].set_index('ID')['Name_x']
print (s)
ID
789    PQR.com
Name: Name_x, dtype: object
</code>```

Last Series.map by ID and replace non matched values by original with Series.fillna:

```<code>df['Name'] = df['ID'].map(s).fillna(df['Name'])
print (df)
      Name   ID
0      Abc  123
1      BCD  123
2      Def  345
3  PQR.com  789
4  PQR.com  789
</code>```

EDIT: If there is more valid strings per ID is is more complicated:

```<code>print (df)
               Name          ID
0      Air Ordnance  1578013421
1  Air-Ordnance.com  1578013421
2          Garreett  1578013421
3           Garrett  1578013421
</code>```

First get fuzz.ratio like in solution before:

```<code>from fuzzywuzzy import fuzz

df1 = df.merge(df, on='ID').query('Name_x != Name_y')
df1['ratio'] = df1.apply(lambda x:  fuzz.ratio(x['Name_x'], x['Name_y']), axis=1)
print (df1)
              Name_x          ID            Name_y  ratio
1       Air Ordnance  1578013421  Air-Ordnance.com     79
2       Air Ordnance  1578013421          Garreett     30
3       Air Ordnance  1578013421           Garrett     32
4   Air-Ordnance.com  1578013421      Air Ordnance     79
6   Air-Ordnance.com  1578013421          Garreett     25
7   Air-Ordnance.com  1578013421           Garrett     26
8           Garreett  1578013421      Air Ordnance     30
9           Garreett  1578013421  Air-Ordnance.com     25
11          Garreett  1578013421           Garrett     93
12           Garrett  1578013421      Air Ordnance     32
13           Garrett  1578013421  Air-Ordnance.com     26
14           Garrett  1578013421          Garreett     93
</code>```

Then filter by threshold:

```<code>N = 50
df2 = df1[df1['ratio'].gt(N)]
print (df2)

              Name_x          ID            Name_y  ratio
1       Air Ordnance  1578013421  Air-Ordnance.com     79
4   Air-Ordnance.com  1578013421      Air Ordnance     79
11          Garreett  1578013421           Garrett     93
14           Garrett  1578013421          Garreett     93
</code>```

But for more precision is necessary specify, what strings are valid in list L, filter by list:

```<code>L = ['Air-Ordnance.com','Garrett']
df2 = df2.loc[df2['Name_x'].isin(L),['Name_x','Name_y','ID']].rename(columns={'Name_y':'Name'})
print (df2)
              Name_x          Name          ID
4   Air-Ordnance.com  Air Ordnance  1578013421
14           Garrett      Garreett  1578013421
</code>```

Last merge with left join to original and repalce missing values:

```<code>df = df.merge(df2, on=['Name','ID'], how='left')
df['Name'] = df.pop('Name_x').fillna(df['Name'])
print (df)
               Name          ID
0  Air-Ordnance.com  1578013421
1  Air-Ordnance.com  1578013421
2           Garrett  1578013421
3           Garrett  1578013421
</code>```

Body:
I have a data frame that has a name and the URL ID of the name. For example:

Abc           123
Abc.com       123
Def           345
Pqr           123
PQR.com       123

Here due to data extraction error, at times different names have same ID. I want to clean the table such that if the names are different and ID is same, then the record should remain the same. If the names are similar and ID is also same, the name should be changed to one. To be clear,

The expected output should be:

Abc.com     123
Abc.com     123
Def         354
PQR.com     123
PQR.com     123

That is, the last one was data entry error..and both were the same name(The first word of the string was the same). So they are changed to one name looking at ID.
But first and second records even though they had a similar ID to the last ones their names did not match and were completely different.

I am not able to understand how to achieve this.

Request some guidance here. Thanks in advance.

Note: The size of the dataset is almost 16 million of such records.

Body:
Idea is use fuzzy matching lib fuzzywuzzy for ratio of all combinations of Names by cross join by DataFrame.merge and removed rows with same names in both columns by DataFrame.query, also was added new column by lengths of data by Series.str.len:

from fuzzywuzzy import fuzz

df1 = df.merge(df, on='ID').query('Name_x != Name_y')
df1['ratio'] = df1.apply(lambda x:  fuzz.ratio(x['Name_x'], x['Name_y']), axis=1)
df1['len'] = df1['Name_x'].str.len()
print (df1)
    Name_x   ID   Name_y  ratio  len
1      Abc  123      BCD      0    3
2      BCD  123      Abc      0    3
6      Pqr  789  PQR.com     20    3
7  PQR.com  789      Pqr     20    7

Then filter rows by treshold and boolean indexing. Then is necessary choose which value is necessary, one possible solution is get longer text. So is uses DataFrameGroupBy.idxmax with DataFrame.loc and then DataFrame.set_index for Series:

N = 15
df2 = df1[df1['ratio'].gt(N)]
s = df2.loc[df2.groupby('ID')['len'].idxmax()].set_index('ID')['Name_x']
print (s)
ID
789    PQR.com
Name: Name_x, dtype: object

Last Series.map by ID and replace non matched values by original with Series.fillna:

df['Name'] = df['ID'].map(s).fillna(df['Name'])
print (df)
      Name   ID
0      Abc  123
1      BCD  123
2      Def  345
3  PQR.com  789
4  PQR.com  789

EDIT: If there is more valid strings per ID is is more complicated:

print (df)
               Name          ID
0      Air Ordnance  1578013421
1  Air-Ordnance.com  1578013421
2          Garreett  1578013421
3           Garrett  1578013421

First get fuzz.ratio like in solution before:

from fuzzywuzzy import fuzz

df1 = df.merge(df, on='ID').query('Name_x != Name_y')
df1['ratio'] = df1.apply(lambda x:  fuzz.ratio(x['Name_x'], x['Name_y']), axis=1)
print (df1)
              Name_x          ID            Name_y  ratio
1       Air Ordnance  1578013421  Air-Ordnance.com     79
2       Air Ordnance  1578013421          Garreett     30
3       Air Ordnance  1578013421           Garrett     32
4   Air-Ordnance.com  1578013421      Air Ordnance     79
6   Air-Ordnance.com  1578013421          Garreett     25
7   Air-Ordnance.com  1578013421           Garrett     26
8           Garreett  1578013421      Air Ordnance     30
9           Garreett  1578013421  Air-Ordnance.com     25
11          Garreett  1578013421           Garrett     93
12           Garrett  1578013421      Air Ordnance     32
13           Garrett  1578013421  Air-Ordnance.com     26
14           Garrett  1578013421          Garreett     93

Then filter by threshold:

N = 50
df2 = df1[df1['ratio'].gt(N)]
print (df2)

              Name_x          ID            Name_y  ratio
1       Air Ordnance  1578013421  Air-Ordnance.com     79
4   Air-Ordnance.com  1578013421      Air Ordnance     79
11          Garreett  1578013421           Garrett     93
14           Garrett  1578013421          Garreett     93

But for more precision is necessary specify, what strings are valid in list L, filter by list:

L = ['Air-Ordnance.com','Garrett']
df2 = df2.loc[df2['Name_x'].isin(L),['Name_x','Name_y','ID']].rename(columns={'Name_y':'Name'})
print (df2)
              Name_x          Name          ID
4   Air-Ordnance.com  Air Ordnance  1578013421
14           Garrett      Garreett  1578013421

Last merge with left join to original and repalce missing values:

df = df.merge(df2, on=['Name','ID'], how='left')
df['Name'] = df.pop('Name_x').fillna(df['Name'])
print (df)
               Name          ID
0  Air-Ordnance.com  1578013421
1  Air-Ordnance.com  1578013421
2           Garrett  1578013421
3           Garrett  1578013421


问:
How to move one HTML element below another with CSS
I am working with a 3rd party support provider and am trying to work around some limitations around what can be customized. I would like to add an HTML element (a) below a label, but only have access to css and footer html. My current idea is to add a hidden anchor in the footer and then try to reposition it via the css. I guess this MIGHT be possible with flexboxes, but my css foo is not that strong. So I figured I would come here and see if there was any way around it.

Concretely, I have a multiline textbox where users will enter their support request, and I need to insert an href to what can be asked right above it. I already have a ::before in place for some basic helper text, but I know that you cannot insert markup using css...thus my current attempt.

Is this even possible without knowing the specific location of each item...only their respective  identifiers?

Here is a jsfiddle that reproduces the page as minimized as I can get it.

Again, please note that I ONLY have the ability to add HTML to the bottom of the page (in the footer element), and a global css file (shown in the separate css). That means I cannot edit the html outside the footer - that would be too easy ;)

HTML

```<code><html id="portal_html"><head>
</head>
<body>
  <div id="container">
    <portal>
      <div data-id="ticketForm" id="layoutContainer">
        <div>
          <div>
            <div><h2>Submit a ticket</h2></div>
            <div id="field_description">
                <label for="description"><!-- react-text: 1235 -->Description<!-- /react-text --></label>
                    <div>
                        <div>
                            <div data-id="description">
                                <div id="description"><iframe name="deskEditor_New"></iframe></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
 <footer id="footerContainer"><div id="footerContainer"><div class="Footer__footerCopyrigt">
    <div class="Footer__container2">
        <span>Powered by </span>
        <a rel="noopener noreferrer" href="supporturl" target="_blank" class="Footer__footerLink">Support Provider</a>
        <span> | </span>
        <a rel="noopener noreferrer" href="terms" target="_blank" class="Footer__footerLink">Terms of Service</a>
        <span> | </span>
        <a rel="noopener noreferrer" href="privacy" target="_blank" class="Footer__footerLink">Privacy Policy</a>
      <a rel="noopener noreferrer" href="foo">target</a>
    </div>
</div>
</div></footer></portal></div></body></html>
</code>```

and current css:

```<code>    .ticketDetail .ConversationForm__list+.ConversationForm__list { display:none; }
div[data-id="description"]::before {
    content: "Some custom content";
    font-size: smaller;
}
label[for="description"], a[href="foo"]{
  order:-1;
}
body {
  display:flex;
  flex-direction:column;
}
</code>```

UPDATE
I found this SO that sadly shows flexbox will not work because they are not in the same heirarchy :/
....so I believe the answer is that this is not possible :(

答:
Can you use JS?

const textAreaWrapper = document.querySelector('.text')
const linky = document.querySelector('[href=linky]')
document.body.insertBefore(linky, textAreaWrapper)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.someclass {
  display: block;
}

.rest {
  display: block;
}

.text {
  display: block;
}</code>```

    foo

    <textarea></textarea>

more stuff
even more stuff
Here is a link I want above the textarea```

Body:
I am working with a 3rd party support provider and am trying to work around some limitations around what can be customized. I would like to add an HTML element (a) below a label, but only have access to css and footer html. My current idea is to add a hidden anchor in the footer and then try to reposition it via the css. I guess this MIGHT be possible with flexboxes, but my css foo is not that strong. So I figured I would come here and see if there was any way around it.

Concretely, I have a multiline textbox where users will enter their support request, and I need to insert an href to what can be asked right above it. I already have a ::before in place for some basic helper text, but I know that you cannot insert markup using css...thus my current attempt.

Is this even possible without knowing the specific location of each item...only their respective  identifiers?

Here is a jsfiddle that reproduces the page as minimized as I can get it.

Again, please note that I ONLY have the ability to add HTML to the bottom of the page (in the footer element), and a global css file (shown in the separate css). That means I cannot edit the html outside the footer - that would be too easy ;)

HTML

    <portal>

Submit a ticket

                Description

        Powered by
        Support Provider
         |
        Terms of Service
         |
        Privacy Policy
      target

</portal>

and current css:

    .ticketDetail .ConversationForm__list+.ConversationForm__list { display:none; }
div[data-id="description"]::before {
    content: "Some custom content";
    font-size: smaller;
}
label[for="description"], a[href="foo"]{
  order:-1;
}
body {
  display:flex;
  flex-direction:column;
}

UPDATE
I found this SO that sadly shows flexbox will not work because they are not in the same heirarchy :/
....so I believe the answer is that this is not possible :(

Body:
Can you use JS?

const textAreaWrapper = document.querySelector('.text')
const linky = document.querySelector('[href=linky]')
document.body.insertBefore(linky, textAreaWrapper)

.someclass {
  display: block;
}

.rest {
  display: block;
}

.text {
  display: block;
}

<span class="someclass">
    <label>foo</label>
  </span>
<span class="text">
    <textarea></textarea>
  </span>
<label class="rest">more stuff</label>
<label class="rest">even more stuff</label>
<a href="linky">Here is a link I want above the textarea</a>


问:
When the innerHTML is modified, why does it seem like the element is replaced in the debugger console?
With the following code, inside of Google Chrome's dev tool, it shows as if root2 is changing every second, but root2 should stay the same. If we say, it is the content of root2 that is changing, then the content of root1 is also updating too, but it is not flashing every second. Why is that?

setInterval(function() {

  document.getElementById('root2').innerHTML = ("
Hello, world!

" +
    new Date().toLocaleTimeString() + "
");

}, 1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="root1">
  <div id="root2"></div>
</div></code>```

root2 is flashing every second:

答:
Because they do highlight the parent node of any node that got removed:

const sentence = 'click to remove last text node';
root2.append.apply(root2, [...sentence]);

onclick = e => {
  lastNode = root2.childNodes[ root2.childNodes.length - 1 ];
  if(lastNode) lastNode.remove();
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="root1">
  <div id="root2"></div>
</div></code>```

They also do highlight any node that becomes a parentNode, as they do highlight any collapsed node where a new node is added:

(async function loop() {
  root2.append("first node insertion highlights the new parentNode");
  await wait(1000);
  // removal does too, as shown in previous snippet
  [...root2.childNodes].forEach(node => node.remove());
  await wait(1000);
  loop();
})();

function wait(ms) { return new Promise(res => setTimeout(res, ms)); }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="root1">
  <div id="root2"></div>
</div></code>```

So when you change you change the innerHTML of your Element, both these situations will happen:

first all its content is removed => highlight,

then your Element becomes a parentNode (again) => highlight.

Body:
With the following code, inside of Google Chrome's dev tool, it shows as if root2 is changing every second, but root2 should stay the same. If we say, it is the content of root2 that is changing, then the content of root1 is also updating too, but it is not flashing every second. Why is that?

setInterval(function() {

  document.getElementById('root2').innerHTML = ("
Hello, world!

" +
    new Date().toLocaleTimeString() + "
");

}, 1000);

root2 is flashing every second:

Body:
Because they do highlight the parent node of any node that got removed:

const sentence = 'click to remove last text node';
root2.append.apply(root2, [...sentence]);

onclick = e => {
  lastNode = root2.childNodes[ root2.childNodes.length - 1 ];
  if(lastNode) lastNode.remove();
};

<div id="root1">
  <div id="root2"></div>
</div>

They also do highlight any node that becomes a parentNode, as they do highlight any collapsed node where a new node is added:

(async function loop() {
  root2.append("first node insertion highlights the new parentNode");
  await wait(1000);
  // removal does too, as shown in previous snippet
  [...root2.childNodes].forEach(node => node.remove());
  await wait(1000);
  loop();
})();

function wait(ms) { return new Promise(res => setTimeout(res, ms)); }

<div id="root1">
  <div id="root2"></div>
</div>

So when you change you change the innerHTML of your Element, both these situations will happen:

first all its content is removed => highlight,

then your Element becomes a parentNode (again) => highlight.


问:
How do I get the handle of a particular window that's open?
Firstly, I have very very limited knowledge of C++.

A couple of years ago I managed to cobble some code together that read a memory area of some fruit machine emulation software. It worked based on the fruit machine window title having the letters "DX" in it.

The code I used was as follows:

```<code>    if (strstr(lpszTitle, "DX") && !strstr(lpszTitle, "=")) {
        cout << "\nFound fruity with name: " << lpszTitle << "\n";
        currentWindowName = lpszTitle;

        // Found "DX" in the title of the window
        // so it must be an MFME window
        GetWindowThreadProcessId(hWnd, &pid);
        HANDLE phandle = OpenProcess(PROCESS_VM_READ, 0, pid);

        if (!phandle)
        {
            cout << "\nCould not get handle!\n";
            soundHopperAlarm(5); // "Error, could not get window process handle"
            cin.get();
        }
        else
        { // rest of code here...
</code>```

Back then someone told me that a better way of getting the window handle was this code:

```<code>wchar_t process[] = L"MFME.exe";
DWORD pid= GetPID(process);
HANDLE phandle = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ, false, pid);
</code>```

I didn't change my code because (at the time) it suited my purpose. I simply changed all the "fruit machines" I was emulating to have the text "DX" in their title and it worked fine...

However, I'm currently trying to add over 1,000 fruit machines to the system and it would be a LOT easier if there was a more robust method for get the window handle without having to alter every window title.

I can't really make sense of the new code and simply copying/pasteing into my existing code causes errors around GetPID being undefined so I wondered if someone could help me with a robust solution to get the handle of the window that's open by the "MFME.exe" software?

Any help/guidance very much appreciated.

答:
To get a process handle (a handle to the process with the permissions you desire, not a window HWND handle) you may need to run your program as administrator.  If you're running it from the VS debugger you will need to run the VS process as admin as well.

Here is some code using CreateToolHelp32Snapshot to enumerate the processes to get the correct one.

#include <Windows.h>
#include <tlhelp32.h>

DWORD GetProcId(const char* procName)
{
    DWORD procId = 0;
    HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hSnap != INVALID_HANDLE_VALUE)
    {
        PROCESSENTRY32 procEntry;
        procEntry.dwSize = sizeof(procEntry);

        if (Process32First(hSnap, &procEntry))
        {
            do
            {
                if (!_stricmp(procEntry.szExeFile, procName))
                {
                    procId = procEntry.th32ProcessID;
                    break;
                }
            } while (Process32Next(hSnap, &procEntry));

        }
    }
    CloseHandle(hSnap);
    return procId;
}

int main()
{
    DWORD procId = GetProcId("MFME.exe");

    HANDLE hProc = 0;
    hProc = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ, false, procId);

    std::cout << std::hex << "0x" << hProc << std::endl;

    std::getchar();
    return 0;
}
```

This should fulfill your needs

Body:
Firstly, I have very very limited knowledge of C++.

A couple of years ago I managed to cobble some code together that read a memory area of some fruit machine emulation software. It worked based on the fruit machine window title having the letters "DX" in it.

The code I used was as follows:

    if (strstr(lpszTitle, "DX") && !strstr(lpszTitle, "=")) {
        cout << "\nFound fruity with name: " << lpszTitle << "\n";
        currentWindowName = lpszTitle;

        // Found "DX" in the title of the window
        // so it must be an MFME window
        GetWindowThreadProcessId(hWnd, &pid);
        HANDLE phandle = OpenProcess(PROCESS_VM_READ, 0, pid);

        if (!phandle)
        {
            cout << "\nCould not get handle!\n";
            soundHopperAlarm(5); // "Error, could not get window process handle"
            cin.get();
        }
        else
        { // rest of code here...

Back then someone told me that a better way of getting the window handle was this code:

wchar_t process[] = L"MFME.exe";
DWORD pid= GetPID(process);
HANDLE phandle = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ, false, pid);

I didn't change my code because (at the time) it suited my purpose. I simply changed all the "fruit machines" I was emulating to have the text "DX" in their title and it worked fine...

However, I'm currently trying to add over 1,000 fruit machines to the system and it would be a LOT easier if there was a more robust method for get the window handle without having to alter every window title.

I can't really make sense of the new code and simply copying/pasteing into my existing code causes errors around GetPID being undefined so I wondered if someone could help me with a robust solution to get the handle of the window that's open by the "MFME.exe" software?

Any help/guidance very much appreciated.

Body:
To get a process handle (a handle to the process with the permissions you desire, not a window HWND handle) you may need to run your program as administrator.  If you're running it from the VS debugger you will need to run the VS process as admin as well.

Here is some code using CreateToolHelp32Snapshot to enumerate the processes to get the correct one.

#include <Windows.h>
#include <tlhelp32.h>

DWORD GetProcId(const char* procName)
{
    DWORD procId = 0;
    HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hSnap != INVALID_HANDLE_VALUE)
    {
        PROCESSENTRY32 procEntry;
        procEntry.dwSize = sizeof(procEntry);

        if (Process32First(hSnap, &procEntry))
        {
            do
            {
                if (!_stricmp(procEntry.szExeFile, procName))
                {
                    procId = procEntry.th32ProcessID;
                    break;
                }
            } while (Process32Next(hSnap, &procEntry));

        }
    }
    CloseHandle(hSnap);
    return procId;
}

int main()
{
    DWORD procId = GetProcId("MFME.exe");

    HANDLE hProc = 0;
    hProc = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ, false, procId);

    std::cout << std::hex << "0x" << hProc << std::endl;

    std::getchar();
    return 0;
}

This should fulfill your needs


问:
Publishing xunit test results in Azure Devops fails with "No Result Found to Publish"
I want to publish xunit test results in an Azure Devops release pipeline using the "Publish test results" task Version 1.* and 2.*.

Although xunit test file is present and has content - I checked with ls and cat commands in the pipepline I get an error message like this:

```<code>2020-02-13T08:23:10.9093662Z Obtained XUnit Test Run Start Date: 2020-02-13T08:23:10.9092530Z and Completed Date: 2020-02-13T08:23:10.9092530Z
2020-02-13T08:23:10.9144214Z No Result Found to Publish '/home/vsts/work/r1/a/report/report.xml'.
2020-02-13T08:23:10.9149123Z Obtained XUnit Test Run Start Date: 2020-02-13T08:23:10.9148260Z and Completed Date: 2020-02-13T08:23:10.9148260Z
2020-02-13T08:23:10.9149993Z No Result Found to Publish '/home/vsts/work/r1/a/report/report1.xml'.
</code>```

The two files report1.xml and report2.xml get discovered properly but Azure DevOps says No Result Found to Publishand hesitates to publish them.

答:
I found a workaround to the problem which does not really solve the xunit publish issue but I can live with that.

The Xunit test result I would like to publish is from a testcafe runner which has many reporting possibilities. I switched to testcafe-reporter-junit and exported a junit test report. Then using the test publisher for junit files and everything works.

Since switching to VSTest also resolved it maybe it is just the xunit test publisher which has an issue.

Body:
I want to publish xunit test results in an Azure Devops release pipeline using the "Publish test results" task Version 1.* and 2.*.

Although xunit test file is present and has content - I checked with ls and cat commands in the pipepline I get an error message like this:

2020-02-13T08:23:10.9093662Z Obtained XUnit Test Run Start Date: 2020-02-13T08:23:10.9092530Z and Completed Date: 2020-02-13T08:23:10.9092530Z
2020-02-13T08:23:10.9144214Z No Result Found to Publish '/home/vsts/work/r1/a/report/report.xml'.
2020-02-13T08:23:10.9149123Z Obtained XUnit Test Run Start Date: 2020-02-13T08:23:10.9148260Z and Completed Date: 2020-02-13T08:23:10.9148260Z
2020-02-13T08:23:10.9149993Z No Result Found to Publish '/home/vsts/work/r1/a/report/report1.xml'.

The two files report1.xml and report2.xml get discovered properly but Azure DevOps says No Result Found to Publishand hesitates to publish them.


问:
Bootstrap Multi select search clear button click event not working
I am using bootstrap multi-selector with search enabled option.

I am trying to unselect all selected items on click of X button. But i am not able to handle click event for this button.

Please help or suggest a better way to do this.

Here is sample code:

```<code><select id="multiselect-users" name="users[]" multiple="multiple">
    <option value="1">User1</option>
    <option value="2">User2</option>
</select>

<script type="text/javascript">
 $('#multiselect-users').multiselect({
    enableFiltering: true
 });
  // .multiselect-clear-filter is X button class. This button is part of bootstrape-multiselect if you enable filter
 $(document).on('click', '.multiselect-clear-filter', function(){

    // not working :(
    alert('test');
 });
</script>
</code>```

I want to unselect all selected items on click of this X button.

答:
Hi You can try this option also</p>

```<code> $('#multiselect-users').multiselect({
        includeFilterClearBtn:true
 });
</code>```

Body:
I am using bootstrap multi-selector with search enabled option.

I am trying to unselect all selected items on click of X button. But i am not able to handle click event for this button.

Please help or suggest a better way to do this.

Here is sample code:

<select id="multiselect-users" name="users[]" multiple="multiple">
    <option value="1">User1</option>
    <option value="2">User2</option>
</select>

I want to unselect all selected items on click of this X button.

Body:
Hi You can try this option also

 $('#multiselect-users').multiselect({
        includeFilterClearBtn:true
 });


问:
See Node-js value in HTML
I want to see a Node-js value in a html file. I used an engine called pug.

app.js:

```<code>const express=require('express');
const app=express();
var bodyParser = require('body-parser');

app.set('views','views');
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({extended:false}));

app.get('/', function(q,r){
    r.render('index', { dataFromServer: 'Alireza'});
});
app.listen(8081,err => {
  console.log('Example app listening on port 8081!');
});
</code>```

index.pug:

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    var data = <%= dataFromServer %>
    alert(data)
  </script>
</html>
</code>```

My app.js is in the following path:

E:\Engine\app.js

index.pug is in:

E:\Engine\views

And modules are in:

E:\Engine\node_modules

But the following error occurrs whenever i request the related port:

```<code>Error: Failed to lookup view "index" in views directory "views"
    at Function.render (E:\Engine\node_modules\express\lib\application.js:580:17)
    at ServerResponse.render (E:\Engine\node_modules\express\lib\response.js:1012:7)
    at E:\Engine\app.js:10:4
    at Layer.handle [as handle_request] (E:\Engine\node_modules\express\lib\router\layer.js:95:5)
    at next (E:\Engine\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (E:\Engine\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (E:\Engine\node_modules\express\lib\router\layer.js:95:5)
    at E:\Engine\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (E:\Engine\node_modules\express\lib\router\index.js:335:12)
    at next (E:\Engine\node_modules\express\lib\router\index.js:275:10)
</code>```

This problem repeats whenever i change the engine. For example, i used ejs too. I altered path of views file many times but that error repeated again with my new paths. Please help a beginner man.

答:
Is this a duplicate for this answer?
Try using:</p>

```<code>app.set('views', path.join(__dirname, 'views'));
</code>```

Title: See Node-js value in HTML

Body:
I want to see a Node-js value in a html file. I used an engine called pug.

app.js:

const express=require('express');
const app=express();
var bodyParser = require('body-parser');

app.set('views','views');
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({extended:false}));

app.get('/', function(q,r){
    r.render('index', { dataFromServer: 'Alireza'});
});
app.listen(8081,err => {
  console.log('Example app listening on port 8081!');
});

index.pug:

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>

My app.js is in the following path:

E:\Engine\app.js

index.pug is in:

E:\Engine\views

And modules are in:

E:\Engine\node_modules

But the following error occurrs whenever i request the related port:

Error: Failed to lookup view "index" in views directory "views"
    at Function.render (E:\Engine\node_modules\express\lib\application.js:580:17)
    at ServerResponse.render (E:\Engine\node_modules\express\lib\response.js:1012:7)
    at E:\Engine\app.js:10:4
    at Layer.handle [as handle_request] (E:\Engine\node_modules\express\lib\router\layer.js:95:5)
    at next (E:\Engine\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (E:\Engine\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (E:\Engine\node_modules\express\lib\router\layer.js:95:5)
    at E:\Engine\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (E:\Engine\node_modules\express\lib\router\index.js:335:12)
    at next (E:\Engine\node_modules\express\lib\router\index.js:275:10)

This problem repeats whenever i change the engine. For example, i used ejs too. I altered path of views file many times but that error repeated again with my new paths. Please help a beginner man.

Body:
Is this a duplicate for this answer?
Try using:

app.set('views', path.join(__dirname, 'views'));


答:
That error seems to indicate that it is trying to find index.pug in some directory named views

Are you trying to hit localhost:8081/index or just localhost:8081? I think you just want to hit / (localhost:8081) to get index.pug in this case.

Also, instead of app.set('views', 'views);, you probably want app.set('views', path.join(__dirname, 'views'));

Title: See Node-js value in HTML


问:
how to send text to server and get array with volley and json
I want to send a name to the server and get some images from the server and put image in image slider.

I write this codes

```<code>private void getrequest(){

    StringRequest stringRequest=new StringRequest(Request.Method.POST, "http://192.168.43.112/image/items_slider/getdata.php",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Toast.makeText(SelectItemsActivity.this, "boa entrou",
                            Toast.LENGTH_LONG).show();
                    try {
                        JSONArray array=new JSONArray(response);
                        for (int i=0; i < array.length(); i++) {
                            JSONObject jo=array.getJSONObject(i);

                            SliderUtils sliderUtils = new SliderUtils();

                            sliderUtils.setSliderImageUrl(jo.getString("game_image"));

                            sliderImg.add(sliderUtils);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    viewPagerAdapter = new ViewPagerAdapter(sliderImg, SelectItemsActivity.this);

                    viewPager.setAdapter(viewPagerAdapter);
                    dotscount = viewPagerAdapter.getCount();
                    dots = new ImageView[dotscount];

                    for (int i = 0; i < dotscount; i++) {

                        dots[i] = new ImageView(SelectItemsActivity.this);
                        dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.nonactive_dot));
                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

                        params.setMargins(8, 0, 8, 0);

                        sliderDotspanel.addView(dots[i], params);

                    }

                    dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));

                    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                        @Override
                        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                        }

                        @Override
                        public void onPageSelected(int position) {

                            for (int i = 0; i < dotscount; i++) {
                                dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.nonactive_dot));
                            }
                            dots[position].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));

                        }

                        @Override
                        public void onPageScrollStateChanged(int state) {

                        }
                    });

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(SelectItemsActivity.this, "erro erro",
                            Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params=new HashMap<String, String>();

            params.put("name", name);

            return params;
        }

    };
    rq = Volley.newRequestQueue(SelectItemsActivity.this);
    rq.add(stringRequest);
}
</code>```

dot[] = This is the point at the bottom of the slider to show multiple images

sliderDotspanel = this is a LinearLayout for show dot

sliderImg = this is a list

And writes this error

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.avm.myapplication, PID: 14867
java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
    at com.avm.gamestore.SelectItemsActivity$5.onResponse(SelectItemsActivity.java:386)
    at com.avm.gamestore.SelectItemsActivity$5.onResponse(SelectItemsActivity.java:347)
    at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:78)
    at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
    at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:106)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:7000)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
</code>```

and get error from this

```<code>dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));
</code>```

please help me this is very important to me

答:
```<code>java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
</code>```

As the error is ArrayIndexOutOfBoundsException, it means that your resulting array has zero size. You should check this api on postman or any other platform to confirm that is it really resulting an array.

Body:
I want to send a name to the server and get some images from the server and put image in image slider.

I write this codes

private void getrequest(){

    StringRequest stringRequest=new StringRequest(Request.Method.POST, "http://192.168.43.112/image/items_slider/getdata.php",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Toast.makeText(SelectItemsActivity.this, "boa entrou",
                            Toast.LENGTH_LONG).show();
                    try {
                        JSONArray array=new JSONArray(response);
                        for (int i=0; i < array.length(); i++) {
                            JSONObject jo=array.getJSONObject(i);

                            SliderUtils sliderUtils = new SliderUtils();

                            sliderUtils.setSliderImageUrl(jo.getString("game_image"));

                            sliderImg.add(sliderUtils);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    viewPagerAdapter = new ViewPagerAdapter(sliderImg, SelectItemsActivity.this);

                    viewPager.setAdapter(viewPagerAdapter);
                    dotscount = viewPagerAdapter.getCount();
                    dots = new ImageView[dotscount];

                    for (int i = 0; i < dotscount; i++) {

                        dots[i] = new ImageView(SelectItemsActivity.this);
                        dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.nonactive_dot));
                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

                        params.setMargins(8, 0, 8, 0);

                        sliderDotspanel.addView(dots[i], params);

                    }

                    dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));

                    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                        @Override
                        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                        }

                        @Override
                        public void onPageSelected(int position) {

                            for (int i = 0; i < dotscount; i++) {
                                dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.nonactive_dot));
                            }
                            dots[position].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));

                        }

                        @Override
                        public void onPageScrollStateChanged(int state) {

                        }
                    });

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(SelectItemsActivity.this, "erro erro",
                            Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params=new HashMap<String, String>();

            params.put("name", name);

            return params;
        }

    };
    rq = Volley.newRequestQueue(SelectItemsActivity.this);
    rq.add(stringRequest);
}

dot[] = This is the point at the bottom of the slider to show multiple images

sliderDotspanel = this is a LinearLayout for show dot

sliderImg = this is a list

And writes this error

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.avm.myapplication, PID: 14867
java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
    at com.avm.gamestore.SelectItemsActivity$5.onResponse(SelectItemsActivity.java:386)
    at com.avm.gamestore.SelectItemsActivity$5.onResponse(SelectItemsActivity.java:347)
    at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:78)
    at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
    at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:106)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:7000)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)

and get error from this

dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));

please help me this is very important to me

Body:
java.lang.ArrayIndexOutOfBoundsException: length=0; index=0

As the error is ArrayIndexOutOfBoundsException, it means that your resulting array has zero size. You should check this api on postman or any other platform to confirm that is it really resulting an array.


问:
how can I remove the notification from the plugin "cordova-plugin-mauron85-background-geolocation"
In my application I do not want to show the notification or this type of messages to the user. I want you not to show up. How can I do it?

this is my configuration:

```<code>BackgroundGeolocation.configure({
locationProvider: BackgroundGeolocation.ACTIVITY_PROVIDER,
desiredAccuracy: BackgroundGeolocation.HIGH_ACCURACY,
stationaryRadius: 50,
distanceFilter: 50,
notificationTitle: 'Background tracking',
notificationText: 'enabled',
debug: true,
interval: 10000,
fastestInterval: 5000,
activitiesInterval: 10000,
url: 'http://192.168.81.15:3000/location',
httpHeaders: {
  'X-FOO': 'bar'
},
// customize post properties
postTemplate: {
  lat: '@latitude',
  lon: '@longitude',
  foo: 'bar' // you can also add your own properties
}
});
</code>```

答:
The toast notification is for debugging.

You can turn it off like this:

debug: false,

Body:
In my application I do not want to show the notification or this type of messages to the user. I want you not to show up. How can I do it?

this is my configuration:

BackgroundGeolocation.configure({
locationProvider: BackgroundGeolocation.ACTIVITY_PROVIDER,
desiredAccuracy: BackgroundGeolocation.HIGH_ACCURACY,
stationaryRadius: 50,
distanceFilter: 50,
notificationTitle: 'Background tracking',
notificationText: 'enabled',
debug: true,
interval: 10000,
fastestInterval: 5000,
activitiesInterval: 10000,
url: 'http://192.168.81.15:3000/location',
httpHeaders: {
  'X-FOO': 'bar'
},
// customize post properties
postTemplate: {
  lat: '@latitude',
  lon: '@longitude',
  foo: 'bar' // you can also add your own properties
}
});


问:
Twilio Autopilot - How can I receive images from Whatsapp?
I'm building a chatbot with Twilio Autopilot and I want to get the images that I send to the bot, how can I get it? How can I get locations as well?

Thanks a lot.

答:
Twilio developer evangelist here.

There isn't a simple way to do this, but there are a few potential work-arounds. One is to have a webhook endpoint that will get the input and if the payload contains elements of an image, then do whatever you want with it, otherwise if it is just text, then maybe send to Autopilot. That is gone over in this blog post on Autopilot enhancements in Node.js.

Another is to make a Twilio Function that would point to a Twilio Studio flow or Assets if it is media in the first message.

Another is to use Twilio Functions or a similar server. You should have an Autopilot task that redirects to that Function with JSON like this:

```<code>{
    "actions": [
        {
            "redirect": {
                "uri": "https://REPLACE-WITH-YOUR-FUNCTION-URL.twil.io/auso",
                "method": "POST"
            }
        }
    ]
}
</code>```

Then your Twilio Function could get the image URL with something like this in Node.js:

```<code>const bodyContent = event.MediaUrl0;
const filename = event.MessageSid + '.png';
</code>```

Now in a Collect Action you can also specify the Twilio.MEDIA  as the type for questions expecting Media and currently we support all media format which are supported by Twilio Messaging.

```<code>{
                        "question": "Please a take a picture of insurance card?",
                        "name": "insurance_card",
                        "type": "Twilio.MEDIA",
                        "validate": {
                            "allowed_types": {
                                "list": [
                                    "image/jpeg",
                                    "image/gif",
                                    "image/png",
                                    "image/bmp"
                                ]
                            },
</code>```

Lastly, you may be interested in this blog post on building an image classifier with Autopilot and TensorFlow.

Let me know if this helps at all! :D

Body:
Twilio developer evangelist here.

There isn't a simple way to do this, but there are a few potential work-arounds. One is to have a webhook endpoint that will get the input and if the payload contains elements of an image, then do whatever you want with it, otherwise if it is just text, then maybe send to Autopilot. That is gone over in this blog post on Autopilot enhancements in Node.js.

Another is to make a Twilio Function that would point to a Twilio Studio flow or Assets if it is media in the first message.

Another is to use Twilio Functions or a similar server. You should have an Autopilot task that redirects to that Function with JSON like this:

{
    "actions": [
        {
            "redirect": {
                "uri": "https://REPLACE-WITH-YOUR-FUNCTION-URL.twil.io/auso",
                "method": "POST"
            }
        }
    ]
}

Then your Twilio Function could get the image URL with something like this in Node.js:

const bodyContent = event.MediaUrl0;
const filename = event.MessageSid + '.png';

Now in a Collect Action you can also specify the Twilio.MEDIA  as the type for questions expecting Media and currently we support all media format which are supported by Twilio Messaging.

{
                        "question": "Please a take a picture of insurance card?",
                        "name": "insurance_card",
                        "type": "Twilio.MEDIA",
                        "validate": {
                            "allowed_types": {
                                "list": [
                                    "image/jpeg",
                                    "image/gif",
                                    "image/png",
                                    "image/bmp"
                                ]
                            },

Lastly, you may be interested in this blog post on building an image classifier with Autopilot and TensorFlow.

Let me know if this helps at all! :D


问:
I cannot get label tag
Hello guys when I click one of these words on Button, I take an error about NullReferenceException was unhandled.   look: error image

error image

namespace HangMan
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

```<code>    string[] words = { "PENCIL", "UMBRELLA", "RUBBER", "RING", "NECKLACE", "SPEED", "PROGRAMMER" };
    private void Form1_Load(object sender, EventArgs e)
    {
        setWords();
        getWords();
    }

    private void getWords()
    {
        Random rnd = new Random();

        string selectedWord = words[rnd.Next(0, words.Length)];

        foreach (char item in selectedWord)
        {
            Label lbl = new Label();
            lbl.AutoSize = false;
            lbl.Width = 25;
            lbl.Height = 25;
            lbl.Text = "_";
            flowLayoutPanel2.Controls.Add(lbl);
        }

    }
    private void setWords()
    {
        for (char i = 'A'; i <= 'Z'; i++)
        {
            Button btn = new Button();
            btn.Text = i.ToString();
            btn.Width = 25;
            btn.Height = 25;
            btn.Click += Btn_Click;

            flowLayoutPanel1.Controls.Add(btn);
        }
    }

    int Score = 0;

    private void Btn_Click(object sender, EventArgs e)
    {

        Button clicked = sender as Button;

        bool IsCharOpened = false;
        foreach (Control item in flowLayoutPanel2.Controls)
        {
            if (item is Label)
            {
                Label lbl = (Label)item;

                if (lbl.Tag.ToString() == clicked.Text)
                {
                    lbl.Text = clicked.Text;
                    Score += 100;
                    IsCharOpened = true;
                }
            }
        }

        if (IsCharOpened == false)
        {
            lblRemaining.Text = (int.Parse(lblRemaining.Text) - 1).ToString();
            if (int.Parse(lblRemaining.Text) == 0)
            {
                MessageBox.Show("YOU HAVE FAILED..!");
                Application.Exit();
            }
        }

        lblScore.Text = Score.ToString();
        clicked.Enabled = false;
    }
}
</code>```

}

I cannot find any solution, and I am new on c#. I need your help guys, thanks.

答:
Just try this and it should work.

```<code>clicked.Text
</code>```

To this:

```<code>clicked.Text.ToString();
</code>```

Title: I cannot get label tag

Body:
Hello guys when I click one of these words on Button, I take an error about NullReferenceException was unhandled.   look: error image

error image

namespace HangMan
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

    string[] words = { "PENCIL", "UMBRELLA", "RUBBER", "RING", "NECKLACE", "SPEED", "PROGRAMMER" };
    private void Form1_Load(object sender, EventArgs e)
    {
        setWords();
        getWords();
    }

    private void getWords()
    {
        Random rnd = new Random();

        string selectedWord = words[rnd.Next(0, words.Length)];

        foreach (char item in selectedWord)
        {
            Label lbl = new Label();
            lbl.AutoSize = false;
            lbl.Width = 25;
            lbl.Height = 25;
            lbl.Text = "_";
            flowLayoutPanel2.Controls.Add(lbl);
        }

    }
    private void setWords()
    {
        for (char i = 'A'; i <= 'Z'; i++)
        {
            Button btn = new Button();
            btn.Text = i.ToString();
            btn.Width = 25;
            btn.Height = 25;
            btn.Click += Btn_Click;

            flowLayoutPanel1.Controls.Add(btn);
        }
    }

    int Score = 0;

    private void Btn_Click(object sender, EventArgs e)
    {

        Button clicked = sender as Button;

        bool IsCharOpened = false;
        foreach (Control item in flowLayoutPanel2.Controls)
        {
            if (item is Label)
            {
                Label lbl = (Label)item;

                if (lbl.Tag.ToString() == clicked.Text)
                {
                    lbl.Text = clicked.Text;
                    Score += 100;
                    IsCharOpened = true;
                }
            }
        }

        if (IsCharOpened == false)
        {
            lblRemaining.Text = (int.Parse(lblRemaining.Text) - 1).ToString();
            if (int.Parse(lblRemaining.Text) == 0)
            {
                MessageBox.Show("YOU HAVE FAILED..!");
                Application.Exit();
            }
        }

        lblScore.Text = Score.ToString();
        clicked.Enabled = false;
    }
}

}

I cannot find any solution, and I am new on c#. I need your help guys, thanks.

Body:
Just try this and it should work.

clicked.Text

To this:

clicked.Text.ToString();


问:
PHP login cookie not recognized after a couple hours, but nonetheless remains, and cannot be replaced, even after deleted
I'm new to PHP, but not programming overall, and this has had me stumped for a few weeks now.

I'm working on a website where the login will start to be used by others so I can't use my workaround at that point.

This is the code to set the cookie.

```<code>ob_start();

...

session_register("myusername");

session_register("mypassword");

$cookiename = "loginsuccess";

$ipforcookie = $_SERVER['REMOTE_ADDR'];

$cookiedata = $myusername._.$ipforcookie;

$cookietime = time()+18000;

setcookie($cookiename, $cookiedata, $cookietime, '/', ".example.com");

...

ob_end_flush();
</code>```

This is the code I use to check if the cookie is valid.

```<code>if(isset($_COOKIE['loginsuccess'])){

    $arr = explode("_", $_COOKIE['loginsuccess']);

    if(strcmp($arr[1], $_SERVER['REMOTE_ADDR']) == 0){

        require("headerLogged.php");

    }else{

        require("header.php");

    }

}else{

    require("header.php");

}
</code>```

It checks if there is a cookie, and if the IP is match, in case someone tries to copy the cookie over to their computer or basic like that.

The problem is, I can login and the cookie is registered everywhere that i check for it... for about two hours. Then the website stops accepting it, and even after i delete the cookie, it will not create a new cookie unless i change the function call from...

```<code>setcookie($cookiename, $cookiedata, $cookietime, '/', ".example.com");
</code>```

to

```<code>setcookie($cookiename, $cookiedata, $cookietime, '/');
</code>```

Then the login and validation works again. Repeating as necessary every 2 hours. I can't do this any longer, because others will begin using this login without the knowledge I have of the code, or access to the site.

Edit: When i changed it to the later just now, it could be validated, but only on the part of the site that it was created (somewhat obviously, perhaps).

I hope I've given you enough information, and I appreciate any help you're willing to give me, related to this issue, because I'm sure even the small amount of code I've supplied reveals my novice status. In any case, thank you very much for your time.

答:
First, session_register() is deprecated since PHP 5.3.0 and should not be used any more. You should use the superglobal $_SESSION instead. See the PHP manpages for more information.

Also just checking whether or not a cookie has some value is not sufficient to secure your site. It is rather easy to fake a cookie in a browser, and the contents of cookies should be treated as any other user input (which means you should not assume it meets your expectations, you cannot be sure it even contains an underscore). Based on a mock cookie I should never get access to any parts of your site that require login.

A cookie could contain some session id value, and the session itself then contains further information about who's logged in (user_id, but no password). You also could use a cookie that contains the user_id and use that as extra verification. Never store any password in cookies or sessions.

Body:
I'm new to PHP, but not programming overall, and this has had me stumped for a few weeks now.

I'm working on a website where the login will start to be used by others so I can't use my workaround at that point.

This is the code to set the cookie.

ob_start();

...

session_register("myusername");

session_register("mypassword");

$cookiename = "loginsuccess";

$ipforcookie = $_SERVER['REMOTE_ADDR'];

$cookiedata = $myusername._.$ipforcookie;

$cookietime = time()+18000;

setcookie($cookiename, $cookiedata, $cookietime, '/', ".example.com");

...

ob_end_flush();

This is the code I use to check if the cookie is valid.

if(isset($_COOKIE['loginsuccess'])){

    $arr = explode("_", $_COOKIE['loginsuccess']);

    if(strcmp($arr[1], $_SERVER['REMOTE_ADDR']) == 0){

        require("headerLogged.php");

    }else{

        require("header.php");

    }

}else{

    require("header.php");

}

It checks if there is a cookie, and if the IP is match, in case someone tries to copy the cookie over to their computer or basic like that.

The problem is, I can login and the cookie is registered everywhere that i check for it... for about two hours. Then the website stops accepting it, and even after i delete the cookie, it will not create a new cookie unless i change the function call from...

setcookie($cookiename, $cookiedata, $cookietime, '/', ".example.com");

to

setcookie($cookiename, $cookiedata, $cookietime, '/');

Then the login and validation works again. Repeating as necessary every 2 hours. I can't do this any longer, because others will begin using this login without the knowledge I have of the code, or access to the site.

Edit: When i changed it to the later just now, it could be validated, but only on the part of the site that it was created (somewhat obviously, perhaps).

I hope I've given you enough information, and I appreciate any help you're willing to give me, related to this issue, because I'm sure even the small amount of code I've supplied reveals my novice status. In any case, thank you very much for your time.


问:
error: ‘imread’ was not declared in this scope
I am using OpenCV 4.0 from https://github.com/opencv/opencv/archive/4.0.0.zip
Below is the code

```<code>#include "opencv2/core.hpp"
#include <opencv2/core/utility.hpp>
#include "opencv2/highgui.hpp"

using namespace std;
using namespace cv;

int main(int argc, const char* argv[]){
    Mat frame0 = imread("hallo");
    return 0;
}
</code>```

I compile it with

```<code>g++ -std=c++11 test.cpp -o test -I/home/user/opencv/modules/core/include/ -I/home/user/opencv/modules/highgui/include/ -L/home/user/opencv/build/lib -lopencv_objdetect -lopencv_features2d -lopencv_imgproc -lopencv_highgui -lopencv_core -lopencv_imgcodecs
</code>```

It throws me error

```<code>test.cpp: In function ‘int main(int, const char**)’:
test.cpp:11:32: error: ‘imread’ was not declared in this scope
     Mat frame0 = imread("hallo");
</code>```

Any direction on how to resolve it?

答:
put #include <opencv2/imgcodecs.hpp> and use

```<code>g++ -std=c++11 test.cpp -o test -I/home/user/opencv/modules/core/include/ -I/home/user/opencv/modules/gapi/include/ -I/home/user/opencv/modules/highgui/include/ -I/home/user/opencv/modules/imgcodecs/include/  -L/home/user/opencv/build/lib -lopencv_objdetect -lopencv_features2d -lopencv_imgproc -lopencv_highgui -lopencv_core -lopencv_imgcodecs
</code>```

to compile will solve the problem

Body:
I am using OpenCV 4.0 from https://github.com/opencv/opencv/archive/4.0.0.zip
Below is the code

#include "opencv2/core.hpp"
#include <opencv2/core/utility.hpp>
#include "opencv2/highgui.hpp"

using namespace std;
using namespace cv;

int main(int argc, const char* argv[]){
    Mat frame0 = imread("hallo");
    return 0;
}

I compile it with

g++ -std=c++11 test.cpp -o test -I/home/user/opencv/modules/core/include/ -I/home/user/opencv/modules/highgui/include/ -L/home/user/opencv/build/lib -lopencv_objdetect -lopencv_features2d -lopencv_imgproc -lopencv_highgui -lopencv_core -lopencv_imgcodecs

It throws me error

test.cpp: In function ‘int main(int, const char**)’:
test.cpp:11:32: error: ‘imread’ was not declared in this scope
     Mat frame0 = imread("hallo");

Any direction on how to resolve it?

Body:
put #include <opencv2/imgcodecs.hpp> and use

g++ -std=c++11 test.cpp -o test -I/home/user/opencv/modules/core/include/ -I/home/user/opencv/modules/gapi/include/ -I/home/user/opencv/modules/highgui/include/ -I/home/user/opencv/modules/imgcodecs/include/  -L/home/user/opencv/build/lib -lopencv_objdetect -lopencv_features2d -lopencv_imgproc -lopencv_highgui -lopencv_core -lopencv_imgcodecs

to compile will solve the problem


问:
How do I select suitable rows from different relevant columns? (pandas Dataframe)
Everyone.I am the beginner for Pandas.
  My aim: select the most valuable team from the "team_list".
  the most valuable team means: most goals,least Yellow and Red Cards .
  the "team_list" consists of "Team","Goals","Yellow Cards","Red Cards" - four columns.
team_list shows

```<code>I want to solve the question like this,but it isn't python style. How can I do that?

sortGoals=euro.sort_values(by=['Goals'],ascending=False);
sortCards=sortGoals.sort_values(by=['Yellow Cards','Red Cards']);
print (sortCards.head(1));
the result :
              Team  Goals  Yellow Cards  Red Cards
5          Germany     10             4          0

the team information :
euro=DataFrame({'Team':['Croatia','Czech
Republic','Denmark','England','France','Germany',
'Greece','Italy','Netherlands','Poland','Portugal','Republic of
Ireland','Russia','Spain','Sweden','Ukraine'],'Goals':[4,4,4,5,3,10,5,6,2,2,6,1,5,12,5,2],'Yellow
Cards':[9,7,4,5,6,4,9,16,5,7,12,6,6,11,7,5],'Red Cards':[0,0,0,0,0,0,1,0,0,1,0,1,0,0,0,0]})

euro:
                Team  Goals  Yellow Cards  Red Cards
0               Croatia      4             9          0
1        Czech Republic      4             7          0
2               Denmark      4             4          0
3               England      5             5          0
4                France      3             6          0
5               Germany     10             4          0
6                Greece      5             9          1
7                 Italy      6            16          0
8           Netherlands      2             5          0
9                Poland      2             7          1
10             Portugal      6            12          0
11  Republic of Ireland      1             6          1
12               Russia      5             6          0
13                Spain     12            11          0
14               Sweden      5             7          0
15              Ukraine      2             5          0
</code>```

Joran Beasley inspires me, thank you.

```<code>   euro['RedCard_rate']=euro['Red Cards']/euro['Goals'];
   euro['YellowCard_rate']=euro['Yellow Cards']/euro['Goals'];
   sort_teams=euro.sort_values(by=['YellowCard_rate','RedCard_rate']);
   print (sort_teams[['Team','Goals','Yellow Cards','Red Cards']].head(1));

  the results:
          Team  Goals  Yellow Cards  Red Cards
   5   Germany     10             4          0
</code>```

答:
```<code>import pandas

df =pandas.DataFrame({'Team':['Croatia','Czech Republic',
'Denmark','England','France','Germany',
'Greece','Italy','Netherlands','Poland','Portugal','Republic of Ireland',
'Russia','Spain','Sweden','Ukraine'],
'Goals':[4,4,4,5,3,10,5,6,2,2,6,1,5,12,5,2],
'Yellow Cards':[9,7,4,5,6,4,9,16,5,7,12,6,6,11,7,5],
'Red Cards':[0,0,0,0,0,0,1,0,0,1,0,1,0,0,0,0]})

scores = df['Goals'] - df['Yellow Cards'] - df['Red Cards']
df2 = pandas.DataFrame({'Team': df['Team'],'score':scores})
print(df2['Team'][df2['score'].idxmax()])
</code>```

is that what you mean?

Body:
Everyone.I am the beginner for Pandas.
  My aim: select the most valuable team from the "team_list".
  the most valuable team means: most goals,least Yellow and Red Cards .
  the "team_list" consists of "Team","Goals","Yellow Cards","Red Cards" - four columns.
team_list shows

I want to solve the question like this,but it isn't python style. How can I do that?

sortGoals=euro.sort_values(by=['Goals'],ascending=False);
sortCards=sortGoals.sort_values(by=['Yellow Cards','Red Cards']);
print (sortCards.head(1));
the result :
              Team  Goals  Yellow Cards  Red Cards
5          Germany     10             4          0

the team information :
euro=DataFrame({'Team':['Croatia','Czech
Republic','Denmark','England','France','Germany',
'Greece','Italy','Netherlands','Poland','Portugal','Republic of
Ireland','Russia','Spain','Sweden','Ukraine'],'Goals':[4,4,4,5,3,10,5,6,2,2,6,1,5,12,5,2],'Yellow
Cards':[9,7,4,5,6,4,9,16,5,7,12,6,6,11,7,5],'Red Cards':[0,0,0,0,0,0,1,0,0,1,0,1,0,0,0,0]})

euro:
                Team  Goals  Yellow Cards  Red Cards
0               Croatia      4             9          0
1        Czech Republic      4             7          0
2               Denmark      4             4          0
3               England      5             5          0
4                France      3             6          0
5               Germany     10             4          0
6                Greece      5             9          1
7                 Italy      6            16          0
8           Netherlands      2             5          0
9                Poland      2             7          1
10             Portugal      6            12          0
11  Republic of Ireland      1             6          1
12               Russia      5             6          0
13                Spain     12            11          0
14               Sweden      5             7          0
15              Ukraine      2             5          0

Joran Beasley inspires me, thank you.

   euro['RedCard_rate']=euro['Red Cards']/euro['Goals'];
   euro['YellowCard_rate']=euro['Yellow Cards']/euro['Goals'];
   sort_teams=euro.sort_values(by=['YellowCard_rate','RedCard_rate']);
   print (sort_teams[['Team','Goals','Yellow Cards','Red Cards']].head(1));

  the results:
          Team  Goals  Yellow Cards  Red Cards
   5   Germany     10             4          0

Body:
import pandas

df =pandas.DataFrame({'Team':['Croatia','Czech Republic',
'Denmark','England','France','Germany',
'Greece','Italy','Netherlands','Poland','Portugal','Republic of Ireland',
'Russia','Spain','Sweden','Ukraine'],
'Goals':[4,4,4,5,3,10,5,6,2,2,6,1,5,12,5,2],
'Yellow Cards':[9,7,4,5,6,4,9,16,5,7,12,6,6,11,7,5],
'Red Cards':[0,0,0,0,0,0,1,0,0,1,0,1,0,0,0,0]})

scores = df['Goals'] - df['Yellow Cards'] - df['Red Cards']
df2 = pandas.DataFrame({'Team': df['Team'],'score':scores})
print(df2['Team'][df2['score'].idxmax()])

is that what you mean?


问:
set entire column to zero and then update a specific row
I want firstly antire def column set to be 0 except the row where id is a variable (this should be 1).

```<code>$sql = "update rolls set def = 0, def = 1 where id = :aid";
$st = $db->prepare($sql);
$st->execute([":aid" => $id]);
</code>```

result - the first part - set to 0 - doesn't work;

Any help?

答:
Separate into 2 queries</p>

```<code>// Query one ; query two
$sql = "update rolls set def = 0; update rolls set def = 1 where id = :aid";
$st = $db->prepare($sql);
$st->execute([":aid" => $id]);
</code>```

Body:
I want firstly antire def column set to be 0 except the row where id is a variable (this should be 1).

$sql = "update rolls set def = 0, def = 1 where id = :aid";
$st = $db->prepare($sql);
$st->execute([":aid" => $id]);

result - the first part - set to 0 - doesn't work;

Any help?

Body:
Separate into 2 queries

// Query one ; query two
$sql = "update rolls set def = 0; update rolls set def = 1 where id = :aid";
$st = $db->prepare($sql);
$st->execute([":aid" => $id]);


问:
Calculate angle (degree) of a straight line
I'm trying to determine angle in degrees of a straight line of two points, I came across many solutions online but none of them worked for me, consider this piece of code

```<code>import matplotlib.pyplot as plt
data = np.array([7405.,7447.4,7433.99,7410.,7443.15,7429.4,7590.03,7550.,7566.32,7619.62,7549.71,7551.8,7530,7522.99,7499.75,7453.99,7542.16,7564.,7552.77,7552])
y = [7606.672474,7570.240928]
plt.plot(data)
plt.plot([6,17], y)
plt.show()
</code>```

The target line is y it should be around -5 degrees just by looking at it.
It seems like most online solutions suggest that we can find the angle by doing

```<code>degree = np.math.atan2(y[-1] - y[0], x[-1] - x[0])
degree = np.degrees(degree)
</code>```

I omitted the other values of y to just the first and last point for simplicity so the x[-1] - x[0] part here would be 11=17-6 which is the length of y line across the x-axis, this is what most online solutions suggest, however all the approaches failed to get the right angle for this, I should note that during my tests some approaches seemed to give the right angle for a given data unit for example while totally failing on a different data unit like

```<code>data = [52.3384984,53.04757978,52.04276249,51.77348257,49.93056673,52.24062341,55.74022485,60.77761392,60.89290148,60.1995072,60.40524964,59.00590344,59.67589831,56.49266698,49.02464746,51.53876823,57.77368203,59.48092106,56.63155446,56.0648491 ]
y = [51.337288,50.331895]
plt.plot(data)
plt.plot([3,15], y)
plt.show()
</code>```

I also tried to min-max normalize the data but no success, so considering we have the first and last point of a line and its length how can we or is it possible to determine its angle in degrees?

答:
There are two angles you need to understand. The first one is calculated based data, the second one is calculated based on figure.

First one

The code you wrote is calculating first one:

```<code>degree = np.math.atan2(y[-1] - y[0], x[-1] - x[0])
degree = np.degrees(degree)
</code>```

It's delta_y = y[-1] - y[0] = -36.43, delta_x = x[-1] - x[0] = 11

degree = -73.20 which totally make sense if you draw a triangle in your mind.

Second one

However, you may question me that you are watching a line around -5 degree. That's second one which involve calculating display ratio, (notice y axis and x axis has different unit length in inches). Here I found a separated question to help you calculate that.

```<code>from operator import sub
def get_aspect(ax):
    # Total figure size
    figW, figH = ax.get_figure().get_size_inches()
    # Axis size on figure
    _, _, w, h = ax.get_position().bounds
    # Ratio of display units
    disp_ratio = (figH * h) / (figW * w)
    # Ratio of data units
    # Negative over negative because of the order of subtraction
    data_ratio = sub(*ax.get_ylim()) / sub(*ax.get_xlim())

    return disp_ratio / data_ratio
</code>```

So you need multiple that ratio to get manhattan distance of line end points.

```<code>ax = plt.gca()
ratio = get_aspect(ax)
degree = np.math.atan2((y[-1] - y[0])*ratio, x[-1] - x[0])
degree = np.degrees(degree)

</code>```

The result is -4.760350735146195 which is around -5.

Body:
I'm trying to determine angle in degrees of a straight line of two points, I came across many solutions online but none of them worked for me, consider this piece of code

import matplotlib.pyplot as plt
data = np.array([7405.,7447.4,7433.99,7410.,7443.15,7429.4,7590.03,7550.,7566.32,7619.62,7549.71,7551.8,7530,7522.99,7499.75,7453.99,7542.16,7564.,7552.77,7552])
y = [7606.672474,7570.240928]
plt.plot(data)
plt.plot([6,17], y)
plt.show()

The target line is y it should be around -5 degrees just by looking at it.
It seems like most online solutions suggest that we can find the angle by doing

degree = np.math.atan2(y[-1] - y[0], x[-1] - x[0])
degree = np.degrees(degree)

I omitted the other values of y to just the first and last point for simplicity so the x[-1] - x[0] part here would be 11=17-6 which is the length of y line across the x-axis, this is what most online solutions suggest, however all the approaches failed to get the right angle for this, I should note that during my tests some approaches seemed to give the right angle for a given data unit for example while totally failing on a different data unit like

data = [52.3384984,53.04757978,52.04276249,51.77348257,49.93056673,52.24062341,55.74022485,60.77761392,60.89290148,60.1995072,60.40524964,59.00590344,59.67589831,56.49266698,49.02464746,51.53876823,57.77368203,59.48092106,56.63155446,56.0648491 ]
y = [51.337288,50.331895]
plt.plot(data)
plt.plot([3,15], y)
plt.show()

I also tried to min-max normalize the data but no success, so considering we have the first and last point of a line and its length how can we or is it possible to determine its angle in degrees?

Body:
There are two angles you need to understand. The first one is calculated based data, the second one is calculated based on figure.

First one

The code you wrote is calculating first one:

degree = np.math.atan2(y[-1] - y[0], x[-1] - x[0])
degree = np.degrees(degree)

It's delta_y = y[-1] - y[0] = -36.43, delta_x = x[-1] - x[0] = 11

degree = -73.20 which totally make sense if you draw a triangle in your mind.

Second one

However, you may question me that you are watching a line around -5 degree. That's second one which involve calculating display ratio, (notice y axis and x axis has different unit length in inches). Here I found a separated question to help you calculate that.

from operator import sub
def get_aspect(ax):
    # Total figure size
    figW, figH = ax.get_figure().get_size_inches()
    # Axis size on figure
    _, _, w, h = ax.get_position().bounds
    # Ratio of display units
    disp_ratio = (figH * h) / (figW * w)
    # Ratio of data units
    # Negative over negative because of the order of subtraction
    data_ratio = sub(*ax.get_ylim()) / sub(*ax.get_xlim())

    return disp_ratio / data_ratio

So you need multiple that ratio to get manhattan distance of line end points.

ax = plt.gca()
ratio = get_aspect(ax)
degree = np.math.atan2((y[-1] - y[0])*ratio, x[-1] - x[0])
degree = np.degrees(degree)

The result is -4.760350735146195 which is around -5.