问:
Does the Sandwich Package work for Robust Standard Errors for Logistic Regression with basic Survey Weights
I am running logistic regressions with a panel data set from survey data and I want to correct the standard errors for the panel design. The weights included in this survey account for sampling probability, panel mortality and post stratification.

If I understood Berger et al 2017 correctly I should use clustered covariances for panel data. However, I am not sure if the commands work for data with survey weights.

I started by estimating the regressions with glm and correcting the standard errors with coeftest from the lmtest package and vcovPL from the sandwichpackage. Subsequently, I used svydesign and svyglm from the survey package to estimate a weighted model and corrected the standard errors again the same way.

In this Question R's sandwich package producing strange results for robust standard errors in linear model Zeileis writes that using svyglm objects might produce incorrect results. However, I am not sure if this applies only for complex survey weight (with strata etc.) or as well for basic survey weights, since its pointed out here that without the use of strata there is not much difference. However, I don't fully understand the explanation there. Moreover, I wonder if the newly implemented features described in Berger et al 2017 allow for using a svyglm object. So I don't know if I can use the commands in the sandwich package for objects of class svyglm if my design has no strata.

Here is the code I used:

```<code># not weighted
model <- glm(depend_var ~ indep_var1 + indep_var2 ,family=quasibinomial(link='logit'),data=dataset)
m_vcov <- coeftest(model,vcov. =  sandwich::vcovPL(x = model, cluster = ~ id_var,order.by = ~ year ,pairwise = T))

# weighted
design.ps <- svydesign(ids=~1, weights=~wgt, data=dataset)
model_wgt <- svyglm(depend_var ~ indep_var1 + indep_var2, design=design.ps,family=quasibinomial(link='logit'),data=dataset)
mwt_vcov <- coeftest(model_wgt, vcov. = sandwich::vcovPL(x = model_wgt, cluster = ~ id_var,order.by = ~ year ,pairwise = T))
</code>```

Looking at the coefficients provided by the test code above, the results seem kind of reasonable unlike the results provided here: R's sandwich package producing strange results for robust standard errors in linear model

```<code># basic model
> summary(model)
                  Estimate Std. Error t value Pr(>|t|)
(Intercept)       -3.68570    0.01264 -291.68   <2e-16 ***
indep_var1_test    0.37538    0.01111   33.78   <2e-16 ***
indep_var2_test    1.05226    0.01100   95.62   <2e-16 ***

# basic model with SE correction
> m_vcov
                   Estimate Std. Error  z value  Pr(>|z|)
(Intercept)       -3.685702   0.176121 -20.9271 < 2.2e-16 ***
indep_var1_test    0.375380   0.049817   7.5353 4.874e-14 ***
indep_var2_test    1.052258   0.068763  15.3027 < 2.2e-16 ***

# weighted model
> summary(model_wgt)
                  Estimate Std. Error t value Pr(>|t|)
(Intercept)       -3.89702    0.01751 -222.57   <2e-16 ***
indep_var1_test    0.42373    0.01454   29.15   <2e-16 ***
indep_var2_test    1.05291    0.01439   73.15   <2e-16 ***

# weighted model with SE correction
> mwt_vcov
                   Estimate Std. Error  z value  Pr(>|z|)
(Intercept)       -3.897021   0.319932 -12.1808 < 2.2e-16 ***
indep_var1_test.   0.423732   0.075202   5.6346 1.755e-08 ***
indep_var2_test    1.052915   0.126569   8.3189 < 2.2e-16 ***
</code>```

My question is: Can I use the commands above to correct the standard errors?

I guess my question is similar to this unanswered one:
https://stats.stackexchange.com/questions/260515/does-coeftest-correctly-use-weights-from-svydesign-in-svyglm-object?rq=1

答:
You want to use

```<code>coeftest(model, vcov=vcov(model))
</code>```

For svyglm models, vcov() already produces the appropriate sandwich estimator, and I don't think the "sandwich" package knows enough about the internals of the object to get it right.

Body:
I am running logistic regressions with a panel data set from survey data and I want to correct the standard errors for the panel design. The weights included in this survey account for sampling probability, panel mortality and post stratification.

If I understood Berger et al 2017 correctly I should use clustered covariances for panel data. However, I am not sure if the commands work for data with survey weights.

I started by estimating the regressions with glm and correcting the standard errors with coeftest from the lmtest package and vcovPL from the sandwichpackage. Subsequently, I used svydesign and svyglm from the survey package to estimate a weighted model and corrected the standard errors again the same way.

In this Question R's sandwich package producing strange results for robust standard errors in linear model Zeileis writes that using svyglm objects might produce incorrect results. However, I am not sure if this applies only for complex survey weight (with strata etc.) or as well for basic survey weights, since its pointed out here that without the use of strata there is not much difference. However, I don't fully understand the explanation there. Moreover, I wonder if the newly implemented features described in Berger et al 2017 allow for using a svyglm object. So I don't know if I can use the commands in the sandwich package for objects of class svyglm if my design has no strata.

Here is the code I used:

# not weighted
model <- glm(depend_var ~ indep_var1 + indep_var2 ,family=quasibinomial(link='logit'),data=dataset)
m_vcov <- coeftest(model,vcov. =  sandwich::vcovPL(x = model, cluster = ~ id_var,order.by = ~ year ,pairwise = T))

# weighted
design.ps <- svydesign(ids=~1, weights=~wgt, data=dataset)
model_wgt <- svyglm(depend_var ~ indep_var1 + indep_var2, design=design.ps,family=quasibinomial(link='logit'),data=dataset)
mwt_vcov <- coeftest(model_wgt, vcov. = sandwich::vcovPL(x = model_wgt, cluster = ~ id_var,order.by = ~ year ,pairwise = T))

Looking at the coefficients provided by the test code above, the results seem kind of reasonable unlike the results provided here: R's sandwich package producing strange results for robust standard errors in linear model

# basic model
> summary(model)
                  Estimate Std. Error t value Pr(>|t|)
(Intercept)       -3.68570    0.01264 -291.68   <2e-16 ***
indep_var1_test    0.37538    0.01111   33.78   <2e-16 ***
indep_var2_test    1.05226    0.01100   95.62   <2e-16 ***

# basic model with SE correction
> m_vcov
                   Estimate Std. Error  z value  Pr(>|z|)
(Intercept)       -3.685702   0.176121 -20.9271 < 2.2e-16 ***
indep_var1_test    0.375380   0.049817   7.5353 4.874e-14 ***
indep_var2_test    1.052258   0.068763  15.3027 < 2.2e-16 ***

# weighted model
> summary(model_wgt)
                  Estimate Std. Error t value Pr(>|t|)
(Intercept)       -3.89702    0.01751 -222.57   <2e-16 ***
indep_var1_test    0.42373    0.01454   29.15   <2e-16 ***
indep_var2_test    1.05291    0.01439   73.15   <2e-16 ***

# weighted model with SE correction
> mwt_vcov
                   Estimate Std. Error  z value  Pr(>|z|)
(Intercept)       -3.897021   0.319932 -12.1808 < 2.2e-16 ***
indep_var1_test.   0.423732   0.075202   5.6346 1.755e-08 ***
indep_var2_test    1.052915   0.126569   8.3189 < 2.2e-16 ***

My question is: Can I use the commands above to correct the standard errors?

I guess my question is similar to this unanswered one:
https://stats.stackexchange.com/questions/260515/does-coeftest-correctly-use-weights-from-svydesign-in-svyglm-object?rq=1

Body:
You want to use

coeftest(model, vcov=vcov(model))

For svyglm models, vcov() already produces the appropriate sandwich estimator, and I don't think the "sandwich" package knows enough about the internals of the object to get it right.


来源: stackexchange

问:
Why does assigning a value to double underscore __ break the behavior of single underscore _ in ipython?
I have been playing with the output caching system in IPython and noticed some strange behavior, giving unexpected results when using the single underscore _ to obain the previous output.

Before writing up this question I didn't know about the output caching system implemented in IPython and figured I should use a double underscore __ as a dummy variable, if I wanted to use the previous output by accessing the special _-Variable.

Consider the following session:

```<code>Python 3.6.7 (default, Oct 22 2018, 11:32:17)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.3.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: 2*3
Out[1]: 6

In [2]: 4 + _  # expect 10, OK
Out[2]: 10

In [3]: __, something = 1, 2

In [4]: 3*3
Out[4]: 9

In [5]: 3 + _  # expect 3+9=12, but:
Out[5]: 13
</code>```

As you can see above, after assigning a value to __, using _ does not give the expected result.

After reading the references linked earlier, I know I probably just shouldn't mess with _, __ or ___. Does assigning one of these simply freeze all others?

The documentation does not hint at these problems. Also, I find this highly counterintuitive since a regular python shell behaves differently. (After going through the example above in a regular shell, the final output is as expected!)

Thanks in advance for your feedback!

答:
IPython have (among others) 3 specific variables: _, __, and ___,
Every time you do an execution they got moved around; _ -> __, __ -> ___, ___ -> discarded, and last result -> _

If one of these variables get assigned; then the rotation stops.

```<code>In [1]: 1
Out[1]: 1

In [2]: 2  # _:1, __:'', ___:''
Out[2]: 2

In [3]: 3  # _:2, __:1, ___:''
Out[3]: 3

In [4]: ___ ='something', # _:3, __:2, ___:1

In [5]: __ # still gonna be 2
Out[5]: 2

In [6]: __ # still gonna be 2 again
Out[6]: 2

In [7]: _ # still 3
Out[7]: 3
</code>```

It's worth discussing but it's quite tough to modify; it is relatively hard to figure out what is meant and wether the user had "modified" _, __ or ___;

In the above example, replace "something" by 1 and because (1 is 1) == True, then IPython won't "detect" you've assigned one of the underscore and resume shifting things around.

ContentLicense: CC BY-SA 4.0

Body:
I have been playing with the output caching system in IPython and noticed some strange behavior, giving unexpected results when using the single underscore _ to obain the previous output.

Before writing up this question I didn't know about the output caching system implemented in IPython and figured I should use a double underscore __ as a dummy variable, if I wanted to use the previous output by accessing the special _-Variable.

Consider the following session:

Python 3.6.7 (default, Oct 22 2018, 11:32:17)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.3.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: 2*3
Out[1]: 6

In [2]: 4 + _  # expect 10, OK
Out[2]: 10

In [3]: __, something = 1, 2

In [4]: 3*3
Out[4]: 9

In [5]: 3 + _  # expect 3+9=12, but:
Out[5]: 13

As you can see above, after assigning a value to __, using _ does not give the expected result.

After reading the references linked earlier, I know I probably just shouldn't mess with _, __ or ___. Does assigning one of these simply freeze all others?

The documentation does not hint at these problems. Also, I find this highly counterintuitive since a regular python shell behaves differently. (After going through the example above in a regular shell, the final output is as expected!)

Thanks in advance for your feedback!

Body:
IPython have (among others) 3 specific variables: _, __, and ___,
Every time you do an execution they got moved around; _ -> __, __ -> ___, ___ -> discarded, and last result -> _

If one of these variables get assigned; then the rotation stops.

In [1]: 1
Out[1]: 1

In [2]: 2  # _:1, __:'', ___:''
Out[2]: 2

In [3]: 3  # _:2, __:1, ___:''
Out[3]: 3

In [4]: ___ ='something', # _:3, __:2, ___:1

In [5]: __ # still gonna be 2
Out[5]: 2

In [6]: __ # still gonna be 2 again
Out[6]: 2

In [7]: _ # still 3
Out[7]: 3

It's worth discussing but it's quite tough to modify; it is relatively hard to figure out what is meant and wether the user had "modified" _, __ or ___;

In the above example, replace "something" by 1 and because (1 is 1) == True, then IPython won't "detect" you've assigned one of the underscore and resume shifting things around.


问:
Refactoring problem from class to function with hooks
I am refactoring some code and now I am stuck.
The original code is from a tuto :
https://github.com/EricLondon/rails5-react-reactstrap-crud-example
All is fine there.
I try to use hooks new feature.
The new code I wrote just fail.

"Original code" is ok tested
"new code" fails

```<code>//"New code"
import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { Container, Row, Col, Alert } from 'reactstrap'
import PostsTable from '../PostsTable'

const Api = require('../../api/Api.js')

export default function Posts() {
  const [posts, setPosts] = useState([])
  const [isLoaded, setIsLoaded] = useState(false)
  const [error, setError] = useState(null)

  useEffect( () => {
    Api.getPosts()
      .then( response => {
        const [errata, data] = response
        if (errata) {
          setIsLoaded(true)
          setPosts([])
          setError(data)
        } else {
          setIsLoaded(true)
          setPosts(data)
        }
      })
  })

  if (error) {

    return (
      <Alert color="danger">
          Error: {error}
      </Alert>
    )

  } else if (!isLoaded) {

    return (
      <Alert color="primary">
          Loading...
      </Alert>
    )

  } else {

    return (
      <Container>
        <Row>
          <Col>
            <PostsTable posts={posts}></PostsTable>
            <Link className="btn btn-primary" to="/posts/new">Add Post</Link>
          </Col>
        </Row>
      </Container>
    )

  }
}

//"Original code"
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { Container, Row, Col, Alert } from 'reactstrap'
import PostsTable from '../PostsTable'

const Api = require('../../api/Api.js')

class Posts extends Component {
  constructor(props) {
    super(props)
    this.state = {
      posts: [],
      isLoaded: false,
      error: null
    }
  }

  componentDidMount() {
    Api.getPosts()
      .then(response => {
        const [error, data] = response
        if (error) {
          this.setState({
            isLoaded: true,
            posts: [],
            error: data
          })
        } else {
          this.setState({
            isLoaded: true,
            posts: data
          })
        }
      })
  }

  render() {
    const { error, isLoaded, posts } = this.state

    if (error) {

      return (
        <Alert color="danger">
          Error: {error}
        </Alert>
      )

    } else if (!isLoaded) {

      return (
        <Alert color="primary">
          Loading...
        </Alert>
      )

    } else {

      return (
        <Container>
          <Row>
            <Col>
              <PostsTable posts={posts}></PostsTable>
              <Link className="btn btn-primary" to="/posts/new">Add Post</Link>
            </Col>
          </Row>
        </Container>
      )

    }

  }
}

export default Posts
</code>```

With "new code" my backend server is driving crazy:
....
Started GET "/api/posts" for 127.0.0.1 at 2019-05-26 20:45:39 +0200
Processing by Api::PostsController#index as HTML
  Post Load (1.3ms)  SELECT "posts".* FROM "posts"
  ↳ app/controllers/api/posts_controller.rb:5
Completed 200 OK in 6ms (Views: 4.4ms | ActiveRecord: 1.3ms)
....
etc.

答:
Sorry to other answers but empty array is not correct. You can read this 49 minute article by Dan Abramov (creator of Redux and React Hooks) on why that is.

https://overreacted.io/a-complete-guide-to-useeffect/

I believe you can solve your problem by combining all your useState hooks like so:

```<code>export default function Posts() {
  const [state, setState] = useState({posts: [],
                                      isLoaded: false,
                                      error: null })

  useEffect( () => {
    Api.getPosts()
      .then( response => {
        const [errata, data] = response
        if (errata) {
          setState({ ...state,
                     isLoaded: true,
                     posts: [],
                     error: data })
        } else {
          setState({ ...state,
                     isLoaded: true,
                     posts: [data],
                     error: null })
        }
      })
  }, [state.isLoaded] )
</code>```

make sure you pass in the previous state with the spread syntax otherwise your previous state will not be saved.

Alternate way use a conditional in the useEffect and pass in the entire state as a dependency to useEffect

```<code>export default function Posts() {
  const [state, setState] = useState({posts: [],
                                      isLoaded: false,
                                      error: null })

  useEffect( () => {
  if(!state.isLoaded) {
    Api.getPosts()
      .then( response => {
        const [errata, data] = response
        if (errata) {
          setState({ ...state,
                     isLoaded: true,
                     posts: [],
                     error: data })
        } else {
          setState({ ...state,
                     isLoaded: true,
                     posts: [data],
                     error: null })
        }
      })
    }
  }, [state] )
</code>```

Body:
I am refactoring some code and now I am stuck.
The original code is from a tuto :
https://github.com/EricLondon/rails5-react-reactstrap-crud-example
All is fine there.
I try to use hooks new feature.
The new code I wrote just fail.

"Original code" is ok tested
"new code" fails

//"New code"
import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { Container, Row, Col, Alert } from 'reactstrap'
import PostsTable from '../PostsTable'

const Api = require('../../api/Api.js')

export default function Posts() {
  const [posts, setPosts] = useState([])
  const [isLoaded, setIsLoaded] = useState(false)
  const [error, setError] = useState(null)

  useEffect( () => {
    Api.getPosts()
      .then( response => {
        const [errata, data] = response
        if (errata) {
          setIsLoaded(true)
          setPosts([])
          setError(data)
        } else {
          setIsLoaded(true)
          setPosts(data)
        }
      })
  })

  if (error) {

    return (
      <Alert color="danger">
          Error: {error}
      </Alert>
    )

  } else if (!isLoaded) {

    return (
      <Alert color="primary">
          Loading...
      </Alert>
    )

  } else {

    return (
      <Container>
        <Row>
          <Col>
            <PostsTable posts={posts}></PostsTable>
            <Link className="btn btn-primary" to="/posts/new">Add Post</Link>
          </Col>
        </Row>
      </Container>
    )

  }
}

//"Original code"
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { Container, Row, Col, Alert } from 'reactstrap'
import PostsTable from '../PostsTable'

const Api = require('../../api/Api.js')

class Posts extends Component {
  constructor(props) {
    super(props)
    this.state = {
      posts: [],
      isLoaded: false,
      error: null
    }
  }

  componentDidMount() {
    Api.getPosts()
      .then(response => {
        const [error, data] = response
        if (error) {
          this.setState({
            isLoaded: true,
            posts: [],
            error: data
          })
        } else {
          this.setState({
            isLoaded: true,
            posts: data
          })
        }
      })
  }

  render() {
    const { error, isLoaded, posts } = this.state

    if (error) {

      return (
        <Alert color="danger">
          Error: {error}
        </Alert>
      )

    } else if (!isLoaded) {

      return (
        <Alert color="primary">
          Loading...
        </Alert>
      )

    } else {

      return (
        <Container>
          <Row>
            <Col>
              <PostsTable posts={posts}></PostsTable>
              <Link className="btn btn-primary" to="/posts/new">Add Post</Link>
            </Col>
          </Row>
        </Container>
      )

    }

  }
}

export default Posts

With "new code" my backend server is driving crazy:
....
Started GET "/api/posts" for 127.0.0.1 at 2019-05-26 20:45:39 +0200
Processing by Api::PostsController#index as HTML
  Post Load (1.3ms)  SELECT "posts".* FROM "posts"
  ↳ app/controllers/api/posts_controller.rb:5
Completed 200 OK in 6ms (Views: 4.4ms | ActiveRecord: 1.3ms)
....
etc.

Body:
Sorry to other answers but empty array is not correct. You can read this 49 minute article by Dan Abramov (creator of Redux and React Hooks) on why that is.

https://overreacted.io/a-complete-guide-to-useeffect/

I believe you can solve your problem by combining all your useState hooks like so:

export default function Posts() {
  const [state, setState] = useState({posts: [],
                                      isLoaded: false,
                                      error: null })

  useEffect( () => {
    Api.getPosts()
      .then( response => {
        const [errata, data] = response
        if (errata) {
          setState({ ...state,
                     isLoaded: true,
                     posts: [],
                     error: data })
        } else {
          setState({ ...state,
                     isLoaded: true,
                     posts: [data],
                     error: null })
        }
      })
  }, [state.isLoaded] )

make sure you pass in the previous state with the spread syntax otherwise your previous state will not be saved.

Alternate way use a conditional in the useEffect and pass in the entire state as a dependency to useEffect

export default function Posts() {
  const [state, setState] = useState({posts: [],
                                      isLoaded: false,
                                      error: null })

  useEffect( () => {
  if(!state.isLoaded) {
    Api.getPosts()
      .then( response => {
        const [errata, data] = response
        if (errata) {
          setState({ ...state,
                     isLoaded: true,
                     posts: [],
                     error: data })
        } else {
          setState({ ...state,
                     isLoaded: true,
                     posts: [data],
                     error: null })
        }
      })
    }
  }, [state] )


问:
How to calculate the length of JSON values in php?
I have a JSON as shown below in which I want to calculate through php how many values are present inside posts_id_en. At present, it is 7 as shown below:

```<code>{
    "posts_id_en": "149968, 149939, 149883, 149877, 149876, 149847, 154303",
    "posts_id_fr": "149974,149953,149926, 149920, 149901",
    "episode_status": "3"
}
</code>```

In php code on doing echo $data->{"posts_id_en"};, it displays the values as shown below:

```<code>149968, 149939, 149883, 149877, 149876, 149847, 154303
</code>```

Problem Statement:

I am wondering what php code I need to use so that we can calculate number of values entered inside posts_id_en. At this moment, it is entered 7 as shown above.

答:
The items you are trying to count are in a single string. First, you must break the string into items, then you can count them.

Take the json and make it into a php array

```<code>$jsonData = '{
    "posts_id_en": "149968, 149939, 149883, 149877, 149876, 149847, 154303",
    "posts_id_fr": "149974,149953,149926, 149920, 149901",
    "episode_status": "3"
}';
$data = json_decode($jsonData, true);
</code>```

then split the string with the delimiter ", "

```<code>$items = explode(", ", $data['posts_id_en']);
</code>```

then count

```<code>echo count($items);
</code>```

Body:
I have a JSON as shown below in which I want to calculate through php how many values are present inside posts_id_en. At present, it is 7 as shown below:

{
    "posts_id_en": "149968, 149939, 149883, 149877, 149876, 149847, 154303",
    "posts_id_fr": "149974,149953,149926, 149920, 149901",
    "episode_status": "3"
}

In php code on doing echo $data->{"posts_id_en"};, it displays the values as shown below:

149968, 149939, 149883, 149877, 149876, 149847, 154303

Problem Statement:

I am wondering what php code I need to use so that we can calculate number of values entered inside posts_id_en. At this moment, it is entered 7 as shown above.

Body:
The items you are trying to count are in a single string. First, you must break the string into items, then you can count them.

Take the json and make it into a php array

$jsonData = '{
    "posts_id_en": "149968, 149939, 149883, 149877, 149876, 149847, 154303",
    "posts_id_fr": "149974,149953,149926, 149920, 149901",
    "episode_status": "3"
}';
$data = json_decode($jsonData, true);

then split the string with the delimiter ", "

$items = explode(", ", $data['posts_id_en']);

then count

echo count($items);


问:
How to check if "unsorted version" of a list already exists in the set?
I want to generate a list of lists. Each sub-list will be generated by sampling from range(100). I need to make sure lists that are identical (i.e. have the exact same elements) but have different sorting do not exist in the main list (i.e. I do not want [1,2,3] and [2,1,3] in the main list at the same time). This is what I have written:

```<code>import random as rd
my_list = []
while len(my_list) < 50:
    p = rd.sample(range(100), 10)
    if p not in my_list: my_list.append(p)
</code>```

The issue is if p not in my_list does not do the job as it does not consider [1,2,3] and [2,1,3] identical. I thought of doing something like this:

```<code>my_list = []
while len(my_list) < 50:
    p = rd.sample(range(100), 10)
    for i in range(len(my_list)):
        if set(p) != set(my_list[i]): my_list.append(p)
</code>```

But it seems this gets stuck in the first loop and the program never ends. I was wondering if there is a simple way of doing this in Python?

答:
Your logic isn't quite right—you only want to add something to the list when it's not already in it. Here's how to do that by using a for loop's option else clause which will only execute if the break is never executed. How this works is described in the documentaton of the for statement.

```<code>my_list = []
for p in [1,2,3], [3,2,1], [4,5,6]:
    for c in my_list:
        if set(p) == set(c):
            break
    else:
        my_list.append(p)

print(my_list)  # -> [[1, 2, 3], [4, 5, 6]]
</code>```

It's also inefficient to convert each combination to a set more than once, so you can take that part out of the loop:

```<code>my_list = []
for p in [1,2,3], [3,2,1], [4,5,6]:
    set_p = set(p)  # do this here
    for c in my_list:
        if set_p == set(c):
            break
    else:
        my_list.append(p)
</code>```

Body:
I want to generate a list of lists. Each sub-list will be generated by sampling from range(100). I need to make sure lists that are identical (i.e. have the exact same elements) but have different sorting do not exist in the main list (i.e. I do not want [1,2,3] and [2,1,3] in the main list at the same time). This is what I have written:

import random as rd
my_list = []
while len(my_list) < 50:
    p = rd.sample(range(100), 10)
    if p not in my_list: my_list.append(p)

The issue is if p not in my_list does not do the job as it does not consider [1,2,3] and [2,1,3] identical. I thought of doing something like this:

my_list = []
while len(my_list) < 50:
    p = rd.sample(range(100), 10)
    for i in range(len(my_list)):
        if set(p) != set(my_list[i]): my_list.append(p)

But it seems this gets stuck in the first loop and the program never ends. I was wondering if there is a simple way of doing this in Python?

Body:
Your logic isn't quite right—you only want to add something to the list when it's not already in it. Here's how to do that by using a for loop's option else clause which will only execute if the break is never executed. How this works is described in the documentaton of the for statement.

my_list = []
for p in [1,2,3], [3,2,1], [4,5,6]:
    for c in my_list:
        if set(p) == set(c):
            break
    else:
        my_list.append(p)

print(my_list)  # -> [[1, 2, 3], [4, 5, 6]]

It's also inefficient to convert each combination to a set more than once, so you can take that part out of the loop:

my_list = []
for p in [1,2,3], [3,2,1], [4,5,6]:
    set_p = set(p)  # do this here
    for c in my_list:
        if set_p == set(c):
            break
    else:
        my_list.append(p)


问:
Error in removing product from cart in Django?
I am facing an error in removing products from cart. When i add product in cart by setting the quantity and click on remove an error is displayed.

local variable 'product' referenced before assignment

I have product in models.py file and referring it from their by importing the models and have tried by changing the name but still it gives an error.

views.py

```<code>def update_cart(request,slug):
request.session.set_expiry(1200000)
try:
    qty=request.GET.get('qty')
    update_qty=True
except:
    qty=None
    update_qty=False
try:
    the_id=request.session['cart_id']
except:
    new_cart=Cart()
    new_cart.save()
    request.session['cart_id']=new_cart.id
    the_id=new_cart.id

cart = Cart.objects.get(id=the_id)
try:
    product=Product.objects.get(slug=slug)
except Product.DoesNotExist:
    pass
except:
    pass

cart_item,created=CartItem.objects.get_or_create(cart=cart,product=product)
if created:
    print("yeah")
    if update_qty and qty:
       if int(qty)<=0:
        cart_item.delete()
       else:
        cart_item.quantity=qty
        cart_item.save()
else:
    pass

return HttpResponseRedirect(reverse("carts:cart"))
</code>```

models.py

```<code>class CartItem(models.Model):
    cart=models.ForeignKey('Cart',on_delete=models.SET_NULL,null=True,blank=True)
    product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True,blank=True)
    accessory = models.ForeignKey(Accessories,on_delete=models.SET_NULL,null=True,blank=True)
    quantity=models.IntegerField(default=1)
    updated  = models.DateTimeField(auto_now_add=True,auto_now=False)
    line_total=models.DecimalField(default=10.99,max_digits=1000,decimal_places=2)
    timestamp = models.DateTimeField(auto_now_add=True,auto_now=False)

    objects = CartManager()

    def __unicode__(self):
        try:
           return str(self.cart.id)
        except:
            return self.product.title
</code>```

If anyone can please help it would be really appreciated?

Note
I have seen other link of stackoverflow but none helped.

答:
Your product variable is inside a try block, and python interpreter can't see it. You could create it outside the try block:

```<code>....
product = None
try:
    product=Product.objects.get(slug=slug)
</code>```

Or move your logic to deal with the product into the try block, just after the product is assign

```<code>cart = Cart.objects.get(id=the_id)
try:
    product=Product.objects.get(slug=slug)
    cart_item,created=CartItem.objects.get_or_create(cart=cart,product=product)
    if created:
        print("yeah")
        if update_qty and qty:
           if int(qty)<=0:
            cart_item.delete()
           else:
            cart_item.quantity=qty
            cart_item.save()
    else:
        pass

    return HttpResponseRedirect(reverse("carts:cart"))
except Product.DoesNotExist:
    pass
except:
    pass
</code>```

Body:
I am facing an error in removing products from cart. When i add product in cart by setting the quantity and click on remove an error is displayed.

local variable 'product' referenced before assignment

I have product in models.py file and referring it from their by importing the models and have tried by changing the name but still it gives an error.

views.py

def update_cart(request,slug):
request.session.set_expiry(1200000)
try:
    qty=request.GET.get('qty')
    update_qty=True
except:
    qty=None
    update_qty=False
try:
    the_id=request.session['cart_id']
except:
    new_cart=Cart()
    new_cart.save()
    request.session['cart_id']=new_cart.id
    the_id=new_cart.id

cart = Cart.objects.get(id=the_id)
try:
    product=Product.objects.get(slug=slug)
except Product.DoesNotExist:
    pass
except:
    pass

cart_item,created=CartItem.objects.get_or_create(cart=cart,product=product)
if created:
    print("yeah")
    if update_qty and qty:
       if int(qty)<=0:
        cart_item.delete()
       else:
        cart_item.quantity=qty
        cart_item.save()
else:
    pass

return HttpResponseRedirect(reverse("carts:cart"))

models.py

class CartItem(models.Model):
    cart=models.ForeignKey('Cart',on_delete=models.SET_NULL,null=True,blank=True)
    product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True,blank=True)
    accessory = models.ForeignKey(Accessories,on_delete=models.SET_NULL,null=True,blank=True)
    quantity=models.IntegerField(default=1)
    updated  = models.DateTimeField(auto_now_add=True,auto_now=False)
    line_total=models.DecimalField(default=10.99,max_digits=1000,decimal_places=2)
    timestamp = models.DateTimeField(auto_now_add=True,auto_now=False)

    objects = CartManager()

    def __unicode__(self):
        try:
           return str(self.cart.id)
        except:
            return self.product.title

If anyone can please help it would be really appreciated?

Note
I have seen other link of stackoverflow but none helped.

Body:
Your product variable is inside a try block, and python interpreter can't see it. You could create it outside the try block:

....
product = None
try:
    product=Product.objects.get(slug=slug)

Or move your logic to deal with the product into the try block, just after the product is assign

cart = Cart.objects.get(id=the_id)
try:
    product=Product.objects.get(slug=slug)
    cart_item,created=CartItem.objects.get_or_create(cart=cart,product=product)
    if created:
        print("yeah")
        if update_qty and qty:
           if int(qty)<=0:
            cart_item.delete()
           else:
            cart_item.quantity=qty
            cart_item.save()
    else:
        pass

    return HttpResponseRedirect(reverse("carts:cart"))
except Product.DoesNotExist:
    pass
except:
    pass


问:
Iterating efficiently over objects
I have designed my own classes in Python as follows:

```<code>class Main:
    def __init__(self):
        self.list = list() # Contains TestA objects

class TestA:
    def __init__(self, start_time, end_time):
        self.elements = list() # Contains TestB objects
        self.start_time = start_time
        self.end_time = end_time

class TestB:
    def __init__(self, timestamp):
        self.timestamp = timestamp
</code>```

The list of the Main class contains objects of TestA class and the list in TestA class contains objects of TestB class. An example is the following:

```<code>testB1 = TestB(121)
testB2 = TestB(155)
testB3 = TestB(891)
testB4 = TestB(901)

testA1 = TestA(100, 200)
testA1.elements.append(testB1)
testA1.elements.append(testB2)

testA2 = TestA(500, 1000)
testA2.elements.append(testB3)
testA2.elements.append(testB4)

main = Main()
main.list.append(testA1)
main.list.append(testA2)
</code>```

Now I would like to filter objects based on timestamps. First, I would like to retrieve all TestA objects which have the TestA.start_time and TestA.end_time in a specific range. Second, I would like to retrieve all TestB objects which have the TestB.timestamps in a given range. Of course, I could just loop over all TestA and TestB objects but this is inefficient if there are a lot of objects.

Is there a more efficient way to do it?

答:
Use a pandas dataframe,
with an index on the timestamp column.
Then, if you have a million entries but only request twenty-four matching rows,
only a couple dozen rows will be examined.</p>

Title: Iterating efficiently over objects

Body:
I have designed my own classes in Python as follows:

class Main:
    def __init__(self):
        self.list = list() # Contains TestA objects

class TestA:
    def __init__(self, start_time, end_time):
        self.elements = list() # Contains TestB objects
        self.start_time = start_time
        self.end_time = end_time

class TestB:
    def __init__(self, timestamp):
        self.timestamp = timestamp

The list of the Main class contains objects of TestA class and the list in TestA class contains objects of TestB class. An example is the following:

testB1 = TestB(121)
testB2 = TestB(155)
testB3 = TestB(891)
testB4 = TestB(901)

testA1 = TestA(100, 200)
testA1.elements.append(testB1)
testA1.elements.append(testB2)

testA2 = TestA(500, 1000)
testA2.elements.append(testB3)
testA2.elements.append(testB4)

main = Main()
main.list.append(testA1)
main.list.append(testA2)

Now I would like to filter objects based on timestamps. First, I would like to retrieve all TestA objects which have the TestA.start_time and TestA.end_time in a specific range. Second, I would like to retrieve all TestB objects which have the TestB.timestamps in a given range. Of course, I could just loop over all TestA and TestB objects but this is inefficient if there are a lot of objects.

Is there a more efficient way to do it?


答:
You are appending the generated list inside the (if conditional from the) for loop.

But, given the fact that my_list is empty at the beginning:

The for loop is a no op

The if is never executed

Thus no element is appended to my_list, so it never gets modified

You get an infinite loop (or you're in a deadlock kind of situation)

To fix it, refactor a bit your loop ([Python 3.Docs]: Compound statements - The for statement) to:

for existing in my_list:
    if set(p) == set(existing):
        break
else:
    my_list.append(p)
```

<p>It runs in less than <em>0.1</em> seconds.</p>

<p>To improve things even more, store the sets in a separate list (to avoid unnecessarily recalculating them waaay too many times than needed) and use that for inclusion test:</p>

<p><em>code.py</em>:</p>

<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3

import sys
import random
import time

def main():
    final_list = list()
    sentinel_list = list()
    start_time = time.time()
    count = 0
    while len(sentinel_list) < 50:
        inner_list = random.sample(range(100), 10)
        inner_set = set(inner_list)
        if inner_set not in sentinel_list:
            final_list.append(inner_list)
            sentinel_list.append(inner_set)
        count += 1
    del sentinel_list
    print("{:d} element list generated in {:d} iterations".format(len(final_list), count))
    print("Took {:.3f} seconds".format(time.time() - start_time))

if __name__ == "__main__":
    print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
    main()
    print("\nDone.")
</code>```

Output:

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q056317300]> "e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe" code.py
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32

50 element list generated in 50 iterations
Took 0.003 seconds

Done.
```

Title: How to check if "unsorted version" of a list already exists in the set?

Body:
You are appending the generated list inside the (if conditional from the) for loop.

But, given the fact that my_list is empty at the beginning:

The for loop is a no op

The if is never executed

Thus no element is appended to my_list, so it never gets modified

You get an infinite loop (or you're in a deadlock kind of situation)

To fix it, refactor a bit your loop ([Python 3.Docs]: Compound statements - The for statement) to:

for existing in my_list:
    if set(p) == set(existing):
        break
else:
    my_list.append(p)

It runs in less than 0.1 seconds.

To improve things even more, store the sets in a separate list (to avoid unnecessarily recalculating them waaay too many times than needed) and use that for inclusion test:

code.py:

#!/usr/bin/env python3

import sys
import random
import time

def main():
    final_list = list()
    sentinel_list = list()
    start_time = time.time()
    count = 0
    while len(sentinel_list) < 50:
        inner_list = random.sample(range(100), 10)
        inner_set = set(inner_list)
        if inner_set not in sentinel_list:
            final_list.append(inner_list)
            sentinel_list.append(inner_set)
        count += 1
    del sentinel_list
    print("{:d} element list generated in {:d} iterations".format(len(final_list), count))
    print("Took {:.3f} seconds".format(time.time() - start_time))

if __name__ == "__main__":
    print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
    main()
    print("\nDone.")

Output:

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q056317300]> "e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe" code.py
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32

50 element list generated in 50 iterations
Took 0.003 seconds

Done.


问:
How can I get the value/content of a custom component inside mat-table?
I want to build a custom table with mat-table where for the last column and for every row I want to define a custom component. This works. But the custom components are for some input, so the user can select some options or type something in.

<mat-table class="mat-elevation-z8" #table [dataSource]='dataSource'>

<ng-container matColumnDef='value'>
      <mat-header-cell *matHeaderCellDef>Values</mat-header-cell>
      <mat-cell *matCellDef='let row'>
          <app-dropdown-element #drop *ngIf="row.value == 'dropdown'" [options$]='row.$options'></app-dropdown-element>

          <app-input-element #text *ngIf="row.value == 'text'" [title]=''></app-input-element>

          <app-input-number-element #num *ngIf="row.value == 'number'" [number$]='row.$number'></app-input-number-element>

      </mat-cell>
    </ng-container>
</mat-table>
```

<p>That is what I get when I load the component outside the table </p>

```'selected' value is also correct:
DropdownElementComponent {options$: {…}, selected: "TEST"}
options$: {label: "TEST", options: Array(2), id: "oil-type"}
selected: "TEST"
__proto__: Object
```

But inside the table, I get an 'undefined'

答:
Thanks for the stackblitz.

You actually touch on a very interesting quirk of the Angular framework... Check out this article for detailed information on it, but essentially, template reference variables are accessible only inside their own template. And when we add the *ngIf (or any structural directive for that matter, including *matCellDef), Angular ends up creating a new <ng-template>, making any template reference variables accessible only in that template.

So when you try to reference "drop" outside of the * directives, it shows up as undefined.

Body:
I want to build a custom table with mat-table where for the last column and for every row I want to define a custom component. This works. But the custom components are for some input, so the user can select some options or type something in.

<mat-table class="mat-elevation-z8" #table [dataSource]='dataSource'>

<ng-container matColumnDef='value'>
      <mat-header-cell *matHeaderCellDef>Values</mat-header-cell>
      <mat-cell *matCellDef='let row'>
          <app-dropdown-element #drop *ngIf="row.value == 'dropdown'" [options$]='row.$options'></app-dropdown-element>

          <app-input-element #text *ngIf="row.value == 'text'" [title]=''></app-input-element>

          <app-input-number-element #num *ngIf="row.value == 'number'" [number$]='row.$number'></app-input-number-element>

      </mat-cell>
    </ng-container>
</mat-table>

That is what I get when I load the component outside the table

'selected' value is also correct:
DropdownElementComponent {options$: {…}, selected: "TEST"}
options$: {label: "TEST", options: Array(2), id: "oil-type"}
selected: "TEST"
__proto__: Object

But inside the table, I get an 'undefined'


问:
iPhone- application crashes on click of menu action button in QLPreviewController ios 4.2
```<code> When I try to click the menu action button in QLPreviewController the application crashes.
</code>```

This is what I'm doing in delegate method

```<code>- (id)previewController:(QLPreviewController *)previewController previewItemAtIndex:(NSInteger)index
{

    NSMutableString*Url = [[NSMutableString alloc] initWithFormat:@"http://10.30.24.21/Documents/abc.doc];

    NSURL *fileURL;
    fileURL = [NSURL URLWithString:Url];// the url of the file which is present in NAS device
    [Url release];
    return fileURL;
}
</code>```

This is the crash report

```<code>2011-01-11 12:21:36.717 iLink[5548:207] *** Assertion failure in -[UIDocumentInteractionController setURL:], /SourceCache/UIKit_Sim/UIKit-1447.6.4/UIDocumentInteractionController.m:1060
2011-01-11 12:21:36.720 iLink[5548:207] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UIDocumentInteractionController: invalid scheme https.  Only the file scheme is supported.'
</code>```

When I try to preview file present locally menu action button click is not crashing.

there I'll be using

```<code> NSURL *fileURL;
    fileURL = [NSURL fileURLWithPath:filePath];// filePath is local file path.
</code>```

I understood that when we preview local files ([NSURL fileURLWithPath:filePath]) menu action button click is not crashing ,, when we preview files from server ([NSURL URLWithString:Url]) menu action button click crashes.

I have two questions,
1. Can we disable the menu action button?
2. Is there any way to avoid the crash using [NSURL URLWithString:Url]?

Thanks

答:
By the way your statement

   NSMutableString*Url = [[NSMutableString alloc] initWithFormat:@"http://10.30.24.21/Documents/abc.doc];has a typo-error. You missed a " to indicate the end of the url string

ContentLicense: CC BY-SA 3.0

Body:
 When I try to click the menu action button in QLPreviewController the application crashes.

This is what I'm doing in delegate method

- (id)previewController:(QLPreviewController *)previewController previewItemAtIndex:(NSInteger)index
{

    NSMutableString*Url = [[NSMutableString alloc] initWithFormat:@"http://10.30.24.21/Documents/abc.doc];

    NSURL *fileURL;
    fileURL = [NSURL URLWithString:Url];// the url of the file which is present in NAS device
    [Url release];
    return fileURL;
}

This is the crash report

2011-01-11 12:21:36.717 iLink[5548:207] *** Assertion failure in -[UIDocumentInteractionController setURL:], /SourceCache/UIKit_Sim/UIKit-1447.6.4/UIDocumentInteractionController.m:1060
2011-01-11 12:21:36.720 iLink[5548:207] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UIDocumentInteractionController: invalid scheme https.  Only the file scheme is supported.'

When I try to preview file present locally menu action button click is not crashing.

there I'll be using

 NSURL *fileURL;
    fileURL = [NSURL fileURLWithPath:filePath];// filePath is local file path.

I understood that when we preview local files ([NSURL fileURLWithPath:filePath]) menu action button click is not crashing ,, when we preview files from server ([NSURL URLWithString:Url]) menu action button click crashes.

I have two questions,
1. Can we disable the menu action button?
2. Is there any way to avoid the crash using [NSURL URLWithString:Url]?

Thanks


问:
How can I convert columns to rows in Pandas?
I have something like this:

```<code>Values     Time
  22        0
  45        1
  65        2
  78        0
  12        1
  45        2
</code>```

and I want this:

```<code>Time    0    1    2
Val1    22   45   65
Val2    78   12   45
</code>```

How can I do it?

答:
You need to transpose your array/matrix.

Use

```<code>list(map(list, zip(*l)))
</code>```

where list is your list

Body:
I have something like this:

Values     Time
  22        0
  45        1
  65        2
  78        0
  12        1
  45        2

and I want this:

Time    0    1    2
Val1    22   45   65
Val2    78   12   45

How can I do it?

Body:
You need to transpose your array/matrix.

Use

list(map(list, zip(*l)))

where list is your list


问:
Oracle SQLDeveloper on MacOS won't open after installation of correct Java
I downloaded the Oracle SQLDeveloper, but when I opened it, it said that it requires a minimum of Java 8 and gave me the website for the download. I went on and downloaded Java 10.0.1, but when I went back on to open SQL, it continued saying it required a minimum of Java 8.

I checked that the Java 10.0.1 had installed correctly, and I'm pretty sure it has. It shows up in System Preferences and when clicked, it opens the Java Control Panel fine.

I'm on a MacOS X El Captain 10.11.6.

答:
I had the same problem, and none of the above solutions worked for me. I am running MacOS 10.14.5

Instead, I had to uninstall Java12 which I had installed via home brew, and sqlDeveloper. After uninstalling and deleting both, I installed Java8 JDK directly from the oracle website via download, and then I reinstalled sqlDeveloper. After wasting three hours trying to get this to work, this set of steps finally did the trick. I hope this helps others.


问:
How can I select the second element from a group of divs with the same class?
I have 4 divs with the same class and I want to select with javaScript only the second one</p>

```<code><div class='container'></div>
<div class='container'></div>
<div class='container'></div>
<div class='container'></div>
</code>```

答: you can select it with this code: document.querySelectorAll('.container')[1] or if they have one parent document.querySelectorAll('.container:nth-child(2)')


问:
Issues using bitbucket git repository source for downloading a module over SSH
When calling a module over from a local source everything went alright, however I decided to refactor the Terraform code to use a git repository for modules.

I created a new repository in our BitBucket account with the name terraform-modules, and refactored the source attribute of the modules to have the following structure:

```<code>source     = "git::ssh://git@bitbucket.org:carepaydev/terraform-modules.git//modules/iam/iam_roles/assumable_role"
</code>```

When calling terraform init I get the following error:

```<code>Error downloading modules: Error loading modules: error downloading 'ssh://git@bitbucket.org:<username>/terraform-modules.git': /usr/local/bin/git exited with 128: Cloning into '.terraform/modules/caf541f5e5ccbb1d204bce3b94091014'...
ssh: Could not resolve hostname bitbucket.org:<username>: nodename nor servname provided, or not known
fatal: Could not read from remote repository.
</code>```

Cloning the repository using git clone does work. I tried setting the TF_LOG env var to TRACE to see if that would give me more insight, but that did not help.

Any clue why this fails?

答:
Change the colon between ssh://git@bitbucket.org and username/repo to a slash:

ssh://git@bitbucket.org/username/repo

In that format, the colon indicates an alternate port - useful if you want to do ssh://git@altssh.bitbucket.org:443/username/repo, and similar to how you'd specify an alternate port for other protocols like HTTP.

Body:
When calling a module over from a local source everything went alright, however I decided to refactor the Terraform code to use a git repository for modules.

I created a new repository in our BitBucket account with the name terraform-modules, and refactored the source attribute of the modules to have the following structure:

source     = "git::ssh://git@bitbucket.org:carepaydev/terraform-modules.git//modules/iam/iam_roles/assumable_role"

When calling terraform init I get the following error:

Error downloading modules: Error loading modules: error downloading 'ssh://git@bitbucket.org:<username>/terraform-modules.git': /usr/local/bin/git exited with 128: Cloning into '.terraform/modules/caf541f5e5ccbb1d204bce3b94091014'...
ssh: Could not resolve hostname bitbucket.org:<username>: nodename nor servname provided, or not known
fatal: Could not read from remote repository.

Cloning the repository using git clone does work. I tried setting the TF_LOG env var to TRACE to see if that would give me more insight, but that did not help.

Any clue why this fails?


问:
What is "_ipython_canary_method_should_not_exist_"?
I implemented my own __getattr__() to loosely handle any non-existent attributes.

I just so happened to define this class in a Jupyter notebook to experiment with it interactively.

IPython creates _ipython_canary_method_should_not_exist_ due to this __getattr__ implementation – and I'd like to understand what this is and how to "clean it up" is possible.

There is this issue opened about it, but it's not clear to my why – if it checks for permissive handling within __getattr__ – it doesn't check to see that _repr_html_ is implemented in the OP's example?

```<code>from types import SimpleNamespace

class Metabox(SimpleNamespace):

    def __getattr__(self, name):
        """
        Create a new namespace for any non-existing attributes.
        """
        print("calling __getattr__")
        self.__dict__[name] = Metabox()
        return self.__dict__[name]
</code>```

答:
As taper mentioned in above comments; IPython sometimes needs to inspect  objects to know whether they have some methods.

To handle object like yours; that always say "yes", when we have doubt we probe for this name; and if the object says "yep, I got that !" we know the object lies and implemented a __getattr__.

Body:
I implemented my own __getattr__() to loosely handle any non-existent attributes.

I just so happened to define this class in a Jupyter notebook to experiment with it interactively.

IPython creates _ipython_canary_method_should_not_exist_ due to this __getattr__ implementation – and I'd like to understand what this is and how to "clean it up" is possible.

There is this issue opened about it, but it's not clear to my why – if it checks for permissive handling within __getattr__ – it doesn't check to see that _repr_html_ is implemented in the OP's example?

from types import SimpleNamespace

class Metabox(SimpleNamespace):

    def __getattr__(self, name):
        """
        Create a new namespace for any non-existing attributes.
        """
        print("calling __getattr__")
        self.__dict__[name] = Metabox()
        return self.__dict__[name]


问:
How to pass parameter dynamically to JQuery click event from HTML elements?
First of all, I have to mention that I am a newbie in the JavaScript and JQuery world. I am not sure if I put down an appropriate title for my question but I'll try my best to explain my problem.

Scenario: I have a list of items whose names are being displayed. When one of the items is being clicked, a popup should show up and display the description of the item. The description is retrieved from the server via an AJAX call upon the click. The AJAX call requires the unique id of the item (in the database) to be provided. Here comes my problem which has two parts:

I don't know how and where to include the item id in the HTML. Note that the list only displays item name not id.

Assume 1) is resolved, how can I pass the id of the item that's being clicked to the AJAX call.

This is the HTML of the list of items. As you can see, it illustrates part 1) of my problem (ie. don't know how to include the ids in the HTML).

```<code><ul>
    <li class="item">Item1</li> <!-- this item has id=1 in the database -->
    <li class="item">Item2</li> <!-- this item has id=2 in the database -->
    <li class="item">Item3</li> <!-- this item has id=3 in the database -->
</ul>
</code>```

Below is the JQuery click event handler that sends the AJAX call (ie. getJSON) to the server. Note that the part 2) of the problem is illustrated by the line var item_id = ??. Note that popup is a self-defined javascript.

```<code>    <script type="text/javascript" charset="utf-8">
        $(document).ready(function() {
            $(".item").click(function() {
                var item_id = ??
                var data = {"item_id":item_id};
                $.getJSON("/item/json", data, function(data) {
                    var name = data[0]["fields"]["name"]
                    var description = data[0]["fields"]["description"]
                    popup.call(this, name, description);
                });
            });
        });
    </script>
</code>```

Additional Info: For the server side I use Django 1.3, and JQuery 1.5.2 for the client side.
I hope I have made my question clear and I appreciate any help from you experts. Thanks.

Here is an example that is similar to what I am looking for.

http://esdi.excelsystems.com/iseries400apps/exmain.pgm?wsname=DIALOG.pgm&wsnumb=214&wsprogtype=P

答:
Javascript (and jQuery in particular) are used for client-side scripting. As such, you will need to supply the data within the HTML document. You can use jQuery' Metadata plug-in to supply the item ID:

```<code><li class="item" data="{ItemID: 'Your_Item_ID'}">Item1</li>
</code>```

and retrieve it via:

```<code>var item_id_structure = $(this).metadata().ItemID;
</code>```

Body:
First of all, I have to mention that I am a newbie in the JavaScript and JQuery world. I am not sure if I put down an appropriate title for my question but I'll try my best to explain my problem.

Scenario: I have a list of items whose names are being displayed. When one of the items is being clicked, a popup should show up and display the description of the item. The description is retrieved from the server via an AJAX call upon the click. The AJAX call requires the unique id of the item (in the database) to be provided. Here comes my problem which has two parts:

I don't know how and where to include the item id in the HTML. Note that the list only displays item name not id.

Assume 1) is resolved, how can I pass the id of the item that's being clicked to the AJAX call.

This is the HTML of the list of items. As you can see, it illustrates part 1) of my problem (ie. don't know how to include the ids in the HTML).

Item1

Item2

Item3

Below is the JQuery click event handler that sends the AJAX call (ie. getJSON) to the server. Note that the part 2) of the problem is illustrated by the line var item_id = ??. Note that popup is a self-defined javascript.

Additional Info: For the server side I use Django 1.3, and JQuery 1.5.2 for the client side.
I hope I have made my question clear and I appreciate any help from you experts. Thanks.

Here is an example that is similar to what I am looking for.

http://esdi.excelsystems.com/iseries400apps/exmain.pgm?wsname=DIALOG.pgm&wsnumb=214&wsprogtype=P

Body:
Javascript (and jQuery in particular) are used for client-side scripting. As such, you will need to supply the data within the HTML document. You can use jQuery' Metadata plug-in to supply the item ID:

<li class="item" data="{ItemID: 'Your_Item_ID'}">Item1</li>

and retrieve it via:

var item_id_structure = $(this).metadata().ItemID;


问:
How to turn this cursor operation into a set based operation on a closure hierarchy?

Trees.DirectReports is a closure (hierarchy) table.

There is a table called Users with: RowID, EmployeeId, and MangerId. @RowCount is the number of records in this table and #EmpMgr is a cursor for this table.

Below is the relevant sql code that I would like to convert from a cursor based operation to a set based operation.

```<code>WHILE @RowCount <= @NumberRecords --loop through each record in Users table
BEGIN
    SET @EmpId = (SELECT EmployeeId FROM #EmpMgr WHERE RowID = @RowCount)
    SET @MgrId = (SELECT ManagerId FROM #EmpMgr WHERE RowID = @RowCount)

    INSERT INTO [Trees].[DirectReports](EmployeeId, ManagerId, Depth)
    SELECT c.EmployeeId, p.ManagerId, p.Depth + c.Depth + 1
    FROM Trees.DirectReports p join Trees.DirectReports c
    WHERE p.EmployeeId = @MgrId AND c.ManagerId = @EmpId

    SET @RowCount = @RowCount + 1
END
</code>```

So I'd really like to figure out how to do this as a set query because I know it would be much faster that way but my brain isn't quite making the proper connections today to figure it out.

*Note that to answer this question you will need to already understand how closure tables work. Otherwise the above probably won't make sense.

答:
Found what I was looking for with the help of a couple other posts. The main answer is this:

```<code>WITH cte AS
(
    SELECT LegacyId ancestor, LegacyId descendant, 0 depth FROM Users
    UNION ALL

    SELECT cte.ancestor, u.LegacyId descendant, cte.depth + 1 depth
    FROM   dbo.Users u JOIN cte ON u.ManagerId = cte.descendant
)
select * from cte
</code>```

However, what threw me off at first was that there was some bad data causing circular dependencies. I was able to use the following query to identify where those instances were:

```<code>with cte (id,pid,list,is_cycle)
as
(
    select      legacyid id, managerid pid,',' + cast (legacyid as varchar(max))  + ',',0
    from        users

    union all

    select      u.legacyid id,
                u.managerid pid,
                cte.list + cast(u.legacyid as varchar(10)) +  ',' ,case when cte.list like '%,' + cast (u.legacyid as varchar(10)) + ',%' then 1 else 0 end
    from        cte join users u on u.managerid = cte.id
    where       cte.is_cycle = 0
)
select      *
from        cte
where       is_cycle = 1
</code>```

Once I corrected the cyclical data everything worked great. Check out the following SO posts for more information as these are what I used to come up with my solution: Is there a way to detect a cycle in Hierarchical Queries in SQL Server? and How can I create a closure table using data from an adjacency list?

Body:
Trees.DirectReports is a closure (hierarchy) table.

There is a table called Users with: RowID, EmployeeId, and MangerId. @RowCount is the number of records in this table and #EmpMgr is a cursor for this table.

Below is the relevant sql code that I would like to convert from a cursor based operation to a set based operation.

WHILE @RowCount <= @NumberRecords --loop through each record in Users table
BEGIN
    SET @EmpId = (SELECT EmployeeId FROM #EmpMgr WHERE RowID = @RowCount)
    SET @MgrId = (SELECT ManagerId FROM #EmpMgr WHERE RowID = @RowCount)

    INSERT INTO [Trees].[DirectReports](EmployeeId, ManagerId, Depth)
    SELECT c.EmployeeId, p.ManagerId, p.Depth + c.Depth + 1
    FROM Trees.DirectReports p join Trees.DirectReports c
    WHERE p.EmployeeId = @MgrId AND c.ManagerId = @EmpId

    SET @RowCount = @RowCount + 1
END

So I'd really like to figure out how to do this as a set query because I know it would be much faster that way but my brain isn't quite making the proper connections today to figure it out.

*Note that to answer this question you will need to already understand how closure tables work. Otherwise the above probably won't make sense.

Body:
Found what I was looking for with the help of a couple other posts. The main answer is this:

WITH cte AS
(
    SELECT LegacyId ancestor, LegacyId descendant, 0 depth FROM Users
    UNION ALL

    SELECT cte.ancestor, u.LegacyId descendant, cte.depth + 1 depth
    FROM   dbo.Users u JOIN cte ON u.ManagerId = cte.descendant
)
select * from cte

However, what threw me off at first was that there was some bad data causing circular dependencies. I was able to use the following query to identify where those instances were:

with cte (id,pid,list,is_cycle)
as
(
    select      legacyid id, managerid pid,',' + cast (legacyid as varchar(max))  + ',',0
    from        users

    union all

    select      u.legacyid id,
                u.managerid pid,
                cte.list + cast(u.legacyid as varchar(10)) +  ',' ,case when cte.list like '%,' + cast (u.legacyid as varchar(10)) + ',%' then 1 else 0 end
    from        cte join users u on u.managerid = cte.id
    where       cte.is_cycle = 0
)
select      *
from        cte
where       is_cycle = 1

Once I corrected the cyclical data everything worked great. Check out the following SO posts for more information as these are what I used to come up with my solution: Is there a way to detect a cycle in Hierarchical Queries in SQL Server? and How can I create a closure table using data from an adjacency list?


问:
What is clojure's "doc" command printing out?
I'm a bit confused by clojure's doc.

The output is a specification of arguments, using the traditional basic regular expression markup, which is:

*: 0..n instances of the marked-up preceding element ("many")

?: 0..1 instances of the marked-up preceding element ("optional")

+: 1..n instances of the marked-up preceding element ("at least one")

Parentheses () and square brackets [] are, however, to be used "as given" to form the correct expression or form, and are not used for grouping of any regular expression elements.

And if there are several valid argument combinations, they are listed on several lines.

But observe for example the output for (doc fn):

```<code>clojure.core/fn
  (fn name? [params*] exprs*)
  (fn name? ([params*] exprs*) +)
([& sigs])
Special Form
  params => positional-params* , or positional-params* & next-param
  positional-param => binding-form
  next-param => binding-form
  name => symbol

  Defines a function

  Please see http://clojure.org/special_forms#fn
  params => positional-params* , or positional-params* & next-param
  positional-param => binding-form
  next-param => binding-form
  name => symbol

  Defines a function
Spec
  args: (cat :fn-name (? simple-symbol?) :fn-tail (alt :arity-1 :clojure.core.specs.alpha/params+body :arity-n (+ (spec :clojure.core.specs.alpha/params+body))))
  ret: any?
nil
</code>```

The first three lines make sense as:

Package and name of var or special form

A valid expression structure (fn name? [params*] exprs*)

Another possible expression structure (fn name? ([params*] exprs*) +)

But then there is a non-indented ([& sigs]). What's that about?

The subsequent output also seems to be in need of cleanup. And what's the "Spec"?

For (doc doc):

```<code>clojure.repl/doc
([name])
Macro
  Prints documentation for a var or special form given its name,
   or for a spec if given a keyword
nil
</code>```

I don't understand the non-indented ([name]).

Or let's try (doc letfn):

```<code>clojure.core/letfn
  (letfn [fnspecs*] exprs*)
([fnspecs & body])
Special Form
  fnspec ==> (fname [params*] exprs) or (fname ([params*] exprs)+)

  Takes a vector of function specs and a body, and generates a set of
  bindings of functions to their names. All of the names are available
  in all of the definitions of the functions, as well as the body.
  fnspec ==> (fname [params*] exprs) or (fname ([params*] exprs)+)

  Takes a vector of function specs and a body, and generates a set of
  bindings of functions to their names. All of the names are available
  in all of the definitions of the functions, as well as the body.
nil
</code>```

Again the meaning of ([fnspecs & body]) is unclear to me.

答:
Those are the parameter lists for the functions.

From the source:

([& sigs]) says that it takes a variadic list of "(sig)natures". "Signature" in this case is referring to the example forms on the previous lines. Either ([params] body) for creating a function with a single parameter list, or a list of (([params] body) ([other-params] body) to create a function with multiple parameter lists.

The doc one is just saying that doc accepts a name as an argument.

Finally, letfn is saying that it takes a "fnspecs" vector, and a variadic body of expressions. You can see that in how it's used:

```<code>(letfn [(some-function [param] ; The vector on these two lines is "fnspecs"
                        (println param))]
  (println "PRINTING!") ; These two lines are grouped into "body"
  (some-function 1))
</code>```

It has an outer set of parenthesis because it's showing a list of all the available parameter lists. doc shows ([name]) (a list of one vector) because it only has one valid parameter list. If you look at the docs for a function like max though:

```<code>clojure.core/max
([x] [x y] [x y & more])
  Returns the greatest of the nums.
</code>```

Its listing multiple parameter lists because max has multiple arities.

As for why letfn shows ([fnspec & body]), that's the way that it's defined in the source:

fnspecs is the first parameter, and any arguments supplied after that are grouped into the body var-arg list. You may need to look over Clojure's var-arg syntax.

Body:
I'm a bit confused by clojure's doc.

The output is a specification of arguments, using the traditional basic regular expression markup, which is:

*: 0..n instances of the marked-up preceding element ("many")

?: 0..1 instances of the marked-up preceding element ("optional")

+: 1..n instances of the marked-up preceding element ("at least one")

Parentheses () and square brackets [] are, however, to be used "as given" to form the correct expression or form, and are not used for grouping of any regular expression elements.

And if there are several valid argument combinations, they are listed on several lines.

But observe for example the output for (doc fn):

clojure.core/fn
  (fn name? [params*] exprs*)
  (fn name? ([params*] exprs*) +)
([& sigs])
Special Form
  params => positional-params* , or positional-params* & next-param
  positional-param => binding-form
  next-param => binding-form
  name => symbol

  Defines a function

  Please see http://clojure.org/special_forms#fn
  params => positional-params* , or positional-params* & next-param
  positional-param => binding-form
  next-param => binding-form
  name => symbol

  Defines a function
Spec
  args: (cat :fn-name (? simple-symbol?) :fn-tail (alt :arity-1 :clojure.core.specs.alpha/params+body :arity-n (+ (spec :clojure.core.specs.alpha/params+body))))
  ret: any?
nil

The first three lines make sense as:

Package and name of var or special form

A valid expression structure (fn name? [params*] exprs*)

Another possible expression structure (fn name? ([params*] exprs*) +)

But then there is a non-indented ([& sigs]). What's that about?

The subsequent output also seems to be in need of cleanup. And what's the "Spec"?

For (doc doc):

clojure.repl/doc
([name])
Macro
  Prints documentation for a var or special form given its name,
   or for a spec if given a keyword
nil

I don't understand the non-indented ([name]).

Or let's try (doc letfn):

clojure.core/letfn
  (letfn [fnspecs*] exprs*)
([fnspecs & body])
Special Form
  fnspec ==> (fname [params*] exprs) or (fname ([params*] exprs)+)

  Takes a vector of function specs and a body, and generates a set of
  bindings of functions to their names. All of the names are available
  in all of the definitions of the functions, as well as the body.
  fnspec ==> (fname [params*] exprs) or (fname ([params*] exprs)+)

  Takes a vector of function specs and a body, and generates a set of
  bindings of functions to their names. All of the names are available
  in all of the definitions of the functions, as well as the body.
nil

Again the meaning of ([fnspecs & body]) is unclear to me.

Body:
Those are the parameter lists for the functions.

From the source:

([& sigs]) says that it takes a variadic list of "(sig)natures". "Signature" in this case is referring to the example forms on the previous lines. Either ([params] body) for creating a function with a single parameter list, or a list of (([params] body) ([other-params] body) to create a function with multiple parameter lists.

The doc one is just saying that doc accepts a name as an argument.

Finally, letfn is saying that it takes a "fnspecs" vector, and a variadic body of expressions. You can see that in how it's used:

(letfn [(some-function [param] ; The vector on these two lines is "fnspecs"
                        (println param))]
  (println "PRINTING!") ; These two lines are grouped into "body"
  (some-function 1))

It has an outer set of parenthesis because it's showing a list of all the available parameter lists. doc shows ([name]) (a list of one vector) because it only has one valid parameter list. If you look at the docs for a function like max though:

clojure.core/max
([x] [x y] [x y & more])
  Returns the greatest of the nums.

Its listing multiple parameter lists because max has multiple arities.

As for why letfn shows ([fnspec & body]), that's the way that it's defined in the source:

fnspecs is the first parameter, and any arguments supplied after that are grouped into the body var-arg list. You may need to look over Clojure's var-arg syntax.


问:
Android studio - Send key events on service
I'm trying to send key events in a service, I know this is not something you should do, however I want to know if there is a way to do it.

I have tried to put a floating widget on the screen so it will have focus, but I couldn't manage to do it.

Here is the key even sending code :

```<code>        String keyCommand = "input keyevent " +
        KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE;
        Runtime runtime = Runtime.getRuntime();
        runtime.exec(keyCommand);
</code>```

Does anyone have a solution for this?

答:
You can try this </p>

```<code>@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    switch (keyCode) {
        case KeyEvent.KEYCODE_A:
            //A
            return true;
        case KeyEvent.KEYCODE_B:
            //B
            return true;
        default:
            return super.onKeyUp(keyCode,event);
    }
}
</code>```

Body:
I'm trying to send key events in a service, I know this is not something you should do, however I want to know if there is a way to do it.

I have tried to put a floating widget on the screen so it will have focus, but I couldn't manage to do it.

Here is the key even sending code :

        String keyCommand = "input keyevent " +
        KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE;
        Runtime runtime = Runtime.getRuntime();
        runtime.exec(keyCommand);

Does anyone have a solution for this?

Body:
You can try this

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    switch (keyCode) {
        case KeyEvent.KEYCODE_A:
            //A
            return true;
        case KeyEvent.KEYCODE_B:
            //B
            return true;
        default:
            return super.onKeyUp(keyCode,event);
    }
}


问:
finding whether the body contains gzipped data
i have a program wherein it searches the reply from a curl request for specific strings. i sometimes get gzipped data. is there a way to find whether the reply is text or gzipped format?
header sometimes contain gziipped,deflate header, but its not consistent. is there a way to search the string and find if its gzipped?</p>

答: You could pipe it through zcat, and if it fails, use the string as is. Sloppy I know, but it ought to be reliable; a plain text file would never contain valid gzipped data.</p>


问:
Set value of bind:group-value in combination with dynamic elements
I am currently trying to create a wizard-like succession of questions in svelte. For this I use a component that gets a question as a parameter and builds a list of radio items (simplified):

```<code><Question question="{{ activeQuestion }}"></Question>
</code>```

Inside the component following code builds the form element:

```<code>{{#each question.options as option}}
  <li class="question-section__option">
    <input type='radio' bind:group='selected' value='{{ option.value }}'>
    <label>{{ option.label }}</label>
  </li>
{{/each}}
</code>```

in oncreate I observe the question parameter and initialize and try to set a default value based on answers from my store:

```<code>oncreate() {
  this.observe('question', question => {
    const answers = this.store.get('answers');

    if (answers[question.id]) {
      this.set({
        selected: answers[question.id]
      });
    }
  })
},
</code>```

Setting the selected value stops working after the "question" property of the component changed once. It doesn't seem to matter if it is set by observing or just in a regular onclick-event.

It would be great if someone has an idea what I did wrong or point me in the right direction!

答:
Here is a simplified wizard of questions in Svelte v3:

```<code><script>
    let questions = [{
        title: "First question",
        id: 'first',
        options: [{
            title: "Option 1",
            value: "option1"
        }, {
            title: "Option 2",
            value: "option2"
        }]
    }, {
        title: "Second question",
        id: 'second',
        options: [{
            title: "Option 3",
            value: "option3"
        }, {
            title: "Option 4",
            value: "option4"
        }]
    }];
    let activeQuestion = 0;
    $: question = questions[activeQuestion];
    function dec() {
        if (activeQuestion === 0) { return }
        activeQuestion -= 1
    }
    function inc() {
        if (activeQuestion === (questions.length - 1)) { return }
        activeQuestion += 1
    }
    let answers = {}
</script>

<h1>{question.title}!</h1>
{#each question.options as option (option.value)}
    <label on:click>
        <input type=radio
                     name={question.id}
                     value={option.value}
                     on:change={() => answers[question.id] = option.value}
                     checked={answers[question.id] == option.value}
                     />
        {option.title}
    </label>
{/each}

<button on:click={dec}>previous</button>
<button on:click={inc}>next</button>
</code>```

REPL: https://svelte.dev/repl/2de246c59cb346ca8cb7244749afe8ea?version=3

It should translate well to stores too. Note the each-loop which uses (option.value) as a key, such that svelte can distinguish radio inputs from each other. Read more about keyed each loops in the documentation.

Body:
I am currently trying to create a wizard-like succession of questions in svelte. For this I use a component that gets a question as a parameter and builds a list of radio items (simplified):

<Question question="{{ activeQuestion }}"></Question>

Inside the component following code builds the form element:

{{#each question.options as option}}

    <input type='radio' bind:group='selected' value='{{ option.value }}'>
    {{ option.label }}

{{/each}}

in oncreate I observe the question parameter and initialize and try to set a default value based on answers from my store:

oncreate() {
  this.observe('question', question => {
    const answers = this.store.get('answers');

    if (answers[question.id]) {
      this.set({
        selected: answers[question.id]
      });
    }
  })
},

Setting the selected value stops working after the "question" property of the component changed once. It doesn't seem to matter if it is set by observing or just in a regular onclick-event.

It would be great if someone has an idea what I did wrong or point me in the right direction!

Body:
Here is a simplified wizard of questions in Svelte v3:

<script>
    let questions = [{
        title: "First question",
        id: 'first',
        options: [{
            title: "Option 1",
            value: "option1"
        }, {
            title: "Option 2",
            value: "option2"
        }]
    }, {
        title: "Second question",
        id: 'second',
        options: [{
            title: "Option 3",
            value: "option3"
        }, {
            title: "Option 4",
            value: "option4"
        }]
    }];
    let activeQuestion = 0;
    $: question = questions[activeQuestion];
    function dec() {
        if (activeQuestion === 0) { return }
        activeQuestion -= 1
    }
    function inc() {
        if (activeQuestion === (questions.length - 1)) { return }
        activeQuestion += 1
    }
    let answers = {}
</script>

<h1>{question.title}!</h1>
{#each question.options as option (option.value)}
    <label on:click>
        <input type=radio
                     name={question.id}
                     value={option.value}
                     on:change={() => answers[question.id] = option.value}
                     checked={answers[question.id] == option.value}
                     />
        {option.title}
    </label>
{/each}

<button on:click={dec}>previous</button>
<button on:click={inc}>next</button>

REPL: https://svelte.dev/repl/2de246c59cb346ca8cb7244749afe8ea?version=3

It should translate well to stores too. Note the each-loop which uses (option.value) as a key, such that svelte can distinguish radio inputs from each other. Read more about keyed each loops in the documentation.


问:
Implement a trait for another trait Item type
I need to convert a parse error to my own Error type while returning Result. Simplified, it looks like the following:

```<code>enum MyError {
    Parse,
    ...,
}

fn process<R: FromStr>(s: &str) -> Result<(), MyError> {
    Ok(s.parse::<R>()?)
}
</code>```

For above to work From trait should be implemented. This doesn't work:

```<code>impl From<std::str::FromStr::Err> for MyError {
    fn from(e: std::str::FromStr::Err) -> MyError {
        MyError::Parse
    }
}
</code>```

The compiler diagnostics:

```<code>help: use fully-qualified syntax: `<Type as std::str::FromStr>::Err`
</code>```

But I don't know the exact Type here. The whole point is to allow conversion from all possible errors.

答:
The type FromStr::Err is an associated type of the FromStr trait. Every implementation of FromStr has its own associated type, and this type is completely unconstrained – it could be any type at all. This means you would need a conversion from any type to MyError to achieve what you want:

```<code>impl<T> From<T> for MyError {
    fn from(e: T) -> MyError {
        MyError::Parse
    }
}
</code>```

However, this implementation is disallowed by the coherence rules – it conflicts with the implementation of From<T> for any type T in the standard library. And even if this implementation was allowed, it wouldn't really do what you want – any error type would be converted to MyError::Parse, not just parse errors.

One possible workaround is to introduce a marker trait for parse error types:

```<code>trait ParseError {}

impl<T: ParseError> From<T> for MyError {
    fn from(e: T) -> MyError {
        MyError::Parse
    }
}
</code>```

You can then implement this marker trait for all parse error types:

```<code>impl ParseError for std::str::ParseBoolError {}
impl ParseError for std::num::ParseFloatError {}
impl ParseError for std::num::ParseIntError {}
impl ParseError for std::net::AddrParseError {}
impl ParseError for std::char::ParseCharError {}
</code>```

Body:
I need to convert a parse error to my own Error type while returning Result. Simplified, it looks like the following:

enum MyError {
    Parse,
    ...,
}

fn process<R: FromStr>(s: &str) -> Result<(), MyError> {
    Ok(s.parse::<R>()?)
}

For above to work From trait should be implemented. This doesn't work:

impl From<std::str::FromStr::Err> for MyError {
    fn from(e: std::str::FromStr::Err) -> MyError {
        MyError::Parse
    }
}

The compiler diagnostics:

help: use fully-qualified syntax: `<Type as std::str::FromStr>::Err`

But I don't know the exact Type here. The whole point is to allow conversion from all possible errors.

Body:
The type FromStr::Err is an associated type of the FromStr trait. Every implementation of FromStr has its own associated type, and this type is completely unconstrained – it could be any type at all. This means you would need a conversion from any type to MyError to achieve what you want:

impl<T> From<T> for MyError {
    fn from(e: T) -> MyError {
        MyError::Parse
    }
}

However, this implementation is disallowed by the coherence rules – it conflicts with the implementation of From<T> for any type T in the standard library. And even if this implementation was allowed, it wouldn't really do what you want – any error type would be converted to MyError::Parse, not just parse errors.

One possible workaround is to introduce a marker trait for parse error types:

trait ParseError {}

impl<T: ParseError> From<T> for MyError {
    fn from(e: T) -> MyError {
        MyError::Parse
    }
}

You can then implement this marker trait for all parse error types:

impl ParseError for std::str::ParseBoolError {}
impl ParseError for std::num::ParseFloatError {}
impl ParseError for std::num::ParseIntError {}
impl ParseError for std::net::AddrParseError {}
impl ParseError for std::char::ParseCharError {}


问:
How to extract an ID number from a string?
How do I retrieve the middle value using regex or preg_match?

```<code>$str = 'fxs_124024574287414=base_domain=.example.com; datr=KWHazxXEIkldzBaVq_of--syv5; csrftoken=szcwad; ds_user_id=219132; mid=XN4bpAAEAAHOyBRR4V17xfbaosyN; sessionid=14811313756%12fasda%3A27; rur=VLL;'
</code>```

How do I only get values from ds_user_id using regex or preg_match?

答:
Ok, nothing can beat the mickmackusa \K construct.

But, for the \K impaired engines, this is the next best thing

(\d(?<=ds_user_id=\d)\d*)(?=;)

Explained

```<code> (                          # (1 start), Consume many ID digits
      \d                         # First digit of ID
      (?<= ds_user_id= \d )      # Look behind, assert ID key exists before digit
      \d*                        # Optional the rest of the digits
 )                          # (1 end)
 (?= ; )                    # Look ahead, assert a colon exists
</code>```

This one is a verb solution (no \K), about %30 faster.

```<code> (                             # (1 start), Consume many ID digits
      \d                            # First digit of ID
      (?:
           (?<! ds_user_id= \d )         # Look behind, if not ID,
           \d*                           # get rest of digits
           (*SKIP)                       # Fail, then start after this
           (?!)
        |
           \d*                           # Rest of ID digits
      )
 )                             # (1 end)
 (?= ; )                       # Look ahead, assert a colon exists
</code>```

Some benchmarks for comparison

```<code>Regex1:   (\d(?:(?<!ds_user_id=\d)\d*(*SKIP)(?!)|\d*))(?=;)
Options:  < none >
Completed iterations:   50  /  50     ( x 1000 )
Matches found per iteration:   1
Elapsed Time:    0.53 s,   534.47 ms,   534473 µs
Matches per sec:   93,550

Regex2:   (\d(?<=ds_user_id=\d)\d*)(?=;)
Options:  < none >
Completed iterations:   50  /  50     ( x 1000 )
Matches found per iteration:   1
Elapsed Time:    0.80 s,   796.97 ms,   796971 µs
Matches per sec:   62,737

Regex3:   ds_user_id=\K\d+(?=;)
Options:  < none >
Completed iterations:   50  /  50     ( x 1000 )
Matches found per iteration:   1
Elapsed Time:    0.21 s,   214.55 ms,   214549 µs
Matches per sec:   233,046

Regex4:   ds_user_id=(\d+)(?=;)
Options:  < none >
Completed iterations:   50  /  50     ( x 1000 )
Matches found per iteration:   1
Elapsed Time:    0.23 s,   231.23 ms,   231233 µs
Matches per sec:   216,232
</code>```

Body:
How do I retrieve the middle value using regex or preg_match?

$str = 'fxs_124024574287414=base_domain=.example.com; datr=KWHazxXEIkldzBaVq_of--syv5; csrftoken=szcwad; ds_user_id=219132; mid=XN4bpAAEAAHOyBRR4V17xfbaosyN; sessionid=14811313756%12fasda%3A27; rur=VLL;'

How do I only get values from ds_user_id using regex or preg_match?

Body:
Ok, nothing can beat the mickmackusa \K construct.

But, for the \K impaired engines, this is the next best thing

(\d(?<=ds_user_id=\d)\d*)(?=;)

Explained

 (                          # (1 start), Consume many ID digits
      \d                         # First digit of ID
      (?<= ds_user_id= \d )      # Look behind, assert ID key exists before digit
      \d*                        # Optional the rest of the digits
 )                          # (1 end)
 (?= ; )                    # Look ahead, assert a colon exists

This one is a verb solution (no \K), about %30 faster.

 (                             # (1 start), Consume many ID digits
      \d                            # First digit of ID
      (?:
           (?<! ds_user_id= \d )         # Look behind, if not ID,
           \d*                           # get rest of digits
           (*SKIP)                       # Fail, then start after this
           (?!)
        |
           \d*                           # Rest of ID digits
      )
 )                             # (1 end)
 (?= ; )                       # Look ahead, assert a colon exists

Some benchmarks for comparison

Regex1:   (\d(?:(?<!ds_user_id=\d)\d*(*SKIP)(?!)|\d*))(?=;)
Options:  < none >
Completed iterations:   50  /  50     ( x 1000 )
Matches found per iteration:   1
Elapsed Time:    0.53 s,   534.47 ms,   534473 µs
Matches per sec:   93,550

Regex2:   (\d(?<=ds_user_id=\d)\d*)(?=;)
Options:  < none >
Completed iterations:   50  /  50     ( x 1000 )
Matches found per iteration:   1
Elapsed Time:    0.80 s,   796.97 ms,   796971 µs
Matches per sec:   62,737

Regex3:   ds_user_id=\K\d+(?=;)
Options:  < none >
Completed iterations:   50  /  50     ( x 1000 )
Matches found per iteration:   1
Elapsed Time:    0.21 s,   214.55 ms,   214549 µs
Matches per sec:   233,046

Regex4:   ds_user_id=(\d+)(?=;)
Options:  < none >
Completed iterations:   50  /  50     ( x 1000 )
Matches found per iteration:   1
Elapsed Time:    0.23 s,   231.23 ms,   231233 µs
Matches per sec:   216,232


问:
to draw graph with mysql data
I need to draw a line graph with mysql data which has two columns. some one help me with a sample code.</p>

答:
Are the two columns the x and y axes of the graph? Why is it important that the data is present in mysql?

Anyways, for reading the data, you need to use jdbc: jdbc tutorial (If you are using Java)

For building the actual graph, I would recommend JFreeChart.

Title: to draw graph with mysql data


问:
How to make random pick python differently?
I want to make a bot that sending 3 emoji but its different emoji , but when im running it , the bot took one emoji and sending a same 3 emoji, how do i make it take the different 3 emoji?

```<code>list  = ['', '', '', '', '', '', '', '', '', '', '', '', '', '']
text = random.choice(list)
</code>```

that the code

edit : can you tell me whats wrong in this one?

```<code>import discord
import requests
import random
import sys

token = sys.argv[1]
chan = sys.argv[2]
client = discord.Client()
list = requests.get('emoji.txt').text.split("\n")

@client.event
async def on_ready():
    txtchan = client.get_channel(int(chan))
    while not client.is_closed():
        message = ''
        for x in range(5):
            message += random.choice(list)
        await txtchan.send(message)
client.run(token, bot=False)
</code>```

答:
You can use random.choices():

```<code>import random

l = [*range(100)]
choices = random.choices(l, k=3)
print(choices)
</code>```

Upd.

Sorry, I've missed that fact, that you need to pick unique values. For that you can use random.sample():

```<code>choices = random.sample(l, 3)
</code>```

Body:
I want to make a bot that sending 3 emoji but its different emoji , but when im running it , the bot took one emoji and sending a same 3 emoji, how do i make it take the different 3 emoji?

list  = ['', '', '', '', '', '', '', '', '', '', '', '', '', '']
text = random.choice(list)

that the code

edit : can you tell me whats wrong in this one?

import discord
import requests
import random
import sys

token = sys.argv[1]
chan = sys.argv[2]
client = discord.Client()
list = requests.get('emoji.txt').text.split("\n")

@client.event
async def on_ready():
    txtchan = client.get_channel(int(chan))
    while not client.is_closed():
        message = ''
        for x in range(5):
            message += random.choice(list)
        await txtchan.send(message)
client.run(token, bot=False)

Body:
You can use random.choices():

import random

l = [*range(100)]
choices = random.choices(l, k=3)
print(choices)

Upd.

Sorry, I've missed that fact, that you need to pick unique values. For that you can use random.sample():

choices = random.sample(l, 3)


问:
Changing md-subheader-inner css property
I am trying to remove the padding:16px; property the md-subheader-inner inherits from the md-subheader directive.

The problem is, that when applying another class on my subheader, it seems like i can't change the inner style properties. I have made a codepen trying to show what the problem is here.

Whenever I inspect the element, it doesn't matter which of the two solution I made, the css properties are not updated... I think I am missing something obvious here, but I can't figure out what this is.

Please note that I don't want to use direct modification on md-subheader class because I am using that directive on a lot of places and I don't want any side effect (hence my 'padding-less-inner' class).

Html:

```<code><md-select name="test" multiple="true" ng-model="whatever">
<md-subheader class="md-sticky padding-less-inner">
  <md-input-container style="width:100%;padding-left:8px;padding-right: 24px;margin-bottom: 0px;">
    <input style="width: calc(100% - 30px);float: right;" ng-model="searchText" class="_md-text" onkeydown="stopPropagation(event)">
  </md-input-container>
</md-subheader>
<md-optgroup>
  <md-option ng-value="item.id" ng-repeat="item in querySearch()">{{item.name_fr}}</md-option>
</md-optgroup>
</code>```

CSS:

```<code>.padding-less-inner {
    .md-subheader-inner {
        padding: 0 !important;
    }
    /*div {
         padding: 0 !important;
    }*/
}
</code>```

答:
I made a slight modification to your CSS:

.padding-less-inner .md-subheader-inner {
    padding: 0 !important;
}```

Body:
I am trying to remove the padding:16px; property the md-subheader-inner inherits from the md-subheader directive.

The problem is, that when applying another class on my subheader, it seems like i can't change the inner style properties. I have made a codepen trying to show what the problem is here.

Whenever I inspect the element, it doesn't matter which of the two solution I made, the css properties are not updated... I think I am missing something obvious here, but I can't figure out what this is.

Please note that I don't want to use direct modification on md-subheader class because I am using that directive on a lot of places and I don't want any side effect (hence my 'padding-less-inner' class).

Html:

<md-select name="test" multiple="true" ng-model="whatever">
<md-subheader class="md-sticky padding-less-inner">
  <md-input-container style="width:100%;padding-left:8px;padding-right: 24px;margin-bottom: 0px;">
    <input style="width: calc(100% - 30px);float: right;" ng-model="searchText" class="_md-text" onkeydown="stopPropagation(event)">
  </md-input-container>
</md-subheader>
<md-optgroup>
  <md-option ng-value="item.id" ng-repeat="item in querySearch()">{{item.name_fr}}</md-option>
</md-optgroup>

CSS:

.padding-less-inner {
    .md-subheader-inner {
        padding: 0 !important;
    }
    /*div {
         padding: 0 !important;
    }*/
}


问:
Some questions about SAMME.R
The picture of the algorithm

The paper about SAMME.R algorithm

Firstly,in the 2a step, if fits a classifier T(x) to the training data using weights,but I don't know how the algorithm uses the classifier T(x) in the following part.

Secondly, in the 2b step, i don't know how to obtain the weighted class probability estimates. It just says we can use decision tree to estimate the probability, but I don't know how to do it.

Thanks in advance. My English is poor and my question may be vague. I am really sorry for this. If you can't understand my question, just comment it and I will try my best to expound my question clearly!  Thank you very much!!

答:
I also found myself contemplating on the same problem not too long ago. For whatever it's worth, here is my opinion on the matter:

Step 2a

Train a DecisionTree or any other classifier that can supply probability estimates. You can find an interesting article on estimating probabilities with DecisionTrees here. This classifier will be used in step 2b.

Step 2b

One way to look at this if you expand the formula:

In words, to compute the weighted probability for some label (i) you multiply the probability estimated at the previous step for label i with the sum of weights of the samples that have the label i. In practice, the classifier at step 2a may use the weights in some other way and at the end only supply the weighted probability estimates. A nice post on this for Decision Trees is here.

I hope you find this answer helpful!

Title: Some questions about SAMME.R


问:
no such element: Unable to locate element modal
I have to test this modal box and I have to
type the name of project

```<code><div class="modal fade bs-create-project-modal show" tabindex="-1" role="dialog" aria-labelledby="create-project" style="display: block; padding-right: 14px;">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title mt-0">Create project</h5>
                            <input class="form-control" type="text" name="title" placeholder="Enter project name">
                        </div>
                <button type="submit" class="btn btn-primary waves-effect waves-light">Create project</button>
</code>```

I tried this

->type('div.modal .fade .bs-create-project-modal input[name^=title]', 'any')
but got "no such element: Unable to locate element"

答:
You may need to use waitFor() to check if the modal is present.

```<code>$dusk->waitFor('input[name^="title"]')
    ->type('input[name^="title"]', 'any')
    ->press('Submit');
</code>```

Body:
I have to test this modal box and I have to
type the name of project

Create project

                            <input class="form-control" type="text" name="title" placeholder="Enter project name">

                <button type="submit" class="btn btn-primary waves-effect waves-light">Create project</button>

I tried this

->type('div.modal .fade .bs-create-project-modal input[name^=title]', 'any')
but got "no such element: Unable to locate element"

Body:
You may need to use waitFor() to check if the modal is present.

$dusk->waitFor('input[name^="title"]')
    ->type('input[name^="title"]', 'any')
    ->press('Submit');