问:
How to get the request.body value in asp classic?
In an .asp classic page I´m getting a POST send to me(a JSON string) and it is send in the request.body, says the guy how send it.
But if I just have theresponse=request.form I am not getting anything?

So how do I get the value from a request.body?

答:
Some payment gateway API's I've used in the past have sent responses in this fashion. The data (JSON) is sent as a binary body post.

To read it you need to use Request.BinaryRead with Request.TotalBytes, then use Adodb.Stream to convert the binary to UTF8 text:

Response.ContentType = "application/json"

Function BytesToStr(bytes)
    Dim Stream
    Set Stream = Server.CreateObject("Adodb.Stream")
        Stream.Type = 1 'adTypeBinary
        Stream.Open
        Stream.Write bytes
        Stream.Position = 0
        Stream.Type = 2 'adTypeText
        Stream.Charset = "utf-8"
        BytesToStr = Stream.ReadText
        Stream.Close
    Set Stream = Nothing
End Function

' You shouldn't really be receiving any posts more than a few KB,
' but it might be wise to include a limit (200KB in this example),
' Anything larger than that is a bit suspicious. If you're dealing
' with a payment gateway the usual protocol is to post the JSON
' back to them for verification before processing.

if Request.TotalBytes > 0 AND Request.TotalBytes <= 200000 then

    Dim postBody
    postBody = BytesToStr(Request.BinaryRead(Request.TotalBytes))

    Response.Write(postBody) ' the JSON... hopefully

end if
```


来源: stackexchange

问:
How to reload/refresh a react-table component from my form component
I have two reactJS components:

CustomerForm component with a form and form handling code.

CustomerList component which lists the customers using react-table.

Both components are functional and I can use the form to add data to the database, and then fetch and display data in react-table.

But I can't figure out how to refresh the react-table data on successful form submission.

I am loading the components directly into an HTML page and using babel to process JSX. I am just starting our with reactJS and more used to PHP/jQuery development, so maybe I am approaching this wrong. Would appreciate any feedback.

My code:

CustomerForm

```<code>class CustomerForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {data: [], name: '', phone: '', nameErr: '', phoneErr: ''};
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event) {
        const target = event.target;
        const name = target.name;
        this.setState({[name]: event.target.value});
    }

    handleSubmit(event) {
        event.preventDefault();

        var self = this;

        axios.post(APP_URL + '/customer/add', {
            name: this.state.name,
            phone: this.state.phone
        }).then(function (response) {
            //console.log(response);
            var data = response.data;
            if (data.status === 0) {
                if (typeof data.payload === 'object') {
                    for (var key in data.payload) {
                        if (data.payload[key]) {
                            self.setState({[key]: data.payload[key]});
                        }
                    }
                }
            }
        }).catch(function (error) {
            console.log(error);
        });
    }

    render() {
        return (
                <div className="container mt-3">
                    <form onSubmit={this.handleSubmit}>
                        <div className="row">
                            <div className="col-6">
                                <div className="form-group">
                                    <label>Name</label>
                                    <input name="name" type="text" className={'form-control ' + (this.state.nameErr ? 'is-invalid' : '')} placeholder="Enter name"  value={this.state.value} onChange={this.handleChange} />
                                    <div className="invalid-feedback">{this.state.nameErr}</div>
                                </div>
                                <div className="form-group">
                                    <label>Email address</label>
                                    <input name="phone" type="text" className="form-control" placeholder="Enter phone"  value={this.state.value} onChange={this.handleChange} />
                                </div>
                                <button type="submit" className="btn btn-primary">Submit</button>
                            </div>
                        </div>
                    </form>
                </div>

                );
    }
}

const domContainer = document.querySelector('#CustomerFormContainer');
ReactDOM.render(e(CustomerForm), domContainer);
</code>```

Customer List

```<code>class CustomerList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {data: [], loading: false, pages: null};
        this.fetchData = this.fetchData.bind(this);
    }

    fetchData(state, instance) {
        var self = this;

        this.setState({loading: true});

        axios.post(APP_URL + '/customer/index', {
            page: state.page,
            pageSize: state.pageSize,
            sorted: state.sorted,
            filtered: state.filtered
        }).then(function (response) {
            // handle success
            self.setState({
                data: response.data.payload,
                pages: 1,
                loading: false
            });
        }).catch(function (error) {
            // handle error
            console.log(error);
        }).finally(function () {
            // always executed
        });
    }

    render() {
        const {data, pages, loading} = this.state;
        return (
                <div className="container mt-3">
                    <ReactTable
                        columns={[
                                    {
                                        Header: "Name",
                                        accessor: "name"
                                    },
                                    {
                                        Header: "Phone",
                                        accessor: "phone"
                                    }
                                ]}
                        manual
                        data={this.state.data}
                        pages={this.state.pages}
                        loading={this.state.loading}
                        onFetchData={this.fetchData}
                        defaultPageSize={10}
                        className="-striped -highlight"
                        />
                    <br />
                </div>
                );
    }
}

const domContainer = document.querySelector('#CustomerListContainer');
ReactDOM.render(e(CustomerList), domContainer);
</code>```

答:
TL;DR

Render both components in a parent component. Lift the table state up and pass a function to the form that will call the function to fetch data.

First of all, one quick tip. Render only one component in one div and then nest all the other components inside.

In both files, you are rendering the component in diferent selectors

CustomerForm

```<code>const domContainer = document.querySelector('#CustomerFormContainer');
ReactDOM.render(e(CustomerForm), domContainer);
</code>```

Customer List

```<code>const domContainer = document.querySelector('#CustomerListContainer');
ReactDOM.render(e(CustomerList), domContainer);
</code>```

This isn't good because this way, it's not easy to share state and props between then.

What you should do is have a root component that render both components.

```<code>class App extends React.Component {
    render() {
        return (
            <CustomerForm />
            <CustomerList />
        )
    }
}

const domContainer = document.querySelector('#app');
ReactDOM.render(e(App), domContainer);
</code>```

OBSERVATION
I'm not sure what is the e function and why you are using, but I assume this won't change anything, but please, specify what it is.

Doing this, you can share state and props between components.

```<code>class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data: [], loading: false, pages: null };
    this.fetchData = this.fetchData.bind(this);
    this.reloadData = this.reloadData.bind(this);
  }

  reloadData() {
    this.fetchData(state);
  }

  fetchData(state, instance) {
    var self = this;

    this.setState({ loading: true });

    axios
      .post(APP_URL + "/customer/index", {
        page: state.page,
        pageSize: state.pageSize,
        sorted: state.sorted,
        filtered: state.filtered
      })
      .then(function(response) {
        // handle success
        self.setState({
          data: response.data.payload,
          pages: 1,
          loading: false
        });
      })
      .catch(function(error) {
        // handle error
        console.log(error);
      })
      .finally(function() {
        // always executed
      });
  }
  render() {
    return (
      <div>
        <CustomerForm reloadData={reloadData} />
        <CustomerList data={data} pages={pages} loading={loading} fetchData={fetchData} />
      </div>
    );
  }
}
</code>```

Here what I'm doing is called Lifting State Up. I'm getting the state of CustomerList to the parent component so you can reload the data when the form calls reloadData.

This way you also need to change CustomerList to get the data from this.props and in CustomerForm call reloadData when the submit is success.

Customer List

```<code>  render() {                                   // getting from props
    const { data, pages, loading, fetchData } = this.props;
    return (
      <div className="container mt-3">
        <ReactTable
          columns={[
            {
              Header: "Name",
              accessor: "name"
            },
            {
              Header: "Phone",
              accessor: "phone"
            }
          ]}
          manual
          data={data}
          pages={pages}
          loading={loading}
          onFetchData={fetchData}
          defaultPageSize={10}
          className="-striped -highlight"
        />
        <br />
      </div>
    );
  }
</code>```

CustomerForm

Call this.props.reloadData() when the submit is success.

*I don't know when you want to reload the data, it's not clear when is a succes.

ContentLicense: CC BY-SA 4.0

Body:
I have two reactJS components:

CustomerForm component with a form and form handling code.

CustomerList component which lists the customers using react-table.

Both components are functional and I can use the form to add data to the database, and then fetch and display data in react-table.

But I can't figure out how to refresh the react-table data on successful form submission.

I am loading the components directly into an HTML page and using babel to process JSX. I am just starting our with reactJS and more used to PHP/jQuery development, so maybe I am approaching this wrong. Would appreciate any feedback.

My code:

CustomerForm

class CustomerForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {data: [], name: '', phone: '', nameErr: '', phoneErr: ''};
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event) {
        const target = event.target;
        const name = target.name;
        this.setState({[name]: event.target.value});
    }

    handleSubmit(event) {
        event.preventDefault();

        var self = this;

        axios.post(APP_URL + '/customer/add', {
            name: this.state.name,
            phone: this.state.phone
        }).then(function (response) {
            //console.log(response);
            var data = response.data;
            if (data.status === 0) {
                if (typeof data.payload === 'object') {
                    for (var key in data.payload) {
                        if (data.payload[key]) {
                            self.setState({[key]: data.payload[key]});
                        }
                    }
                }
            }
        }).catch(function (error) {
            console.log(error);
        });
    }

    render() {
        return (

                    <form onSubmit={this.handleSubmit}>

                                    Name
                                    <input name="name" type="text" className={'form-control ' + (this.state.nameErr ? 'is-invalid' : '')} placeholder="Enter name"  value={this.state.value} onChange={this.handleChange} />

{this.state.nameErr}

                                    Email address
                                    <input name="phone" type="text" className="form-control" placeholder="Enter phone"  value={this.state.value} onChange={this.handleChange} />

                                <button type="submit" className="btn btn-primary">Submit</button>

                    </form>

                );
    }
}

const domContainer = document.querySelector('#CustomerFormContainer');
ReactDOM.render(e(CustomerForm), domContainer);

Customer List

class CustomerList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {data: [], loading: false, pages: null};
        this.fetchData = this.fetchData.bind(this);
    }

    fetchData(state, instance) {
        var self = this;

        this.setState({loading: true});

        axios.post(APP_URL + '/customer/index', {
            page: state.page,
            pageSize: state.pageSize,
            sorted: state.sorted,
            filtered: state.filtered
        }).then(function (response) {
            // handle success
            self.setState({
                data: response.data.payload,
                pages: 1,
                loading: false
            });
        }).catch(function (error) {
            // handle error
            console.log(error);
        }).finally(function () {
            // always executed
        });
    }

    render() {
        const {data, pages, loading} = this.state;
        return (

                    <ReactTable
                        columns={[
                                    {
                                        Header: "Name",
                                        accessor: "name"
                                    },
                                    {
                                        Header: "Phone",
                                        accessor: "phone"
                                    }
                                ]}
                        manual
                        data={this.state.data}
                        pages={this.state.pages}
                        loading={this.state.loading}
                        onFetchData={this.fetchData}
                        defaultPageSize={10}
                        className="-striped -highlight"
                        />

                );
    }
}

const domContainer = document.querySelector('#CustomerListContainer');
ReactDOM.render(e(CustomerList), domContainer);

Body:
TL;DR

Render both components in a parent component. Lift the table state up and pass a function to the form that will call the function to fetch data.

First of all, one quick tip. Render only one component in one div and then nest all the other components inside.

In both files, you are rendering the component in diferent selectors

CustomerForm

const domContainer = document.querySelector('#CustomerFormContainer');
ReactDOM.render(e(CustomerForm), domContainer);

Customer List

const domContainer = document.querySelector('#CustomerListContainer');
ReactDOM.render(e(CustomerList), domContainer);

This isn't good because this way, it's not easy to share state and props between then.

What you should do is have a root component that render both components.

class App extends React.Component {
    render() {
        return (
            <CustomerForm />
            <CustomerList />
        )
    }
}

const domContainer = document.querySelector('#app');
ReactDOM.render(e(App), domContainer);

OBSERVATION
I'm not sure what is the e function and why you are using, but I assume this won't change anything, but please, specify what it is.

Doing this, you can share state and props between components.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data: [], loading: false, pages: null };
    this.fetchData = this.fetchData.bind(this);
    this.reloadData = this.reloadData.bind(this);
  }

  reloadData() {
    this.fetchData(state);
  }

  fetchData(state, instance) {
    var self = this;

    this.setState({ loading: true });

    axios
      .post(APP_URL + "/customer/index", {
        page: state.page,
        pageSize: state.pageSize,
        sorted: state.sorted,
        filtered: state.filtered
      })
      .then(function(response) {
        // handle success
        self.setState({
          data: response.data.payload,
          pages: 1,
          loading: false
        });
      })
      .catch(function(error) {
        // handle error
        console.log(error);
      })
      .finally(function() {
        // always executed
      });
  }
  render() {
    return (
      <div>
        <CustomerForm reloadData={reloadData} />
        <CustomerList data={data} pages={pages} loading={loading} fetchData={fetchData} />
      </div>
    );
  }
}

Here what I'm doing is called Lifting State Up. I'm getting the state of CustomerList to the parent component so you can reload the data when the form calls reloadData.

This way you also need to change CustomerList to get the data from this.props and in CustomerForm call reloadData when the submit is success.

Customer List

  render() {                                   // getting from props
    const { data, pages, loading, fetchData } = this.props;
    return (
      <div className="container mt-3">
        <ReactTable
          columns={[
            {
              Header: "Name",
              accessor: "name"
            },
            {
              Header: "Phone",
              accessor: "phone"
            }
          ]}
          manual
          data={data}
          pages={pages}
          loading={loading}
          onFetchData={fetchData}
          defaultPageSize={10}
          className="-striped -highlight"
        />
        <br />
      </div>
    );
  }

CustomerForm

Call this.props.reloadData() when the submit is success.

*I don't know when you want to reload the data, it's not clear when is a succes.


问:
How to sort values from value <String, Long> in an arraylist?
Is it possible to sort the current output of the code below in descending order without using comparators?

I've tried using one but I can't seem to make it work as it always gives an error.

I've tried looking at these two links as I know the answers might be in there:
Sort Map<String, Long> by value reversed , Sort a Map<Key, Value> by values

But since I'm quite new to java I don't really get what I need to do in order to get it working.

myRef.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(@NonNull DataSnapshot dataSnapshot , String s) {
        Map<String, Object> userInfo = (Map<String, Object>)dataSnapshot.getValue();
        String username = (String) userInfo.get("username");

        Map<String, Long> steps = (Map<String, Long>) userInfo.get("steps");

        long existingSteps = 0;
        for (Map.Entry<String, Long> step : steps.entrySet()) {
            existingSteps += Long.valueOf(step.getValue());
        }

        arrayList.add(new String( username + "  -  " + "steps:  " + existingSteps));

        arrayAdapter = new ArrayAdapter<>(Leaderboard.this ,
        android.R.layout.simple_list_item_1 , arrayList);

        listView.setAdapter(arrayAdapter);
}
```

<p>The current output of this code is:  </p>

```John Doe I - Steps: 79
John Doe II - Steps: 111
John Doe III - Steps: 0
John Doe IV - Steps: 88
John Doe V - Steps: 12
John Doe VI - Steps: 0
```

<p>preferred this code to run the following output:  </p>

```John Doe II - Steps: 111
John Doe IV - Steps: 88
John Doe I - Steps: 79
John Doe V - Steps: 12
John Doe III - Steps: 0
John Doe VI - Steps: 0
```

Is it possible for someone to explain to me how I would need to use those said links to get it working for me so I could get the output as listed above ?

答:
The Firebase Realtime Database can return child nodes ordered by the value of a property of each child node. But since you determine existingSteps by aggregating values from the database, there is no way to get the node from the database in this order, unless you also store the aggregated value in the database.

In your current data format, you will need to re-order the items in your array list client-side after aggregating the steps for all users.

If you were to modify the data format to include the aggregated existingSteps value, keep in mind that Firebase can only return results in ascending order. That means that to show them in reverse order, you'll either have to reverse the array list client-side, or store an additional property in the database that has the inverted value of existingSteps so that ordering on that gives the reversed results. For more on this, see firebase -> date order reverse

Body:
Is it possible to sort the current output of the code below in descending order without using comparators?

I've tried using one but I can't seem to make it work as it always gives an error.

I've tried looking at these two links as I know the answers might be in there:
Sort Map<String, Long> by value reversed , Sort a Map<Key, Value> by values

But since I'm quite new to java I don't really get what I need to do in order to get it working.

myRef.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(@NonNull DataSnapshot dataSnapshot , String s) {
        Map<String, Object> userInfo = (Map<String, Object>)dataSnapshot.getValue();
        String username = (String) userInfo.get("username");

        Map<String, Long> steps = (Map<String, Long>) userInfo.get("steps");

        long existingSteps = 0;
        for (Map.Entry<String, Long> step : steps.entrySet()) {
            existingSteps += Long.valueOf(step.getValue());
        }

        arrayList.add(new String( username + "  -  " + "steps:  " + existingSteps));

        arrayAdapter = new ArrayAdapter<>(Leaderboard.this ,
        android.R.layout.simple_list_item_1 , arrayList);

        listView.setAdapter(arrayAdapter);
}

The current output of this code is:

John Doe I - Steps: 79
John Doe II - Steps: 111
John Doe III - Steps: 0
John Doe IV - Steps: 88
John Doe V - Steps: 12
John Doe VI - Steps: 0

preferred this code to run the following output:

John Doe II - Steps: 111
John Doe IV - Steps: 88
John Doe I - Steps: 79
John Doe V - Steps: 12
John Doe III - Steps: 0
John Doe VI - Steps: 0

Is it possible for someone to explain to me how I would need to use those said links to get it working for me so I could get the output as listed above ?


问:
how to modify query string whose filter value contains &
I have constructed an URL like -

```<code>http://server_name/_vti_bin/owssvr.dll?Cmd=Display&List={List-Id}&XMLDATA=TRUE&View={View-Id}&Query=*&FilterField1=Country_x0020_Name&FilterValue1=UK & Ireland
</code>```

which ofcourse doesnot give me the expected output.
How to specify the filer value if there is an '&' character in the string?
The filter value is retrieved from a sharepoint list that contains the list of countries

答:
You need to encode the value of the filter parameter according to RFC 3986. If you're building the url using javascript, then you would do this using a call to encodeURIComponent(rawData):

```<code>var url = hostpath + "?Query=" + encodeURIComponent(filterValue);
</code>```

This will take care of '&', spaces and other characters that would otherwise cause a problem. If you're hard-coding the URL, then you can use one of the many public access tools to see what the encoded value should look like, e.g. W3Schools.com

ContentLicense: CC BY-SA 3.0

Body:
I have constructed an URL like -

http://server_name/_vti_bin/owssvr.dll?Cmd=Display&List={List-Id}&XMLDATA=TRUE&View={View-Id}&Query=*&FilterField1=Country_x0020_Name&FilterValue1=UK & Ireland

which ofcourse doesnot give me the expected output.
How to specify the filer value if there is an '&' character in the string?
The filter value is retrieved from a sharepoint list that contains the list of countries

Body:
You need to encode the value of the filter parameter according to RFC 3986. If you're building the url using javascript, then you would do this using a call to encodeURIComponent(rawData):

var url = hostpath + "?Query=" + encodeURIComponent(filterValue);

This will take care of '&', spaces and other characters that would otherwise cause a problem. If you're hard-coding the URL, then you can use one of the many public access tools to see what the encoded value should look like, e.g. W3Schools.com


问:
Make public domain name only accessible from internal network
I bought a domain name from 1and1 but would like it to only be accessible for people connected to our company's internal network. Is it possible to continue letting 1and1 host the domain while also preventing access to the website unless connected to company network?</p>

答:
To Make public domain name only accessible from internal network, you can place a .htaccess at the root of your host with a 403 Error for All but your company network IP (xx.xx.xx.xx).

```<code>order deny,allow
deny from all
allow from xx.xx.xx.xx
</code>```

To go further and make it cleaner, you should also redirect unwanted users to a public page with this line below the previous code:

```<code>ErrorDocument 403 http://example.com
</code>```

Body:
To Make public domain name only accessible from internal network, you can place a .htaccess at the root of your host with a 403 Error for All but your company network IP (xx.xx.xx.xx).

order deny,allow
deny from all
allow from xx.xx.xx.xx

To go further and make it cleaner, you should also redirect unwanted users to a public page with this line below the previous code:

ErrorDocument 403 http://example.com


问:
Calculate mean of specific row pattern
I have a dataframe like this:

```<code>V1 = paste0("AB", seq(1:48))
V2 = seq(1:48)

test = data.frame(name = V1, value = V2)
</code>```

I want to calculate the means of the value-column and specific rows.

The pattern of the rows is pretty complicated:

```<code>Rows of MeanA1: 1, 5, 9
Rows of MeanA2: 2, 6, 10
Rows of MeanA3: 3, 7, 11
Rows of MeanA4: 4, 8, 12

Rows of MeanB1: 13, 17, 21
Rows of MeanB2: 14, 18, 22
Rows of MeanB3: 15, 19, 23
Rows of MeanB4: 16, 20, 24

Rows of MeanC1: 25, 29, 33
Rows of MeanC2: 26, 30, 34
Rows of MeanC3: 27, 31, 35
Rows of MeanC4: 28, 32, 36

Rows of MeanD1: 37, 41, 45
Rows of MeanD2: 38, 42, 46
Rows of MeanD3: 39, 43, 47
Rows of MeanD4: 40, 44, 48
</code>```

As you see its starting at 4 different points (1, 13, 25, 37) then always +4 and for the following 4 means its just stepping 1 more row down.

I would like to have an output of all these means in one list.

Any ideas? NOTE: In this example the mean is of course always the middle number, but my real df is different.

答:
And yet another way.</p>

```<code>fun <- function(DF, col, step = 4){
  run <- nrow(DF)/step^2
  res <- lapply(seq_len(step), function(inc){
    inx <- seq_len(run*step) + (inc - 1)*run*step
    dftmp <- DF[inx, ]
    tapply(dftmp[[col]], rep(seq_len(step), run), mean, na.rm = TRUE)
  })
  names(res) <- sprintf("Mean%s", LETTERS[seq_len(step)])
  res
}

fun(test, 2, 4)
#$MeanA
#1 2 3 4
#5 6 7 8
#
#$MeanB
# 1  2  3  4
#17 18 19 20
#
#$MeanC
# 1  2  3  4
#29 30 31 32
#
#$MeanD
# 1  2  3  4
#41 42 43 44
</code>```

Title: Calculate mean of specific row pattern

Body:
I have a dataframe like this:

V1 = paste0("AB", seq(1:48))
V2 = seq(1:48)

test = data.frame(name = V1, value = V2)

I want to calculate the means of the value-column and specific rows.

The pattern of the rows is pretty complicated:

Rows of MeanA1: 1, 5, 9
Rows of MeanA2: 2, 6, 10
Rows of MeanA3: 3, 7, 11
Rows of MeanA4: 4, 8, 12

Rows of MeanB1: 13, 17, 21
Rows of MeanB2: 14, 18, 22
Rows of MeanB3: 15, 19, 23
Rows of MeanB4: 16, 20, 24

Rows of MeanC1: 25, 29, 33
Rows of MeanC2: 26, 30, 34
Rows of MeanC3: 27, 31, 35
Rows of MeanC4: 28, 32, 36

Rows of MeanD1: 37, 41, 45
Rows of MeanD2: 38, 42, 46
Rows of MeanD3: 39, 43, 47
Rows of MeanD4: 40, 44, 48

As you see its starting at 4 different points (1, 13, 25, 37) then always +4 and for the following 4 means its just stepping 1 more row down.

I would like to have an output of all these means in one list.

Any ideas? NOTE: In this example the mean is of course always the middle number, but my real df is different.

Body:
And yet another way.

fun <- function(DF, col, step = 4){
  run <- nrow(DF)/step^2
  res <- lapply(seq_len(step), function(inc){
    inx <- seq_len(run*step) + (inc - 1)*run*step
    dftmp <- DF[inx, ]
    tapply(dftmp[[col]], rep(seq_len(step), run), mean, na.rm = TRUE)
  })
  names(res) <- sprintf("Mean%s", LETTERS[seq_len(step)])
  res
}

fun(test, 2, 4)
#$MeanA
#1 2 3 4
#5 6 7 8
#
#$MeanB
# 1  2  3  4
#17 18 19 20
#
#$MeanC
# 1  2  3  4
#29 30 31 32
#
#$MeanD
# 1  2  3  4
#41 42 43 44


问:
How to get Variation ID of Variable Product in WooCommerce?
On single product page of variable product, when I change different variation from the dropdown, I want to show the price from another custom field instead of default variation price (which field I already created in Dashboard). But, I didn't find a way to show the price on product page.

Here's my code:

```<code>add_filter('woocommerce_product_variation_get_regular_price', 'custom_price', 99, 2 );
add_filter('woocommerce_product_variation_get_price', 'custom_price', 99, 2 );

function custom_price( $price, $product )
{
    return $price;
}
</code>```

Inside the function custom_price, if I get the variation id, I could do something like this:

```<code>function custom_price( $price, $product )
{
    $variation_id = ???
    return get_post_meta( $variation_id, 'custom_field', true );
}
</code>```

How can I get variation id inside this function? Thanks in advance.

答:
You can simply use $product->get_id();

```<code>add_filter('woocommerce_product_variation_get_regular_price', 'custom_price', 99, 2 );
add_filter('woocommerce_product_variation_get_price', 'custom_price', 99, 2 );

function custom_price( $price, $product )
{
    $variation_id = $product->get_id();

    return get_post_meta( $variation_id, 'custom_field', true );
}
</code>```

Body:
On single product page of variable product, when I change different variation from the dropdown, I want to show the price from another custom field instead of default variation price (which field I already created in Dashboard). But, I didn't find a way to show the price on product page.

Here's my code:

add_filter('woocommerce_product_variation_get_regular_price', 'custom_price', 99, 2 );
add_filter('woocommerce_product_variation_get_price', 'custom_price', 99, 2 );

function custom_price( $price, $product )
{
    return $price;
}

Inside the function custom_price, if I get the variation id, I could do something like this:

function custom_price( $price, $product )
{
    $variation_id = ???
    return get_post_meta( $variation_id, 'custom_field', true );
}

How can I get variation id inside this function? Thanks in advance.

Body:
You can simply use $product->get_id();

add_filter('woocommerce_product_variation_get_regular_price', 'custom_price', 99, 2 );
add_filter('woocommerce_product_variation_get_price', 'custom_price', 99, 2 );

function custom_price( $price, $product )
{
    $variation_id = $product->get_id();

    return get_post_meta( $variation_id, 'custom_field', true );
}


问:
How to avoid java.lang.NoSuchMethodError: org.apache.poi.util.IOUtils.copy(Ljava/io/InputStream;Ljava/io/OutputStream;) in Apache POI
I have a code for adding watermark to existing .doc file.

The following is the code I have tried so far

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

    try
    {
        XWPFDocument xDoc = new XWPFDocument(new FileInputStream("test.doc"));
        XWPFHeaderFooterPolicy xFooter = new XWPFHeaderFooterPolicy(xDoc);
        xFooter.createWatermark("My Watermark");
    }
    catch(Exception e) {
        e.printStackTrace();
    }
}
</code>```

The following is what I got

```<code>Exception in thread "main" java.lang.NoSuchMethodError: org.apache.poi.util.IOUtils.copy(Ljava/io/InputStream;Ljava/io/OutputStream;)V
at org.apache.poi.util.PackageHelper.open(PackageHelper.java:50)
at org.apache.poi.xwpf.usermodel.XWPFDocument.<init>(XWPFDocument.java:71)
at com.avi.Test.ReadDoc.main(Watermark.java:38)
</code>```

答:
I had a similar issue with apache Tika (java.lang.NoSuchMethodError Error): javax.servlet.ServletException: java.lang.NoSuchMethodError: org.apache.poi.util.IOUtils.closeQuietly(Ljava/io/Closeable;)

I resolved the issue by updating the POI jars.

Body:
I have a code for adding watermark to existing .doc file.

The following is the code I have tried so far

public static void main(String[] args)
{

    try
    {
        XWPFDocument xDoc = new XWPFDocument(new FileInputStream("test.doc"));
        XWPFHeaderFooterPolicy xFooter = new XWPFHeaderFooterPolicy(xDoc);
        xFooter.createWatermark("My Watermark");
    }
    catch(Exception e) {
        e.printStackTrace();
    }
}

The following is what I got

Exception in thread "main" java.lang.NoSuchMethodError: org.apache.poi.util.IOUtils.copy(Ljava/io/InputStream;Ljava/io/OutputStream;)V
at org.apache.poi.util.PackageHelper.open(PackageHelper.java:50)
at org.apache.poi.xwpf.usermodel.XWPFDocument.<init>(XWPFDocument.java:71)
at com.avi.Test.ReadDoc.main(Watermark.java:38)


问:
Flutter ListView Load Data from Nested JSON
I've been trying some code from this

I'm trying to load data from local JSON, this JSON is nested model, here's the JSON.

list.json :

```<code>{
    "response": "200",
    "categorylist": [
        {
            "categoryId": 1,
            "categoryTitle": "Working",
            "categoryPost": [
                {
                    "postId": 1,
                    "postTitle": "Some Working Title",
                    "reference": "Some Working Reference",
                    "postContent": [
                        {
                            "contentId": 1,
                            "author": "Some Author Name 1",
                            "content": "Some long content long content long content 1",
                            "note": "Some notes 1",
                            "explanation": "Some Explanation 1"
                        },
                        {
                            "contentId": 2,
                            "author": "Some Author Name 2",
                            "content": "Some long content long content long content 2",
                            "note": "Some notes 2",
                            "explanation": "Some Explanation 2"
                        }
                    ]
                },
                {
                    "postId": 2,
                    "postTitle": "Some Title 2",
                    "reference": "Some reference 2",
                    "postContent": [
                        {
                            "contentId": 1,
                            "author": "Some Author Name 1",
                            "content": "Some long content long content long content 1",
                            "note": "Some notes 1",
                            "explanation": "Some Explanation 1"
                        },
                        {
                            "contentId": 2,
                            "author": "Some Author Name 2",
                            "content": "Some long content long content long content 2",
                            "note": "Some notes 2",
                            "explanation": "Some Explanation 2"
                        }
                    ]
                }
            ]
        },
        {
            "categoryId": 2,
            "categoryTitle": "Order",
            "categoryPost": [
                {
                    "postId": 1,
                    "postTitle": "Some Order Title",
                    "reference": "Some Order Reference",
                    "postContent": [
                        {
                            "contentId": 1,
                            "author": "Some Author Name 1",
                            "content": "Some long content long content long content 1",
                            "note": "Some notes 1",
                            "explanation": "Some Explanation 1"
                        },
                        {
                            "contentId": 2,
                            "author": "Some Author Name 2",
                            "content": "Some long content long content long content 2",
                            "note": "Some notes 2",
                            "explanation": "Some Explanation 2"
                        }
                    ]
                },
                {
                    "postId": 2,
                    "postTitle": "Some Title 2",
                    "reference": "Some reference 2",
                    "postContent": [
                        {
                            "contentId": 1,
                            "author": "Some Author Name 1",
                            "content": "Some long content long content long content 1",
                            "note": "Some notes 1",
                            "explanation": "Some Explanation 1"
                        },
                        {
                            "contentId": 2,
                            "author": "Some Author Name 2",
                            "content": "Some long content long content long content 2",
                            "note": "Some notes 2",
                            "explanation": "Some Explanation 2"
                        }
                    ]
                }
            ]
        }
    ]
}
</code>```

and here's my list_model.dart :

```<code>class Category {
  String response;
  List<Categorylist> categorylist;

  Category({this.response, this.categorylist});

  Category.fromJson(Map<String, dynamic> json) {
    response = json['response'];
    if (json['categorylist'] != null) {
      categorylist = new List<Categorylist>();
      json['categorylist'].forEach((v) {
        categorylist.add(new Categorylist.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['response'] = this.response;
    if (this.categorylist != null) {
      data['categorylist'] = this.categorylist.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Categorylist {
  int categoryId;
  String categoryTitle;
  List<CategoryPost> categoryPost;

  Categorylist({this.categoryId, this.categoryTitle, this.categoryPost});

  Categorylist.fromJson(Map<String, dynamic> json) {
    categoryId = json['categoryId'];
    categoryTitle = json['categoryTitle'];
    if (json['categoryPost'] != null) {
      categoryPost = new List<CategoryPost>();
      json['categoryPost'].forEach((v) {
        categoryPost.add(new CategoryPost.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['categoryId'] = this.categoryId;
    data['categoryTitle'] = this.categoryTitle;
    if (this.categoryPost != null) {
      data['categoryPost'] = this.categoryPost.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class CategoryPost {
  int postId;
  String postTitle;
  String reference;
  List<PostContent> postContent;

  CategoryPost({this.postId, this.postTitle, this.reference, this.postContent});

  CategoryPost.fromJson(Map<String, dynamic> json) {
    postId = json['postId'];
    postTitle = json['postTitle'];
    reference = json['reference'];
    if (json['postContent'] != null) {
      postContent = new List<PostContent>();
      json['postContent'].forEach((v) {
        postContent.add(new PostContent.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['postId'] = this.postId;
    data['postTitle'] = this.postTitle;
    data['reference'] = this.reference;
    if (this.postContent != null) {
      data['postContent'] = this.postContent.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class PostContent {
  int contentId;
  String author;
  String content;
  String note;
  String explanation;

  PostContent(
      {this.contentId, this.author, this.content, this.note, this.explanation});

  PostContent.fromJson(Map<String, dynamic> json) {
    contentId = json['contentId'];
    author = json['author'];
    content = json['content'];
    note = json['note'];
    explanation = json['explanation'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['contentId'] = this.contentId;
    data['author'] = this.author;
    data['content'] = this.content;
    data['note'] = this.note;
    data['explanation'] = this.explanation;
    return data;
  }
}
</code>```

here's my view_list.dart :

```<code>import 'dart:async' show Future;
import 'dart:convert';
import 'package:flutter/services.dart' show rootBundle;
import 'package:flutter/material.dart';
import 'model.dart';

  Future<String>  _loadCategoryfromAssets() async {
    return await rootBundle.loadString('assets/data/list.json');
  }

  Future loadCategory() async {
    await wait(1);
    String jsonString = await _loadCategoryfromAssets();
    final jsonResponse = json.decode(jsonString);
    Category category = Category.fromJson(jsonResponse);
    print(category.categorylist[0].categoryTitle);
    print(category.categorylist[0].categoryPost[0].postTitle);
  }

  Future wait(int seconds) {
    return new Future.delayed(Duration(seconds: seconds), () => {});
  }

class Doa extends StatefulWidget {
  Doa({Key key}) : super(key: key);

  _DoaState createState() => _DoaState();
}

class _DoaState extends State<Doa> {

  Widget futureWidget() {
    return new FutureBuilder(
      future: loadCategory(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return new Container(
            child: Row(
              children: <Widget>[
                ListView.builder(
                  itemBuilder: (BuildContext context, index) {
                    return Column(
                      children: <Widget>[
                      InkWell(
                        onTap: () {},
                        child: Text(
                          snapshot.data.category.categorylist[index].categoryTitle,
                        ),
                      )

                      ],
                    );
                  }
                )
              ],
            ),
          );
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        top: false,
        bottom: false,
        child: Scaffold(
        body: futureWidget(),
        ));
  }
}
</code>```

I'm stuck load the data from JSON inside categorylist into listview.builder.

in the view code above, I'm only want to list all "categoryTitle" from json, with ontap action to detail page. how to do that ?

答:
I've solve this problem, write into listviewBuilder with this code inside a widget :

```<code>  Widget futureWidget() {
    return new FutureBuilder(
      future: loadCategory(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return new Container(
            child: Row(
              children: <Widget>[
                ListView.builder(
                  itemBuilder: (BuildContext context, index) {
                    return Column(
                      children: <Widget>[
                      InkWell(
                        onTap: () {},
                        child: Text(
                          snapshot.data.category.categorylist[index].categoryTitle,
                        ),
                      )

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

and then I add this code below to load nested json :

```<code>  Future<String>  _loadCategoryfromAssets() async {
    return await rootBundle.loadString('assets/data/list.json');
  }

  Future loadCategory() async {
    await wait(1);
    String jsonString = await _loadCategoryfromAssets();
    final jsonResponse = json.decode(jsonString);
    Category category = Category.fromJson(jsonResponse);
    print(category.categorylist[0].categoryTitle);
    print(category.categorylist[0].categoryPost[0].postTitle);
  }

  Future wait(int seconds) {
    return new Future.delayed(Duration(seconds: seconds), () => {});
  }
</code>```

Body:
I've been trying some code from this

I'm trying to load data from local JSON, this JSON is nested model, here's the JSON.

list.json :

{
    "response": "200",
    "categorylist": [
        {
            "categoryId": 1,
            "categoryTitle": "Working",
            "categoryPost": [
                {
                    "postId": 1,
                    "postTitle": "Some Working Title",
                    "reference": "Some Working Reference",
                    "postContent": [
                        {
                            "contentId": 1,
                            "author": "Some Author Name 1",
                            "content": "Some long content long content long content 1",
                            "note": "Some notes 1",
                            "explanation": "Some Explanation 1"
                        },
                        {
                            "contentId": 2,
                            "author": "Some Author Name 2",
                            "content": "Some long content long content long content 2",
                            "note": "Some notes 2",
                            "explanation": "Some Explanation 2"
                        }
                    ]
                },
                {
                    "postId": 2,
                    "postTitle": "Some Title 2",
                    "reference": "Some reference 2",
                    "postContent": [
                        {
                            "contentId": 1,
                            "author": "Some Author Name 1",
                            "content": "Some long content long content long content 1",
                            "note": "Some notes 1",
                            "explanation": "Some Explanation 1"
                        },
                        {
                            "contentId": 2,
                            "author": "Some Author Name 2",
                            "content": "Some long content long content long content 2",
                            "note": "Some notes 2",
                            "explanation": "Some Explanation 2"
                        }
                    ]
                }
            ]
        },
        {
            "categoryId": 2,
            "categoryTitle": "Order",
            "categoryPost": [
                {
                    "postId": 1,
                    "postTitle": "Some Order Title",
                    "reference": "Some Order Reference",
                    "postContent": [
                        {
                            "contentId": 1,
                            "author": "Some Author Name 1",
                            "content": "Some long content long content long content 1",
                            "note": "Some notes 1",
                            "explanation": "Some Explanation 1"
                        },
                        {
                            "contentId": 2,
                            "author": "Some Author Name 2",
                            "content": "Some long content long content long content 2",
                            "note": "Some notes 2",
                            "explanation": "Some Explanation 2"
                        }
                    ]
                },
                {
                    "postId": 2,
                    "postTitle": "Some Title 2",
                    "reference": "Some reference 2",
                    "postContent": [
                        {
                            "contentId": 1,
                            "author": "Some Author Name 1",
                            "content": "Some long content long content long content 1",
                            "note": "Some notes 1",
                            "explanation": "Some Explanation 1"
                        },
                        {
                            "contentId": 2,
                            "author": "Some Author Name 2",
                            "content": "Some long content long content long content 2",
                            "note": "Some notes 2",
                            "explanation": "Some Explanation 2"
                        }
                    ]
                }
            ]
        }
    ]
}

and here's my list_model.dart :

class Category {
  String response;
  List<Categorylist> categorylist;

  Category({this.response, this.categorylist});

  Category.fromJson(Map<String, dynamic> json) {
    response = json['response'];
    if (json['categorylist'] != null) {
      categorylist = new List<Categorylist>();
      json['categorylist'].forEach((v) {
        categorylist.add(new Categorylist.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['response'] = this.response;
    if (this.categorylist != null) {
      data['categorylist'] = this.categorylist.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Categorylist {
  int categoryId;
  String categoryTitle;
  List<CategoryPost> categoryPost;

  Categorylist({this.categoryId, this.categoryTitle, this.categoryPost});

  Categorylist.fromJson(Map<String, dynamic> json) {
    categoryId = json['categoryId'];
    categoryTitle = json['categoryTitle'];
    if (json['categoryPost'] != null) {
      categoryPost = new List<CategoryPost>();
      json['categoryPost'].forEach((v) {
        categoryPost.add(new CategoryPost.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['categoryId'] = this.categoryId;
    data['categoryTitle'] = this.categoryTitle;
    if (this.categoryPost != null) {
      data['categoryPost'] = this.categoryPost.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class CategoryPost {
  int postId;
  String postTitle;
  String reference;
  List<PostContent> postContent;

  CategoryPost({this.postId, this.postTitle, this.reference, this.postContent});

  CategoryPost.fromJson(Map<String, dynamic> json) {
    postId = json['postId'];
    postTitle = json['postTitle'];
    reference = json['reference'];
    if (json['postContent'] != null) {
      postContent = new List<PostContent>();
      json['postContent'].forEach((v) {
        postContent.add(new PostContent.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['postId'] = this.postId;
    data['postTitle'] = this.postTitle;
    data['reference'] = this.reference;
    if (this.postContent != null) {
      data['postContent'] = this.postContent.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class PostContent {
  int contentId;
  String author;
  String content;
  String note;
  String explanation;

  PostContent(
      {this.contentId, this.author, this.content, this.note, this.explanation});

  PostContent.fromJson(Map<String, dynamic> json) {
    contentId = json['contentId'];
    author = json['author'];
    content = json['content'];
    note = json['note'];
    explanation = json['explanation'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['contentId'] = this.contentId;
    data['author'] = this.author;
    data['content'] = this.content;
    data['note'] = this.note;
    data['explanation'] = this.explanation;
    return data;
  }
}

here's my view_list.dart :

import 'dart:async' show Future;
import 'dart:convert';
import 'package:flutter/services.dart' show rootBundle;
import 'package:flutter/material.dart';
import 'model.dart';

  Future<String>  _loadCategoryfromAssets() async {
    return await rootBundle.loadString('assets/data/list.json');
  }

  Future loadCategory() async {
    await wait(1);
    String jsonString = await _loadCategoryfromAssets();
    final jsonResponse = json.decode(jsonString);
    Category category = Category.fromJson(jsonResponse);
    print(category.categorylist[0].categoryTitle);
    print(category.categorylist[0].categoryPost[0].postTitle);
  }

  Future wait(int seconds) {
    return new Future.delayed(Duration(seconds: seconds), () => {});
  }

class Doa extends StatefulWidget {
  Doa({Key key}) : super(key: key);

  _DoaState createState() => _DoaState();
}

class _DoaState extends State<Doa> {

  Widget futureWidget() {
    return new FutureBuilder(
      future: loadCategory(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return new Container(
            child: Row(
              children: <Widget>[
                ListView.builder(
                  itemBuilder: (BuildContext context, index) {
                    return Column(
                      children: <Widget>[
                      InkWell(
                        onTap: () {},
                        child: Text(
                          snapshot.data.category.categorylist[index].categoryTitle,
                        ),
                      )

                      ],
                    );
                  }
                )
              ],
            ),
          );
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        top: false,
        bottom: false,
        child: Scaffold(
        body: futureWidget(),
        ));
  }
}

I'm stuck load the data from JSON inside categorylist into listview.builder.

in the view code above, I'm only want to list all "categoryTitle" from json, with ontap action to detail page. how to do that ?

Body:
I've solve this problem, write into listviewBuilder with this code inside a widget :

  Widget futureWidget() {
    return new FutureBuilder(
      future: loadCategory(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return new Container(
            child: Row(
              children: <Widget>[
                ListView.builder(
                  itemBuilder: (BuildContext context, index) {
                    return Column(
                      children: <Widget>[
                      InkWell(
                        onTap: () {},
                        child: Text(
                          snapshot.data.category.categorylist[index].categoryTitle,
                        ),
                      )

                      ],
                    );
                  }
                )
              ],
            ),
          );
        }
      },
    );
  }

and then I add this code below to load nested json :

  Future<String>  _loadCategoryfromAssets() async {
    return await rootBundle.loadString('assets/data/list.json');
  }

  Future loadCategory() async {
    await wait(1);
    String jsonString = await _loadCategoryfromAssets();
    final jsonResponse = json.decode(jsonString);
    Category category = Category.fromJson(jsonResponse);
    print(category.categorylist[0].categoryTitle);
    print(category.categorylist[0].categoryPost[0].postTitle);
  }

  Future wait(int seconds) {
    return new Future.delayed(Duration(seconds: seconds), () => {});
  }


问:
How to include a custom AlertDialog in OnClickListener of ImageView?
I'm trying to put a custom alertDialog when I press an imageView, but the application breaks.

I tried to pass an activity and onClicklistener, but it does not work

My custom AlertDialog is this:

```<code>public vlass viewInfoAjustes{
   public void showDialog(Activity activity){
      final Dialog dialog = new Dialog(activity);
      dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
      dialog.setCancelable(false);
      dialog.setContentView(R.layout.icono_info_ajustes);
      Button ok = dialog.findViewById(R.id.ok);

      ok.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            dialog.dismiss();
         }
      });

      dialog.show();
   }
}
</code>```

and I call it this way:

```<code>    ImageView info = findViewById(R.id.boton_infoServer);
    info.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ViewInfoAjustes iconoInfo = new ViewInfoAjustes();
            iconoInfo.showDialog(this);
        }
    });
</code>```

this is the error:

答: Use MyActivity.this for that case

Body:
I'm trying to put a custom alertDialog when I press an imageView, but the application breaks.

I tried to pass an activity and onClicklistener, but it does not work

My custom AlertDialog is this:

public vlass viewInfoAjustes{
   public void showDialog(Activity activity){
      final Dialog dialog = new Dialog(activity);
      dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
      dialog.setCancelable(false);
      dialog.setContentView(R.layout.icono_info_ajustes);
      Button ok = dialog.findViewById(R.id.ok);

      ok.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            dialog.dismiss();
         }
      });

      dialog.show();
   }
}

and I call it this way:

    ImageView info = findViewById(R.id.boton_infoServer);
    info.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ViewInfoAjustes iconoInfo = new ViewInfoAjustes();
            iconoInfo.showDialog(this);
        }
    });

this is the error:

Body: Use MyActivity.this for that case


问:
django msg.send() not working as it should
when i send mail through django view (code below):

```<code>subject = "Audit report for all staff  "
email_msg = "Hello Everyone," + '\n \n' + subject + '\n \n' + 'Thanks \n-Admin'
report_name = response['Content-Disposition'].split('=')[1]

msg = EmailMessage(
            subject = subject,
            body = email_msg,
            attachments=(('%s' % report_name,f.read(), 'text/csv'),),
            to = ['prateekm@localhost','prateek@gmail.com' ],
       )
    msg.send()
</code>```

My mail is only being sent  to the localhost email id and not to the gmail id . How to rectify this?

答:
For configuring SMTP server, u have to give something like this in your settings.py [provided SMTP is installed]</p>

```<code>EMAIL_HOST = "smtp.gmail.com"
EMAIL_PORT = '587'
EMAIL_HOST_USER = "xxx@gmail.com" #create a gmail id
EMAIL_HOST_PASSWORD = "xxxx"#pwd for that id
EMAIL_USE_TLS = True
</code>```

Body:
when i send mail through django view (code below):

subject = "Audit report for all staff  "
email_msg = "Hello Everyone," + '\n \n' + subject + '\n \n' + 'Thanks \n-Admin'
report_name = response['Content-Disposition'].split('=')[1]

msg = EmailMessage(
            subject = subject,
            body = email_msg,
            attachments=(('%s' % report_name,f.read(), 'text/csv'),),
            to = ['prateekm@localhost','prateek@gmail.com' ],
       )
    msg.send()

My mail is only being sent  to the localhost email id and not to the gmail id . How to rectify this?

Body:
For configuring SMTP server, u have to give something like this in your settings.py [provided SMTP is installed]

EMAIL_HOST = "smtp.gmail.com"
EMAIL_PORT = '587'
EMAIL_HOST_USER = "xxx@gmail.com" #create a gmail id
EMAIL_HOST_PASSWORD = "xxxx"#pwd for that id
EMAIL_USE_TLS = True


答:
Since you said you wanted a long list of the means, I assumed it could also be a vector where you just have all these values. You would get that like this:</p>

```<code>V1 = paste0("AB", seq(1:48))
V2 = seq(1:48)

test = data.frame(name = V1, value = V2)
meanVector <- NULL

for (i in 1:(nrow(test)-8)) {
  x <- c(test$value[i], test$value[i+4], test$value[i+8])
  m <- mean(x)
  meanVector <- c(meanVector, m)
}
</code>```

Title: Calculate mean of specific row pattern

Body:
Since you said you wanted a long list of the means, I assumed it could also be a vector where you just have all these values. You would get that like this:

V1 = paste0("AB", seq(1:48))
V2 = seq(1:48)

test = data.frame(name = V1, value = V2)
meanVector <- NULL

for (i in 1:(nrow(test)-8)) {
  x <- c(test$value[i], test$value[i+4], test$value[i+8])
  m <- mean(x)
  meanVector <- c(meanVector, m)
}


问:
Save ggplot object as image in the environment as object/value
I have a ggplot object. Let's call it plot. I would like to convert it to png format, but I don't want to save it to a file on my local drive. I'm trying to work with that png object but I want to keep everything in the environment. Everything I've found, including ggsave, appears to force one to save the image as a file on the local drive first. I know image files can be stored as values, but I can't seem to get over the "save as" image and "import" image steps.

Here's some code for repoducibility:

```<code>library(tidyverse)
df <- as.data.frame(Titanic)
gg <- ggplot(data = df, aes(x = Survived, y = Freq))
plot <- gg + geom_bar(stat = "identity")
</code>```

Now, I'd like to convert plot to a png to png without having to save it to a file. Something like:

```<code>png <- save.png(plot)
</code>```

Thanks for the help!

答:
I was faced with a similar issue and followed @eipi12 approach of using magick. The code bellow should work:

```<code>library(ggplot2)
library(magrittr)

ggsave_to_variable <- function(p, width = 10, height = 10, dpi = 300){
  pixel_width  = (width  * dpi) / 2.54
  pixel_height = (height * dpi) / 2.54

  img <- magick::image_graph(pixel_width, pixel_height, res = dpi)

  on.exit(utils::capture.output({
    grDevices::dev.off()}))
  plot(p)

  return(img)
}

p <- data.frame(x = 1:100, y = 1:100) %>%
  ggplot(aes(x = x, y = y)) +
  geom_line()

my_img <- ggsave_to_variable(p)

my_img %>%
  magick::image_write("my_img.png")

</code>```

Body:
I have a ggplot object. Let's call it plot. I would like to convert it to png format, but I don't want to save it to a file on my local drive. I'm trying to work with that png object but I want to keep everything in the environment. Everything I've found, including ggsave, appears to force one to save the image as a file on the local drive first. I know image files can be stored as values, but I can't seem to get over the "save as" image and "import" image steps.

Here's some code for repoducibility:

library(tidyverse)
df <- as.data.frame(Titanic)
gg <- ggplot(data = df, aes(x = Survived, y = Freq))
plot <- gg + geom_bar(stat = "identity")

Now, I'd like to convert plot to a png to png without having to save it to a file. Something like:

png <- save.png(plot)

Thanks for the help!

Body:
I was faced with a similar issue and followed @eipi12 approach of using magick. The code bellow should work:

library(ggplot2)
library(magrittr)

ggsave_to_variable <- function(p, width = 10, height = 10, dpi = 300){
  pixel_width  = (width  * dpi) / 2.54
  pixel_height = (height * dpi) / 2.54

  img <- magick::image_graph(pixel_width, pixel_height, res = dpi)

  on.exit(utils::capture.output({
    grDevices::dev.off()}))
  plot(p)

  return(img)
}

p <- data.frame(x = 1:100, y = 1:100) %>%
  ggplot(aes(x = x, y = y)) +
  geom_line()

my_img <- ggsave_to_variable(p)

my_img %>%
  magick::image_write("my_img.png")


问:
Attaching Application load balancer / Network Load balancer directly with aws Autoscaling group
How do I attach aws Application Load Balancer and Network Load balancer directly with auto-scaling group(ASG)?
In AWS Console only available option is for Classic Load Balancer.
What i want is whenever an instance is launched in autoscaling group it'll start reporting to Application/Network load balancer directly rather manually entering each instance in the target group.

答:
While using ALB and NLB, you need to have Target Group created to wire an EC2 or ASG.
 So, you need ALB/NLB <- Target Group <- AutoScaling Group.

In Target Group you specify the instances/ips and ports you want to point.


问:
Material Instance Created in Car Model Prefab
I don't know why my car 3d model's mesh renderer creating own instances of all materials when I spawn it using prefab.
Please check below image for the same:

My environment models not creating own instances of materials but all cars models doing when I initialize via prefab.
I hope you are getting my point.

Here I am attaching an image for car model import settings:

So I want to stop these new materials instance creation process

After spawning of car model, it has own material instance created at runtime so I want to solve this problem.

I have created another demo project in that this kind of situation not get created. There is no new instance of material gets created within mesh renderer.

答: When you access renderer's material via code and modify something, Unity duplicate your material (the instance you're seeing) so that it doesn't modify every objects that share this material. If you want to change something globally, either get a reference to the material (not going through the renderer), or create multiple materials and assign the one you want at runtime.</p>


问:
Laravel 5.4 on PHP 7.0: PDO Exception - Could not find driver (MySQL)
I have a Laravel 5.4 project on my Ubuntu 14.04 (VPS with Plesk 12.5.30). After creating the database and setted up the .env file with required information I ran php artisan migrate and exceptions were thrown:

[Illuminate\Database\QueryException]

    could not find driver (SQL: select * from information_schema.tables where table_schema = pmaramaldb and table_name = migrations)

[PDOException]

    could not find driver

My .env file has:

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=pmaramaldb

DB_USERNAME=user

DB_PASSWORD=password

I've followed most of the guides to solve this error and there wasn't any positive results:

Enabling Extension Solution:

PDO is enabled

The php.ini file is being generated automatically, I guess this is made by Plesk. At the start of the file it says:

; ATTENTION!

  ;

  ; DO NOT MODIFY THIS FILE BECAUSE IT WAS GENERATED AUTOMATICALLY,

  ; SO ALL YOUR CHANGES WILL BE LOST THE NEXT TIME THE FILE IS GENERATED.

So I've tried it anyway. After that I've restarted Apache and then tried again... Didn't work.

Installing php7.0-mysql Solution:

I've also tried to install MySQL in case is not:

user@server:/var/www/vhosts$ sudo apt-get install php7.0-mysql

Leyendo lista de paquetes... Hecho

Creando árbol de dependencias

Leyendo la información de estado... Hecho

php7.0-mysql is already the newest version.

0 actualizados, 0 se instalarán, 0 para eliminar y 67 no actualizados.

** SQL Lite Install Solution:**

I've also tried as question link says: sudo apt-get install php5-sqlite and the result was:

user@server:/var/www/vhosts/system/maramal.io/etc$ sudo apt-get install php5-sqlite

Leyendo lista de paquetes... Hecho

Creando árbol de dependencias

Leyendo la información de estado... Hecho

php5-sqlite is already the newest version.

0 actualizados, 0 se instalarán, 0 para eliminar y 67 no actualizados.

Composer Dump-autoload Solution:

It didn't work either. I've tried composer dump-autoload and it didn't work.

After ran the command php -i:

PDO

PDO support => enabled

PDO drivers =>

...

PHP Version => 5.6.30-1+deb.sury.org~trusty+1

Well, I am not sure if this has anything to do with the error, but the version shown by running php -v is:

user@server: ~/path$ php -v

PHP 5.6.30-1+deb.sury.org~trusty+1 (cli)

Copyright (c) 1997-2016 The PHP Group

Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies

      with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2016, by Zend Technologies

答:
in linux do like that

first check your php version  like this :

```<code>php -v
</code>```

after you get  version number for example i get 7.1 then install like that

```<code>sudo apt-get install  php7.1-sqlite     //for laravel testing with sqlite
sudo apt-get install  php-mysql         //for default mysql
sudo apt-get install  php7.1-mysql      //for version based mysql
sudo apt-get install  php7.1-common     //for other necessary package for php
</code>```

and need to restart apache2

```<code>sudo service apache2 restart
</code>```

Body:
in linux do like that

first check your php version  like this :

php -v

after you get  version number for example i get 7.1 then install like that

sudo apt-get install  php7.1-sqlite     //for laravel testing with sqlite
sudo apt-get install  php-mysql         //for default mysql
sudo apt-get install  php7.1-mysql      //for version based mysql
sudo apt-get install  php7.1-common     //for other necessary package for php

and need to restart apache2

sudo service apache2 restart


问:
How to evaluate a python variable and pass it as a argument to a command
In a python script below, I am trying to get current date and time stamp into a python variable named logfile which is passed as argument to output redirection of a windows command which is executed using os.system(...)

But I am unable to pass the variable logfile. After executing this script, I am hoping to see a file: e.g. log_28052019_133838.txt whose name has date and timestamp at time it is executed, and which has output of the dir /od command, but instead it is stored in file logfile, telling me that python expression for variable name logfile is not getting evaluated before passing as output redirection file name.

Can someone point me, what am i missing and what would be the correct way to achieve what I am looking to do.

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

import os
import time

fstr = time.strftime("%d%b%Y_%H%M%S")
logfile = "log_"+fstr+".txt"
rcmd = 'dir /OD >logfile '

os.system(rcmd)
</code>```

答:
It appears that the value of logfile would allow you to use string formatting to define the command (though this is fragile and should not be used in practice):

```<code>logfile = time.strftime("log_%d%b%Y_%H%M%S.txt")
rcmd = 'dir /OD > {}'.format(logfile)
os.system(rcmd)
</code>```

It would be safer to use the subprocess module, though, to avoid any shell issues.

```<code>logfile = time.strftime("log_%d%b%Y_%H%M%S.txt")
with open(logfile, "w") as fh:
    subprocess.run(['dir', '/OD'], stdout=fh)
</code>```

Body:
In a python script below, I am trying to get current date and time stamp into a python variable named logfile which is passed as argument to output redirection of a windows command which is executed using os.system(...)

But I am unable to pass the variable logfile. After executing this script, I am hoping to see a file: e.g. log_28052019_133838.txt whose name has date and timestamp at time it is executed, and which has output of the dir /od command, but instead it is stored in file logfile, telling me that python expression for variable name logfile is not getting evaluated before passing as output redirection file name.

Can someone point me, what am i missing and what would be the correct way to achieve what I am looking to do.

#!/bin/python

import os
import time

fstr = time.strftime("%d%b%Y_%H%M%S")
logfile = "log_"+fstr+".txt"
rcmd = 'dir /OD >logfile '

os.system(rcmd)

Body:
It appears that the value of logfile would allow you to use string formatting to define the command (though this is fragile and should not be used in practice):

logfile = time.strftime("log_%d%b%Y_%H%M%S.txt")
rcmd = 'dir /OD > {}'.format(logfile)
os.system(rcmd)

It would be safer to use the subprocess module, though, to avoid any shell issues.

logfile = time.strftime("log_%d%b%Y_%H%M%S.txt")
with open(logfile, "w") as fh:
    subprocess.run(['dir', '/OD'], stdout=fh)


问:
how can we access and get props that are passed to a component (wrapper.props().propname) always return undefined
I am testing a list component with enzyme i want to test if my component renders a list with same data that is passed to component in props

```<code>import React from 'react';
import { shallow, mount } from 'enzyme';
import renderer from 'react-test-renderer';
import { MemoryRouter } from 'react-router';

import ListComponent from '.';

const listOfLinks = [
    { url: '/one', text: 'Link one', internal: false },
    { url: '/two', text: 'Link two', internal: false },
    { url: '/datasets', text: 'Datasets', internal: true }
];

const itemsToDisplay = 4;

const props = {
    listOfLinks, itemsToDisplay
};

describe('list-Component', () => {
    it('Check if rendered list size is same as passed', () => {
        const wrapper = mount(<MemoryRouter><ListComponent {...props} /></MemoryRouter>);
        expect(wrapper.props().listOfLinks.length).toEqual(3);
    });
});
</code>```

but i get
expected 3 recieved : undefined

答:
Your wrapper here is a MemoryRouter, not a ListComponent. The MemoryRouter has no props.

If you want to check the props passed to ListComponent, you could do it like this:

```<code>wrapper.find(ListComponent).props()
</code>```

However, as an aside... what would you be testing if you did that? In this case, it would be that your test was providing the expected props correctly, but nothing about the component itself. Checking props like this is checking an implementation detail, when what you should be interested in is the rendered output. Better to find the actual links themselves in the wrapper and then count them.

eta: If the component was updated to take different props (but with the same rendered result) then your test would fail, even though the app is still working as required. If you check the rendered output then you are free to refactor and update and your tests will only fail when the important stuff fails - i.e. there are an incorrect number of links showing. Kent C Dodds writes a lot about this sort of stuff - check out his React Testing Library

Body:
I am testing a list component with enzyme i want to test if my component renders a list with same data that is passed to component in props

import React from 'react';
import { shallow, mount } from 'enzyme';
import renderer from 'react-test-renderer';
import { MemoryRouter } from 'react-router';

import ListComponent from '.';

const listOfLinks = [
    { url: '/one', text: 'Link one', internal: false },
    { url: '/two', text: 'Link two', internal: false },
    { url: '/datasets', text: 'Datasets', internal: true }
];

const itemsToDisplay = 4;

const props = {
    listOfLinks, itemsToDisplay
};

describe('list-Component', () => {
    it('Check if rendered list size is same as passed', () => {
        const wrapper = mount(<MemoryRouter><ListComponent {...props} /></MemoryRouter>);
        expect(wrapper.props().listOfLinks.length).toEqual(3);
    });
});

but i get
expected 3 recieved : undefined

Body:
Your wrapper here is a MemoryRouter, not a ListComponent. The MemoryRouter has no props.

If you want to check the props passed to ListComponent, you could do it like this:

wrapper.find(ListComponent).props()

However, as an aside... what would you be testing if you did that? In this case, it would be that your test was providing the expected props correctly, but nothing about the component itself. Checking props like this is checking an implementation detail, when what you should be interested in is the rendered output. Better to find the actual links themselves in the wrapper and then count them.

eta: If the component was updated to take different props (but with the same rendered result) then your test would fail, even though the app is still working as required. If you check the rendered output then you are free to refactor and update and your tests will only fail when the important stuff fails - i.e. there are an incorrect number of links showing. Kent C Dodds writes a lot about this sort of stuff - check out his React Testing Library


问:
Redirect HTTPS on multidomain Varnish
i have got two domain based on same framework (magento2)
domain1.it
domain2.com

I would like to redirect them to their respective SSL version.
https://domain1.it
https://domain2.com

Domain 1 is correctly configured to redirect to HTTPS and my varnish Config file is:

```<code>sub vcl_recv {
if ( (req.http.host ~ "^(?i)www.domain1.it" || req.http.host ~ "^(?i)domain1.it") && req.http.X-Forwarded-Proto !~ "(?i)https") {
return (synth(750, ""));
    }

sub vcl_synth {
if (resp.status == 750) {
    set resp.status = 301;
    set resp.http.Location = "https://domain1.it" + req.url;
return(deliver);
}
</code>```

the problem is the synth always redirect to the same domain.

I should add an if condition where i could call a subroutines that redirect to https for domain2

答:
Bitnami Engineer here. I just reviewed the Varnish documentation and found this:

```<code>sub vcl_recv {
    if (client.ip != "127.0.0.1" && std.port(server.ip) == 80 && req.http.host ~ "^(?i)example.com") {
        set req.http.x-redir = "https://" + req.http.host + req.url;
        return(synth(850, "Moved permanently"));
    }
}

sub vcl_synth {
    if (resp.status == 850) {
        set resp.http.Location = req.http.x-redir;
        set resp.status = 302;
        return (deliver);
    }
}
</code>```

This is useful when you want to redirect the clients to an SSL-version of your site. More info here:

https://varnish-cache.org/trac/wiki/VCLExampleRedirectInVCL

Title: Redirect HTTPS on multidomain Varnish

Body:
i have got two domain based on same framework (magento2)
domain1.it
domain2.com

I would like to redirect them to their respective SSL version.
https://domain1.it
https://domain2.com

Domain 1 is correctly configured to redirect to HTTPS and my varnish Config file is:

sub vcl_recv {
if ( (req.http.host ~ "^(?i)www.domain1.it" || req.http.host ~ "^(?i)domain1.it") && req.http.X-Forwarded-Proto !~ "(?i)https") {
return (synth(750, ""));
    }

sub vcl_synth {
if (resp.status == 750) {
    set resp.status = 301;
    set resp.http.Location = "https://domain1.it" + req.url;
return(deliver);
}

the problem is the synth always redirect to the same domain.

I should add an if condition where i could call a subroutines that redirect to https for domain2

Body:
Bitnami Engineer here. I just reviewed the Varnish documentation and found this:

sub vcl_recv {
    if (client.ip != "127.0.0.1" && std.port(server.ip) == 80 && req.http.host ~ "^(?i)example.com") {
        set req.http.x-redir = "https://" + req.http.host + req.url;
        return(synth(850, "Moved permanently"));
    }
}

sub vcl_synth {
    if (resp.status == 850) {
        set resp.http.Location = req.http.x-redir;
        set resp.status = 302;
        return (deliver);
    }
}

This is useful when you want to redirect the clients to an SSL-version of your site. More info here:

https://varnish-cache.org/trac/wiki/VCLExampleRedirectInVCL


问:
font-display unknown property wordpress GoDaddy
Recently I've been trying different methods to improve my site performance, and as I found one of the being font-display.

As I read about it, it is part of the @font-face rule.

The warning:
Unknown property: 'font-display'

What should I do in this case? Been looking around for a solution but haven't found any yet.

答: Godaddy may say that it is an unknown property, but once it is online, it doesn't matter anymore. Just keep going with your code.</p>


问:
Resizing images to fit width in ipython
Can anyone get images to fit width in Firefox using, say, custom CSS without leaving a lot of white space at the bottom of the cell? A minimal Markdown example with custom.css is appreciated. Here is something to replicate the problem:

Cell one:

```<code>![Big image](http://cantelofmedford.com/wp-content/uploads/2011/02/oversize1.jpg)

See the white space after this?
</code>```

Cell two:

```<code>%run talktools.py
</code>```

Now execute both cells. The image will not fit unless you create a custom css with the following entry: p img {width: 100%;} And when you do that, there will be white space at the bottom of the first cell:

答:
I find adding an HTML cell to update the CSS on a per-notebook basis to be a better alternative to changing style.css.</p>

```<code>%%html
<style>
img { width: 100%; }
</style>
</code>```

Title: Resizing images to fit width in ipython

Body:
Can anyone get images to fit width in Firefox using, say, custom CSS without leaving a lot of white space at the bottom of the cell? A minimal Markdown example with custom.css is appreciated. Here is something to replicate the problem:

Cell one:

![Big image](http://cantelofmedford.com/wp-content/uploads/2011/02/oversize1.jpg)

See the white space after this?

Cell two:

%run talktools.py

Now execute both cells. The image will not fit unless you create a custom css with the following entry: p img {width: 100%;} And when you do that, there will be white space at the bottom of the first cell:

Body:
I find adding an HTML cell to update the CSS on a per-notebook basis to be a better alternative to changing style.css.

%%html
<style>
img { width: 100%; }
</style>


问:
How to make a image move towards mouse click?
I'm trying to recreate ballz using pygame for a summative for my ics class. Except i don't know how to make the ball(which is a image) to move to where the user clicks.

This is for pygame, I've tried updating the location, except the ball just flickers in and out in the same spot.

```<code>def level_2():
    class Ball(pygame.sprite.Sprite):
        def __init__(self):
            pygame.sprite.Sprite.__init__(self) #construct the parent component
            self.image = pygame.image.load("ball.png").convert_alpha()
            self.image.set_colorkey(self.image.get_at( (0,0) ))
            self.rect = self.image.get_rect() #loads the rect from the image

            #set the position, direction, and speed of the ball
            self.rect.left = 300
            self.rect.top = 600
            self.speed = 4
            self.dir = 0

        def update(self):
            click = pygame.mouse.get_pressed()
            #Handle the walls by changing direction(s)
            if self.rect.left < 0 or self.rect.right >= screen.get_width():
                self.dir_x *= -1

            if self.rect.top < 0:
                self.dir_y *= -1

    ####CHECK TO SEE IF BALL HITS THE BLOCK AND WILL BOUNCE####
            if pygame.sprite.groupcollide(ball_group, block_group, False, True):
                self.rect.move_ip(self.speed*self.dir_x, self.speed*self.dir_y)

            if self.rect.bottom >= screen.get_height():
                speed = 0
                self.dir_y = 0
                self.dir_x = 0
                self.rect.left = 300
                self.rect.top = 600
                self.rect.move_ip(self.speed*self.dir_x, self.speed*self.dir_y)

            #Move the ball to where the user clicked
            if ev.type == MOUSEBUTTONDOWN:
                (x, y) = pygame.mouse.get_pos()
                #ASK MS WUN HOW TO DO #
                if self.rect.left != x and self.rect.top != y:
                    #self.rect.move_ip(x, y)
                    self.rect.move_ip(self.speed*self.dir_x, self.speed*self.dir_y)
</code>```

There isn't any error messages, the only thing that happens is either the ball will move in a set direction (if the user clicks on the right side, the ball will move to the right, and if the user clicks on the left, the ball will still move to the right).

Or the ball will just flicker in and out on the same spot

答:
The problem, I think (I can't tell properly without a minimal, complete and verifiable example) is a misunderstanding of Rect.move_ip(). This method translates the Rect in a direction, rather than moving towards it. Since you can only click on positive co-ordinates (negative ones are off-screen), this means it will always move down and to the right. If you want to move towards something, the easiest way is something like this:

target_x = 100
target_y = 300
ball_x = 600
ball_y = 200
movedir_x = target_x - ball_x
movedir_y = target_y - ball_y
# Now adjust so that the speed is unaffected by distance to target
length = (movedir_x ** 2 + movedir_y ** 2) ** 0.5
movedir_x *= speed / length
movedir_y *= speed / length
```

<p>and then translate the ball by this <code>movedir</code> rather than the ball's position. I think at this point you should probably just use Pygame's Vector2 class. Then the equivalent would just be:</p>

<pre class="lang-py prettyprint-override"><code>target = pygame.math.Vector2(100, 300)
ball = pygame.math.Vector2(600, 200)
movedir = (target - ball).normalize() * speed
</code>```

Body:
I'm trying to recreate ballz using pygame for a summative for my ics class. Except i don't know how to make the ball(which is a image) to move to where the user clicks.

This is for pygame, I've tried updating the location, except the ball just flickers in and out in the same spot.

def level_2():
    class Ball(pygame.sprite.Sprite):
        def __init__(self):
            pygame.sprite.Sprite.__init__(self) #construct the parent component
            self.image = pygame.image.load("ball.png").convert_alpha()
            self.image.set_colorkey(self.image.get_at( (0,0) ))
            self.rect = self.image.get_rect() #loads the rect from the image

            #set the position, direction, and speed of the ball
            self.rect.left = 300
            self.rect.top = 600
            self.speed = 4
            self.dir = 0

        def update(self):
            click = pygame.mouse.get_pressed()
            #Handle the walls by changing direction(s)
            if self.rect.left < 0 or self.rect.right >= screen.get_width():
                self.dir_x *= -1

            if self.rect.top < 0:
                self.dir_y *= -1

    ####CHECK TO SEE IF BALL HITS THE BLOCK AND WILL BOUNCE####
            if pygame.sprite.groupcollide(ball_group, block_group, False, True):
                self.rect.move_ip(self.speed*self.dir_x, self.speed*self.dir_y)

            if self.rect.bottom >= screen.get_height():
                speed = 0
                self.dir_y = 0
                self.dir_x = 0
                self.rect.left = 300
                self.rect.top = 600
                self.rect.move_ip(self.speed*self.dir_x, self.speed*self.dir_y)

            #Move the ball to where the user clicked
            if ev.type == MOUSEBUTTONDOWN:
                (x, y) = pygame.mouse.get_pos()
                #ASK MS WUN HOW TO DO #
                if self.rect.left != x and self.rect.top != y:
                    #self.rect.move_ip(x, y)
                    self.rect.move_ip(self.speed*self.dir_x, self.speed*self.dir_y)

There isn't any error messages, the only thing that happens is either the ball will move in a set direction (if the user clicks on the right side, the ball will move to the right, and if the user clicks on the left, the ball will still move to the right).

Or the ball will just flicker in and out on the same spot

Body:
The problem, I think (I can't tell properly without a minimal, complete and verifiable example) is a misunderstanding of Rect.move_ip(). This method translates the Rect in a direction, rather than moving towards it. Since you can only click on positive co-ordinates (negative ones are off-screen), this means it will always move down and to the right. If you want to move towards something, the easiest way is something like this:

target_x = 100
target_y = 300
ball_x = 600
ball_y = 200
movedir_x = target_x - ball_x
movedir_y = target_y - ball_y
# Now adjust so that the speed is unaffected by distance to target
length = (movedir_x ** 2 + movedir_y ** 2) ** 0.5
movedir_x *= speed / length
movedir_y *= speed / length

and then translate the ball by this movedir rather than the ball's position. I think at this point you should probably just use Pygame's Vector2 class. Then the equivalent would just be:

target = pygame.math.Vector2(100, 300)
ball = pygame.math.Vector2(600, 200)
movedir = (target - ball).normalize() * speed


问:
how can i change the checkbox attribute which are in the 9th column of a table
How to modify the checkbox attribute (checkbok in the 9th cells of the table MyTab) ?

MyTab contains 9 columns and the last is a checkbox.

None of the following code is working.

```<code>$('#MyTab tr').filter(':visible').each(function( index,element) {

     element.cells[8].attr('checked', true);

     $(this).attr('checked',true);

     $(this).prop('checked',true);

     $(element "input[type='checkbox']").attr('checked',true) ;

     element.cells[8].attr('checked', true);

     element.cells[8].prop('checked', true);

 });

HTML part = exemple with one row =
<table id="MyTab"  border=0 width=1400 cellspacing=2 cellpadding=2 class="table" >
<tr class='impair' onMouseOver="this.className='ModuleCorpsColorOver';" onMouseOut="this.className='impair';">
   <td>USER</td>
   <td>964469597</td>
   <td>17231215</td>
   <td>450,60</td>
   <td>22-11-18</td>
   <td>08-10-18</td>
   <td>DOCUMENT1</td>
   <td>LIBELLE1</td>
   <td><input type='checkbox' class='inputNoBord' name='upd_statut[]' value='1' enable></td>
</tr>

<tr>
    ....
</tr>
</table>

I am also using following jquery =
<script src="../lib/jquery-1.11.1.min.js"></script>
<script src="../lib/sorttable.js"></script>
<script src="../lib/jquery.filtertable.min.js"></script>
</code>```

答:
```<code>$('#MyTab tr').filter(':visible').find('td:eq(8) input[type=checkbox]').prop('checked', true);
</code>```

You can just use :eq(8) to directly filter only the 9th table cell of each row.

You don’t even need to loop over the elements, since in setting mode, .prop works on all elements in the collection.

Body:
How to modify the checkbox attribute (checkbok in the 9th cells of the table MyTab) ?

MyTab contains 9 columns and the last is a checkbox.

None of the following code is working.

$('#MyTab tr').filter(':visible').each(function( index,element) {

     element.cells[8].attr('checked', true);

     $(this).attr('checked',true);

     $(this).prop('checked',true);

     $(element "input[type='checkbox']").attr('checked',true) ;

     element.cells[8].attr('checked', true);

     element.cells[8].prop('checked', true);

 });

HTML part = exemple with one row =

   USER
   964469597
   17231215
   450,60
   22-11-18
   08-10-18
   DOCUMENT1
   LIBELLE1
   <input type='checkbox' class='inputNoBord' name='upd_statut[]' value='1' enable>

    ....

I am also using following jquery =

Body:
$('#MyTab tr').filter(':visible').find('td:eq(8) input[type=checkbox]').prop('checked', true);

You can just use :eq(8) to directly filter only the 9th table cell of each row.

You don’t even need to loop over the elements, since in setting mode, .prop works on all elements in the collection.


问:
Disable is not function using jQuery
Users are requested to select an option in step 1, then step 2 will appear, otherwise step 2 is disabled. The same goes for step 3 whereby users are requested to select step 2, otherwise step 3 is disabled.

The problem is that a user already selected at step 2 but step 3 is still disabled. The user should be able to select on Step 3.

$(function() {
  //1st Step
  $("#selRegion").change(function() {
    $(".subCat").hide();

    $("#stateplaceholder").hide();

    //2nd Step
    if ($("#selRegion").val() == "") {
      $("#stateplaceholder").show();

      //3rd step
      if ($("#selAllRegions").val() != "" || $("#selCentral").val() != "") {
        $("#datefrom").removeAttr("disabled");
        $("#dateto").removeAttr("disabled");
        $("#time").removeAttr("disabled");
      }
    }

    var val = $(this).val();
    if (val == "all") {
      $("#selAllRegions").show();
    } else if (val == "central") {
      $("#selCentral").show();
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.subCat {
  display: none;
}</code>```

<form name="myform" id="myform" action="">

STEP 1 : Choose Region

      <select id="selRegion">
        <option value="">..Select..</option>
        <option value="all" id="AllRegions">All Regions</option>
      </select>

STEP 2 : Choose State

    <select id="stateplaceholder" onchange="getAllRegions(this)" disabled>
      <option value="">Please select Region first</option>
    </select>
    <select id="selAllRegions" onchange="getAllRegions(this)" class="subCat">
      <option value="">..Select..</option>
      <option value="abc">ABC</option>
    </select>
    <select id="selCentral" onchange="getCentral(this)" class="subCat">
      <option value="">..Select..</option>
      <option value="xyz">XYZ</option>
    </select>

STEP 3 : Choose Date and Time

Please choose Date FROM.

    <input id="datefrom" class="date-picker" placeholder="Date From" type="text" disabled>

Please choose Date TO.

    <input id="dateto" class="date-picker" placeholder="Date To" type="text" disabled>

Please choose TIME Interval.

    <input id="time" class="time-picker" placeholder="Time by Hourly" type="text" disabled>
    <button id="btnSubmit" type="button">Submit</button>

</form>```

JSFiddle

答:
I have modified the jquery snippet to make it work.
I have added a change() method to Step 2 selector.</p>

```<code>$(function() {
    //1st Step
    $("#selRegion").change(function() {

    $(".subCat").hide();

    $("#stateplaceholder").hide();
    //2nd Step
    if ($("#selRegion").val() == "") {
      $("#stateplaceholder").show();

      //3rd step
      if ($("#selAllRegions").val() != "" || $("#selCentral").val() != "") {

        $("#datefrom").removeAttr("disabled");
        $("#dateto").removeAttr("disabled");
        $("#time").removeAttr("disabled");

      }

    }

    var val = $(this).val();
    if (val == "all") {
      $("#selAllRegions").show();
    } else if(val == "central") {
      $("#selCentral").show();
    }
  });
  $("#selAllRegions").change(function(){
        if ($("#selAllRegions").val() != "" || $("#selCentral").val() != "") {

        $("#datefrom").removeAttr("disabled");
        $("#dateto").removeAttr("disabled");
        $("#time").removeAttr("disabled");

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

Title: Disable is not function using jQuery

Body:
Users are requested to select an option in step 1, then step 2 will appear, otherwise step 2 is disabled. The same goes for step 3 whereby users are requested to select step 2, otherwise step 3 is disabled.

The problem is that a user already selected at step 2 but step 3 is still disabled. The user should be able to select on Step 3.

$(function() {
  //1st Step
  $("#selRegion").change(function() {
    $(".subCat").hide();

    $("#stateplaceholder").hide();

    //2nd Step
    if ($("#selRegion").val() == "") {
      $("#stateplaceholder").show();

      //3rd step
      if ($("#selAllRegions").val() != "" || $("#selCentral").val() != "") {
        $("#datefrom").removeAttr("disabled");
        $("#dateto").removeAttr("disabled");
        $("#time").removeAttr("disabled");
      }
    }

    var val = $(this).val();
    if (val == "all") {
      $("#selAllRegions").show();
    } else if (val == "central") {
      $("#selCentral").show();
    }
  });
});

.subCat {
  display: none;
}

<form name="myform" id="myform" action="">

STEP 1 : Choose Region

      <select id="selRegion">
        <option value="">..Select..</option>
        <option value="all" id="AllRegions">All Regions</option>
      </select>

STEP 2 : Choose State

    <select id="stateplaceholder" onchange="getAllRegions(this)" disabled>
      <option value="">Please select Region first</option>
    </select>
    <select id="selAllRegions" onchange="getAllRegions(this)" class="subCat">
      <option value="">..Select..</option>
      <option value="abc">ABC</option>
    </select>
    <select id="selCentral" onchange="getCentral(this)" class="subCat">
      <option value="">..Select..</option>
      <option value="xyz">XYZ</option>
    </select>

STEP 3 : Choose Date and Time

Please choose Date FROM.

    <input id="datefrom" class="date-picker" placeholder="Date From" type="text" disabled>

Please choose Date TO.

    <input id="dateto" class="date-picker" placeholder="Date To" type="text" disabled>

Please choose TIME Interval.

    <input id="time" class="time-picker" placeholder="Time by Hourly" type="text" disabled>
    <button id="btnSubmit" type="button">Submit</button>

</form>

JSFiddle

Body:
I have modified the jquery snippet to make it work.
I have added a change() method to Step 2 selector.

$(function() {
    //1st Step
    $("#selRegion").change(function() {

    $(".subCat").hide();

    $("#stateplaceholder").hide();
    //2nd Step
    if ($("#selRegion").val() == "") {
      $("#stateplaceholder").show();

      //3rd step
      if ($("#selAllRegions").val() != "" || $("#selCentral").val() != "") {

        $("#datefrom").removeAttr("disabled");
        $("#dateto").removeAttr("disabled");
        $("#time").removeAttr("disabled");

      }

    }

    var val = $(this).val();
    if (val == "all") {
      $("#selAllRegions").show();
    } else if(val == "central") {
      $("#selCentral").show();
    }
  });
  $("#selAllRegions").change(function(){
        if ($("#selAllRegions").val() != "" || $("#selCentral").val() != "") {

        $("#datefrom").removeAttr("disabled");
        $("#dateto").removeAttr("disabled");
        $("#time").removeAttr("disabled");

      }
  })
});