问:
Microsoft Outlook - Add custom parameter authorization-request
I am using Microsoft Outlook rest php api to auth account and get user event.
I want to add custom parameters into the redirect URL.
I did not found any way to add custom parameters into the redirect url.

I am using this outlook/rest/php api - here is the url:

https://learn.microsoft.com/en-us/outlook/rest/php-tutorial#implementing-oauth2

Here is the my controller AuthController.php.

```<code><?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

class AuthController extends Controller
{
  public function signin()
  {
    if (session_status() == PHP_SESSION_NONE) {
      session_start();
    }

    // Initialize the OAuth client
    $oauthClient = new \League\OAuth2\Client\Provider\GenericProvider([
      'clientId'                => env('OAUTH_APP_ID'),
      'clientSecret'            => env('OAUTH_APP_PASSWORD'),
      'redirectUri'             => env('OAUTH_REDIRECT_URI'),
      'urlAuthorize'            => env('OAUTH_AUTHORITY').env('OAUTH_AUTHORIZE_ENDPOINT'),
      'urlAccessToken'          => env('OAUTH_AUTHORITY').env('OAUTH_TOKEN_ENDPOINT'),
      'urlResourceOwnerDetails' => '',
      'scopes'                  => env('OAUTH_SCOPES')
    ]);

    // Output the authorization endpoint
    echo 'Auth URL: '.$oauthClient->getAuthorizationUrl();
    exit();
  }

public function gettoken()
{
  if (session_status() == PHP_SESSION_NONE) {
    session_start();
  }

  // Authorization code should be in the "code" query param
  if (isset($_GET['code'])) {
    // Check that state matches
    if (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth_state'])) {
      exit('State provided in redirect does not match expected value.');
    }

    // Clear saved state
    unset($_SESSION['oauth_state']);

    // Initialize the OAuth client
    $oauthClient = new \League\OAuth2\Client\Provider\GenericProvider([
      'clientId'                => env('OAUTH_APP_ID'),
      'clientSecret'            => env('OAUTH_APP_PASSWORD'),
      'redirectUri'             => env('OAUTH_REDIRECT_URI'),
      'urlAuthorize'            => env('OAUTH_AUTHORITY').env('OAUTH_AUTHORIZE_ENDPOINT'),
      'urlAccessToken'          => env('OAUTH_AUTHORITY').env('OAUTH_TOKEN_ENDPOINT'),
      'urlResourceOwnerDetails' => '',
      'scopes'                  => env('OAUTH_SCOPES')
    ]);

    try {
      // Make the token request
      $accessToken = $oauthClient->getAccessToken('authorization_code', [
        'code' => $_GET['code']
      ]);

      // Save the access token and refresh tokens in session
      // This is for demo purposes only. A better method would
      // be to store the refresh token in a secured database
      $tokenCache = new \App\TokenStore\TokenCache;
      $tokenCache->storeTokens($accessToken->getToken(), $accessToken->getRefreshToken(),
        $accessToken->getExpires());

      // Redirect back to mail page
      return redirect()->route('mail');
    }
    catch (League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
      exit('ERROR getting tokens: '.$e->getMessage());
    }
    exit();
  }
  elseif (isset($_GET['error'])) {
    exit('ERROR: '.$_GET['error'].' - '.$_GET['error_description']);
  }
}
}
</code>```

Here is the .env file details

```<code>OAUTH_APP_ID=YOUR_APP_ID_HERE
OAUTH_APP_PASSWORD=YOUR_APP_PASSWORD_HERE
OAUTH_REDIRECT_URI=http://localhost:8000/authorize
OAUTH_SCOPES='openid profile offline_access User.Read Mail.Read'
OAUTH_AUTHORITY=https://login.microsoftonline.com/common
OAUTH_AUTHORIZE_ENDPOINT=/oauth2/v2.0/authorize
OAUTH_TOKEN_ENDPOINT=/oauth2/v2.0/token

</code>```

Kindly provide me some suggestions how to add custom param.

I need to add custom param with user_id.

答:
I believe the Azure auth folks would recommend using the state parameter, which is designed to do what you want. From https://learn.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow:

state   A value included in the request that will also be returned in the token response. It can be a string of any content that you wish. A randomly generated unique value is typically used for preventing cross-site request forgery attacks. The value can also encode information about the user's state in the app before the authentication request occurred, such as the page or view they were on.

Body:
I am using Microsoft Outlook rest php api to auth account and get user event.
I want to add custom parameters into the redirect URL.
I did not found any way to add custom parameters into the redirect url.

I am using this outlook/rest/php api - here is the url:

https://learn.microsoft.com/en-us/outlook/rest/php-tutorial#implementing-oauth2

Here is the my controller AuthController.php.

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

class AuthController extends Controller
{
  public function signin()
  {
    if (session_status() == PHP_SESSION_NONE) {
      session_start();
    }

    // Initialize the OAuth client
    $oauthClient = new \League\OAuth2\Client\Provider\GenericProvider([
      'clientId'                => env('OAUTH_APP_ID'),
      'clientSecret'            => env('OAUTH_APP_PASSWORD'),
      'redirectUri'             => env('OAUTH_REDIRECT_URI'),
      'urlAuthorize'            => env('OAUTH_AUTHORITY').env('OAUTH_AUTHORIZE_ENDPOINT'),
      'urlAccessToken'          => env('OAUTH_AUTHORITY').env('OAUTH_TOKEN_ENDPOINT'),
      'urlResourceOwnerDetails' => '',
      'scopes'                  => env('OAUTH_SCOPES')
    ]);

    // Output the authorization endpoint
    echo 'Auth URL: '.$oauthClient->getAuthorizationUrl();
    exit();
  }

public function gettoken()
{
  if (session_status() == PHP_SESSION_NONE) {
    session_start();
  }

  // Authorization code should be in the "code" query param
  if (isset($_GET['code'])) {
    // Check that state matches
    if (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth_state'])) {
      exit('State provided in redirect does not match expected value.');
    }

    // Clear saved state
    unset($_SESSION['oauth_state']);

    // Initialize the OAuth client
    $oauthClient = new \League\OAuth2\Client\Provider\GenericProvider([
      'clientId'                => env('OAUTH_APP_ID'),
      'clientSecret'            => env('OAUTH_APP_PASSWORD'),
      'redirectUri'             => env('OAUTH_REDIRECT_URI'),
      'urlAuthorize'            => env('OAUTH_AUTHORITY').env('OAUTH_AUTHORIZE_ENDPOINT'),
      'urlAccessToken'          => env('OAUTH_AUTHORITY').env('OAUTH_TOKEN_ENDPOINT'),
      'urlResourceOwnerDetails' => '',
      'scopes'                  => env('OAUTH_SCOPES')
    ]);

    try {
      // Make the token request
      $accessToken = $oauthClient->getAccessToken('authorization_code', [
        'code' => $_GET['code']
      ]);

      // Save the access token and refresh tokens in session
      // This is for demo purposes only. A better method would
      // be to store the refresh token in a secured database
      $tokenCache = new \App\TokenStore\TokenCache;
      $tokenCache->storeTokens($accessToken->getToken(), $accessToken->getRefreshToken(),
        $accessToken->getExpires());

      // Redirect back to mail page
      return redirect()->route('mail');
    }
    catch (League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
      exit('ERROR getting tokens: '.$e->getMessage());
    }
    exit();
  }
  elseif (isset($_GET['error'])) {
    exit('ERROR: '.$_GET['error'].' - '.$_GET['error_description']);
  }
}
}

Here is the .env file details

OAUTH_APP_ID=YOUR_APP_ID_HERE
OAUTH_APP_PASSWORD=YOUR_APP_PASSWORD_HERE
OAUTH_REDIRECT_URI=http://localhost:8000/authorize
OAUTH_SCOPES='openid profile offline_access User.Read Mail.Read'
OAUTH_AUTHORITY=https://login.microsoftonline.com/common
OAUTH_AUTHORIZE_ENDPOINT=/oauth2/v2.0/authorize
OAUTH_TOKEN_ENDPOINT=/oauth2/v2.0/token

Kindly provide me some suggestions how to add custom param.

I need to add custom param with user_id.


来源: stackexchange

问:
Apply log2 transformation only to numeric columns of a data.frame
I am trying to run a log2 transformation on my data set but I keep getting an error that says "non-numeric variable(s) in data frame". My data has row.names = 1 and header = TRUE and is of class data.frame()

I tried adding lappy(na.strings) but this does not fix the problem

```<code>Shared_DEGs <- cbind(UT.Degs_heatmap[2:11], MT.Degs_heatmap[2:11], HT.Degs_heatmap[2:11])
Shared_DEGs1 <- `row.names<-`(Shared_DEGs, (UT.Degs_heatmap[,1]))
MyData.INF.log2 <- log2(Shared_DEGs1)
</code>```

The data should be log2 transformed as an output

答:
Yet another way using base R's rapply, kindly using the data provided by @r2evans.

```<code>rapply(mydf, f = log2, classes = c("numeric", "integer"), how = "replace")
#       num      int chr  lgl
#1 1.651496 2.321928   A TRUE
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to run a log2 transformation on my data set but I keep getting an error that says "non-numeric variable(s) in data frame". My data has row.names = 1 and header = TRUE and is of class data.frame()

I tried adding lappy(na.strings) but this does not fix the problem

Shared_DEGs <- cbind(UT.Degs_heatmap[2:11], MT.Degs_heatmap[2:11], HT.Degs_heatmap[2:11])
Shared_DEGs1 <- `row.names<-`(Shared_DEGs, (UT.Degs_heatmap[,1]))
MyData.INF.log2 <- log2(Shared_DEGs1)

The data should be log2 transformed as an output

Body:
Yet another way using base R's rapply, kindly using the data provided by @r2evans.

rapply(mydf, f = log2, classes = c("numeric", "integer"), how = "replace")
#       num      int chr  lgl
#1 1.651496 2.321928   A TRUE


问:
Is it possible to determine if a named window is open in JavaScript?
I'm working on an inter-site single-sign-on project and have had a pretty little problem dropped in my lap.  When a user logs out of the "parent" site, a particular page needs to be loaded in the popup window containing the "child" site.  However, I can't store a reference to the return value of window.open(…), because the user must be allowed to navigate wherever they like on each site before logging out.

This would be easy if I could assume that the child site is always open, as another window.open(…) to the same named window would change its URL.  However, the popup cannot be caused to appear if it isn't already open (not all users have access to the child site).

I think this gives me two conflicting scenarios.  When the user visits the child site:

User logs in to parent site.

User clicks link for child site

Child site appears in a window named "child_popup".

User browses far and wide in the parent site, forgetting that the child window exists.

User logs out of parent site.

Child popup is redirected to the child site's logout page.

And when the user does not or cannot visit the child site:

User logs in to parent site.

User browses far and wide in the parent site.

User logs out of the parent site.

No popup should appear!

So my limitations are:

I cannot store a reference to the window in JS, as the user may navigate to any number of pages between visiting the child site and logging out.

I have zero control over the contents of the child site (my employer runs the parent site).

The parent site cannot be converted to frames to provide a "global" JS scope. :-)

I was not able to find any relevant resources on Google or SO.  Is there a way to accomplish this?

答:
Yes, you can, subject to one important restriction.

It hinges on the following behaviour:

the first 2 parameters of window.open are a URL and a window name

window.open returns a reference to a window

if a window is already open with the specified name, then a reference to that window is returned rather than a reference to a new window

If the URL is NULL, an existing window won't navigate to a new page

This means that you can get a reference to an existing window, without losing the page that window has open. However, if a window doesn't exist with that name it will be opened.

We used this approach at http://carbonlogic.co.uk/ but because of a Flash Player issue the contents of the popup aren't working properly at the moment

OwnerDisplayName: Ben Blank

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Gareth


问:
Have fixed parameters in Java constructor - possible?
I've defined an object in Java - as far as the Java is concerned, they're the same thing, but as far as the data which populates them is concerned, they can be one of three types (wildly named 1,2,3 with 0 for the "root").

What I'd really like to be able to do is have four constructors defined, as they need slightly different params for each type. I could do it with strategic nulls, but it seems like the wrong thing to do. What I'd love to have is something like:

```<code>public MenuNode(int type = 1, param1, param2, param3) {
    doStuffHere();
}
public MenuNode(int type = 2, paramX, paramY) {
    doStuffHere();
}
</code>```

and then call something along the lines of:

```<code>switch (toQueue.itemType) {

    when ITEM_TYPE_STATIC {
        MenuNode mn1 = new MenuNode(ITEM_TYPE_STATIC, param1, param2, param3);
    }

    when ITEM_TYPE_DYNAMIC {
        MenuNode mn2 = new MenuNode(ITEM_TYPE_DYNAMIC, paramX, paramY);
    }

}
</code>```

etc etc.

I hope this makes some sort of sense - it's a bit out there, and Googling only comes up with references to public static void etc.
If someone with a bit more experience/know-how with Java than me can take a look, eternal love and gratitude will be forthcoming.

答:
Consider using factory methods to construct your MenuNodes:

```<code>public MenuNode createTypeOneMenuNode(Object param1, Object param2, Object param3) {
    ...
}

public MenuNode createTypeTwoMenuNode(Object paramx, Object paramy) {
    ...
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've defined an object in Java - as far as the Java is concerned, they're the same thing, but as far as the data which populates them is concerned, they can be one of three types (wildly named 1,2,3 with 0 for the "root").

What I'd really like to be able to do is have four constructors defined, as they need slightly different params for each type. I could do it with strategic nulls, but it seems like the wrong thing to do. What I'd love to have is something like:

public MenuNode(int type = 1, param1, param2, param3) {
    doStuffHere();
}
public MenuNode(int type = 2, paramX, paramY) {
    doStuffHere();
}

and then call something along the lines of:

switch (toQueue.itemType) {

    when ITEM_TYPE_STATIC {
        MenuNode mn1 = new MenuNode(ITEM_TYPE_STATIC, param1, param2, param3);
    }

    when ITEM_TYPE_DYNAMIC {
        MenuNode mn2 = new MenuNode(ITEM_TYPE_DYNAMIC, paramX, paramY);
    }

}

etc etc.

I hope this makes some sort of sense - it's a bit out there, and Googling only comes up with references to public static void etc.
If someone with a bit more experience/know-how with Java than me can take a look, eternal love and gratitude will be forthcoming.

Body:
Consider using factory methods to construct your MenuNodes:

public MenuNode createTypeOneMenuNode(Object param1, Object param2, Object param3) {
    ...
}

public MenuNode createTypeTwoMenuNode(Object paramx, Object paramy) {
    ...
}


问:
Retrieving documents on keys using nested query
Started learning NIQL on couchbase. I am trying to retrieve multiple documents based on the keys using following nested query. Can't get it working. Is that even possible ?</p>

```<code>SELECT * FROM Cart USE KEYS (
  SELECT META().id FROM Cart WHERE META().id LIKE "100%"
)
</code>```

答:
USE KEYS expecting array of strings. Subquery generates array of Object of strings.
Use RAW in subquery to remove object when you projecting single field.

You have one of the following options

```<code>SELECT META().id, * FROM Cart WHERE META().id LIKE "100%";
</code>```

OR

```<code>SELECT * FROM Cart USE KEYS (SELECT RAW META().id FROM Cart WHERE META().id LIKE "100%");
</code>```

You can checkout N1QL tutorial https://query-tutorial.couchbase.com/tutorial/#1

Body:
Started learning NIQL on couchbase. I am trying to retrieve multiple documents based on the keys using following nested query. Can't get it working. Is that even possible ?

SELECT * FROM Cart USE KEYS (
  SELECT META().id FROM Cart WHERE META().id LIKE "100%"
)

Body:
USE KEYS expecting array of strings. Subquery generates array of Object of strings.
Use RAW in subquery to remove object when you projecting single field.

You have one of the following options

SELECT META().id, * FROM Cart WHERE META().id LIKE "100%";

OR

SELECT * FROM Cart USE KEYS (SELECT RAW META().id FROM Cart WHERE META().id LIKE "100%");

You can checkout N1QL tutorial https://query-tutorial.couchbase.com/tutorial/#1


问:
Cannot download file PDF from chrome pdf viewer run on 'https server'
Using 'TCPDF' library to generate file pdf, then view with chrome browser as well but when i click download from this viewer I get Feiled - Network Error at bottom of my browser. This problem happen when my server run on SSL. So how could I solve this? plz help.

Image:

答:
If you are using Content-Disposition: inline; filename=..., try changing inline to attachment.

The PDF wouldn't display in browser anymore, but it will download correctly.


问:
Is there a way to change the chromedriver location for Selenium in VBA?
I want to use a chromedriver.exe which is in a different location than the standard installation folder AppData/Local/SeleniumBasic. No I can't just replace it.

I hoped to achieve it using driver.SetPreference("webdriver.chrome.driver", chromedriver) with chromedriver being the path to the chromedriver.exe which unfortunately did not work.

The standard driver in the installation folder is deleted, so VBA naturally throws a FileNotFound-Error, stating that it could not find the chromedriver.exe in AppData/Local/SeleniumBasic.

Could "webdriver.chrome.driver" be a wrong preference? Is it even possible to change the location of the driver in VBA?

答: Yes you can place it elsewhere but then you need to ensure the containing folder (housing the exe) is on the environmental path as this is also searchable by the application.</p>


问:
Why does my objective function in my LP file, generated with Ilog Cplex, contains variables with coefficient equal to 0 ?
I am using Ilog Cplex to solve my problem. I also use it to print out an LP file of my problem in order to solve it again with different parameters later on.

When solving, I want to print out the value of each variable in the objective function. The problem is, the objective function contains variables with a coefficient equal to 0. Therefore, not all the variables in the objective function are relevant to me.

I would like to know :

Why does Cplex add variables with a null coefficient in the objective function ?

Can I remove them somehow ?

If I find a way to print the value of a variable from a partial name, that would also answer my question, since I know part of the name of all relevant variables. For example, I would like to print the value of all variables that contains 'global' in their name. Although, I don't think I can do that with Cplex Interactive Optimizer.

答:
There are several reasons why CPLEX includes all variables in the objective when writing to LP format (even those with a coefficient of zero). One reason is that, when reading in an LP file, some types of constraints require that a variable "exists" before it can be used (note that this is a legacy implementation detail, not necessarily a hard requirement).

For example, consider the following toy LP:

```<code>Minimize
obj: x1 + x2
Subject to
c1: x1 + x2 <= 10
SOS
s1: s1:: x1:1 x2:2 x3:3
End
</code>```

If we try to read this with the interactive, we'll get:

```<code>CPLEX> Warning, line 6: Name 'x3' does not exist.
CPLEX Error  1616: Line 6: Expected identifier, found ':'.
No file read.
</code>```

If we instead include x3 in the objective, like so:

```<code>Minimize
obj: x1 + x2 + 0 x3
Subject to
c1: x1 + x2 <= 10
SOS
s1: s1:: x1:1 x2:2 x3:3
End
</code>```

Then, CPLEX will happily accept the problem.

Another possibly more compelling reason why CPLEX does this, is that sometimes when a program builds a model, there are temporary or dummy variables that are created. These may or may not be important to the actual model. In order to write something to the LP file that is as close as possible as what the program built in memory, there are times when useless or innocuous things are written to the LP file. For example, if a variable is created, but never used, it at least shows up in the LP file as a variable with a zero coefficient in the objective file. This may make it possible to reproduce some behavior that the user observes in tech support situations.

There are many quirks to the LP format. You can read about them here.

Body:
There are several reasons why CPLEX includes all variables in the objective when writing to LP format (even those with a coefficient of zero). One reason is that, when reading in an LP file, some types of constraints require that a variable "exists" before it can be used (note that this is a legacy implementation detail, not necessarily a hard requirement).

For example, consider the following toy LP:

Minimize
obj: x1 + x2
Subject to
c1: x1 + x2 <= 10
SOS
s1: s1:: x1:1 x2:2 x3:3
End

If we try to read this with the interactive, we'll get:

CPLEX> Warning, line 6: Name 'x3' does not exist.
CPLEX Error  1616: Line 6: Expected identifier, found ':'.
No file read.

If we instead include x3 in the objective, like so:

Minimize
obj: x1 + x2 + 0 x3
Subject to
c1: x1 + x2 <= 10
SOS
s1: s1:: x1:1 x2:2 x3:3
End

Then, CPLEX will happily accept the problem.

Another possibly more compelling reason why CPLEX does this, is that sometimes when a program builds a model, there are temporary or dummy variables that are created. These may or may not be important to the actual model. In order to write something to the LP file that is as close as possible as what the program built in memory, there are times when useless or innocuous things are written to the LP file. For example, if a variable is created, but never used, it at least shows up in the LP file as a variable with a zero coefficient in the objective file. This may make it possible to reproduce some behavior that the user observes in tech support situations.

There are many quirks to the LP format. You can read about them here.


问:
how to move Tmux panes
I like to work with 3 tmux panes. one horizontal pane at the upper half of the screen and two more panes at the bottom half. These panes are split vertically.

There are cases where I would like to take the last pane and make it go from top to bottom. like this:

How can I achieve this? using [ctrl+b ctrl+o] and [ctrl+b space] did not reach the desired position and is cumbersome.

答:
There is probably an easier way, but what you can do is arrange the panes manually in each of the two configurations, noting each layout in a variable with e.g.:

```<code>layout1=$(tmux list-windows -F '#{window_layout}')
</code>```

This holds a string something like:

```<code>5f2f,80x23,0,0[80x11,0,0,0,80x11,0,12{39x11,0,12,1,40x11,40,12,2}]
</code>```

which you must not alter in any way as the first number is a checksum of the rest of the string.

Once you have the two strings you can set a binding to set that layout using select-layout, or by giving the command from the shell where you have the variables:

```<code>tmux select-layout "$layout1"
</code>```

You might find it easier to write a small helper script, say mtmux to toggle between the layouts:

```<code>#!/usr/bin/bash
# https://stackoverflow.com/q/56343223/5008284
# toggle between 2 layouts, previously saved
layout1='5f2f,80x23,0,0[80x11,0,0,0,80x11,0,12{39x11,0,12,1,40x11,40,12,2}]'
layout2='093c,80x23,0,0{39x23,0,0[39x11,0,0,0,39x11,0,12,4],40x23,40,0,3}'
layout="$(tmux list-windows -F '#{window_layout}')"
case "$layout" in
*80x11*)    new=$layout2 ;;
*)          new=$layout1 ;;
esac
tmux select-layout "$new"
tmux display-panes
exit 0
</code>```

and have a binding, say control-L, to run this shell:

```<code>    bind-key -n C-l run-shell 'mtmux'
</code>```

Title: how to move Tmux panes

Body:
There is probably an easier way, but what you can do is arrange the panes manually in each of the two configurations, noting each layout in a variable with e.g.:

layout1=$(tmux list-windows -F '#{window_layout}')

This holds a string something like:

5f2f,80x23,0,0[80x11,0,0,0,80x11,0,12{39x11,0,12,1,40x11,40,12,2}]

which you must not alter in any way as the first number is a checksum of the rest of the string.

Once you have the two strings you can set a binding to set that layout using select-layout, or by giving the command from the shell where you have the variables:

tmux select-layout "$layout1"

You might find it easier to write a small helper script, say mtmux to toggle between the layouts:

#!/usr/bin/bash
# https://stackoverflow.com/q/56343223/5008284
# toggle between 2 layouts, previously saved
layout1='5f2f,80x23,0,0[80x11,0,0,0,80x11,0,12{39x11,0,12,1,40x11,40,12,2}]'
layout2='093c,80x23,0,0{39x23,0,0[39x11,0,0,0,39x11,0,12,4],40x23,40,0,3}'
layout="$(tmux list-windows -F '#{window_layout}')"
case "$layout" in
*80x11*)    new=$layout2 ;;
*)          new=$layout1 ;;
esac
tmux select-layout "$new"
tmux display-panes
exit 0

and have a binding, say control-L, to run this shell:

    bind-key -n C-l run-shell 'mtmux'


问:
Enemies stop when I press a key in tkinter game
For practice programming, I made a game in Python with turtle graphics and tkinter. I have a problem: if I press a key, the game loop stops and the enemies don't move.  Is there any solution for this problem? </p>

```<code>import random
import time
import turtle
from tkinter import *

running = True

#window

wn = Tk()
wn.geometry("900x700")

canvas = Canvas(wn, width=750, height=600)
canvas.pack()
canvas.place(relx=0.5, rely=0.5, anchor=CENTER)

#player

player = turtle.RawTurtle(canvas)

player_speed = 3

#enemies

enemies = []

for enemy in range(5):
    enemies.append((turtle.RawTurtle(canvas), 10))

for enemy in enemies:
    enemy[0].penup()
    enemy[0].speed(0)
    enemy[0].setheading(90)
    enemy[0].goto(enemy_position_x(), enemy_position_y())#random position

#move the player
def move_left(event):
    player.setheading(180)
    player.setx(player.xcor() - player_speed)

def move_right(event):
    player.setheading(360)
    player.setx(player.xcor() + player_speed)

def move_up(event):
    player.setheading(90)
    player.sety(player.ycor() + player_speed)

def move_down(event):
    player.setheading(270)
    player.sety(player.ycor() - player_speed)

def shoot(event):
    #I don't write the shoot function, because it's long
    print("shoot")

wn.bind('<Left>', move_left)
wn.bind('<Right>', move_right)
wn.bind('<Up>', move_up)
wn.bind('<Down>', move_down)
wn.bind('<space>', shoot)

#game loop
while running:

    #move the enemy
    for this_enemy in enemies:
        if this_enemy[0].xcor() < player.xcor():
            this_enemy[0].setx(this_enemy[0].xcor() + 3)
            time.sleep(0.1)

        if this_enemy[0].xcor() > player.xcor():
            this_enemy[0].setx(this_enemy[0].xcor() - 3)
            time.sleep(0.1)

        if this_enemy[0].ycor() < player.ycor():
            this_enemy[0].sety(this_enemy[0].ycor() + 3)
            time.sleep(0.1)

        if this_enemy[0].ycor() > player.ycor():
            this_enemy[0].sety(this_enemy[0].ycor() - 3)
            time.sleep(0.1)

wn.mainloop()
</code>```

答:
The basic design of your program is incorrect.  Turtle (and tkinter) are event-driven but using a while True: loop with time.sleep() works against that.  I've rewritten your code below to use timer events, along with other changes.  Enemies should keep moving while you control the player with the keyboard.  I tossed the tkinter wrapper code as it wasn't doing anything that turtle couldn't do for itself:

```<code>from turtle import Screen, Turtle
from random import randint

def enemy_position_x():
    return randint(-325, 325)

def enemy_position_y():
    return randint(-300, 300)

# move the player
def move_left():
    player.setheading(180)
    player.setx(player.xcor() - player_speed)

def move_right():
    player.setheading(360)
    player.setx(player.xcor() + player_speed)

def move_up():
    player.setheading(90)
    player.sety(player.ycor() + player_speed)

def move_down():
    player.setheading(270)
    player.sety(player.ycor() - player_speed)

def move():

    # move the enemy
    for enemy in enemies:
        enemy.setheading(enemy.towards(player))

        if enemy.distance(player) > 10:
            enemy.forward(enemy_speed)

    screen.ontimer(move, 100)

# window

screen = Screen()
screen.setup(900, 700)

# player

player = Turtle()
player.speed('fastest')
player.color('green')
player.penup()

player_speed = 3

# enemies

enemies = []

for _ in range(5):
    enemy = Turtle()
    enemy.penup()
    enemy.speed('fastest')
    enemy.color('red')
    enemy.goto(enemy_position_x(), enemy_position_y())

    enemies.append(enemy)

enemy_speed = 3

screen.onkey(move_left, 'Left')
screen.onkey(move_right, 'Right')
screen.onkey(move_up, 'Up')
screen.onkey(move_down, 'Down')
screen.listen()

move()

screen.mainloop()
</code>```

Body:
For practice programming, I made a game in Python with turtle graphics and tkinter. I have a problem: if I press a key, the game loop stops and the enemies don't move.  Is there any solution for this problem?

import random
import time
import turtle
from tkinter import *

running = True

#window

wn = Tk()
wn.geometry("900x700")

canvas = Canvas(wn, width=750, height=600)
canvas.pack()
canvas.place(relx=0.5, rely=0.5, anchor=CENTER)

#player

player = turtle.RawTurtle(canvas)

player_speed = 3

#enemies

enemies = []

for enemy in range(5):
    enemies.append((turtle.RawTurtle(canvas), 10))

for enemy in enemies:
    enemy[0].penup()
    enemy[0].speed(0)
    enemy[0].setheading(90)
    enemy[0].goto(enemy_position_x(), enemy_position_y())#random position

#move the player
def move_left(event):
    player.setheading(180)
    player.setx(player.xcor() - player_speed)

def move_right(event):
    player.setheading(360)
    player.setx(player.xcor() + player_speed)

def move_up(event):
    player.setheading(90)
    player.sety(player.ycor() + player_speed)

def move_down(event):
    player.setheading(270)
    player.sety(player.ycor() - player_speed)

def shoot(event):
    #I don't write the shoot function, because it's long
    print("shoot")

wn.bind('<Left>', move_left)
wn.bind('<Right>', move_right)
wn.bind('<Up>', move_up)
wn.bind('<Down>', move_down)
wn.bind('<space>', shoot)

#game loop
while running:

    #move the enemy
    for this_enemy in enemies:
        if this_enemy[0].xcor() < player.xcor():
            this_enemy[0].setx(this_enemy[0].xcor() + 3)
            time.sleep(0.1)

        if this_enemy[0].xcor() > player.xcor():
            this_enemy[0].setx(this_enemy[0].xcor() - 3)
            time.sleep(0.1)

        if this_enemy[0].ycor() < player.ycor():
            this_enemy[0].sety(this_enemy[0].ycor() + 3)
            time.sleep(0.1)

        if this_enemy[0].ycor() > player.ycor():
            this_enemy[0].sety(this_enemy[0].ycor() - 3)
            time.sleep(0.1)

wn.mainloop()

Body:
The basic design of your program is incorrect.  Turtle (and tkinter) are event-driven but using a while True: loop with time.sleep() works against that.  I've rewritten your code below to use timer events, along with other changes.  Enemies should keep moving while you control the player with the keyboard.  I tossed the tkinter wrapper code as it wasn't doing anything that turtle couldn't do for itself:

from turtle import Screen, Turtle
from random import randint

def enemy_position_x():
    return randint(-325, 325)

def enemy_position_y():
    return randint(-300, 300)

# move the player
def move_left():
    player.setheading(180)
    player.setx(player.xcor() - player_speed)

def move_right():
    player.setheading(360)
    player.setx(player.xcor() + player_speed)

def move_up():
    player.setheading(90)
    player.sety(player.ycor() + player_speed)

def move_down():
    player.setheading(270)
    player.sety(player.ycor() - player_speed)

def move():

    # move the enemy
    for enemy in enemies:
        enemy.setheading(enemy.towards(player))

        if enemy.distance(player) > 10:
            enemy.forward(enemy_speed)

    screen.ontimer(move, 100)

# window

screen = Screen()
screen.setup(900, 700)

# player

player = Turtle()
player.speed('fastest')
player.color('green')
player.penup()

player_speed = 3

# enemies

enemies = []

for _ in range(5):
    enemy = Turtle()
    enemy.penup()
    enemy.speed('fastest')
    enemy.color('red')
    enemy.goto(enemy_position_x(), enemy_position_y())

    enemies.append(enemy)

enemy_speed = 3

screen.onkey(move_left, 'Left')
screen.onkey(move_right, 'Right')
screen.onkey(move_up, 'Up')
screen.onkey(move_down, 'Down')
screen.listen()

move()

screen.mainloop()


问:
How to get the html document contained inside an HTML tag using selenium in python
I want to get the source code of HTML document which is inside an HTML tag which is generated after some JavaScript and store it in a variable. Here, the HTML tag is  and it contains a variable kind of something that looks like #document and when I expand this, I get an HTML document which looks something like <!DOCTYPE html> ...

To summarize:

```<code><iframe src="https://www.XXXXXX.com/" allow="autoplay; fullscreen" frameborder="no" scrolling="no" allowfullscreen="yes" style="width: 100%; height: 100%;">
    #document
        <!DOCTYPE html>
        <html>...</html>  // a whole new HTML document
</iframe>
</code>```

I want to store all the content of this HTML document as a string in python

What I have done:

```<code>driver.find_element_by_xpath('/path/to/iframe/tag').get_attribute('innerHTML')
</code>```

but, this just returns an empty string. Also, I have checked if it is working with BeautifulSoup

```<code>html = driver.execute_script("return document.body.innerHTML")
soup = BeautifulSoup(html, 'html5lib')
print(soup.prettify())
</code>```

but, this also isn't working

NOTE: I run these test only after the script is executed, also, I guess the problem seems to be with the #document thing

答:
You can't get iframe content by using innerHTML, as you can't do it even with javascript inside a self made html document, like so:

function Button(){
    var iframe = document.getElementsByTagName("iframe")[0];
    var p = document.getElementsByTagName("p")[0];
    p.innerHTML = "Result of iframe.innerHTML: " + iframe.innerHTML;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><iframe src="https://bing.com/"></iframe>
<br>
<button onclick="Button();">Click me to alert innerHTML</button>
<p></p></code>```

Instead, you want to redirect to iframe's src and get html content.

Didn't test the following code but i hope it helps you.

```<code>driver = webdriver.Firefox(executable_path=firefox_path, firefox_profile=firefox_profile)
driver.get('https://example.com/')
documentText = driver.page_source

soup =  BeautifulSoup(documentText)
iframe_source = soup.find('iframe')['src']

driver.get(iframe_source)

documentText = driver.page_source
soup = BeautifulSoup(documentText)
html = soup.find('html')

print(html.content)
</code>```

Body:
I want to get the source code of HTML document which is inside an HTML tag which is generated after some JavaScript and store it in a variable. Here, the HTML tag is  and it contains a variable kind of something that looks like #document and when I expand this, I get an HTML document which looks something like <!DOCTYPE html> ...

To summarize:

    #document
        <!DOCTYPE html>
        ...  // a whole new HTML document

I want to store all the content of this HTML document as a string in python

What I have done:

driver.find_element_by_xpath('/path/to/iframe/tag').get_attribute('innerHTML')

but, this just returns an empty string. Also, I have checked if it is working with BeautifulSoup

html = driver.execute_script("return document.body.innerHTML")
soup = BeautifulSoup(html, 'html5lib')
print(soup.prettify())

but, this also isn't working

NOTE: I run these test only after the script is executed, also, I guess the problem seems to be with the #document thing

Body:
You can't get iframe content by using innerHTML, as you can't do it even with javascript inside a self made html document, like so:

function Button(){
    var iframe = document.getElementsByTagName("iframe")[0];
    var p = document.getElementsByTagName("p")[0];
    p.innerHTML = "Result of iframe.innerHTML: " + iframe.innerHTML;
}

<iframe src="https://bing.com/"></iframe>
<br>
<button onclick="Button();">Click me to alert innerHTML</button>
<p></p>

Instead, you want to redirect to iframe's src and get html content.

Didn't test the following code but i hope it helps you.

driver = webdriver.Firefox(executable_path=firefox_path, firefox_profile=firefox_profile)
driver.get('https://example.com/')
documentText = driver.page_source

soup =  BeautifulSoup(documentText)
iframe_source = soup.find('iframe')['src']

driver.get(iframe_source)

documentText = driver.page_source
soup = BeautifulSoup(documentText)
html = soup.find('html')

print(html.content)


问:
Luanchd not starting mopidy & UDP listener
I'm trying to write a Launchd script to execute a simple sh script that will 1) launch mopidy 2) mkfifo /tmp/mopidy.fifo 3) pass data from port 5555 into this file using socat.

I've tried setting up a mopidy.plist LaunchAgent that executes a mopidy.sh script file at login. I've verified that the LaunchAgent gets started correctly and that the script has execution permissions. I've also tried the Program Arguments approach by passing the script as a one-liner to /bin/bash, but when I try that I get errors logged saying that its unable to find socat.

mopidy.sh

nohup mopidy;
mkfifo /tmp/mopidy.fifo;
while :; do
    socat -d -d -T 1 -u UDP4-LISTEN:5555 OPEN:/tmp/mopidy.fifo;
done
```

<p>mopidy.plist</p>

```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.me.mopidy.plist</string>
    <key>Program</key>
      <string>/Users/me/.config/scripts/mopidy.sh</string>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/Users/me/logfile.log</string>
    <key>StandardErrorPath</key>
    <string>/Users/me/error_logfile.log</string>
</dict>
</plist>
```

I am able to execute the bash script normally without error from the command line, however it doesn't seem like the service is able to because the /tmp/modipy.fifo file never gets created and the listener is never made. The logfile and error_logfile are never populated either.

答:
I was able to get it working by including environment variables. I don't fully understand this, but everything works now with the following:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.me.mopidy.plist</string>
    <key>EnvironmentVariables</key>
    <dict>
        <key>PATH</key>
        <string>/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/sbin</string>
    </dict>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/bash</string>
        <string>/Users/me/.config/scripts/mopidy.sh</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/Users/me/logfile.log</string>
    <key>StandardErrorPath</key>
    <string>/Users/me/error_logfile.log</string>
</dict>
</plist>
```

Body:
I'm trying to write a Launchd script to execute a simple sh script that will 1) launch mopidy 2) mkfifo /tmp/mopidy.fifo 3) pass data from port 5555 into this file using socat.

I've tried setting up a mopidy.plist LaunchAgent that executes a mopidy.sh script file at login. I've verified that the LaunchAgent gets started correctly and that the script has execution permissions. I've also tried the Program Arguments approach by passing the script as a one-liner to /bin/bash, but when I try that I get errors logged saying that its unable to find socat.

mopidy.sh

nohup mopidy;
mkfifo /tmp/mopidy.fifo;
while :; do
    socat -d -d -T 1 -u UDP4-LISTEN:5555 OPEN:/tmp/mopidy.fifo;
done

mopidy.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.me.mopidy.plist</string>
    <key>Program</key>
      <string>/Users/me/.config/scripts/mopidy.sh</string>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/Users/me/logfile.log</string>
    <key>StandardErrorPath</key>
    <string>/Users/me/error_logfile.log</string>
</dict>
</plist>

I am able to execute the bash script normally without error from the command line, however it doesn't seem like the service is able to because the /tmp/modipy.fifo file never gets created and the listener is never made. The logfile and error_logfile are never populated either.

Body:
I was able to get it working by including environment variables. I don't fully understand this, but everything works now with the following:

<!-- Starts mopidy server -->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.me.mopidy.plist</string>
    <key>EnvironmentVariables</key>
    <dict>
        <key>PATH</key>
        <string>/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/sbin</string>
    </dict>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/bash</string>
        <string>/Users/me/.config/scripts/mopidy.sh</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/Users/me/logfile.log</string>
    <key>StandardErrorPath</key>
    <string>/Users/me/error_logfile.log</string>
</dict>
</plist>


问:
Apply style with setTimeout()
I created the next code:

  setTimeout(function () {
        var dot = document.querySelectorAll('.dot');
        for (var i=0;i<dot.length;i++) {
            dot[i].style.backgroundColor = 'blue';
        }
    },2000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code> .container{
        display: flex;
        justify-content: space-around;
    }
   .dot{
       background-color: red;
       width: 20px;
       height: 20px;
       border-radius: 50%;
   }</code>```

```

This code apply background-color for each dot at the same time after 2 seconds, but i want to apply the style for each dot separately. Fo example: after 2 seconds to apply the style for first dot, then after 2 seconds to apply the style for second dot, and so on. Who has a solution?

答:
The simple way is to create separate timers, making each wait 2000ms longer than the last by multiplying by the loop index:

```<code>var dot = document.querySelectorAll('.dot');
for (let i=0;i<dot.length;i++) { // ***
    setTimeout(function () {
        dot[i].style.backgroundColor = 'blue';
    }, i * 2000);
}
</code>```

Note also the use of let rather than var in the loop, so that each loop iteration gets its own copy of i. If you can't use ES2015 features, see this question's answers for how to deal with i in the for loop.

If we're using ES2015, we may as well use a for-of loop instead:

```<code>let i = 0;
for (const dot of document.querySelectorAll('.dot')) {
    setTimeout(() => {
        dot.style.backgroundColor = 'blue';
    }, i++ * 2000);
}
</code>```

That relies on the NodeList from querySelectorAll being iterable, which it is on modern browsers. I don't know if there are any browsers with ES2015 but which don't (yet) make NodeList iterable; if there are any, you can use this answer's technique to add iterability.

Title: Apply style with setTimeout()

Body:
I created the next code:

  setTimeout(function () {
        var dot = document.querySelectorAll('.dot');
        for (var i=0;i<dot.length;i++) {
            dot[i].style.backgroundColor = 'blue';
        }
    },2000);

 .container{
        display: flex;
        justify-content: space-around;
    }
   .dot{
       background-color: red;
       width: 20px;
       height: 20px;
       border-radius: 50%;
   }

This code apply background-color for each dot at the same time after 2 seconds, but i want to apply the style for each dot separately. Fo example: after 2 seconds to apply the style for first dot, then after 2 seconds to apply the style for second dot, and so on. Who has a solution?

Body:
The simple way is to create separate timers, making each wait 2000ms longer than the last by multiplying by the loop index:

var dot = document.querySelectorAll('.dot');
for (let i=0;i<dot.length;i++) { // ***
    setTimeout(function () {
        dot[i].style.backgroundColor = 'blue';
    }, i * 2000);
}

Note also the use of let rather than var in the loop, so that each loop iteration gets its own copy of i. If you can't use ES2015 features, see this question's answers for how to deal with i in the for loop.

If we're using ES2015, we may as well use a for-of loop instead:

let i = 0;
for (const dot of document.querySelectorAll('.dot')) {
    setTimeout(() => {
        dot.style.backgroundColor = 'blue';
    }, i++ * 2000);
}

That relies on the NodeList from querySelectorAll being iterable, which it is on modern browsers. I don't know if there are any browsers with ES2015 but which don't (yet) make NodeList iterable; if there are any, you can use this answer's technique to add iterability.


问:
How to make more precise the reading of AnalogPins in Arduino?
I'm new here so, if I make any mistake, sorry. Well, I'm working with Arduino (Mega2560) to construct an Ammeter and found out a little problem... Arduino Mega measures voltage from 0 to 5V, and the AnalogPins return a 10-bit value according with the reading (that is, 1 bit represents 5/(2^10)=4mV (approximately)). But, in the case of ammeter, I need to use a resistor with small resistance so that my circuit don't get changes. So my objective is read the voltage drop and from V = R.I, calculate the current. But, as the voltage drop is such as slowly, the pin can't read any value.
Eg.: there is a current flowing from 2mA in the region that I would like to measure. With a resistance of 0.3 ohms (the lower value I found here) , would be: V = 2m . 0.3 = 0.6mV.
As I said, the lower posssible value of reading in analogPins is 4mV.
Thus, how to improve my precision of reading? For example, instead of 1023 represents only 5V, the same value represents around of 30 or 40mV...
                                    0     -  0 V
                                    1023  -  30/40 mV</p>

答:
In below example, voltage_meter reads 500 samples in about 1 millisecond and returns the average. I set the reference to 1.1v for better precision.

```<code>int battery_pin = A3;

float voltage_meter()
{
    //read battery voltage per %
    long sum = 0;        // sum of samples taken
    float voltage = 0.0; // calculated voltage
    float output = 0.0;  //output value

    for (int i = 0; i < 500; i++)
    {
        sum += analogRead(battery_pin);
        delayMicroseconds(1000);
    }
    // calculate the voltage
    voltage = sum / (float)500;
    // voltage = (voltage * 5.0) / 1023.0; //for default reference voltage
    voltage = (voltage * 1.1) / 1023.0; //for internal 1.1v reference
    //round value by two precision
    voltage = roundf(voltage * 100) / 100;
    return voltage;
}

void setup()
{
    analogReference(INTERNAL); //set reference voltage to internal
    Serial.begin(9600);
}

void loop()
{
    Serial.print("Voltage Level: ");
    Serial.print(voltage_meter(), 4);
    Serial.println(" V");
    delay(1000);
}
</code>```

Body:
In below example, voltage_meter reads 500 samples in about 1 millisecond and returns the average. I set the reference to 1.1v for better precision.

int battery_pin = A3;

float voltage_meter()
{
    //read battery voltage per %
    long sum = 0;        // sum of samples taken
    float voltage = 0.0; // calculated voltage
    float output = 0.0;  //output value

    for (int i = 0; i < 500; i++)
    {
        sum += analogRead(battery_pin);
        delayMicroseconds(1000);
    }
    // calculate the voltage
    voltage = sum / (float)500;
    // voltage = (voltage * 5.0) / 1023.0; //for default reference voltage
    voltage = (voltage * 1.1) / 1023.0; //for internal 1.1v reference
    //round value by two precision
    voltage = roundf(voltage * 100) / 100;
    return voltage;
}

void setup()
{
    analogReference(INTERNAL); //set reference voltage to internal
    Serial.begin(9600);
}

void loop()
{
    Serial.print("Voltage Level: ");
    Serial.print(voltage_meter(), 4);
    Serial.println(" V");
    delay(1000);
}


问:
Display many routes in google maps from already defined routes
I need to map routes already defined in my variable testf in google maps. I need to trace a route from point Id 1 to point Id 2, then draw another route from point Id 3 to point Id 4, that is, different routes for each pair of points, how to do? I can not make google maps understand how to read from a starting point to the end point by passing through a variable that contains all of these points. This is only the part of the javascript that I can not make work:

```<code>var testef = [{
"Id": 1,
"Latitude": 38.726177,
"Longitude": -9.180716
},
{
"Id": 2,
"Latitude": 38.716177,
"Longitude": -9.170716
},
{
"Id": 3,
"Latitude": 38.736177,
"Longitude": -9.160716
},
 {
"Id": 4,
"Latitude": 38.729177,
"Longitude": -9.110716
 }];

 //traçando a rota
for(var k=0; k < testef.length; k++){
    var objk=testef[k];

    var mypath = new google.maps.LatLng(objk.Latitude,objk.Longitude);

    var teste = new google.maps.Polyline({
        path: mypath,
        geodesic: true,
        strokeColor: '#ff0000',
        strokeOpacity: 1.0,
        strokeWeight: 3
    });
}

  teste.setMap(map);
</code>```

I hoped to draw several routes already defined

答:
I get a javascript error with the posted code: InvalidValueError: not an Array, because the value of mypath is not an array.

Create points from your array by pairs, creating an array with each set of points (the path for each to point segment):

```<code>for (var k = 0; k < testef.length-1; k+=2) {
    // start of segment
    var objk = testef[k];
    var pt = new google.maps.LatLng(objk.Latitude, objk.Longitude);
    // end of segment
    var objkp1 = testef[k+1];
    var pt1 = new google.maps.LatLng(objkp1.Latitude, objkp1.Longitude);
    // create the path for this segment
    var mypath = [pt, pt1];
    // create the polyline for this segment
    var teste = new google.maps.Polyline({
      path: mypath,
      geodesic: true,
      strokeColor: '#ff0000',
      strokeOpacity: 1.0,
      strokeWeight: 3
    });
    // add this segment to the map
    teste.setMap(map);
}
</code>```

proof of concept fiddle

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 3,
    center: {
      lat: 0,
      lng: -180
    },
    mapTypeId: 'terrain'
  });

  //traçando a rota
  var bounds = new google.maps.LatLngBounds();
  for (var k = 0; k < testef.length - 1; k += 2) {
    var objk = testef[k];
    var pt = new google.maps.LatLng(objk.Latitude, objk.Longitude);
    bounds.extend(pt);
    var objkp1 = testef[k + 1];
    var pt1 = new google.maps.LatLng(objkp1.Latitude, objkp1.Longitude);
    bounds.extend(pt1);
    var mypath = [pt, pt1];
    var teste = new google.maps.Polyline({
      path: mypath,
      geodesic: true,
      strokeColor: '#ff0000',
      strokeOpacity: 1.0,
      strokeWeight: 3
    });
    teste.setMap(map);
  }
  map.fitBounds(bounds);
}
var testef = [{
    "Id": 1,
    "Latitude": 38.726177,
    "Longitude": -9.180716
  },
  {
    "Id": 2,
    "Latitude": 38.716177,
    "Longitude": -9.170716
  },
  {
    "Id": 3,
    "Latitude": 38.736177,
    "Longitude": -9.160716
  },
  {
    "Id": 4,
    "Latitude": 38.729177,
    "Longitude": -9.110716
  }
];```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
}</code>```

```

Body:
I need to map routes already defined in my variable testf in google maps. I need to trace a route from point Id 1 to point Id 2, then draw another route from point Id 3 to point Id 4, that is, different routes for each pair of points, how to do? I can not make google maps understand how to read from a starting point to the end point by passing through a variable that contains all of these points. This is only the part of the javascript that I can not make work:

var testef = [{
"Id": 1,
"Latitude": 38.726177,
"Longitude": -9.180716
},
{
"Id": 2,
"Latitude": 38.716177,
"Longitude": -9.170716
},
{
"Id": 3,
"Latitude": 38.736177,
"Longitude": -9.160716
},
 {
"Id": 4,
"Latitude": 38.729177,
"Longitude": -9.110716
 }];

 //traçando a rota
for(var k=0; k < testef.length; k++){
    var objk=testef[k];

    var mypath = new google.maps.LatLng(objk.Latitude,objk.Longitude);

    var teste = new google.maps.Polyline({
        path: mypath,
        geodesic: true,
        strokeColor: '#ff0000',
        strokeOpacity: 1.0,
        strokeWeight: 3
    });
}

  teste.setMap(map);

I hoped to draw several routes already defined

Body:
I get a javascript error with the posted code: InvalidValueError: not an Array, because the value of mypath is not an array.

Create points from your array by pairs, creating an array with each set of points (the path for each to point segment):

for (var k = 0; k < testef.length-1; k+=2) {
    // start of segment
    var objk = testef[k];
    var pt = new google.maps.LatLng(objk.Latitude, objk.Longitude);
    // end of segment
    var objkp1 = testef[k+1];
    var pt1 = new google.maps.LatLng(objkp1.Latitude, objkp1.Longitude);
    // create the path for this segment
    var mypath = [pt, pt1];
    // create the polyline for this segment
    var teste = new google.maps.Polyline({
      path: mypath,
      geodesic: true,
      strokeColor: '#ff0000',
      strokeOpacity: 1.0,
      strokeWeight: 3
    });
    // add this segment to the map
    teste.setMap(map);
}

proof of concept fiddle

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 3,
    center: {
      lat: 0,
      lng: -180
    },
    mapTypeId: 'terrain'
  });

  //traçando a rota
  var bounds = new google.maps.LatLngBounds();
  for (var k = 0; k < testef.length - 1; k += 2) {
    var objk = testef[k];
    var pt = new google.maps.LatLng(objk.Latitude, objk.Longitude);
    bounds.extend(pt);
    var objkp1 = testef[k + 1];
    var pt1 = new google.maps.LatLng(objkp1.Latitude, objkp1.Longitude);
    bounds.extend(pt1);
    var mypath = [pt, pt1];
    var teste = new google.maps.Polyline({
      path: mypath,
      geodesic: true,
      strokeColor: '#ff0000',
      strokeOpacity: 1.0,
      strokeWeight: 3
    });
    teste.setMap(map);
  }
  map.fitBounds(bounds);
}
var testef = [{
    "Id": 1,
    "Latitude": 38.726177,
    "Longitude": -9.180716
  },
  {
    "Id": 2,
    "Latitude": 38.716177,
    "Longitude": -9.170716
  },
  {
    "Id": 3,
    "Latitude": 38.736177,
    "Longitude": -9.160716
  },
  {
    "Id": 4,
    "Latitude": 38.729177,
    "Longitude": -9.110716
  }
];

html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
}

<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>


问:
Undefined variable: all_data (View: /var/www/html/resources/views/welcome.blade.php)
I'm trying to post data from controller to view, basically when page loads user sees the form and when it get submits, it returns the data. I'm not sure what I'm doing wrong. I have tried the following to returns the data

Return methods tried:

```<code>return view('welcome',['all_data'=>$all_data]);
return view('welcome')->with('all_data', $all_data);
return view('welcome')->with('data', json_decode($data, true));
return View::make('welcome', array('all_data'=>$all_data));
</code>```

Controller:

```<code>public function getStatus(Request $request){

//SQLQuery which returns $all_data

$all_data = json_encode($data);
return view('welcome', compact('all_data'));
}
</code>```

Route:

```<code>Route::get('/', function () {
    return view('welcome');
});

Route::post('/getstatus', 'GetApplicationStatusController@getStatus');
</code>```

View:

```<code>@foreach ($all_data as $data)
<td id="appid">{{$data->appid}}</td>
<td id="firstname">{{$data->firstname}}</td>
<td id="middlename">{{$data->middlename}}</td>
<td id="lastname">{{$data->lastname}}</td>
<td id="action">{{$data->action}}</td>
@endforeach
</code>```

答: my first thought is that you are visiting the / route, which doesn't have the variable all_data. to fix this just call the controller from this route as well: Route::get('/', 'GetApplicationStatusController@getStatus')

Body:
I'm trying to post data from controller to view, basically when page loads user sees the form and when it get submits, it returns the data. I'm not sure what I'm doing wrong. I have tried the following to returns the data

Return methods tried:

return view('welcome',['all_data'=>$all_data]);
return view('welcome')->with('all_data', $all_data);
return view('welcome')->with('data', json_decode($data, true));
return View::make('welcome', array('all_data'=>$all_data));

Controller:

public function getStatus(Request $request){

//SQLQuery which returns $all_data

$all_data = json_encode($data);
return view('welcome', compact('all_data'));
}

Route:

Route::get('/', function () {
    return view('welcome');
});

Route::post('/getstatus', 'GetApplicationStatusController@getStatus');

View:

@foreach ($all_data as $data)
{{$data->appid}}
{{$data->firstname}}
{{$data->middlename}}
{{$data->lastname}}
{{$data->action}}
@endforeach


问:
Validating models against the parent model
I have two models, one is the parent of the other, and the parent accepts_nested_attributes_for and validates_associated the children.

However, some of my validations have an :if that needs to check one of the properties of the parent.

I was thinking that I could do something like this:

```<code>validates_presence_of :blah, :if => Proc.new{|thing| thing.parent.some_value.present?}
</code>```

However, the 'parent' relationship doesn't appear to be setup at the time of validation (I would assume the children get instantiated and validated first.

Therefore is there any way of doing what I'm thinking of? Is it possible?

答:
You can use before_update or before_create callbacks as per your need like this..</p>

```<code>def before_update
  self.errors.add("Error Message") if self.parent.some_value.present?
  return false if self.errors.count > 0
end

def before_create
  self.errors.add("Error Message") if self.parent.some_value.present?
  return false if self.errors.count > 0
end
</code>```

Body:
I have two models, one is the parent of the other, and the parent accepts_nested_attributes_for and validates_associated the children.

However, some of my validations have an :if that needs to check one of the properties of the parent.

I was thinking that I could do something like this:

validates_presence_of :blah, :if => Proc.new{|thing| thing.parent.some_value.present?}

However, the 'parent' relationship doesn't appear to be setup at the time of validation (I would assume the children get instantiated and validated first.

Therefore is there any way of doing what I'm thinking of? Is it possible?

Body:
You can use before_update or before_create callbacks as per your need like this..

def before_update
  self.errors.add("Error Message") if self.parent.some_value.present?
  return false if self.errors.count > 0
end

def before_create
  self.errors.add("Error Message") if self.parent.some_value.present?
  return false if self.errors.count > 0
end


问:
How to clone github repo using unix type linefeeds
I'm trying to deploy the latest scrapinghub/splash

I am using git-bash on win10. I forked the repo to https://github.com/kc1/splash/blob/master

I've run into some problems in my original question (Docker: /bin/sh: 1: /tmp/provision.sh: not found)

Its been suggested that the problem is that the shell scripts have windows line endings (crlf) instead of the unix type (lf). I checked and indeed windows ending are being used in my cloned repo locally.

How can I clone the repo so that I get the unix type endings in my local windows environment?

答:
```<code>git clone --config core.eol=lf <repository>
</code>```

Basically, you want to set this config param to control the line endings on your machine.  The default of native will use whatever is native on your machine (which is crlf on windows).  You can also set this in you global configs before doing the clone if you want it to apply to every repo

```<code>git config --global core.eol lf
</code>```

Body:
git clone --config core.eol=lf <repository>

Basically, you want to set this config param to control the line endings on your machine.  The default of native will use whatever is native on your machine (which is crlf on windows).  You can also set this in you global configs before doing the clone if you want it to apply to every repo

git config --global core.eol lf


问:
Find duplicates in Laravel Eloquent
The following code I have on the controller is below.

public function add(Request $request)
{
    $request->validate([
        'userSelected' => 'required',
        'projectSelected' => 'required',
    ]);

    $researcherToProject = new ProjectResearchers();
    $researcherToProject->user_id = $request->userSelected;
    $researcherToProject->project_id = $request->projectSelected;
    $researcherToProject->created_at = Carbon::now();
    $researcherToProject->updated_at = Carbon::now();
    $researcherToProject->save();

    return new ProjectsResearchersResource($researcherToProject);
}
```

Should I make another validation or create a function?

Ex: I create a user id "5" with project id "13" and user id "2" with project id "17". If I try creating again a user id "5" with project id "13" it allows me, so I get two times the same data in the database. How do I avoid duplicate entries?

答:
You can do it using updateOrCreate method, the first array is the unique values that you are looking for, if not found it will create the entry, if it finds them it will just update the fields in the second array so do this instead:

```<code>public function add(Request $request){

    $request->validate([
        'userSelected' => 'required',
        'projectSelected' => 'required',
    ]);

    $researcherToProject = ProjectResearchers::updateOrCreate(
        ['user_id' => $request->userSelected, 'project_id' => $request->projectSelected],
        ['created_at' => Carbon::now(), 'updated_at' => Carbon::now()]
    );

    return new ProjectsResearchersResource($researcherToProject);
}
</code>```

or if you don't want to update at all, you can just check if it exists before storing:

```<code>public function add(Request $request){

    $request->validate([
        'userSelected' => 'required',
        'projectSelected' => 'required',
    ]);

       $researcherToProject = new ProjectResearchers();

    if( ! ProjectResearchers::where('user_id', $request->userSelected)->where('project_id', $request->projectSelected)->exists()) {
       $researcherToProject = new ProjectResearchers();
       $researcherToProject->user_id = $request->userSelected;
       $researcherToProject->project_id = $request->projectSelected;
       $researcherToProject->created_at = Carbon::now();
       $researcherToProject->updated_at = Carbon::now();

       $researcherToProject->save();
    } else {
        $researcherToProject = ProjectResearchers::where('user_id', $request->userSelected)->where('project_id', $request->projectSelected)->first();
    }

    return new ProjectsResearchersResource($researcherToProject);
}
</code>```

Title: Find duplicates in Laravel Eloquent

Body:
The following code I have on the controller is below.

public function add(Request $request)
{
    $request->validate([
        'userSelected' => 'required',
        'projectSelected' => 'required',
    ]);

    $researcherToProject = new ProjectResearchers();
    $researcherToProject->user_id = $request->userSelected;
    $researcherToProject->project_id = $request->projectSelected;
    $researcherToProject->created_at = Carbon::now();
    $researcherToProject->updated_at = Carbon::now();
    $researcherToProject->save();

    return new ProjectsResearchersResource($researcherToProject);
}

Should I make another validation or create a function?

Ex: I create a user id "5" with project id "13" and user id "2" with project id "17". If I try creating again a user id "5" with project id "13" it allows me, so I get two times the same data in the database. How do I avoid duplicate entries?

Body:
You can do it using updateOrCreate method, the first array is the unique values that you are looking for, if not found it will create the entry, if it finds them it will just update the fields in the second array so do this instead:

public function add(Request $request){

    $request->validate([
        'userSelected' => 'required',
        'projectSelected' => 'required',
    ]);

    $researcherToProject = ProjectResearchers::updateOrCreate(
        ['user_id' => $request->userSelected, 'project_id' => $request->projectSelected],
        ['created_at' => Carbon::now(), 'updated_at' => Carbon::now()]
    );

    return new ProjectsResearchersResource($researcherToProject);
}

or if you don't want to update at all, you can just check if it exists before storing:

public function add(Request $request){

    $request->validate([
        'userSelected' => 'required',
        'projectSelected' => 'required',
    ]);

       $researcherToProject = new ProjectResearchers();

    if( ! ProjectResearchers::where('user_id', $request->userSelected)->where('project_id', $request->projectSelected)->exists()) {
       $researcherToProject = new ProjectResearchers();
       $researcherToProject->user_id = $request->userSelected;
       $researcherToProject->project_id = $request->projectSelected;
       $researcherToProject->created_at = Carbon::now();
       $researcherToProject->updated_at = Carbon::now();

       $researcherToProject->save();
    } else {
        $researcherToProject = ProjectResearchers::where('user_id', $request->userSelected)->where('project_id', $request->projectSelected)->first();
    }

    return new ProjectsResearchersResource($researcherToProject);
}


问:
Having trouble with Array.find in Zapier - Can't Read Property of Undefined
I'm trying to parse an array coming from a webhook response and provide the field "id" for use in another step of the Zap.

I'm using Array.find to parse the array and find the id.

Here's my code:

```<code>const result = JSON.parse(inputData.body);
return {
  result,
  SectionId: result.data.find(
    x => x.name === inputData.sectionText).id
};
</code>```

and here's my webhook data

```<code>{"data":
[{"id":1124815237432228,"gid":"1124815237432228","name":"Last Name, First Name","resource_type":"task"},
{"id":1124814957166815,"gid":"1124814957166815","name":"Final Signing:","resource_type":"task"},
{"id":1124815361088518,"gid":"1124815361088518","name":"Matter Closing:","resource_type":"task"},
{"id":1124815216609386,"gid":"1124815216609386","name":"Setup:","resource_type":"task"},
{"id":1124815361502365,"gid":"1124815361502365","name":"Drafting:","resource_type":"task"}]}
</code>```

This should pull out the id based on the value of sectionText. The variable sectionText comes from another Code by Zapier step in the Zap. If the sectionText were Drafting, for example, I would expect this code to pull the id, "1124815361502365". Instead, I receive the error "Cannot read property 'id' of undefined". Could it be related to the length of the array?

Any help is sincerely appreciated.

答: Verify what exact value is passed in inputData.sectionText property. Values in name contains ":", so if sectionText does not, then those two values never match.

Body:
I'm trying to parse an array coming from a webhook response and provide the field "id" for use in another step of the Zap.

I'm using Array.find to parse the array and find the id.

Here's my code:

const result = JSON.parse(inputData.body);
return {
  result,
  SectionId: result.data.find(
    x => x.name === inputData.sectionText).id
};

and here's my webhook data

{"data":
[{"id":1124815237432228,"gid":"1124815237432228","name":"Last Name, First Name","resource_type":"task"},
{"id":1124814957166815,"gid":"1124814957166815","name":"Final Signing:","resource_type":"task"},
{"id":1124815361088518,"gid":"1124815361088518","name":"Matter Closing:","resource_type":"task"},
{"id":1124815216609386,"gid":"1124815216609386","name":"Setup:","resource_type":"task"},
{"id":1124815361502365,"gid":"1124815361502365","name":"Drafting:","resource_type":"task"}]}

This should pull out the id based on the value of sectionText. The variable sectionText comes from another Code by Zapier step in the Zap. If the sectionText were Drafting, for example, I would expect this code to pull the id, "1124815361502365". Instead, I receive the error "Cannot read property 'id' of undefined". Could it be related to the length of the array?

Any help is sincerely appreciated.


问:
Save value of then in a variable outside of the Promise
I'm fairly new to the concept of Promises and I'm trying to understand how the scopes work. I'm basically trying to store the value from inside a then() into a variable outside of the Promise

Below is a simple function I've written in Nodejs (Express), using Sequelize to run the query on the DB.

```<code>exports.getTest = (req, res, next) => {
    var categories = [];
    var names = ['Category 1', 'Category 2', 'Category 3', 'Category 4'];
    for (var i = 0; i < names.length; i++) {
        model.Category.findOne({
            where: {
                name: names[i]
            },
            attributes: ['id']
        }).then(id => {
            categories.push(
            {
                category_id: id.id
            });
        });
    }
    res.json(categories);
}
</code>```

I have other logic to be run after that, and I have a for loop around the Promise. So, I can't run my next logic inside the then, otherwise I'll have it running multiple times because of the for loop. I need to populate the array categories to use it in my next operation.

Currently, my response (res.json(categories)) is []

Any help would be appreciated.

PS: I know this is a common topic, but as I mentioned, I'm fairly new to this and the other answers didn't fit my scenario and were further confusing me.

Thanks in advance!

答:
In your case, categories will always return [] because you aren't waiting for all your promises to finish before returning your response. For loops do not wait for asynchronous actions to complete before continuing on to the next iteration. Therefore the loop ends, and a response is returned before any of them finish.

Instead of calling promises within a for loop, you should push them to an array, which you can then pass to Promise.all() function.

Here is what it should look like

```<code>exports.getTest = () => {
    var categories = [];
    var names = ['Category 1', 'Category 2', 'Category 3', 'Category 4'];
    var promiseArray = [];
    for (var i = 0; i < names.length; i++) {
        promiseArray.push(
          model.Category.findOne({
              where: {
                  name: names[i]
              },
              attributes: ['id']
          }).then(id => {
              categories.push(
              {
                  category_id: id.id
              });
          });
        )
    }

    return Promise.all(promiseArr)
}
</code>```

getTest() now returns a promise, so it can be called like this

```<code>getTest()
  .then(data => {
    // data will be an array of promise responses
  }).catch(err => {
    console.log(err);
  })
</code>```

Body:
I'm fairly new to the concept of Promises and I'm trying to understand how the scopes work. I'm basically trying to store the value from inside a then() into a variable outside of the Promise

Below is a simple function I've written in Nodejs (Express), using Sequelize to run the query on the DB.

exports.getTest = (req, res, next) => {
    var categories = [];
    var names = ['Category 1', 'Category 2', 'Category 3', 'Category 4'];
    for (var i = 0; i < names.length; i++) {
        model.Category.findOne({
            where: {
                name: names[i]
            },
            attributes: ['id']
        }).then(id => {
            categories.push(
            {
                category_id: id.id
            });
        });
    }
    res.json(categories);
}

I have other logic to be run after that, and I have a for loop around the Promise. So, I can't run my next logic inside the then, otherwise I'll have it running multiple times because of the for loop. I need to populate the array categories to use it in my next operation.

Currently, my response (res.json(categories)) is []

Any help would be appreciated.

PS: I know this is a common topic, but as I mentioned, I'm fairly new to this and the other answers didn't fit my scenario and were further confusing me.

Thanks in advance!

Body:
In your case, categories will always return [] because you aren't waiting for all your promises to finish before returning your response. For loops do not wait for asynchronous actions to complete before continuing on to the next iteration. Therefore the loop ends, and a response is returned before any of them finish.

Instead of calling promises within a for loop, you should push them to an array, which you can then pass to Promise.all() function.

Here is what it should look like

exports.getTest = () => {
    var categories = [];
    var names = ['Category 1', 'Category 2', 'Category 3', 'Category 4'];
    var promiseArray = [];
    for (var i = 0; i < names.length; i++) {
        promiseArray.push(
          model.Category.findOne({
              where: {
                  name: names[i]
              },
              attributes: ['id']
          }).then(id => {
              categories.push(
              {
                  category_id: id.id
              });
          });
        )
    }

    return Promise.all(promiseArr)
}

getTest() now returns a promise, so it can be called like this

getTest()
  .then(data => {
    // data will be an array of promise responses
  }).catch(err => {
    console.log(err);
  })


问:
find if 4 points on a plane form a rectangle?
Can somebody please show me in C-style pseudocode how to write a function (represent the points however you like) that returns true if 4-points (args to the function) form a rectangle, and false otherwise?

I came up with a solution that first tries to find 2 distinct pairs of points with equal x-value, then does this for the y-axis.  But the code is rather long.  Just curious to see what others come up with.

答:
Here is my algorithm proposal, for an axis-aligned rectangle test, but in Python.

The idea is to grab the first point as a pivot, and that all the other points must conform to the same width and height, and checks that all points are distinct, via a set, to account for cases such as (1, 2), (1, 2), (10, 30), (10, 30).

```<code>from collections import namedtuple

Point = namedtuple('Point', ('x', 'y'))

def is_rectangle(p1, p2, p3, p4) -> bool:
    width = None
    height = None

    # All must be distinct
    if (len(set((p1, p2, p3, p4))) < 4):
        return False

    pivot = p1

    for point in (p2, p3, p4):
        candidate_width = point.x - pivot.x
        candidate_height = point.y - pivot.y

        if (candidate_width != 0):
            if (width is None):
                width = candidate_width
            elif (width != candidate_width):
                return False

        if (candidate_height != 0):
            if (height is None):
                height = candidate_height
            elif (height != candidate_height):
                return False

    return width is not None and height is not None

# Some Examples
print(is_rectangle(Point(10, 50), Point(20, 50), Point(10, 40), Point(20, 40)))
print(is_rectangle(Point(100, 50), Point(20, 50), Point(10, 40), Point(20, 40)))
print(is_rectangle(Point(10, 10), Point(20, 50), Point(10, 40), Point(20, 40)))
print(is_rectangle(Point(10, 30), Point(20, 30), Point(10, 30), Point(20, 30)))
print(is_rectangle(Point(10, 30), Point(10, 30), Point(10, 30), Point(10, 30)))
print(is_rectangle(Point(1, 2), Point(10, 30), Point(1, 2), Point(10, 30)))
print(is_rectangle(Point(10, 50), Point(80, 50), Point(10, 40), Point(80, 40)))
</code>```

Body:
Here is my algorithm proposal, for an axis-aligned rectangle test, but in Python.

The idea is to grab the first point as a pivot, and that all the other points must conform to the same width and height, and checks that all points are distinct, via a set, to account for cases such as (1, 2), (1, 2), (10, 30), (10, 30).

from collections import namedtuple

Point = namedtuple('Point', ('x', 'y'))

def is_rectangle(p1, p2, p3, p4) -> bool:
    width = None
    height = None

    # All must be distinct
    if (len(set((p1, p2, p3, p4))) < 4):
        return False

    pivot = p1

    for point in (p2, p3, p4):
        candidate_width = point.x - pivot.x
        candidate_height = point.y - pivot.y

        if (candidate_width != 0):
            if (width is None):
                width = candidate_width
            elif (width != candidate_width):
                return False

        if (candidate_height != 0):
            if (height is None):
                height = candidate_height
            elif (height != candidate_height):
                return False

    return width is not None and height is not None

# Some Examples
print(is_rectangle(Point(10, 50), Point(20, 50), Point(10, 40), Point(20, 40)))
print(is_rectangle(Point(100, 50), Point(20, 50), Point(10, 40), Point(20, 40)))
print(is_rectangle(Point(10, 10), Point(20, 50), Point(10, 40), Point(20, 40)))
print(is_rectangle(Point(10, 30), Point(20, 30), Point(10, 30), Point(20, 30)))
print(is_rectangle(Point(10, 30), Point(10, 30), Point(10, 30), Point(10, 30)))
print(is_rectangle(Point(1, 2), Point(10, 30), Point(1, 2), Point(10, 30)))
print(is_rectangle(Point(10, 50), Point(80, 50), Point(10, 40), Point(80, 40)))


问:
Tried to get frame for out of range index NaN (realtime database)
I'm trying to render some rows from firebase database, I'm getting this error:

TaskQueue: Error with task : Invariant Violation: Tried to get frame
  for out of range index NaN

```<code>  const { currentUser } = firebase.auth();
    var userfavorites = firebase.database().ref(`/users/${currentUser.uid}/favorites/`);
    userfavorites.once('value').then(snapshot => {
      this.setState({ userfav: snapshot.val() })
    })

...

  <FlatList
    data={this.state.userfav}
    renderItem={({ item }) => (
      <Text>{item.favdata}</Text>
    )}
  />
</code>```

答:
I came across this error, I had a PHP back-end and trying to get json_encoded data into a FlatList.

Problem: The REST endpoint was returning an object eg

{"Total_Excavator":2,"Active_Excavator":2,"Total_load":6804}

Solution: Fixed it to return an array rather eg

```<code>[{"Total_Excavator":2,"Active_Excavator":2,"Total_load":6804}]
</code>```

Take note of the Square Brackets.
I used  $data[] = json_encode($excavatorArray) instead of
$data = json_encode($excavatorArray)
. Hope it helps someone one day

Body:
I'm trying to render some rows from firebase database, I'm getting this error:

TaskQueue: Error with task : Invariant Violation: Tried to get frame
  for out of range index NaN

  const { currentUser } = firebase.auth();
    var userfavorites = firebase.database().ref(`/users/${currentUser.uid}/favorites/`);
    userfavorites.once('value').then(snapshot => {
      this.setState({ userfav: snapshot.val() })
    })

...

  <FlatList
    data={this.state.userfav}
    renderItem={({ item }) => (
      <Text>{item.favdata}</Text>
    )}
  />

Body:
I came across this error, I had a PHP back-end and trying to get json_encoded data into a FlatList.

Problem: The REST endpoint was returning an object eg

{"Total_Excavator":2,"Active_Excavator":2,"Total_load":6804}

Solution: Fixed it to return an array rather eg

[{"Total_Excavator":2,"Active_Excavator":2,"Total_load":6804}]

Take note of the Square Brackets.
I used  $data[] = json_encode($excavatorArray) instead of
$data = json_encode($excavatorArray)
. Hope it helps someone one day


问:
Rock Paper Scissors score keeps resetting
I'm making a rock, paper, scissors game with a pointing system and it seems to always give me a value of zero every time the scores are revealed. Help is appreciated.-------------------------------------------------------------------------------------------------------------------------------------------------------------</p>

```<code>def play():
    player = input("Which will you choose? Rock, Paper or Scissors? Type 'E' to exit ")

    elements = ['rock', 'paper', 'scissors']

    cpu = random.choice(elements)

    scoreplayer = 0

    scorecpu = 0

    if player.lower() == cpu:
        print("This is a tie, no one scores a point")
        play()

    elif player.lower() == "rock":
        if cpu == "paper":
            print("Paper beats Rock, CPU gains 1 point")
            scorecpu = scorecpu + 1
            play()
        elif cpu == "scissors":
            print("Rock beats Scissors, you gain 1 point")
            scoreplayer = scoreplayer + 1
            play()

    elif player.lower() == "paper":
        if cpu == "scissors":
            print("Scissors beats Paper, CPU gains 1 point")
            scorecpu = scorecpu + 1
            play()
        elif cpu == "rock":
            print("Paper Beats Rock, you gain 1 point")
            scoreplayer = scoreplayer + 1
            play()

    elif player == "scissors":
        if cpu == "rock":
            print("Rock beats Scissors, CPU gains 1 point")
            scorecpu = scorecpu + 1
            play()
        elif cpu == "paper":
            print("Scissors beats Paper, you gain 1 point")
            scoreplayer = scoreplayer + 1
            play()

    elif player.lower() == "e":
        print("")
        print("You have " + str(scoreplayer) + " points")
        print("")
        print("CPU has " + str(scorecpu) + " points")
        sys.exit()

    else:
        play()
</code>```

答:
As already mentioned, you're resetting the score every time you call the play() function.
A solution to your problem is to make your score variable a global variable

```<code>scoreplayer = 0
scorecpu = 0

def play():
    player = input("Which will you choose? Rock, Paper or Scissors? Type 'E' to exit ")

    elements = ['rock', 'paper', 'scissors']

    cpu = random.choice(elements)

    global scoreplayer
    global scorecpu

    # rest of your code

play()
</code>```

When defining variables outside of functions we can access them by using the global keyword

You can read more about the global keyword here: https://www.programiz.com/python-programming/global-keyword

Body:
I'm making a rock, paper, scissors game with a pointing system and it seems to always give me a value of zero every time the scores are revealed. Help is appreciated.-------------------------------------------------------------------------------------------------------------------------------------------------------------

def play():
    player = input("Which will you choose? Rock, Paper or Scissors? Type 'E' to exit ")

    elements = ['rock', 'paper', 'scissors']

    cpu = random.choice(elements)

    scoreplayer = 0

    scorecpu = 0

    if player.lower() == cpu:
        print("This is a tie, no one scores a point")
        play()

    elif player.lower() == "rock":
        if cpu == "paper":
            print("Paper beats Rock, CPU gains 1 point")
            scorecpu = scorecpu + 1
            play()
        elif cpu == "scissors":
            print("Rock beats Scissors, you gain 1 point")
            scoreplayer = scoreplayer + 1
            play()

    elif player.lower() == "paper":
        if cpu == "scissors":
            print("Scissors beats Paper, CPU gains 1 point")
            scorecpu = scorecpu + 1
            play()
        elif cpu == "rock":
            print("Paper Beats Rock, you gain 1 point")
            scoreplayer = scoreplayer + 1
            play()

    elif player == "scissors":
        if cpu == "rock":
            print("Rock beats Scissors, CPU gains 1 point")
            scorecpu = scorecpu + 1
            play()
        elif cpu == "paper":
            print("Scissors beats Paper, you gain 1 point")
            scoreplayer = scoreplayer + 1
            play()

    elif player.lower() == "e":
        print("")
        print("You have " + str(scoreplayer) + " points")
        print("")
        print("CPU has " + str(scorecpu) + " points")
        sys.exit()

    else:
        play()

Body:
As already mentioned, you're resetting the score every time you call the play() function.
A solution to your problem is to make your score variable a global variable

scoreplayer = 0
scorecpu = 0

def play():
    player = input("Which will you choose? Rock, Paper or Scissors? Type 'E' to exit ")

    elements = ['rock', 'paper', 'scissors']

    cpu = random.choice(elements)

    global scoreplayer
    global scorecpu

    # rest of your code

play()

When defining variables outside of functions we can access them by using the global keyword

You can read more about the global keyword here: https://www.programiz.com/python-programming/global-keyword


问:
AngularJS $routeProvider Resolve Method Not Working
In my code, I define the following two routes:

```<code>    $routeProvider.when('/problem/report', {
        templateUrl: '/app/management/problem/reportAProblem.html',
        controller: 'reportAProblemCtrl',
        resolve: {
            authorized: function($http, $location) {
                var path = $location.path();
                return $http.get('/svc/authorize/view?urlPath=' + path).then(function(response) {
                    var data = response.data;
                    if (response.data.result === 'NOT_AUTHORIZED') {
                        throw "NOT_AUTHORIZED";
                    }

                    return data;
                })
            }
        }
    });

    $routeProvider.when('/problem', {
        templateUrl: '/app/management/problem/problem.tmpl.html',
        controller: 'problemCtrl',
        resolve: {
            authorized: ['$authorization', function($authorization) {
                $authorization.authorize();
            }]
        }
    });
</code>```

The first case seems to work. However, the second case has had the function refactored into a Service, and AngularJS does not seem to be waiting for the Promise to resolve before displaying the page.

The refactored code looks like the following:

```<code>angular.module('authorization', [])
.factory('$authorization', ['$http', '$location',function($http, $location) {

    var $authorization = {};

    $authorization.authorize = function() {

        var path = $location.path();
        return $http.get('/svc/authorize/view?urlPath=' + path).then(function(response) {
            var data = response.data;
            if (response.data.result === 'NOT_AUTHORIZED') {
                throw "NOT_AUTHORIZED";
            }

            return data;
        });
    }

    return $authorization;
}]);
</code>```

Can anyone tell me why the second case above doesn't wait for the promise to resolve before displaying the page?

答:
Add return:</p>

```<code>authorized: ['$authorization', function($authorization) { **return** $authorization.authorize(); }]
</code>```

Body:
In my code, I define the following two routes:

    $routeProvider.when('/problem/report', {
        templateUrl: '/app/management/problem/reportAProblem.html',
        controller: 'reportAProblemCtrl',
        resolve: {
            authorized: function($http, $location) {
                var path = $location.path();
                return $http.get('/svc/authorize/view?urlPath=' + path).then(function(response) {
                    var data = response.data;
                    if (response.data.result === 'NOT_AUTHORIZED') {
                        throw "NOT_AUTHORIZED";
                    }

                    return data;
                })
            }
        }
    });

    $routeProvider.when('/problem', {
        templateUrl: '/app/management/problem/problem.tmpl.html',
        controller: 'problemCtrl',
        resolve: {
            authorized: ['$authorization', function($authorization) {
                $authorization.authorize();
            }]
        }
    });

The first case seems to work. However, the second case has had the function refactored into a Service, and AngularJS does not seem to be waiting for the Promise to resolve before displaying the page.

The refactored code looks like the following:

angular.module('authorization', [])
.factory('$authorization', ['$http', '$location',function($http, $location) {

    var $authorization = {};

    $authorization.authorize = function() {

        var path = $location.path();
        return $http.get('/svc/authorize/view?urlPath=' + path).then(function(response) {
            var data = response.data;
            if (response.data.result === 'NOT_AUTHORIZED') {
                throw "NOT_AUTHORIZED";
            }

            return data;
        });
    }

    return $authorization;
}]);

Can anyone tell me why the second case above doesn't wait for the promise to resolve before displaying the page?

Body:
Add return:

authorized: ['$authorization', function($authorization) { **return** $authorization.authorize(); }]


答:
Put the setTimeout inside the for loop and the multiply i with 2000 to set different interval

var dot = document.querySelectorAll('.dot');
for (let i = 0; i < dot.length; i++) {
  setTimeout(function() {
    dot[i].style.backgroundColor = 'blue';
  }, i * 2000);

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  display: flex;
  justify-content: space-around;
}

.dot {
  background-color: red;
  width: 20px;
  height: 20px;
  border-radius: 50%;
}</code>```

```

Title: Apply style with setTimeout()

Body:
I created the next code:

  setTimeout(function () {
        var dot = document.querySelectorAll('.dot');
        for (var i=0;i<dot.length;i++) {
            dot[i].style.backgroundColor = 'blue';
        }
    },2000);

 .container{
        display: flex;
        justify-content: space-around;
    }
   .dot{
       background-color: red;
       width: 20px;
       height: 20px;
       border-radius: 50%;
   }

This code apply background-color for each dot at the same time after 2 seconds, but i want to apply the style for each dot separately. Fo example: after 2 seconds to apply the style for first dot, then after 2 seconds to apply the style for second dot, and so on. Who has a solution?

Body:
Put the setTimeout inside the for loop and the multiply i with 2000 to set different interval

var dot = document.querySelectorAll('.dot');
for (let i = 0; i < dot.length; i++) {
  setTimeout(function() {
    dot[i].style.backgroundColor = 'blue';
  }, i * 2000);

}

.container {
  display: flex;
  justify-content: space-around;
}

.dot {
  background-color: red;
  width: 20px;
  height: 20px;
  border-radius: 50%;
}

<div class="container">
  <div class="dot"></div>
  <div class="dot"></div>
  <div class="dot"></div>
</div>


答:
```<code>  var i = 0;
  var dot = document.querySelectorAll('.dot');
  var interval = setInterval(function () {
    dot[i].style.backgroundColor = 'blue';
    i++;
    if (i >= dot.length) clearInterval(interval);
  },2000);
</code>```

Title: Apply style with setTimeout()