问:
I cant translate a math problem into python
I'm currently learning python, and I just can't wrap my head around this.
I was taking some python classes, and one of the program examples required the user to enter two inputs  v0 = 100 and theta = 30 (gave them the values in the example) and use the following formulas to get the flight time of a ball, and Horizontal distance reached

v0x = v0 * cos(theta)

v0y = v0 * sin(theta)

v0y * t- 1/2 * 9.8 * t^2 = 0

d = v0x * t

My problem is I'm not sure how I'm supposed to convert the third formula into python code. I'm  assuming I need to solve for  T, but how would I go about doing that in python.

so far all I can do is this

```<code>v0 = 100
theta = 30
v0x = v0 * math.cos(theta)
v0y = v0 * math.sin(theta)
t = ???
d = v0 * t

print(f"Flight time of the ball is: {t}")
print(f"Horizontal distance reached by the ball is: {d} " )

</code>```

答:
Seems a bit of physics but , you will have to calculate the t(time) equation to feed it into python , some what like below

```<code>v0y * t- 1/2 * 9.8 * t^2 = 0
t * ( v0y - 1/2 * 9.8 * t) = 0
t = 0 or v0y - 1/2 * 9.8 * t = 0
v0y = 1/2 * 9.8 * t
t = 2 * v0y / 9.8
</code>```

So to convert that into python

```<code>t = 2 * v0y / 9.8
</code>```

Overall code will look like

```<code>import math

v0 = 100
theta = math.radians(30)
v0x = v0 * math.cos(theta)
v0y = v0 * math.sin(theta)
t =  2 * v0y / 9.8
d = v0 * t

print(f"Flight time of the ball is: {t}")
print(f"Horizontal distance reached by the ball is: {d} " )
</code>```

Body:
I'm currently learning python, and I just can't wrap my head around this.
I was taking some python classes, and one of the program examples required the user to enter two inputs  v0 = 100 and theta = 30 (gave them the values in the example) and use the following formulas to get the flight time of a ball, and Horizontal distance reached

v0x = v0 * cos(theta)

v0y = v0 * sin(theta)

v0y * t- 1/2 * 9.8 * t^2 = 0

d = v0x * t

My problem is I'm not sure how I'm supposed to convert the third formula into python code. I'm  assuming I need to solve for  T, but how would I go about doing that in python.

so far all I can do is this

v0 = 100
theta = 30
v0x = v0 * math.cos(theta)
v0y = v0 * math.sin(theta)
t = ???
d = v0 * t

print(f"Flight time of the ball is: {t}")
print(f"Horizontal distance reached by the ball is: {d} " )

Body:
Seems a bit of physics but , you will have to calculate the t(time) equation to feed it into python , some what like below

v0y * t- 1/2 * 9.8 * t^2 = 0
t * ( v0y - 1/2 * 9.8 * t) = 0
t = 0 or v0y - 1/2 * 9.8 * t = 0
v0y = 1/2 * 9.8 * t
t = 2 * v0y / 9.8

So to convert that into python

t = 2 * v0y / 9.8

Overall code will look like

import math

v0 = 100
theta = math.radians(30)
v0x = v0 * math.cos(theta)
v0y = v0 * math.sin(theta)
t =  2 * v0y / 9.8
d = v0 * t

print(f"Flight time of the ball is: {t}")
print(f"Horizontal distance reached by the ball is: {d} " )


来源: stackexchange

问:
how to dynamically rewrite filepath .htaccess based on domain?
I have this apache rule in my .htaccess file:

```<code>RewriteCond %{HTTP_HOST} ^testURL.localhost.local
RewriteRule ^index.php$ /_testURL/index.php [L]
</code>```

How would I write this so that testURL2.localhost.local or any other subdomain would be rewritten to the corresponding directories?

For instance testURL2.localhost.local would be rewritten  to _testURL2/index.php etc

I already tried the option below but I didn't get the intended result:

```<code>RewriteCond %{HTTP_HOST} ^testURL
RewriteRule ^cms.php$ /_%1/cms.php [L]
</code>```

答:
With your shown samples, attempts; please try following htaccess rules file. I have posted 2 sets of htaccess rules file here, you have to use ONLY one set at a time.

1st solution: This is specifically for host testURL.localhost.local and will look for either index.php OR cms.php only in UI.

```<code>RewriteEngine ON
RewriteCond %{HTTP_HOST} ^(?:www\.)?(testURL)\.localhost\.local$ [NC]
RewriteRule ^((?:index|cms)\.php)$  _%1/$1 [NC,L]
</code>```

2nd solution: A Generic solution, where it will look for anyvalue.localhost.local and it will add anyvalue in path while rewriting, also it will look for any php files in uri.

```<code>RewriteEngine ON
RewriteCond %{HTTP_HOST} ^(?:www\.)?([^.]*)\.localhost\.local$ [NC]
RewriteRule ^([^.]*\.php)$  _%1/$1 [NC,L]
</code>```

NOTE1: Also please make sure to clear your browser cache before testing your URLs.

NOTE2: Please keep these rules at the top of your htaccess rules file.

NOTE3: I am also additionally/optimally  matching www. in host in case you don't want it you could remove it (?:www\.)? part in condition.

ContentLicense: CC BY-SA 4.0

Body:
I have this apache rule in my .htaccess file:

RewriteCond %{HTTP_HOST} ^testURL.localhost.local
RewriteRule ^index.php$ /_testURL/index.php [L]

How would I write this so that testURL2.localhost.local or any other subdomain would be rewritten to the corresponding directories?

For instance testURL2.localhost.local would be rewritten  to _testURL2/index.php etc

I already tried the option below but I didn't get the intended result:

RewriteCond %{HTTP_HOST} ^testURL
RewriteRule ^cms.php$ /_%1/cms.php [L]

Body:
With your shown samples, attempts; please try following htaccess rules file. I have posted 2 sets of htaccess rules file here, you have to use ONLY one set at a time.

1st solution: This is specifically for host testURL.localhost.local and will look for either index.php OR cms.php only in UI.

RewriteEngine ON
RewriteCond %{HTTP_HOST} ^(?:www\.)?(testURL)\.localhost\.local$ [NC]
RewriteRule ^((?:index|cms)\.php)$  _%1/$1 [NC,L]

2nd solution: A Generic solution, where it will look for anyvalue.localhost.local and it will add anyvalue in path while rewriting, also it will look for any php files in uri.

RewriteEngine ON
RewriteCond %{HTTP_HOST} ^(?:www\.)?([^.]*)\.localhost\.local$ [NC]
RewriteRule ^([^.]*\.php)$  _%1/$1 [NC,L]

NOTE1: Also please make sure to clear your browser cache before testing your URLs.

NOTE2: Please keep these rules at the top of your htaccess rules file.

NOTE3: I am also additionally/optimally  matching www. in host in case you don't want it you could remove it (?:www\.)? part in condition.


问:
How do I move/copy a symlink to a different folder as a symlink under Solaris?
It is an odd behaviour seen only on Solaris that when I try to copy a symbolic link with the "cp -R -P" command to some other folder with a different name, it copies the entire directory/file it's pointing to.

For example:

```<code>link -> dir

cp -R -P link folder/new_link
</code>```

答: The cp man page seems to say that you want to use an '-H' to preserve symlinks within the source directory.</p>

OwnerDisplayName: kadeshpa

ContentLicense: CC BY-SA 2.5

Body:
It is an odd behaviour seen only on Solaris that when I try to copy a symbolic link with the "cp -R -P" command to some other folder with a different name, it copies the entire directory/file it's pointing to.

For example:

link -> dir

cp -R -P link folder/new_link

LastEditorDisplayName: Eddie

OwnerDisplayName: BonkaBonka

ContentLicense: CC BY-SA 3.0


问:
Webkit isn't loading a long JavaScript file
I'm having issues where both Chrome and Safari aren't loading all my JavaScript. My file is rather large uncompressed, 16000+ lines, but it's working fine in Firefox and Opera. I'm using Mac as well and haven't tested Windows yet.

Does anyone know if Webkit clips a file after a certain line number?

答:
I have a few files that are about that long and don't have problems with any web kit browsers.
Are you using any debug tools to see if any errors are being generated?

In chrome you can press ctrl+shift+I and get a developer tools console that could help with things.


问:
parsing complicated json with Angular
I want to parse an http request of this format:

[
    {
        "id": 1,
        "date": "2022-01-13T00:00:00.000+00:00",
        "time": "2022-01-13T21:21:21.000+00:00",
        "office": {
            "id": 2,
            "description": "Office2",
            "phone": "123456789",
            "enabled": 1
        },
        "officeDescr": "Office2",
        "reason": 2,
        "reasonDescr": "Studies",
        "file": "1.pdf",
        "status": 0,
        "userIn": {
            "username": "name",
            "password": "'$2a$04$DR/f..s1siWJc8Xg3eJgpeB28a4V6kYpnkMPeOuq4rLQ42mJUYFGC",
            "enabled": 1,
            "firstname": "fname",
            "lastname": "lanme",
            "asm": 123,
            "office": 2,
            "authorities": [
                {
                    "authority": "ROLE_POLITIS"
                }
            ]
        },
        "commentIn": null,
        "userValid": null,
        "commentValid": null,
        "userApproved": null,
        "commentApproved": null
    },
    {
        "id": 2,
        "date": "2022-01-13T00:00:00.000+00:00",
        "time": "2022-01-13T22:22:22.000+00:00",
        "office": {
            "id": 2,
            "description": "Office2",
            "phone": "123456789",
            "enabled": 1
        },
        "officeDescr": "Office2",
        "reason": 3,
        "reasonDescr": "Health",
        "file": "2.pdf",
        "status": 0,
        "userIn": {
            "username": "somename",
            "password": "'$2a$04$DR/f..s1siWJc8Xg3eJgpeB28a4V6kYpnkMPeOuq4rLQ42mJUYFGC",
            "enabled": 1,
            "firstname": "somename",
            "lastname": "saomelastname",
            "asm": 456,
            "office": 2,
            "authorities": [
                {
                    "authority": "ROLE_POLITIS"
                }
            ]
        },
        "commentIn": null,
        "userValid": null,
        "commentValid": null,
        "userApproved": null,
        "commentApproved": null
    },
    {
        "id": 3,
        "date": "2022-01-13T00:00:00.000+00:00",
        "time": "2022-01-13T23:23:23.000+00:00",
        "office": {
            "id": 3,
            "description": "Office3",
            "phone": "777777777",
            "enabled": 1
        },
        "officeDescr": "Office3",
        "reason": 3,
        "reasonDescr": "Health",
        "file": "3.pdf",
        "status": 0,
        "userIn": {
            "username": "politis3",
            "password": "'$2a$04$DR/f..s1siWJc8Xg3eJgpeB28a4V6kYpnkMPeOuq4rLQ42mJUYFGC",
            "enabled": 1,
            "firstname": "Politis3",
            "lastname": "PolitisOffice3",
            "asm": 789,
            "office": 3,
            "authorities": [
                {
                    "authority": "ROLE_POLITIS"
                }
            ]
        },
        "commentIn": null,
        "userValid": null,
        "commentValid": null,
        "userApproved": null,
        "commentApproved": null
    }
]
```
<p>I want get the username form the Object userIn but so far i only managed to get the whole userIn object with this:</p>
<pre class="lang-js prettyprint-override"><code>    this.applicationService.get().subscribe(
      (applications) => (console.log(applications.body.find(s=>s.userIn).userIn)));
</code>```

Is there a way to get the attributes separately?

I tried to use brackets [] ant the end of applications.body.find(s=>s.userIn).userIn to get the attribute i want but it always returns undefined.

EDIT

I have this service that uses HttpClient to get an api from the Backend server

  getPostponements(): Observable<HttpResponse<Application[]>> {
    const url = `${this.apiUrl2}/postponements`;
    return this.http.get<Application[]>(url,{ observe: 'response' })
  }
```
<p>The <code>applications</code> type inside the <code>.subscribe</code> is <code> HttpResponse<Application[]></code></p>
<p>I also have a Model called Application.ts:</p>
<pre class="lang-js prettyprint-override"><code>export interface Application {
    id?: number;
    date: string;
    time: string;
    reason: number;
    reasonDescr: string;
    office: number;
    officeDescr: string;
    file: string;
    userIn: number;
    commentIn: string;
    userValid: string;
    commentValid: string;
    userApproved: string;
    commentApproved: string;
    status: number;
}
</code>```

答:
As @GetOffMyLawn mentioned in the comment that your model was wrong for userIn.

With Json2Ts, theApplication class should be as below:

export interface Office {
  id: number;
  description: string;
  phone: string;
  enabled: number;
}

export interface Authority {
  authority: string;
}

export interface UserIn {
  username: string;
  password: string;
  enabled: number;
  firstname: string;
  lastname: string;
  asm: number;
  office: number;
  authorities: Authority[];
}

export interface Application {
  id: number;
  date: Date;
  time: Date;
  office: Office;
  officeDescr: string;
  reason: number;
  reasonDescr: string;
  file: string;
  status: number;
  userIn: UserIn;
  commentIn?: any;
  userValid?: any;
  commentValid?: any;
  userApproved?: any;
  commentApproved?: any;
}
```
<p>Meanwhile, to get the <code>userIn</code>, you have to modify logic as well. <em>(Since you don't specify which <code>userIn</code>'s <code>username</code> you want to get, I provide some methods for your reference.)</em></p>
<blockquote>
<p>Get the first <code>Application</code> item for <code>userIn</code>'s <code>username</code> (Provided by @GetOffMyLawn's comment)</p>
</blockquote>
<pre class="lang-js prettyprint-override"><code>applications.body[0].userIn.username
</code>```

Get userIn's username by Application's id

applications.body.find((x) => x.id == /* applicationId */).userIn.username
```
<blockquote>
<p>Get all <code>userIn</code>s' <code>username</code></p>
</blockquote>
<pre class="lang-js prettyprint-override"><code>applications.body.map(
  (x: Application) => x.userIn.username
)
</code>```

Sample Demo on StackBlitz

Title: parsing complicated json with Angular

Body:
I want to parse an http request of this format:

[
    {
        "id": 1,
        "date": "2022-01-13T00:00:00.000+00:00",
        "time": "2022-01-13T21:21:21.000+00:00",
        "office": {
            "id": 2,
            "description": "Office2",
            "phone": "123456789",
            "enabled": 1
        },
        "officeDescr": "Office2",
        "reason": 2,
        "reasonDescr": "Studies",
        "file": "1.pdf",
        "status": 0,
        "userIn": {
            "username": "name",
            "password": "'$2a$04$DR/f..s1siWJc8Xg3eJgpeB28a4V6kYpnkMPeOuq4rLQ42mJUYFGC",
            "enabled": 1,
            "firstname": "fname",
            "lastname": "lanme",
            "asm": 123,
            "office": 2,
            "authorities": [
                {
                    "authority": "ROLE_POLITIS"
                }
            ]
        },
        "commentIn": null,
        "userValid": null,
        "commentValid": null,
        "userApproved": null,
        "commentApproved": null
    },
    {
        "id": 2,
        "date": "2022-01-13T00:00:00.000+00:00",
        "time": "2022-01-13T22:22:22.000+00:00",
        "office": {
            "id": 2,
            "description": "Office2",
            "phone": "123456789",
            "enabled": 1
        },
        "officeDescr": "Office2",
        "reason": 3,
        "reasonDescr": "Health",
        "file": "2.pdf",
        "status": 0,
        "userIn": {
            "username": "somename",
            "password": "'$2a$04$DR/f..s1siWJc8Xg3eJgpeB28a4V6kYpnkMPeOuq4rLQ42mJUYFGC",
            "enabled": 1,
            "firstname": "somename",
            "lastname": "saomelastname",
            "asm": 456,
            "office": 2,
            "authorities": [
                {
                    "authority": "ROLE_POLITIS"
                }
            ]
        },
        "commentIn": null,
        "userValid": null,
        "commentValid": null,
        "userApproved": null,
        "commentApproved": null
    },
    {
        "id": 3,
        "date": "2022-01-13T00:00:00.000+00:00",
        "time": "2022-01-13T23:23:23.000+00:00",
        "office": {
            "id": 3,
            "description": "Office3",
            "phone": "777777777",
            "enabled": 1
        },
        "officeDescr": "Office3",
        "reason": 3,
        "reasonDescr": "Health",
        "file": "3.pdf",
        "status": 0,
        "userIn": {
            "username": "politis3",
            "password": "'$2a$04$DR/f..s1siWJc8Xg3eJgpeB28a4V6kYpnkMPeOuq4rLQ42mJUYFGC",
            "enabled": 1,
            "firstname": "Politis3",
            "lastname": "PolitisOffice3",
            "asm": 789,
            "office": 3,
            "authorities": [
                {
                    "authority": "ROLE_POLITIS"
                }
            ]
        },
        "commentIn": null,
        "userValid": null,
        "commentValid": null,
        "userApproved": null,
        "commentApproved": null
    }
]

I want get the username form the Object userIn but so far i only managed to get the whole userIn object with this:

    this.applicationService.get().subscribe(
      (applications) => (console.log(applications.body.find(s=>s.userIn).userIn)));

Is there a way to get the attributes separately?

I tried to use brackets [] ant the end of applications.body.find(s=>s.userIn).userIn to get the attribute i want but it always returns undefined.

EDIT

I have this service that uses HttpClient to get an api from the Backend server

  getPostponements(): Observable<HttpResponse<Application[]>> {
    const url = `${this.apiUrl2}/postponements`;
    return this.http.get<Application[]>(url,{ observe: 'response' })
  }

The applications type inside the .subscribe is  HttpResponse<Application[]>

I also have a Model called Application.ts:

export interface Application {
    id?: number;
    date: string;
    time: string;
    reason: number;
    reasonDescr: string;
    office: number;
    officeDescr: string;
    file: string;
    userIn: number;
    commentIn: string;
    userValid: string;
    commentValid: string;
    userApproved: string;
    commentApproved: string;
    status: number;
}

Body:
As @GetOffMyLawn mentioned in the comment that your model was wrong for userIn.

With Json2Ts, theApplication class should be as below:

export interface Office {
  id: number;
  description: string;
  phone: string;
  enabled: number;
}

export interface Authority {
  authority: string;
}

export interface UserIn {
  username: string;
  password: string;
  enabled: number;
  firstname: string;
  lastname: string;
  asm: number;
  office: number;
  authorities: Authority[];
}

export interface Application {
  id: number;
  date: Date;
  time: Date;
  office: Office;
  officeDescr: string;
  reason: number;
  reasonDescr: string;
  file: string;
  status: number;
  userIn: UserIn;
  commentIn?: any;
  userValid?: any;
  commentValid?: any;
  userApproved?: any;
  commentApproved?: any;
}

Meanwhile, to get the userIn, you have to modify logic as well. (Since you don't specify which userIn's username you want to get, I provide some methods for your reference.)

Get the first Application item for userIn's username (Provided by @GetOffMyLawn's comment)

applications.body[0].userIn.username

Get userIn's username by Application's id

applications.body.find((x) => x.id == /* applicationId */).userIn.username

Get all userIns' username

applications.body.map(
  (x: Application) => x.userIn.username
)

Sample Demo on StackBlitz


问:
Isn't the time complexity for combinations in Python O(n)?
I was curious about the time complexity of Python's itertools.combinations function. I did some searching and it seems that many resources claim the time complexity is O(n!) or O(nCr).

However, for the two extremes of when r = 1 and r = n, the formula nCr reduces to n and 1, respectively. Does this mean we can conclude that the time complexity of itertools.combinations is O(n)?

答:
Does this mean we can conclude that the time complexity of itertools.combinations is O(n)?

No you / we can't do that.

Consider this statement:

Algorithm X to compute the combinations of r values from a set of n  is O(nCr).

It is in fact trivial to prove1 that any algorithm to do the above must be at least O(nCr).  But we would need to examine the actual code to determine that a given algorithm is exactly O(nCr)

What you are doing is setting one or both of the variables to fixed values. This is effectively changing the problem.

To illustrate this, we can just substitute the fixed values into the above statement; e.g.

Algorithm X to compute the combinations of 1 value from a set of n  is O(nC1).

Since nC1 is n, we can rewrite this as:

Algorithm X to compute the combinations of 1 value from a set of n  is O(n).

But notice that this problem is different to the original one.

In short ... this is NOT invalidating the original statement.

Note that the (alleged) claim that itertools.combinations is O(n!) is (I think) a misreading on your part.  What that "source" actually says is:

"Getting all combinations of a list is O(n!). Since you're doing that n times to get combinations with different values of r, the whole algorithm is O(n * n!)."

My reading is that it is talking about Pn not nCr.  But either way, it is too vague to be considered a credible source.

1 - Informal proof.  The set of combinations of r from a set of n has nCr elements.  Constructing this set will entail adding nCr elements to a data structure.  That involves (at least) nCr memory writes.  It will take (at least) O(nCr) time to do this ... assuming a (real world) computer with an upper limit on memory bandwidth.


问:
Search multiple arrays for a string and then set a var - jQuery
I'm looking to set a variable based on which array a string exists in.

For example:

```<code>var primary   = ["red", blue", "yellow"];
var secondary = ["orange", "purple", "green"];
</code>```

Then check for "purple" and return that it is in the "secondary" array and assign it to a variable to use later.

jQuery or Javascript is fine.

答:
Not sure what you wanted to assign to a variable, so I just used alerts to illustrate the result

```<code>var plen = primary.length;

var idx = $.inArray( 'purple', primary.concat( secondary ) );

if( idx === -1 ) {
    alert( 'not found' );
} else if( idx < plen ) {
    alert( idx + ' in primary' );
} else {
    alert( (idx - plen) + ' in secondary' );
}
</code>```

Example: http://jsfiddle.net/S9WL6/

Then you can make it into a reusable function:

```<code>function inArrays( val, arr1, arr2 ) {
    var len1 = arr1.length;

    var idx = $.inArray( val, arr1.concat( arr2 ) );

    var ret = {index:idx,array:null};

    if( idx > -1 ) {
        if( idx < len1 ) {
            ret.array = arr1;
        } else {
            ret.array = arr2;
            ret.index -= len1;
        }
    }
    return ret;
}

inArrays( 'purple', primary, secondary );
</code>```

EDIT: Or make it into a function that can accept a variable number of Arrays.

Example: http://jsfiddle.net/5pZUQ/

```<code>var first = ["red", "blue", "yellow"];
var second = ["orange", "purple", "green"];
var third = ["brown", "black", "white"];

function inArrays(val) {
    var arrays = Array.prototype.slice.call(arguments, 1);

    var len = 0;
    var i = 0;

    var idx = $.inArray(val, [].concat.apply([], arrays));

    var ret = {
        index: idx,
        array: null
    };

    if (idx > -1) {
        do {
            ret.array = arrays[i];
            ret.index = idx - len;
            len += arrays[i].length;
            i++;
        } while (idx >= len)
    }
    return ret;
}

console.log( inArrays('white', first, second, third) );
</code>```

Body:
I'm looking to set a variable based on which array a string exists in.

For example:

var primary   = ["red", blue", "yellow"];
var secondary = ["orange", "purple", "green"];

Then check for "purple" and return that it is in the "secondary" array and assign it to a variable to use later.

jQuery or Javascript is fine.

Body:
Not sure what you wanted to assign to a variable, so I just used alerts to illustrate the result

var plen = primary.length;

var idx = $.inArray( 'purple', primary.concat( secondary ) );

if( idx === -1 ) {
    alert( 'not found' );
} else if( idx < plen ) {
    alert( idx + ' in primary' );
} else {
    alert( (idx - plen) + ' in secondary' );
}

Example: http://jsfiddle.net/S9WL6/

Then you can make it into a reusable function:

function inArrays( val, arr1, arr2 ) {
    var len1 = arr1.length;

    var idx = $.inArray( val, arr1.concat( arr2 ) );

    var ret = {index:idx,array:null};

    if( idx > -1 ) {
        if( idx < len1 ) {
            ret.array = arr1;
        } else {
            ret.array = arr2;
            ret.index -= len1;
        }
    }
    return ret;
}

inArrays( 'purple', primary, secondary );

EDIT: Or make it into a function that can accept a variable number of Arrays.

Example: http://jsfiddle.net/5pZUQ/

var first = ["red", "blue", "yellow"];
var second = ["orange", "purple", "green"];
var third = ["brown", "black", "white"];

function inArrays(val) {
    var arrays = Array.prototype.slice.call(arguments, 1);

    var len = 0;
    var i = 0;

    var idx = $.inArray(val, [].concat.apply([], arrays));

    var ret = {
        index: idx,
        array: null
    };

    if (idx > -1) {
        do {
            ret.array = arrays[i];
            ret.index = idx - len;
            len += arrays[i].length;
            i++;
        } while (idx >= len)
    }
    return ret;
}

console.log( inArrays('white', first, second, third) );


问:
count the distance between to strings in an array Ruby
i have an array

```<code>line_one = ["flinders street", "richmond", "east richmond", "burnley", "hawthorn", "glenferrie"]

user_input1 = "flinders street"
user_input2 = "glenferrie"
</code>```

how could I count the distance between the two strings?
expected output 5.

答:
```<code>line_one = ["flinders street", "richmond", "east richmond", "burnley", "hawthorn", "glenferrie"]
</code>```

Code

```<code>p (line_one.index("flinders street")...line_one.index("glenferrie")).count
</code>```

output

```<code>5
</code>```

Body:
i have an array

line_one = ["flinders street", "richmond", "east richmond", "burnley", "hawthorn", "glenferrie"]

user_input1 = "flinders street"
user_input2 = "glenferrie"

how could I count the distance between the two strings?
expected output 5.

Body:
line_one = ["flinders street", "richmond", "east richmond", "burnley", "hawthorn", "glenferrie"]

Code

p (line_one.index("flinders street")...line_one.index("glenferrie")).count

output

5


问:
How to make dynamic link in Vue JS?
I have:

```<code><b-dropdown text="Select Factory" block variant="primary" class="m-2" menu-class="w-100">
<b-dropdown-item @click="selectedFactory='China'">China</b-dropdown-item>
<b-dropdown-item @click="selectedFactory='Europe'">Europe</b-dropdown-item>
</b-dropdown>

<b-dropdown text="Select Toy" block variant="primary" class="m-2" menu-class="w-100">
<b-dropdown-item @click="selectedToy='Marvel'">Marvel</b-dropdown-item>
<b-dropdown-item @click="selectedToy='Toy Story'">Toy Story</b-dropdown-item>
</b-dropdown>
</code>```

How can I make this line of code work, such that the source link is dynamic? Currently it does work with the dropdown selection when embeded into an iframe. I am guessing probably something to do with the compute function, am not very sure

```<code>export default {

el: '#apps',
  data () {
     return {

        source:'http://127.0.0.1:5503/src/html/`{{this.selectedFactory}}`_{{this.selectedToy}}.html',
        selectedFactory: '',
        selectedToy:'',
     }
  },
  computed:{

  }

}
</code>```

答:
should use <router-link> inside , like this:

```<code><b-dropdown-item><router-link :to="some_url">China</router-link></b-dropdown-item>
...
data() {
  return {
    some_url: '',
  };
},
</code>```

or:

```<code>computed: {    some_url() { return 'foo' } }
</code>```

Title: How to make dynamic link in Vue JS?

Body:
I have:

China
Europe

Marvel
Toy Story

How can I make this line of code work, such that the source link is dynamic? Currently it does work with the dropdown selection when embeded into an iframe. I am guessing probably something to do with the compute function, am not very sure

export default {

el: '#apps',
  data () {
     return {

        source:'http://127.0.0.1:5503/src/html/`{{this.selectedFactory}}`_{{this.selectedToy}}.html',
        selectedFactory: '',
        selectedToy:'',
     }
  },
  computed:{

  }

}

Body:
should use <router-link> inside <b-dropdown-item>, like this:

<b-dropdown-item><router-link :to="some_url">China</router-link></b-dropdown-item>
...
data() {
  return {
    some_url: '',
  };
},

or:

computed: {    some_url() { return 'foo' } }


问:
Saving object in android in onSaveInstanceState()
This is a puzzle app. I have a class of Puzzle that contains the object itself and business logics. In onCreate, I created the object itself, I need to save the instance. Is it a good idea to save the same object I created in onCreate in onSaveInstanceState()? If so, what is the best way to do it? Otherwise, should I save the variables of the object Puzzle in onSaveInstanceState()?</p>
```<code> @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Read in the arrays
        String[] targetWords = getResources().getStringArray(R.array.target_words);
        String[] okWords = getResources().getStringArray(R.array.acceptable_words);

        // TODO: Now we always create a new puzzle when the Activity is created. You
        // will need to restore the existing activity if the Framework has destroyed
        // and recreated it.
        newPuzzle = new Puzzle(targetWords, okWords);
        for (int i = 0; i < newPuzzle.getGuessCount(); i++) {
            displayResult(i);
        }
    }

    // save the puzzle obj?
    @Override
    public void onSaveInstanceState(Bundle outState){
        super.onSaveInstanceState(outState);

    }
</code>```

答:
Make your Puzzle Object Parcelable or Serializable, then save it in:

```<code>@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putSerializable("puzzleObj", newPuzzle);
}
</code>```

You can retrieve it in onCreate()

```<code>if (savedInstanceState != null) {
        newPuzzle = (Puzzle) savedInstanceState.getSerializable("puzzleObj");
  }
</code>```

Body:
This is a puzzle app. I have a class of Puzzle that contains the object itself and business logics. In onCreate, I created the object itself, I need to save the instance. Is it a good idea to save the same object I created in onCreate in onSaveInstanceState()? If so, what is the best way to do it? Otherwise, should I save the variables of the object Puzzle in onSaveInstanceState()?

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Read in the arrays
        String[] targetWords = getResources().getStringArray(R.array.target_words);
        String[] okWords = getResources().getStringArray(R.array.acceptable_words);

        // TODO: Now we always create a new puzzle when the Activity is created. You
        // will need to restore the existing activity if the Framework has destroyed
        // and recreated it.
        newPuzzle = new Puzzle(targetWords, okWords);
        for (int i = 0; i < newPuzzle.getGuessCount(); i++) {
            displayResult(i);
        }
    }

    // save the puzzle obj?
    @Override
    public void onSaveInstanceState(Bundle outState){
        super.onSaveInstanceState(outState);

    }

Body:
Make your Puzzle Object Parcelable or Serializable, then save it in:

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putSerializable("puzzleObj", newPuzzle);
}

You can retrieve it in onCreate()

if (savedInstanceState != null) {
        newPuzzle = (Puzzle) savedInstanceState.getSerializable("puzzleObj");
  }


问:
How to Add Randomness in Discord.py
I am new to Python, I need help adding randomness into my bot on Discord. I made a command where there was a 0.01% chance of getting a message. However only the else statement worked, if the rare chance happened, no message was sent to the channel.</p>
```<code>@client.command()
@commands.cooldown(1, 86400, commands.BucketType.user)
@commands.has_role("Member")
async def addrole(ctx):
    if random.randint(1, 10000) < 2:
        await ctx.channel.send("wow rare")

    else:
        await ctx.channel.send("not cool")
</code>```

答:
if random.randrange(1, 10000) < 2:
```

Try this

Title: How to Add Randomness in Discord.py

Body:
I am new to Python, I need help adding randomness into my bot on Discord. I made a command where there was a 0.01% chance of getting a message. However only the else statement worked, if the rare chance happened, no message was sent to the channel.

@client.command()
@commands.cooldown(1, 86400, commands.BucketType.user)
@commands.has_role("Member")
async def addrole(ctx):
    if random.randint(1, 10000) < 2:
        await ctx.channel.send("wow rare")

    else:
        await ctx.channel.send("not cool")

Body:
if random.randrange(1, 10000) < 2:

Try this


问:
npm install hangs forever in EC2
Trying to deploy a react app on AWS EC2.
I'm using apache so I got git clone under /var/www/html.

I didn't have any problem when I deployed other projects,
but when I npm install in this new project folder, within some seconds (when it's installing webpack), it just stuck at the same point with the same message.

It stuck there forever and any other command doesn't work. So I have to force quit the terminal. After that, I can't connect on my EC2 instance for 10 - 20min.

I tried npm install --verbose, removing package-lock.json, npm config set registry http://registry.npmjs.org/ --global, npm cache verify ... nothing worked.

It's really frustrating.
I don't know what should I do. Any advice will be appreciated.

答:
In my case, i had to create a swap file on my micro ec2 instance. My npm install hanged and was killed eventually. Once i increased the memory with the swap file, all worked fine!

Commands i used:

```<code>fallocate -l 4G /swapfile
chmod 600 /swapfile
mkswap  /swapfile
swapon /swapfile
swapon  --show
free -h
</code>```

Title: npm install hangs forever in EC2

Body:
In my case, i had to create a swap file on my micro ec2 instance. My npm install hanged and was killed eventually. Once i increased the memory with the swap file, all worked fine!

Commands i used:

fallocate -l 4G /swapfile
chmod 600 /swapfile
mkswap  /swapfile
swapon /swapfile
swapon  --show
free -h


问:
How to tag VPC and subnets for multiple EKS clusters
I have a VPC, 4 subnets (2 public and 2 private) and an EKS Cluster which all created with Terraform. My infra is working without a problem right now. I'm thinking about creating a second EKS Cluster, but I'm a little bit confused about subnet tagging.

For example, one of my private subnets was created like below;

```<code>resource "aws_subnet" "vpc-private" {
  vpc_id            = aws_vpc.vpc.id
  cidr_block        = var.private_cidr
  availability_zone = data.aws_availability_zones.available.names[0]

  tags = {
    Environment                                 = var.environment
    Name                                        = "${var.environment}-vpc-private"
    "kubernetes.io/cluster/${var.cluster_name}" = "shared"
    "kubernetes.io/role/internal-elb"           = "1"
  }
}
</code>```

As you can see, it's tagged with "kubernetes.io/cluster/${var.cluster_name}" = "shared" to enable subnet discovery. Since I'm thinking about creating second cluster for the same subnets, I'm trying to clarify how should subnets be tagged. There is no clear information in AWS documents, at least I didn't find anything clear about this situation. Will adding the second tag like "kubernetes.io/cluster/${var.cluster_2_name}" = "shared" be alright like below ?

```<code>resource "aws_subnet" "vpc-private" {
  vpc_id            = aws_vpc.vpc.id
  cidr_block        = var.private_cidr
  availability_zone = data.aws_availability_zones.available.names[0]

  tags = {
    Environment                                 = var.environment
    Name                                        = "${var.environment}-vpc-private"
    "kubernetes.io/cluster/${var.cluster_name}" = "shared"
    "kubernetes.io/cluster/${var.cluster_2_name}" = "shared"
    "kubernetes.io/role/internal-elb"           = "1"
  }
}
</code>```

Any help/recommendation will be highly appreciated, thank you very much.

答:
To answer my own question, yes tagging the subnet for each EKS Cluster is needed, otherwise load balancers couldn't find where to provision.

In Terraform, I used exact format I asked above

```<code>resource "aws_subnet" "vpc-private" {
  vpc_id            = aws_vpc.vpc.id
  cidr_block        = var.private_cidr
  availability_zone = data.aws_availability_zones.available.names[0]

  tags = {
    Environment                                 = var.environment
    Name                                        = "${var.environment}-vpc-private"
    "kubernetes.io/cluster/${var.cluster_name}" = "shared"
    "kubernetes.io/cluster/${var.cluster_2_name}" = "shared"
    "kubernetes.io/role/internal-elb"           = "1"
  }
}
</code>```

Body:
I have a VPC, 4 subnets (2 public and 2 private) and an EKS Cluster which all created with Terraform. My infra is working without a problem right now. I'm thinking about creating a second EKS Cluster, but I'm a little bit confused about subnet tagging.

For example, one of my private subnets was created like below;

resource "aws_subnet" "vpc-private" {
  vpc_id            = aws_vpc.vpc.id
  cidr_block        = var.private_cidr
  availability_zone = data.aws_availability_zones.available.names[0]

  tags = {
    Environment                                 = var.environment
    Name                                        = "${var.environment}-vpc-private"
    "kubernetes.io/cluster/${var.cluster_name}" = "shared"
    "kubernetes.io/role/internal-elb"           = "1"
  }
}

As you can see, it's tagged with "kubernetes.io/cluster/${var.cluster_name}" = "shared" to enable subnet discovery. Since I'm thinking about creating second cluster for the same subnets, I'm trying to clarify how should subnets be tagged. There is no clear information in AWS documents, at least I didn't find anything clear about this situation. Will adding the second tag like "kubernetes.io/cluster/${var.cluster_2_name}" = "shared" be alright like below ?

resource "aws_subnet" "vpc-private" {
  vpc_id            = aws_vpc.vpc.id
  cidr_block        = var.private_cidr
  availability_zone = data.aws_availability_zones.available.names[0]

  tags = {
    Environment                                 = var.environment
    Name                                        = "${var.environment}-vpc-private"
    "kubernetes.io/cluster/${var.cluster_name}" = "shared"
    "kubernetes.io/cluster/${var.cluster_2_name}" = "shared"
    "kubernetes.io/role/internal-elb"           = "1"
  }
}

Any help/recommendation will be highly appreciated, thank you very much.

Body:
To answer my own question, yes tagging the subnet for each EKS Cluster is needed, otherwise load balancers couldn't find where to provision.

In Terraform, I used exact format I asked above

resource "aws_subnet" "vpc-private" {
  vpc_id            = aws_vpc.vpc.id
  cidr_block        = var.private_cidr
  availability_zone = data.aws_availability_zones.available.names[0]

  tags = {
    Environment                                 = var.environment
    Name                                        = "${var.environment}-vpc-private"
    "kubernetes.io/cluster/${var.cluster_name}" = "shared"
    "kubernetes.io/cluster/${var.cluster_2_name}" = "shared"
    "kubernetes.io/role/internal-elb"           = "1"
  }
}


问:
If-Else Branches not executing - Python 3
I am working through a problem asking me to define a function that mixes two primary colours. I am wondering why, when i execute the program calling the function, it is only executing the first "if" branch and does not execute any of the other statements. My code is as follows:</p>
```<code>    if "red" and "blue":
        result = "fuchsia"
    elif "red" and "green":
        result = "yellow"
    elif "green" and "blue":
        result = "aqua"
    elif "red" and "red":
        result = "red"
    elif "blue" and "blue":
        result = 'blue'
    elif "green" and "green":
        result = "green"
    else:
        result = "Error"
    return result
</code>```

答:
An "if" statement checks if the statement evaluates to True or False. You are trying to check if the string "red" and the string "blue" are True. Non-empty strings evaluate to True, so your program will always return fuchsia. If you had two variables, each with a color, you could substitute each if statement to be like</p>
```<code>if color1 == "red" and color2 == "blue"
</code>```

Body:
I am working through a problem asking me to define a function that mixes two primary colours. I am wondering why, when i execute the program calling the function, it is only executing the first "if" branch and does not execute any of the other statements. My code is as follows:

    if "red" and "blue":
        result = "fuchsia"
    elif "red" and "green":
        result = "yellow"
    elif "green" and "blue":
        result = "aqua"
    elif "red" and "red":
        result = "red"
    elif "blue" and "blue":
        result = 'blue'
    elif "green" and "green":
        result = "green"
    else:
        result = "Error"
    return result

Body:
An "if" statement checks if the statement evaluates to True or False. You are trying to check if the string "red" and the string "blue" are True. Non-empty strings evaluate to True, so your program will always return fuchsia. If you had two variables, each with a color, you could substitute each if statement to be like

if color1 == "red" and color2 == "blue"


问:
Finding duplicates in Dataframe and returning 1s and 0s
```<code>import pandas as pd
data_list = [['Name', 'Fruit'],
              ['Abel', 'Apple'],
              ['Abel', 'Pear'],
              ['Abel', 'Coconut'],
              ['Abel', 'Pear'],
              ['Benny', 'Apple'],
              ['Benny', 'Apple'],
              ['Cain', 'Apple'],
              ['Cain', 'Coconut'],
              ['Cain', 'Pear'],
              ['Cain', 'Lemon'],
              ['Cain', 'Orange']]

record_df = pd.DataFrame(data_list[1:], columns = data_list[0])
</code>```

I am trying to create another DataFrame to tell me if someone has the same fruit.

Expected Output:

```<code>Name | Repeated_Fruits
Abel | 1
Benny| 1
Cain | 0
</code>```

I have tried

```<code>bool_series = record_df.duplicated(subset=['Name'], keep=False)
record_df_2 = record_df[~bool_series]
</code>```

But everything is True. What am I missing?

答:
The subset parameter is for saying where you're looking for duplicates, so it should be 'Fruit'. The name column is what you want to group by, so you can do:

```<code>record_df.groupby('Name').apply(lambda x: x.duplicated().sum())

Name
Abel     1
Benny    1
Cain     0
dtype: int64
</code>```

You say that you want 0 and 1 as output, but this will give larger numbers if there are more than one duplicate.

Body:
import pandas as pd
data_list = [['Name', 'Fruit'],
              ['Abel', 'Apple'],
              ['Abel', 'Pear'],
              ['Abel', 'Coconut'],
              ['Abel', 'Pear'],
              ['Benny', 'Apple'],
              ['Benny', 'Apple'],
              ['Cain', 'Apple'],
              ['Cain', 'Coconut'],
              ['Cain', 'Pear'],
              ['Cain', 'Lemon'],
              ['Cain', 'Orange']]

record_df = pd.DataFrame(data_list[1:], columns = data_list[0])

I am trying to create another DataFrame to tell me if someone has the same fruit.

Expected Output:

Name | Repeated_Fruits
Abel | 1
Benny| 1
Cain | 0

I have tried

bool_series = record_df.duplicated(subset=['Name'], keep=False)
record_df_2 = record_df[~bool_series]

But everything is True. What am I missing?

Body:
The subset parameter is for saying where you're looking for duplicates, so it should be 'Fruit'. The name column is what you want to group by, so you can do:

record_df.groupby('Name').apply(lambda x: x.duplicated().sum())

Name
Abel     1
Benny    1
Cain     0
dtype: int64

You say that you want 0 and 1 as output, but this will give larger numbers if there are more than one duplicate.


答:
You can do pd.crosstab

```<code>out = pd.crosstab(df.Name, df.Fruit).gt(1).sum(axis=1).reset_index(name='rep_name')
Out[10]:
    Name  rep_name
0   Abel         1
1  Benny         1
2   Cain         0
</code>```

Title: Finding duplicates in Dataframe and returning 1s and 0s

Body:
You can do pd.crosstab

out = pd.crosstab(df.Name, df.Fruit).gt(1).sum(axis=1).reset_index(name='rep_name')
Out[10]:
    Name  rep_name
0   Abel         1
1  Benny         1
2   Cain         0


问:
ST_EQUALS is not returning correct result?
I've come to these weird results when running ST_EQUALS on two Polygons:

```<code>SELECT ST_EQUALS(
ST_GEOMFROMTEXT(
'POLYGON((81.65 34.8667,81.65 5.9167,75.9833 34.8667,75.9833 5.9167,81.65 34.8667))',4326),
ST_GEOMFROMTEXT(
'POLYGON((81.65 34.8667,81.65 5.9167,75.9833 34.8667,75.9833 5.9167,81.65 34.8667))',4326));
</code>```

The coordinates of the polygon are exactly alike and yet MYSQL returns 0 indicating they are not equal.

When I ran the query without SRID (default = 0),

```<code>SELECT ST_EQUALS(
ST_GEOMFROMTEXT(
'POLYGON((81.65 34.8667,81.65 5.9167,75.9833 34.8667,75.9833 5.9167,81.65 34.8667))'),
ST_GEOMFROMTEXT(
'POLYGON((81.65 34.8667,81.65 5.9167,75.9833 34.8667,75.9833 5.9167,81.65 34.8667))'));
</code>```

MySQL returns 1 indicating they are indeed equal.

Is there something I'm missing here? Thank you.

答:
It is an invalid polygon:

```<code>SELECT ST_IsValid(ST_GEOMFROMTEXT('POLYGON((81.65 34.8667,81.65 5.9167,75.9833 34.8667,75.9833 5.9167,81.65 34.8667))',4326)) AS v

0
</code>```

And with invalid geometries, the result of any geospatial function is undefined - it could give correct result, or could give random value. It seems to work as you expected with geometric SRID (0), and give different result with geodesic SRID (4326).

See this for more details on valid geometries:
https://dev.mysql.com/doc/refman/5.7/en/geometry-well-formedness-validity.html

The rule Polygons are not self-intersecting is broken here.

With invalid geometry, this doc says "Due to the computational expense, MySQL does not check explicitly for geometric validity. Spatial computations may detect some cases of invalid geometries and raise an error, but they may also return an undefined result without detecting the invalidity."

Body:
I've come to these weird results when running ST_EQUALS on two Polygons:

SELECT ST_EQUALS(
ST_GEOMFROMTEXT(
'POLYGON((81.65 34.8667,81.65 5.9167,75.9833 34.8667,75.9833 5.9167,81.65 34.8667))',4326),
ST_GEOMFROMTEXT(
'POLYGON((81.65 34.8667,81.65 5.9167,75.9833 34.8667,75.9833 5.9167,81.65 34.8667))',4326));

The coordinates of the polygon are exactly alike and yet MYSQL returns 0 indicating they are not equal.

When I ran the query without SRID (default = 0),

SELECT ST_EQUALS(
ST_GEOMFROMTEXT(
'POLYGON((81.65 34.8667,81.65 5.9167,75.9833 34.8667,75.9833 5.9167,81.65 34.8667))'),
ST_GEOMFROMTEXT(
'POLYGON((81.65 34.8667,81.65 5.9167,75.9833 34.8667,75.9833 5.9167,81.65 34.8667))'));

MySQL returns 1 indicating they are indeed equal.

Is there something I'm missing here? Thank you.

Body:
It is an invalid polygon:

SELECT ST_IsValid(ST_GEOMFROMTEXT('POLYGON((81.65 34.8667,81.65 5.9167,75.9833 34.8667,75.9833 5.9167,81.65 34.8667))',4326)) AS v

0

And with invalid geometries, the result of any geospatial function is undefined - it could give correct result, or could give random value. It seems to work as you expected with geometric SRID (0), and give different result with geodesic SRID (4326).

See this for more details on valid geometries:
https://dev.mysql.com/doc/refman/5.7/en/geometry-well-formedness-validity.html

The rule Polygons are not self-intersecting is broken here.

With invalid geometry, this doc says "Due to the computational expense, MySQL does not check explicitly for geometric validity. Spatial computations may detect some cases of invalid geometries and raise an error, but they may also return an undefined result without detecting the invalidity."


问:
Rust static lifetime conflicting anonymous
I'm trying to mock a trait for testing, but ATM not able to implement a function.

I use the crate mockall.

Error msg is:

```<code>cannot infer an appropriate lifetime due to conflicting requirements
but, the lifetime must be valid for the static lifetime...
expected `&mut __get_mapping::Expectation<'_>`
   found `&mut __get_mapping::Expectation<'static>`
</code>```

I'm aware that the problem is, a lifetime conflict.
But the item passed to the closure already has an anonymous lifetime, even if I do not state it explicitly.

I tried to find some examples with a solution or hints....
But I could not find a solution.

Is there a way to specify that the returning item has a lifetime other than static?
I also tried specifying the lifetime of the return type of the closure, but the error was still the same.

My code so far is:

#[mockall::automock]
pub trait Analyzer {
    //...
    fn get_mapping<'a>(&'a self, old: &Item) -> Option<&'a Item>;
    //...
}

fn test() {
    let mut analyzer = MockAnalyzer::new();
    analyzer.expect_get_mapping().returning(|item:&'_ Item| Some(item));
    // also tried ... returning(|item:&'_ Item| -> Option<&'_ Item> {Some(item)})
    // my initial code was ... returning(|item| Some(item))
    //...
}

```

答:
If your Item is Clone, you might get away with the following:

analyzer
    .expect_get_mapping()
    .returning(|item: &'_ Item| Some(Box::leak(Box::new(item.clone()))));
```

This does indeed leak heap memory, so if your test code executes this more than a few 10 million times, it may cause trouble.

Body:
I'm trying to mock a trait for testing, but ATM not able to implement a function.

I use the crate mockall.

Error msg is:

cannot infer an appropriate lifetime due to conflicting requirements
but, the lifetime must be valid for the static lifetime...
expected `&mut __get_mapping::Expectation<'_>`
   found `&mut __get_mapping::Expectation<'static>`

I'm aware that the problem is, a lifetime conflict.
But the item passed to the closure already has an anonymous lifetime, even if I do not state it explicitly.

I tried to find some examples with a solution or hints....
But I could not find a solution.

Is there a way to specify that the returning item has a lifetime other than static?
I also tried specifying the lifetime of the return type of the closure, but the error was still the same.

My code so far is:

#[mockall::automock]
pub trait Analyzer {
    //...
    fn get_mapping<'a>(&'a self, old: &Item) -> Option<&'a Item>;
    //...
}

fn test() {
    let mut analyzer = MockAnalyzer::new();
    analyzer.expect_get_mapping().returning(|item:&'_ Item| Some(item));
    // also tried ... returning(|item:&'_ Item| -> Option<&'_ Item> {Some(item)})
    // my initial code was ... returning(|item| Some(item))
    //...
}

Body:
If your Item is Clone, you might get away with the following:

analyzer
    .expect_get_mapping()
    .returning(|item: &'_ Item| Some(Box::leak(Box::new(item.clone()))));

This does indeed leak heap memory, so if your test code executes this more than a few 10 million times, it may cause trouble.


问:
Is it OK to show localized pricing information in an ios app
I've read in a number of places (ie. http://iphoneincubator.com/blog/app-store/rejections) that you should not include price information in your app for either the "full version" or in app purchases.

The reasoning is generally that the apps are sold globally, and prices and currency vary by region.

I've used the localized currency value (I'm actually using MKStoreKit, it's great and you should try it), and I'm wondering if anyone has displayed localized price information in their app and had it pass app store submission?

I'd sure like to include the price in my promotional view for my IAP, but I don't want to be rejected for doing so.

答: Using the official Store Kit Framework is the recommended way of doing it. It is advised that you don't display prices outside of this value as it can be confusing to customers. Through iTunesConnect, you can adjust prices remotely so there is never an un-localized, or conflicting price. In fact, I think you could even be rejected for higher priced items if you don't tell the user how much an in-app purchase is.


问:
Replace every letter in a string using dictionary values
coders of the internet,

The goal of this assignment was to replace the letters of a sequence with their opposite. 'A' would be 'U', 'C' would be 'G', and vice versa. Here is the string that I came up with so far, but the output is wrong. I can't find a pattern in the output, so I can't reverse-engineer the problem.

```<code>sequence = input('Please enter a sequence: ')
def reverse(sequence):
  dic = { ' A ' : ' U ' , ' G ' : ' C ' , ' C ' : ' G ' , ' U ' : ' A ' }
  for i in range( len ( sequence ) ):
    if sequence[i] in dic.keys():
      sequence = sequence.replace(sequence[i], dic[sequence[i]])
  return sequence
reverse(sequence)
</code>```

Does anyone know how to simply return turn an input (let's just use "GUGU"), and make the code return the output: "CACA"?

答:
When you have circular replacements, you need to only convert each letter once.  The translate method can do that for you (better than replace):

```<code>dic = { ' A ' : ' U ' , ' G ' : ' C ' , ' C ' : ' G ' , ' U ' : ' A ' }

sequence = sequence.translate({ord(k):ord(v) for k,v in dic.items()})
</code>```

You could also use maketrans to setup the mapping:

```<code>mapping = str.maketrans("AGCU","UCGA")

sequence  = sequence.translate(mapping)
</code>```

without translate or replace, you could use the dictionary on each individual character and join the converted characters:

```<code>sequence = "".join(dic.get(c,c) for c in sequence)
</code>```

Body:
coders of the internet,

The goal of this assignment was to replace the letters of a sequence with their opposite. 'A' would be 'U', 'C' would be 'G', and vice versa. Here is the string that I came up with so far, but the output is wrong. I can't find a pattern in the output, so I can't reverse-engineer the problem.

sequence = input('Please enter a sequence: ')
def reverse(sequence):
  dic = { ' A ' : ' U ' , ' G ' : ' C ' , ' C ' : ' G ' , ' U ' : ' A ' }
  for i in range( len ( sequence ) ):
    if sequence[i] in dic.keys():
      sequence = sequence.replace(sequence[i], dic[sequence[i]])
  return sequence
reverse(sequence)

Does anyone know how to simply return turn an input (let's just use "GUGU"), and make the code return the output: "CACA"?

Body:
When you have circular replacements, you need to only convert each letter once.  The translate method can do that for you (better than replace):

dic = { ' A ' : ' U ' , ' G ' : ' C ' , ' C ' : ' G ' , ' U ' : ' A ' }

sequence = sequence.translate({ord(k):ord(v) for k,v in dic.items()})

You could also use maketrans to setup the mapping:

mapping = str.maketrans("AGCU","UCGA")

sequence  = sequence.translate(mapping)

without translate or replace, you could use the dictionary on each individual character and join the converted characters:

sequence = "".join(dic.get(c,c) for c in sequence)


问:
Efficient Node Enumeration, SceneKit SWIFT
I have a very large tree structure of nodes for some of my animation models. As such, the below code can sometimes filter through 1000+ nodes. If I'm doing that quickly, it can overwhelm my app. Is there a way to confine the rootNode search to only the top level or two and not the entire tree structure?</p>
```<code>self.sceneView.scene.rootNode.enumerateChildNodes { (node, stop) in
            if node.name == "myRootNode" {
         //This is the node to manipulate
      }

}
</code>```

答:
If you want to search just the top level use func childNode(withName name: String, recursively: Bool). If you want to search two levels:

```<code>if let node = self.sceneView.scene.rootNode.childNode(withName: "myRootNode", recursively: false) {
  // Do whatever you need to do
} else {
  for node in self.sceneView.scene.rootNode.children {
     if let node = node.childNode(withName: "myRootNode", recursively: false) {
         // Do whatever you need to do
         break
     }
  }
}
</code>```

Body:
I have a very large tree structure of nodes for some of my animation models. As such, the below code can sometimes filter through 1000+ nodes. If I'm doing that quickly, it can overwhelm my app. Is there a way to confine the rootNode search to only the top level or two and not the entire tree structure?

self.sceneView.scene.rootNode.enumerateChildNodes { (node, stop) in
            if node.name == "myRootNode" {
         //This is the node to manipulate
      }

}

Body:
If you want to search just the top level use func childNode(withName name: String, recursively: Bool). If you want to search two levels:

if let node = self.sceneView.scene.rootNode.childNode(withName: "myRootNode", recursively: false) {
  // Do whatever you need to do
} else {
  for node in self.sceneView.scene.rootNode.children {
     if let node = node.childNode(withName: "myRootNode", recursively: false) {
         // Do whatever you need to do
         break
     }
  }
}


问:
If Statement Not Returning an Output
I am finishing an assignment for Introduction to Java and have been stuck for hours.

When I run the code below, enter the integers and hit enter, I do not get anything in the output. Please help!

```<code>import java.util.Scanner;

public class U3A1_DebugFixIFStmts {

    public static void main(String[] args) {

        System.out.println("If Statements");
        Scanner input = new Scanner(System.in);

        // Prompt User to Enter Three Integers
        System.out.print("Enter three integers: ");
        int firstChoice = input.nextInt();
        int secondChoice = input.nextInt();
        int thirdChoice = input.nextInt();

        //Determine & print the state of choices made
        if (firstChoice == 0)
        {System.out.println("State of choices: \n" +
                    "no choices made yet");}
        else if (secondChoice == 0)
        {System.out.println("State of choices: \n" +
                    "user made first choice (" + firstChoice + ")\n" +
                    "number of choices = 1");}
        else if (thirdChoice == 0)
        {System.out.println("State of choices: \n" +
                    "user made first choice (" + firstChoice + ")\n" +
                    "user made second choice (" + secondChoice + ")\n" +
                    "number of choices = 2");}

        else
        {System.out.println("State of choices: \n" +
                    "user made first choice (" + firstChoice + ")\n" +
                    "user made second choice (" + secondChoice + ")\n" +
                    "user made third choice (" + thirdChoice + ")\n" +
                    "number of choices = 3");}

    }
}
</code>```

答:
```<code>int firstChoice = input.nextInt();
int secondChoice = input.nextInt();
int thirdChoice = input.nextInt();
</code>```

These three lines of your codes require your input before your program moves ahead. Hence, give 3 numbers and then you'll see it work.

Title: If Statement Not Returning an Output

Body:
I am finishing an assignment for Introduction to Java and have been stuck for hours.

When I run the code below, enter the integers and hit enter, I do not get anything in the output. Please help!

import java.util.Scanner;

public class U3A1_DebugFixIFStmts {

    public static void main(String[] args) {

        System.out.println("If Statements");
        Scanner input = new Scanner(System.in);

        // Prompt User to Enter Three Integers
        System.out.print("Enter three integers: ");
        int firstChoice = input.nextInt();
        int secondChoice = input.nextInt();
        int thirdChoice = input.nextInt();

        //Determine & print the state of choices made
        if (firstChoice == 0)
        {System.out.println("State of choices: \n" +
                    "no choices made yet");}
        else if (secondChoice == 0)
        {System.out.println("State of choices: \n" +
                    "user made first choice (" + firstChoice + ")\n" +
                    "number of choices = 1");}
        else if (thirdChoice == 0)
        {System.out.println("State of choices: \n" +
                    "user made first choice (" + firstChoice + ")\n" +
                    "user made second choice (" + secondChoice + ")\n" +
                    "number of choices = 2");}

        else
        {System.out.println("State of choices: \n" +
                    "user made first choice (" + firstChoice + ")\n" +
                    "user made second choice (" + secondChoice + ")\n" +
                    "user made third choice (" + thirdChoice + ")\n" +
                    "number of choices = 3");}

    }
}

Body:
int firstChoice = input.nextInt();
int secondChoice = input.nextInt();
int thirdChoice = input.nextInt();

These three lines of your codes require your input before your program moves ahead. Hence, give 3 numbers and then you'll see it work.


答:
I am seeing two issues:

replace affects all occurrences. That i is only used for evaluating the arguments (sequence[i] and dic[sequence[i]]), but once they are evaluated, the call is equivalent to e.g. sequence.replace("A", "U"), and then all occurrences of A are replaced with U, not just the once at index i.

Keys and values in the dictionary are wrapped with spaces. Assuming the sequence is something like ACCAGUUA, there are no matches, due to those spaces.

Title: Replace every letter in a string using dictionary values


问:
Icon toggle disappears on refresh
I'm trying to toggle between a moon icon and a sun icon on a dark mode project. The original javascript code was simply a button that switched from day mode to dark mode. After some research, I ended up with the following code, which "kinda" works but is sketchy; it switches from day mode to dark mode and the icon toggles from moon to sun BUT, when I come back to the page after setting my preference as dark mode (or refreshing the page in dark mode), the icon disappears.

```<code>const btn = document.querySelector(".btn-mode");
const icon = document.querySelector(".mode");
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");

const currentTheme = localStorage.getItem("theme");
if (currentTheme == "dark") {
  document.body.classList.toggle("dark-theme");
  icon.classList.toggle("fa-sun-o");
} else if (currentTheme == "light") {
  document.body.classList.toggle("light-theme");
  icon.classList.toggle("fa-moon-o");
}

btn.addEventListener("click", function () {
  if (prefersDarkScheme.matches) {
    document.body.classList.toggle("light-theme");
    var theme = document.body.classList.contains("light-theme")
      ? "light"
      : "dark";
    icon.classList.toggle("fa-sun-o");
  } else {
    document.body.classList.toggle("dark-theme");
    var theme = document.body.classList.contains("dark-theme")
      ? "dark"
      : "light";
    icon.classList.toggle("fa-moon-o");
  }
  localStorage.setItem("theme", theme);
});
</code>```

Any idea what I am missing here?

I created a codepen to show the issue

答:
You need to toggle both classes each time you want to make a switch.

Your code was using the toggle method as though it would swap moon for sun but it really just toggles whether the individual class is there. I've toggled both classes when we need to make a change, and commented out the local storage stuff to avoid JS errors with the SO snippet, but otherwise didn't change your code.

const btn = document.querySelector(".btn-mode");
const icon = document.querySelector(".mode");
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");

// const currentTheme = localStorage.getItem("theme");
// if (currentTheme == "dark") {
//   document.body.classList.toggle("dark-theme");
//   icon.classList.toggle("fa-moon-o");
// }

btn.addEventListener("click", function() {
  if (prefersDarkScheme.matches) {
    document.body.classList.toggle("light-theme");
    var theme = document.body.classList.contains("light-theme") ?
      "light" :
      "dark";
  } else {
    document.body.classList.toggle("dark-theme");
    var theme = document.body.classList.contains("dark-theme") ?
      "dark" :
      "light";
  }
  icon.classList.toggle("fa-moon-o");
  icon.classList.toggle("fa-sun-o");
  // localStorage.setItem("theme", theme);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  --text-color: #555;
  --bkg-color: #fff;
}

body.dark-theme {
  --text-color: #999;
  --bkg-color: #222;
}

body {
  background: var(--bkg-color, #fff);
  color: var(--text-color, #555);
}

.btn-mode {
  background: #000;
  font-size: 20px;
  padding: 10px 10px;
  width: 50px;
  cursor: pointer;
  color: #fff;
  display: block;
  text-align: center;
}

.btn-mode:hover {
  color: #da0000;
}</code>```

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

Some title

</body ```

Title: Icon toggle disappears on refresh

Body:
I'm trying to toggle between a moon icon and a sun icon on a dark mode project. The original javascript code was simply a button that switched from day mode to dark mode. After some research, I ended up with the following code, which "kinda" works but is sketchy; it switches from day mode to dark mode and the icon toggles from moon to sun BUT, when I come back to the page after setting my preference as dark mode (or refreshing the page in dark mode), the icon disappears.

const btn = document.querySelector(".btn-mode");
const icon = document.querySelector(".mode");
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");

const currentTheme = localStorage.getItem("theme");
if (currentTheme == "dark") {
  document.body.classList.toggle("dark-theme");
  icon.classList.toggle("fa-sun-o");
} else if (currentTheme == "light") {
  document.body.classList.toggle("light-theme");
  icon.classList.toggle("fa-moon-o");
}

btn.addEventListener("click", function () {
  if (prefersDarkScheme.matches) {
    document.body.classList.toggle("light-theme");
    var theme = document.body.classList.contains("light-theme")
      ? "light"
      : "dark";
    icon.classList.toggle("fa-sun-o");
  } else {
    document.body.classList.toggle("dark-theme");
    var theme = document.body.classList.contains("dark-theme")
      ? "dark"
      : "light";
    icon.classList.toggle("fa-moon-o");
  }
  localStorage.setItem("theme", theme);
});

Any idea what I am missing here?

I created a codepen to show the issue

Body:
You need to toggle both classes each time you want to make a switch.

Your code was using the toggle method as though it would swap moon for sun but it really just toggles whether the individual class is there. I've toggled both classes when we need to make a change, and commented out the local storage stuff to avoid JS errors with the SO snippet, but otherwise didn't change your code.

const btn = document.querySelector(".btn-mode");
const icon = document.querySelector(".mode");
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");

// const currentTheme = localStorage.getItem("theme");
// if (currentTheme == "dark") {
//   document.body.classList.toggle("dark-theme");
//   icon.classList.toggle("fa-moon-o");
// }

btn.addEventListener("click", function() {
  if (prefersDarkScheme.matches) {
    document.body.classList.toggle("light-theme");
    var theme = document.body.classList.contains("light-theme") ?
      "light" :
      "dark";
  } else {
    document.body.classList.toggle("dark-theme");
    var theme = document.body.classList.contains("dark-theme") ?
      "dark" :
      "light";
  }
  icon.classList.toggle("fa-moon-o");
  icon.classList.toggle("fa-sun-o");
  // localStorage.setItem("theme", theme);
});

body {
  --text-color: #555;
  --bkg-color: #fff;
}

body.dark-theme {
  --text-color: #999;
  --bkg-color: #222;
}

body {
  background: var(--bkg-color, #fff);
  color: var(--text-color, #555);
}

.btn-mode {
  background: #000;
  font-size: 20px;
  padding: 10px 10px;
  width: 50px;
  cursor: pointer;
  color: #fff;
  display: block;
  text-align: center;
}

.btn-mode:hover {
  color: #da0000;
}

<html>

<head>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</head>

<body class="light-theme">
  <h1>Some title</h1>
  <ul>
    <li class="btn-mode">
      <i class="mode fa fa-sun-o"></i>
    </li>
  </ul>
</body </html>


问:
Why strings are not read correctly using easydict？
I use the easydict library to set the configurations, but when I store the configuration as strings, it turns the string into a list of the string itself, as follows:

```<code>from easydict import EasyDict
conf = EasyDict()
conf.name = 'CD Group'
print(conf.name)

> ['CD Group']    # a list
</code>```

But what I hope to achieve is:

```<code>> CD Group    # string type
</code>```

Why is it like this?
Thanks for any feedback!

easydict source

An interesting point is that when I pass the configuration from the argparse into the easydict, the type doesn't get an error, as follow:

```<code>conf.file_name = args.file_name    # --file_name input.xlsx
print(conf.file_name)

> input.xlsx
</code>```

答:
looking at __setattr__

```<code>    def __setattr__(self, name, value):
        if isinstance(value, (list, tuple)):
            value = [self.__class__(x)
                     if isinstance(x, dict) else x for x in value]
        elif isinstance(value, dict) and not isinstance(value, self.__class__):
            value = self.__class__(value)
</code>```

as you can see in __setattr__ method , if you pass a variable as list or tuple , you get a list, if not you get the original type back.

and I don't have the problem you are mentioning :

```<code>conf = EasyDict()
conf.name = 'CD Group'
conf.name2 = ['CD Group']
print(conf.name , conf.name2, sep='\n')
</code>```

output:

```<code>>>
CD Group
['CD Group']
</code>```

Body:
I use the easydict library to set the configurations, but when I store the configuration as strings, it turns the string into a list of the string itself, as follows:

from easydict import EasyDict
conf = EasyDict()
conf.name = 'CD Group'
print(conf.name)

> ['CD Group']    # a list

But what I hope to achieve is:

> CD Group    # string type

Why is it like this?
Thanks for any feedback!

easydict source

An interesting point is that when I pass the configuration from the argparse into the easydict, the type doesn't get an error, as follow:

conf.file_name = args.file_name    # --file_name input.xlsx
print(conf.file_name)

> input.xlsx

Body:
looking at __setattr__

    def __setattr__(self, name, value):
        if isinstance(value, (list, tuple)):
            value = [self.__class__(x)
                     if isinstance(x, dict) else x for x in value]
        elif isinstance(value, dict) and not isinstance(value, self.__class__):
            value = self.__class__(value)

as you can see in __setattr__ method , if you pass a variable as list or tuple , you get a list, if not you get the original type back.

and I don't have the problem you are mentioning :

conf = EasyDict()
conf.name = 'CD Group'
conf.name2 = ['CD Group']
print(conf.name , conf.name2, sep='\n')

output:

>>
CD Group
['CD Group']


问:
PHP error connecting to MS SQL database using PDO_DBLIB
I am attempting to use PHP's PDO_DBLIB driver to connect to a remote database and am having some issues.

The database is connectable via the same environment using telnet and a SQL client. However, connecting using the following code in PHP does not work:

```<code><?php
$conn = new PDO('dblib:dbname=TestDB;host=RemoteServer;charset=utf8', 'my_user', 'my_pass');
</code>```

Running this code, whether it be from the command line or Apache, yields the following error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] Unable to connect: Adaptive Server is unavailable or does not exist (severity 9)'

I am able to connect to the database using the same code on a different web server, which leads me to believe that it's a configuration issue. The php.ini files on the two servers look relatively the same. They each have the same PDO libraries enabled with the same options configured.

Does anyone have any idea why this could be happening?

答:
Turns out that it was a much simpler issue than I thought. For whatever reason, the development server was not using Port 1433 as the default port in the connection and was instead using Port 4000.

I discovered this by enabling the logs in the freetds.conf file and monitoring them as I was making the request.

Also, something to note: The DBLIB extension uses a colon (:) as a separator between the host and the port instead of the comma. Unfortunately, the error that you receive when you use a comma isn't very descriptive, so hopefully someone benefits from this discovery.

Body:
I am attempting to use PHP's PDO_DBLIB driver to connect to a remote database and am having some issues.

The database is connectable via the same environment using telnet and a SQL client. However, connecting using the following code in PHP does not work:

<?php
$conn = new PDO('dblib:dbname=TestDB;host=RemoteServer;charset=utf8', 'my_user', 'my_pass');

Running this code, whether it be from the command line or Apache, yields the following error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] Unable to connect: Adaptive Server is unavailable or does not exist (severity 9)'

I am able to connect to the database using the same code on a different web server, which leads me to believe that it's a configuration issue. The php.ini files on the two servers look relatively the same. They each have the same PDO libraries enabled with the same options configured.

Does anyone have any idea why this could be happening?


问:
How can I divide the frequency found from two different summarise function in R?
How can I divide the frequency found from two different summaries?

The code of first summary :

```<code>brfss2013 %>%
  filter( !is.na(income2), Depression == "SignsOfDepression") %>%
  group_by(X_state) %>%
   summarise(depressed=n())
</code>```

Depressed frequency state wise

The code of second summary:

```<code>brfss2013 %>%
  filter( !is.na(income2)) %>%
  group_by(X_state) %>%
   summarise(total=n())
</code>```

total frequency state wise

Now I want to find the relative frequency of "depressed" and "total" state-wise where I divide "depressed"/ "total".

I tried to use the following code:

```<code> brfss2013 %>%
  filter( !is.na(income2)) %>%
  group_by(X_state) %>%
   summarise(ratio = depressed/total)
</code>```

But it does not work.

Can somebody please help me to find the state-wise relative frequency.

答:
```<code>brfss2013 %>%
  filter( !is.na(income2) ) %>%
  group_by(X_state) %>%
  summarise(depressed=sum(Depression == "SignsOfDepression"), total=n()) %>%
  mutate(ratio=depressed/total)
</code>```

Body:
How can I divide the frequency found from two different summaries?

The code of first summary :

brfss2013 %>%
  filter( !is.na(income2), Depression == "SignsOfDepression") %>%
  group_by(X_state) %>%
   summarise(depressed=n())

Depressed frequency state wise

The code of second summary:

brfss2013 %>%
  filter( !is.na(income2)) %>%
  group_by(X_state) %>%
   summarise(total=n())

total frequency state wise

Now I want to find the relative frequency of "depressed" and "total" state-wise where I divide "depressed"/ "total".

I tried to use the following code:

 brfss2013 %>%
  filter( !is.na(income2)) %>%
  group_by(X_state) %>%
   summarise(ratio = depressed/total)

But it does not work.

Can somebody please help me to find the state-wise relative frequency.


问:
Fastest way to remove duplicate points on the edges of polygon?
As shown following, I have a polygon that contains the integer points:

```<code>type
  TPoint = array [1 .. 2] of Integer;
  TPointArray = array of TPoint;
</code>```

The points on edges are given in clock-wise order, and I want to remove the intermediate points (marked as red).

For example, given any continuous 3 points A, B, C if  B is exactly on the line between A and C, then B can be safely removed.

How can I do this in fast and efficient manner?

My Psedu-code is:

```<code>procedure RemovePoints(var pt: TPointArray);
var
  i, j, sz, k, u: integer;
  xoffset, yoffset: integer;
begin
  sz := High(pt);
  i := 0;
  while (True) do
  begin
    Inc(i);
    // points represent array index, so can't be negative,
    // we use -1 to mark deletion
    if (pt[i][1] = -1) then continue;
    if (i = 0) then
    begin
      break; // finish a loop
    end;
    j := i + 1;
    if (j > sz) then
    begin
      j := 0;
    end;
    k := j + 1;
    if (k > sz) then
    begin
      k := 0;
    end;
    if ((pt[i][1] - pt[j][1] = pt[j][1] - pt[k][1]) and ((pt[i][2] - pt[j][2] = pt[j][2] - pt[k][2]))) then
    begin
      // remove pt[j];
      pt[j][1] := -1;
    end;
  end;
  // TODO: shrink the array to remove deleted points
end;
</code>```

答:
been fighting with this problem for few hours and looks like DouglasPeucker with 0 sqTolerance works ok.

```<code>function getSqSegDist(p, p1, p2) {

var x = p1.x,
    y = p1.y,
    dx = p2.x - x,
    dy = p2.y - y;

if (dx !== 0 || dy !== 0) {

    var t = ((p.x - x) * dx + (p.y - y) * dy) / (dx * dx + dy * dy);

    if (t > 1) {
        x = p2.x;
        y = p2.y;

    } else if (t > 0) {
        x += dx * t;
        y += dy * t;
    }
}

dx = p.x - x;
dy = p.y - y;

return dx * dx + dy * dy;
}

function simplifyDPStep(points, first, last, sqTolerance, simplified) {
var maxSqDist = sqTolerance,
    index;

for (var i = first + 1; i < last; i++) {
    var sqDist = getSqSegDist(points[i], points[first], points[last]);

    if (sqDist > maxSqDist) {
        index = i;
        maxSqDist = sqDist;
    }
}

if (maxSqDist > sqTolerance) {
    if (index - first > 1) simplifyDPStep(points, first, index, sqTolerance, simplified);
    simplified.push(points[index]);
    if (last - index > 1) simplifyDPStep(points, index, last, sqTolerance, simplified);
}
}

function simplifyDouglasPeucker(points, sqTolerance) {
var last = points.length - 1;

var simplified = [points[0]];
simplifyDPStep(points, 0, last, sqTolerance, simplified);
simplified.push(points[last]);

return simplified;
}
</code>```

see simplifyDouglasPeucker

Body:
As shown following, I have a polygon that contains the integer points:

type
  TPoint = array [1 .. 2] of Integer;
  TPointArray = array of TPoint;

The points on edges are given in clock-wise order, and I want to remove the intermediate points (marked as red).

For example, given any continuous 3 points A, B, C if  B is exactly on the line between A and C, then B can be safely removed.

How can I do this in fast and efficient manner?

My Psedu-code is:

procedure RemovePoints(var pt: TPointArray);
var
  i, j, sz, k, u: integer;
  xoffset, yoffset: integer;
begin
  sz := High(pt);
  i := 0;
  while (True) do
  begin
    Inc(i);
    // points represent array index, so can't be negative,
    // we use -1 to mark deletion
    if (pt[i][1] = -1) then continue;
    if (i = 0) then
    begin
      break; // finish a loop
    end;
    j := i + 1;
    if (j > sz) then
    begin
      j := 0;
    end;
    k := j + 1;
    if (k > sz) then
    begin
      k := 0;
    end;
    if ((pt[i][1] - pt[j][1] = pt[j][1] - pt[k][1]) and ((pt[i][2] - pt[j][2] = pt[j][2] - pt[k][2]))) then
    begin
      // remove pt[j];
      pt[j][1] := -1;
    end;
  end;
  // TODO: shrink the array to remove deleted points
end;

Body:
been fighting with this problem for few hours and looks like DouglasPeucker with 0 sqTolerance works ok.

function getSqSegDist(p, p1, p2) {

var x = p1.x,
    y = p1.y,
    dx = p2.x - x,
    dy = p2.y - y;

if (dx !== 0 || dy !== 0) {

    var t = ((p.x - x) * dx + (p.y - y) * dy) / (dx * dx + dy * dy);

    if (t > 1) {
        x = p2.x;
        y = p2.y;

    } else if (t > 0) {
        x += dx * t;
        y += dy * t;
    }
}

dx = p.x - x;
dy = p.y - y;

return dx * dx + dy * dy;
}

function simplifyDPStep(points, first, last, sqTolerance, simplified) {
var maxSqDist = sqTolerance,
    index;

for (var i = first + 1; i < last; i++) {
    var sqDist = getSqSegDist(points[i], points[first], points[last]);

    if (sqDist > maxSqDist) {
        index = i;
        maxSqDist = sqDist;
    }
}

if (maxSqDist > sqTolerance) {
    if (index - first > 1) simplifyDPStep(points, first, index, sqTolerance, simplified);
    simplified.push(points[index]);
    if (last - index > 1) simplifyDPStep(points, index, last, sqTolerance, simplified);
}
}

function simplifyDouglasPeucker(points, sqTolerance) {
var last = points.length - 1;

var simplified = [points[0]];
simplifyDPStep(points, 0, last, sqTolerance, simplified);
simplified.push(points[last]);

return simplified;
}

see simplifyDouglasPeucker


答:
Code is below & uses or and and keyword inside if statement to determine the color.

```<code>color1 = "red"
color2 = "green"

def getColor(color1, color2):
    if color1 == "red" and color2 == "blue" or color1=="blue" and color2=="red":
        result = "fuchsia"
    elif color1 == "red" and color2=="green" or color1=="green" and color2== "red":
        result = "yellow"
    elif color1 == "green" and color2 == "blue" or color1 == "blue" and color2 == "green":
        result = "aqua"
    elif color1=="red" and color2=="red":
        result = "red"
    elif color1 == "blue" and color2=="blue":
        result = 'blue'
    elif color1 == "green" and color1=="green":
        result = "green"
    else:
        result = "Error"
    return result

print(getColor(color1, color2))
</code>```

output:

```<code>$ python3 color.py
yellow
</code>```

A better approach use Enum in python to determine the color:

```<code>import enum

color1 = "red"
color2 = "green"

class Color(enum.Enum):
    RED = "RED"
    GREEN = "GREEN"
    BLUE = "BLUE"

def getColor(color1 :Color, color2:Color):
    red = False
    green = False
    blue = False

    red = color1==Color.RED or color2 == Color.RED
    green = color1==Color.GREEN or color2 == Color.GREEN
    blue = color1==Color.BLUE or color2 == Color.BLUE

    if red and blue:
        return "fuchsia"
    if red and green:
        return "yellow"
    if green and blue:
        return "aqua"
    if color1 is Color.RED and color2 is Color.RED:
        return "red"
    if color1 is Color.GREEN and color2 is Color.GREEN:
        return "green"
    if color1 is Color.BLUE and color2 is Color.BLUE:
        return "blue"
    return "Error"
print(getColor(Color.RED, Color.GREEN))
print(getColor(Color.GREEN, Color.RED))
print(getColor(Color.GREEN, Color.GREEN))
</code>```

Output:

```<code>$ python3 color.py
yellow
yellow
green
</code>```

Title: If-Else Branches not executing - Python 3

Body:
I am working through a problem asking me to define a function that mixes two primary colours. I am wondering why, when i execute the program calling the function, it is only executing the first "if" branch and does not execute any of the other statements. My code is as follows:

    if "red" and "blue":
        result = "fuchsia"
    elif "red" and "green":
        result = "yellow"
    elif "green" and "blue":
        result = "aqua"
    elif "red" and "red":
        result = "red"
    elif "blue" and "blue":
        result = 'blue'
    elif "green" and "green":
        result = "green"
    else:
        result = "Error"
    return result

Body:
Code is below & uses or and and keyword inside if statement to determine the color.

color1 = "red"
color2 = "green"

def getColor(color1, color2):
    if color1 == "red" and color2 == "blue" or color1=="blue" and color2=="red":
        result = "fuchsia"
    elif color1 == "red" and color2=="green" or color1=="green" and color2== "red":
        result = "yellow"
    elif color1 == "green" and color2 == "blue" or color1 == "blue" and color2 == "green":
        result = "aqua"
    elif color1=="red" and color2=="red":
        result = "red"
    elif color1 == "blue" and color2=="blue":
        result = 'blue'
    elif color1 == "green" and color1=="green":
        result = "green"
    else:
        result = "Error"
    return result

print(getColor(color1, color2))

output:

$ python3 color.py
yellow

A better approach use Enum in python to determine the color:

import enum

color1 = "red"
color2 = "green"

class Color(enum.Enum):
    RED = "RED"
    GREEN = "GREEN"
    BLUE = "BLUE"

def getColor(color1 :Color, color2:Color):
    red = False
    green = False
    blue = False

    red = color1==Color.RED or color2 == Color.RED
    green = color1==Color.GREEN or color2 == Color.GREEN
    blue = color1==Color.BLUE or color2 == Color.BLUE

    if red and blue:
        return "fuchsia"
    if red and green:
        return "yellow"
    if green and blue:
        return "aqua"
    if color1 is Color.RED and color2 is Color.RED:
        return "red"
    if color1 is Color.GREEN and color2 is Color.GREEN:
        return "green"
    if color1 is Color.BLUE and color2 is Color.BLUE:
        return "blue"
    return "Error"
print(getColor(Color.RED, Color.GREEN))
print(getColor(Color.GREEN, Color.RED))
print(getColor(Color.GREEN, Color.GREEN))

Output:

$ python3 color.py
yellow
yellow
green


问:
NavHostFragment initialization results in NullPointerException
I am attempting to set a navHostFragment in my MainActivity.kt file, but the code below results in the error:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lunchtray/com.example.lunchtray.MainActivity}: java.lang.NullPointerException: null cannot be cast to non-null type androidx.navigation.fragment.NavHostFragment
</code>```
```<code>class MainActivity : AppCompatActivity() {

    private lateinit var navController: NavController

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val navHostFragment = supportFragmentManager // NULL CANNOT BE CAST TO NON NULL TYPE
            .findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        navController = navHostFragment.navController

        setupActionBarWithNavController(navController)
    }

    override fun onSupportNavigateUp(): Boolean {
        return navController.navigateUp() || super.onSupportNavigateUp()
    }
}
</code>```

activity_main.xml layout file:

```<code><androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/mobile_navigation"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

What am I doing wrong?  Similar questions exist on SO but they involve using menu IDs or initializing the navHostFragment from within a fragment, this is a much more straightforward situation and I do not understand why any value should be null.

答:
You forgot to call setContentView(R.layout.activity_main), which means you have no FragmentContainerView and no fragment within it, hence why findFragmentById(R.id.nav_host_fragment) returns null.

```<code>    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val navHostFragment = supportFragmentManager
        .findFragmentById(R.id.nav_host_fragment) as NavHostFragment
    navController = navHostFragment.navController
</code>```

As an alternative, you can also call the AppCompatActivity construct that takes a LayoutRes, which will automatically call setContentView for you as part of super.onCreate():

```<code>class MainActivity : AppCompatActivity(R.ayout.activity_main) {
</code>```

Body:
I am attempting to set a navHostFragment in my MainActivity.kt file, but the code below results in the error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lunchtray/com.example.lunchtray.MainActivity}: java.lang.NullPointerException: null cannot be cast to non-null type androidx.navigation.fragment.NavHostFragment

class MainActivity : AppCompatActivity() {

    private lateinit var navController: NavController

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val navHostFragment = supportFragmentManager // NULL CANNOT BE CAST TO NON NULL TYPE
            .findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        navController = navHostFragment.navController

        setupActionBarWithNavController(navController)
    }

    override fun onSupportNavigateUp(): Boolean {
        return navController.navigateUp() || super.onSupportNavigateUp()
    }
}

activity_main.xml layout file:

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/mobile_navigation"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

What am I doing wrong?  Similar questions exist on SO but they involve using menu IDs or initializing the navHostFragment from within a fragment, this is a much more straightforward situation and I do not understand why any value should be null.

Body:
You forgot to call setContentView(R.layout.activity_main), which means you have no FragmentContainerView and no fragment within it, hence why findFragmentById(R.id.nav_host_fragment) returns null.

    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val navHostFragment = supportFragmentManager
        .findFragmentById(R.id.nav_host_fragment) as NavHostFragment
    navController = navHostFragment.navController

As an alternative, you can also call the AppCompatActivity construct that takes a LayoutRes, which will automatically call setContentView for you as part of super.onCreate():

class MainActivity : AppCompatActivity(R.ayout.activity_main) {


问:
Waiting for update signal from WDS
I am currently trying to create a login page using Twitter authentication for my Vue.js application. I have been following this tutorial and this code. Whenever I run my project, I get

[HMR] Waiting for update signal from WDS...

Any ideas how I can overcome this WDS error? Thank you.

This is the error I receive in the browser's console.

答: In my case, I had an infinite loop at the start of the app as it had some bugs with authentication checks, preventing the Vue app to start correctly.</p>

Title: Waiting for update signal from WDS


问:
Trying to get value determined by javascript using selenium
As title says, I am currently trying to acquire a dynamic value. I am lost as originally I was using beautiful soup and found out the value was dynamic.
Here are how the values are determined

```<code>        .call({from: from})
        .then(function(res) {
            console.log("Node Price (Wei AVAX): " + res);
            const avax = Number(Web3.utils.fromWei(res, 'ether'));
            console.log("Node Price (AVAX): " + avax);
            const items = document.querySelectorAll(".node-info-price-avax");
            items.forEach(i => {
                i.innerHTML = avax.toFixed(2) + " AVAX";
            });
        })
</code>```

Then here is how its displayed,

```<code><span class="node-info-price-avax">27.88 AVAX</span>
</code>```

I've been watching tutorials and reading over guides all day and can not for the love of me figure out how to acquire said value.

答:
I found a pretty detailed video that did exactly what I was looking for.
The solution was finding the data I needed and copying the xpath by using find_element, then I appened it to a list and used pandas to make it look pretty. Here is the finished code:

```<code>from selenium import webdriver
import pandas as pd

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)

driver.get("https://playa3ull.games")

node_data = driver.find_elements_by_class_name('wpb_wrapper')

data_list = []

for data in node_data:
    node_price = data.find_element_by_xpath('//*[@id="pb-node-info-table"]/tbody/tr[6]/td[2]/span[1]').text
    nodes_sold = data.find_element_by_xpath('//*[@id="pb-node-info-table"]/tbody/tr[3]/td[2]').text
    token_price = data.find_element_by_xpath('//*[@id="pb-node-info-table"]/tbody/tr[6]/td[2]/span[2]').text
    data_item = {
        'Node Price': node_price,
        'Nodes Sold': nodes_sold,
        'Token Price': token_price
    }
    data_list.append(data_item)

df = pd.DataFrame(data_list)
df_last = df[-1]
print(df_last)
</code>```

Here is the link for a more detailed explanation: youtube.com/watch?v=lTypMlVBFM4

Body:
As title says, I am currently trying to acquire a dynamic value. I am lost as originally I was using beautiful soup and found out the value was dynamic.
Here are how the values are determined

        .call({from: from})
        .then(function(res) {
            console.log("Node Price (Wei AVAX): " + res);
            const avax = Number(Web3.utils.fromWei(res, 'ether'));
            console.log("Node Price (AVAX): " + avax);
            const items = document.querySelectorAll(".node-info-price-avax");
            items.forEach(i => {
                i.innerHTML = avax.toFixed(2) + " AVAX";
            });
        })

Then here is how its displayed,

27.88 AVAX

I've been watching tutorials and reading over guides all day and can not for the love of me figure out how to acquire said value.

Body:
I found a pretty detailed video that did exactly what I was looking for.
The solution was finding the data I needed and copying the xpath by using find_element, then I appened it to a list and used pandas to make it look pretty. Here is the finished code:

from selenium import webdriver
import pandas as pd

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)

driver.get("https://playa3ull.games")

node_data = driver.find_elements_by_class_name('wpb_wrapper')

data_list = []

for data in node_data:
    node_price = data.find_element_by_xpath('//*[@id="pb-node-info-table"]/tbody/tr[6]/td[2]/span[1]').text
    nodes_sold = data.find_element_by_xpath('//*[@id="pb-node-info-table"]/tbody/tr[3]/td[2]').text
    token_price = data.find_element_by_xpath('//*[@id="pb-node-info-table"]/tbody/tr[6]/td[2]/span[2]').text
    data_item = {
        'Node Price': node_price,
        'Nodes Sold': nodes_sold,
        'Token Price': token_price
    }
    data_list.append(data_item)

df = pd.DataFrame(data_list)
df_last = df[-1]
print(df_last)

Here is the link for a more detailed explanation: youtube.com/watch?v=lTypMlVBFM4