问:
TI-Basic Raycasting (TI-83 Plus)
I've been following this thread: https://www.omnimaga.org/ti-basic-language/raycasting-halp/

I've tried anything. How do I do Raycasting in TI-Basic, is it possible to just draw a simple wall and move around? I have a TI-83 Plus.

答:
Can ray casting be done in TI-83 Basic? Yes; let's try it.

First, what exactly is ray casting?

Ray casting is a term used to describe a collection of algorithms for rendering 3D graphics. What ray casting algorithms generally have in common is that they:

Send out rays from a single point in different directions

Compute the closest object that intersects that ray

Render the part of that object that intersects the ray at a position dependent on the ray's direction

For TI-83, we'll implement a simple ray caster that only sends out horizontal rays. From a top down view, it might looks like this:

Of course, we'll need to use more than 5 rays if we want a decent image. Now that we've defined what we're implementing, let's move on to figuring out how.

What values do we need to keep track of?

This is easy. The values we need to keep track of are right in the ray casting algorithm.

We need to keep track of the rays. Specifically, we need to know their directions.

We need to keep track of the origin of the rays, or the camera's position.

We need to keep track of all of "objects"' locations. For simplicity, we'll just keep track of walls.

Now, the next part is easy too. How do we keep track of these values? Well, since there are a bunch of rays, we'll store their directions in a list, L₁. On the other hand, since there is only one camera, we'll store it's position in two variables, S and T (because they are right above X and Y an the TI-83 keyboard. We'd like to use X and Y, but these get modified by the Line operation we use later). The walls give us more options, but for simplicity, we'll store a matrix that represents a floor plan. If there is non-zero number at a position in the matrix, that means there is a wall at the corresponding location in the world. We'll say that each value in the matrix cooresponds to a 1 × 1 location in the world.

What do we do with the values?

Now that we know what values we need to store (these values are called our model), we need to figure out what we actually have to do with them. In other words, we need to elaborate on the ray casting algorithm.

Before we do anything, we need to set initial states for all of our values. We'll use the contents of [A] for the map information. The starting location of the camera is arbitrary, so we'll just set it at (1.5, 1.5), right in the middle of the first tile.

Before we talk about the direction of the rays, we need to decide on how many to use. Ideally, we'd use at least one ray for each pixel, but the TI-83 has a horizontal resolution of 96 pixels, and using 96 rays may cause our ray caster to be too slow. Instead, we'll use 24 rays, or one ray for every 4 pixels. This should give us a reasonable image quality, while hopefully not being too much for the TI-83 to handle. We also need to choose a Field of View. We'll pick 96°, because that means one pixel represents 1°. Finally, we'll say the middle ray starts pointing 45° below horizontal.

Now, back to the algorithm. By considering how a general raycasting algorithm applies to our model, we get the steps:

Set up the graph screen

Set S and T to 1.5

Get the width and height of the map

Compute the initial directions for each ray

Loop these while running:

For each ray:

Compute if it intersects a wall

If it does, draw a vertical line on the screen representing the wall

If pressing ▲ move forward; Else, if pressing ▼, move backward

If pressing ◀, turn left; Else, if pressing ▶, turn right

If pressing CLEAR, stop running

Let's tackle these one by one.

Implementation

1. Set up the graph screen

We need to turn off the graph axes and set the limits. We'll see why these limits are what they are in part 5.2.2.

```<code>AxesOff
4 → Xmin
24 * 4 + 3 → Xmax
-1 → Ymin
1 → Ymax
</code>```

2. Set S and T to 1.5

Easy:

```<code>1.5 → S
1.5 → T
</code>```

3. Get the width and height of the map

```<code>dim([A]) → L₁
L₁(1) → H
L₁(2) → W
</code>```

4. Compute the initial directions for each ray

Not bad:

```<code>seq((I - 12.5) * 4° + 45°, I, 1, 24) → L₁
</code>```

5. Loop these while running:

```<code>1 → R
While R
    ...
End
</code>```

5.1. For each ray:

```<code>For(I, 1, 24)
    ...
End
</code>```

5.1.1. Compute if it intersects a wall

This is the first really tricky part. Basically, we are going to start at the camera, and then keep moving out along the ray, tile by tile, until we either hit a wall or go out of the map. If we hit a wall we will set C (for collision) to 1.

Within the while loop:

U and V represent the current position of the ray trace

The first If Else block checks in which quadrant the ray is pointing. Then, based on the quadrant it stores prospective next values for U and V into P and Q. Basically, it follows the ray horizontally to the next tile, and stores that into P, and follows the ray vertically to the next tile and stores it to Q.

The next If Else block determines whether P or Q was the right prospective value. Whichever would lead to a shorter distance traveled is the right guess. If we picked the longer one, we would skip a tile. Due to symmetry in trig functions, the new U and V values can be calculated from P and Q regardless of the quadrant. The distance of the step is also updated in this block. We will use the distance later to determine the height of the drawn line.

Finally, the last if statement tests If the current block is a wall. If it is, C is set so that the ray trace stops.

If this part is unclear, let me know and I can add a diagram.

```<code>0 → C
S → U
T → V
0 → D
While C = 0 and 1 ≤ int(U) and int(U) ≤ W and 1 ≤ int(V) and int(V) ≤ H
    L₁(I) → A
    If A > 0° :Then
        If A > 90° :Then
            -int(-U - 1) → P
            int(V + 1) → Q
        Else
            int(U + 1) → P
            int(V + 1) → Q
        End
    Else
        If A > -90° :Then
            int(U + 1) → P
            -int(-V - 1) → Q
        Else
            -int(-U - 1) → P
            -int(-V - 1) → Q
        End
    End
    If abs((P - U) / cos(A)) < abs((Q - V) / sin(A)) :Then
        D + abs((P - U) / cos(A)) → D
        V + (P - U) * tan(A) → V
        P → U
    Else
        D + abs((Q - V) / sin(A)) → D
        U + (Q - V) / tan(A) → U
        Q → V
    End
    If int(U) ≥ 1 and int(U) ≤ W and int(V) ≥ 1 and int(V) ≤ H :Then
        If [A](int(U), int(V))
        1 → C
    End
    If -int(-U + 1) ≥ 1 and -int(-U + 1) ≤ W and -int(-V + 1) ≥ 1 and -int(-V + 1) ≤ H :Then
        If [A](-int(-U + 1), -int(-V + 1))
        1 → C
    End
End
</code>```

5.1.2. If it does, draw a vertical line on the screen representing the wall

This part just uses a little trig to determine how tall the line on screen should be. Since the horizontal FOV is 96° and the resolution of a TI-83 is 96 pixels by 64 pixels, the vertical FOV should be 96° * 64 / 96, or 64°. To find the height of the displayed line, we want to find the inclantion to the top of the wall (the angle required to look up to the top of the wall) divided by half the vertical field of view. We use the value in [A] for the height of the wall. Remember, we set up the graph screen earlier, and since each ray represents four horizontal pixels, we need to draw 4 lines.

Additionally, before drawing the lines, we clear the part of the screen we will be drawing on by drawing 4 full height white lines.

Again, if this part is not clear, I can add a diagram.

```<code>I * 4 → N
Line(N, 1, N, -1, 0)
Line(N + 1, 1, N + 1, -1, 0)
Line(N + 2, 1, N + 2, -1, 0)
Line(N + 3, 1, N + 3, -1, 0)
If C :Then
    tan⁻¹(([A](int(U), int(V)) + [A](-int(-U + 1), -int(-V + 1))) / D) / 32° → Z
    Line(N, Z, N, -Z)
    Line(N + 1, Z, N + 1, -Z)
    Line(N + 2, Z, N + 2, -Z)
    Line(N + 3, Z, N + 3, -Z)
End
</code>```

5.2. If pressing ▲ move forward; Else, if pressing ▼, move backward

This and the next part ar straightforward. F is the angle the camer is facing, and is determined by averaging the middle two rays.

```<code>getKey → K
(L₁(12) + L₁(13)) / 2 → F
If K = 25 :Then
    S + 0.1 * cos(F) → S
    T + 0.1 * sin(F) → T
End
If K = 34 :Then
    S - 0.1 * cos(F) → S
    T - 0.1 * sin(F) → T
End
</code>```

5.3. If pressing ◀, turn left; Else, if pressing ▶, turn right

```<code>If K = 24 :Then
    L₁ + 2° → L₁
End
If K = 26 :Then
    L₁ - 2° → L₁
End
</code>```

5.4. If pressing CLEAR, stop running

```<code>1.5 → S
1.5 → T
</code>```0

Everything together

By putting all of the code together, and removing the whitespace which was added for readability, we get the complete (and ugly) program, shown below. It runs, but it is pretty slow, certainly too slow for a game. Most of the execution time is spent in step 5.1.1, the actual ray casting algorithm. The speed of the ray casting algorithm could potentially be improved by making clever use of builtin procedures, but that's outside the scope of the question.

```<code>1.5 → S
1.5 → T
</code>```1

Title: TI-Basic Raycasting (TI-83 Plus)

Body:
Can ray casting be done in TI-83 Basic? Yes; let's try it.

First, what exactly is ray casting?

Ray casting is a term used to describe a collection of algorithms for rendering 3D graphics. What ray casting algorithms generally have in common is that they:

Send out rays from a single point in different directions

Compute the closest object that intersects that ray

Render the part of that object that intersects the ray at a position dependent on the ray's direction

For TI-83, we'll implement a simple ray caster that only sends out horizontal rays. From a top down view, it might looks like this:

Of course, we'll need to use more than 5 rays if we want a decent image. Now that we've defined what we're implementing, let's move on to figuring out how.

What values do we need to keep track of?

This is easy. The values we need to keep track of are right in the ray casting algorithm.

We need to keep track of the rays. Specifically, we need to know their directions.

We need to keep track of the origin of the rays, or the camera's position.

We need to keep track of all of "objects"' locations. For simplicity, we'll just keep track of walls.

Now, the next part is easy too. How do we keep track of these values? Well, since there are a bunch of rays, we'll store their directions in a list, L₁. On the other hand, since there is only one camera, we'll store it's position in two variables, S and T (because they are right above X and Y an the TI-83 keyboard. We'd like to use X and Y, but these get modified by the Line operation we use later). The walls give us more options, but for simplicity, we'll store a matrix that represents a floor plan. If there is non-zero number at a position in the matrix, that means there is a wall at the corresponding location in the world. We'll say that each value in the matrix cooresponds to a 1 × 1 location in the world.

What do we do with the values?

Now that we know what values we need to store (these values are called our model), we need to figure out what we actually have to do with them. In other words, we need to elaborate on the ray casting algorithm.

Before we do anything, we need to set initial states for all of our values. We'll use the contents of [A] for the map information. The starting location of the camera is arbitrary, so we'll just set it at (1.5, 1.5), right in the middle of the first tile.

Before we talk about the direction of the rays, we need to decide on how many to use. Ideally, we'd use at least one ray for each pixel, but the TI-83 has a horizontal resolution of 96 pixels, and using 96 rays may cause our ray caster to be too slow. Instead, we'll use 24 rays, or one ray for every 4 pixels. This should give us a reasonable image quality, while hopefully not being too much for the TI-83 to handle. We also need to choose a Field of View. We'll pick 96°, because that means one pixel represents 1°. Finally, we'll say the middle ray starts pointing 45° below horizontal.

Now, back to the algorithm. By considering how a general raycasting algorithm applies to our model, we get the steps:

Set up the graph screen

Set S and T to 1.5

Get the width and height of the map

Compute the initial directions for each ray

Loop these while running:

For each ray:

Compute if it intersects a wall

If it does, draw a vertical line on the screen representing the wall

If pressing ▲ move forward; Else, if pressing ▼, move backward

If pressing ◀, turn left; Else, if pressing ▶, turn right

If pressing CLEAR, stop running

Let's tackle these one by one.

Implementation

1. Set up the graph screen

We need to turn off the graph axes and set the limits. We'll see why these limits are what they are in part 5.2.2.

AxesOff
4 → Xmin
24 * 4 + 3 → Xmax
-1 → Ymin
1 → Ymax

2. Set S and T to 1.5

Easy:

1.5 → S
1.5 → T

3. Get the width and height of the map

dim([A]) → L₁
L₁(1) → H
L₁(2) → W

4. Compute the initial directions for each ray

Not bad:

seq((I - 12.5) * 4° + 45°, I, 1, 24) → L₁

5. Loop these while running:

1 → R
While R
    ...
End

5.1. For each ray:

For(I, 1, 24)
    ...
End

5.1.1. Compute if it intersects a wall

This is the first really tricky part. Basically, we are going to start at the camera, and then keep moving out along the ray, tile by tile, until we either hit a wall or go out of the map. If we hit a wall we will set C (for collision) to 1.

Within the while loop:

U and V represent the current position of the ray trace

The first If Else block checks in which quadrant the ray is pointing. Then, based on the quadrant it stores prospective next values for U and V into P and Q. Basically, it follows the ray horizontally to the next tile, and stores that into P, and follows the ray vertically to the next tile and stores it to Q.

The next If Else block determines whether P or Q was the right prospective value. Whichever would lead to a shorter distance traveled is the right guess. If we picked the longer one, we would skip a tile. Due to symmetry in trig functions, the new U and V values can be calculated from P and Q regardless of the quadrant. The distance of the step is also updated in this block. We will use the distance later to determine the height of the drawn line.

Finally, the last if statement tests If the current block is a wall. If it is, C is set so that the ray trace stops.

If this part is unclear, let me know and I can add a diagram.

0 → C
S → U
T → V
0 → D
While C = 0 and 1 ≤ int(U) and int(U) ≤ W and 1 ≤ int(V) and int(V) ≤ H
    L₁(I) → A
    If A > 0° :Then
        If A > 90° :Then
            -int(-U - 1) → P
            int(V + 1) → Q
        Else
            int(U + 1) → P
            int(V + 1) → Q
        End
    Else
        If A > -90° :Then
            int(U + 1) → P
            -int(-V - 1) → Q
        Else
            -int(-U - 1) → P
            -int(-V - 1) → Q
        End
    End
    If abs((P - U) / cos(A)) < abs((Q - V) / sin(A)) :Then
        D + abs((P - U) / cos(A)) → D
        V + (P - U) * tan(A) → V
        P → U
    Else
        D + abs((Q - V) / sin(A)) → D
        U + (Q - V) / tan(A) → U
        Q → V
    End
    If int(U) ≥ 1 and int(U) ≤ W and int(V) ≥ 1 and int(V) ≤ H :Then
        If [A](int(U), int(V))
        1 → C
    End
    If -int(-U + 1) ≥ 1 and -int(-U + 1) ≤ W and -int(-V + 1) ≥ 1 and -int(-V + 1) ≤ H :Then
        If [A](-int(-U + 1), -int(-V + 1))
        1 → C
    End
End

5.1.2. If it does, draw a vertical line on the screen representing the wall

This part just uses a little trig to determine how tall the line on screen should be. Since the horizontal FOV is 96° and the resolution of a TI-83 is 96 pixels by 64 pixels, the vertical FOV should be 96° * 64 / 96, or 64°. To find the height of the displayed line, we want to find the inclantion to the top of the wall (the angle required to look up to the top of the wall) divided by half the vertical field of view. We use the value in [A] for the height of the wall. Remember, we set up the graph screen earlier, and since each ray represents four horizontal pixels, we need to draw 4 lines.

Additionally, before drawing the lines, we clear the part of the screen we will be drawing on by drawing 4 full height white lines.

Again, if this part is not clear, I can add a diagram.

I * 4 → N
Line(N, 1, N, -1, 0)
Line(N + 1, 1, N + 1, -1, 0)
Line(N + 2, 1, N + 2, -1, 0)
Line(N + 3, 1, N + 3, -1, 0)
If C :Then
    tan⁻¹(([A](int(U), int(V)) + [A](-int(-U + 1), -int(-V + 1))) / D) / 32° → Z
    Line(N, Z, N, -Z)
    Line(N + 1, Z, N + 1, -Z)
    Line(N + 2, Z, N + 2, -Z)
    Line(N + 3, Z, N + 3, -Z)
End

5.2. If pressing ▲ move forward; Else, if pressing ▼, move backward

This and the next part ar straightforward. F is the angle the camer is facing, and is determined by averaging the middle two rays.

getKey → K
(L₁(12) + L₁(13)) / 2 → F
If K = 25 :Then
    S + 0.1 * cos(F) → S
    T + 0.1 * sin(F) → T
End
If K = 34 :Then
    S - 0.1 * cos(F) → S
    T - 0.1 * sin(F) → T
End

5.3. If pressing ◀, turn left; Else, if pressing ▶, turn right

If K = 24 :Then
    L₁ + 2° → L₁
End
If K = 26 :Then
    L₁ - 2° → L₁
End

5.4. If pressing CLEAR, stop running

If K = 45
0 → R

Everything together

By putting all of the code together, and removing the whitespace which was added for readability, we get the complete (and ugly) program, shown below. It runs, but it is pretty slow, certainly too slow for a game. Most of the execution time is spent in step 5.1.1, the actual ray casting algorithm. The speed of the ray casting algorithm could potentially be improved by making clever use of builtin procedures, but that's outside the scope of the question.

AxesOff
4→Xmin
24*4+3→Xmax
-1→Ymin
1→Ymax
1.5→S
1.5→T
dim([A])→L₁
L₁(1)→H
L₁(2)→W
seq((I-12.5)*4°+45°,I,1,24)→L₁
1→R
While R
For(I,1,24)
0→C
S→U
T→V
0→D
While C=0 and 1≤int(U) and int(U)≤W and 1≤int(V) and int(V)≤H
L₁(I)→A
If A>0°:Then
If A>90°:Then
-int(-U-1)→P
int(V+1)→Q
Else
int(U+1)→P
int(V+1)→Q
End
Else
If A>-90°:Then
int(U+1)→P
-int(-V-1)→Q
Else
-int(-U-1)→P
-int(-V-1)→Q
End
End
If abs((P-U)/cos(A))<abs((Q-V)/sin(A)):Then
D+abs((P-U)/cos(A))→D
V+(P-U)*tan(A)→V
P→U
Else
D+abs((Q-V)/sin(A))→D
U+(Q-V)/tan(A)→U
Q→V
End
If int(U)≥1 and int(U)≤W and int(V)≥1 and int(V)≤H:Then
If [A](int(U),int(V))
1→C
End
If -int(-U+1)≥1 and -int(-U+1)≤W and -int(-V+1)≥1 and -int(-V+1)≤H:Then
If [A](-int(-U+1),-int(-V+1))
1→C
End
End
I*4→N
Line(N,1,N,-1,0)
Line(N+1,1,N+1,-1,0)
Line(N+2,1,N+2,-1,0)
Line(N+3,1,N+3,-1,0)
If C:Then
tan⁻¹(([A](int(U),int(V))+[A](-int(-U+1),-int(-V+1)))/D)/32°→Z
Line(N,Z,N,-Z)
Line(N+1,Z,N+1,-Z)
Line(N+2,Z,N+2,-Z)
Line(N+3,Z,N+3,-Z)
End
End
getKey→K
(L₁(12)+L₁(13))/2→F
If K=25:Then
S+0.1*cos(F)→S
T+0.1*sin(F)→T
End
If K=34:Then
S-0.1*cos(F)→S
T-0.1*sin(F)→T
End
If K=24:Then
L₁+2°→L₁
End
If K=26:Then
L₁-2°→L₁
End
If K=45
0→R
End


来源: stackexchange

问:
Cannot access the ADLS account '(accountname)'
I am attempting to use azure data factory v2 to copy data to an Azure data lake store sink.  I have created the data lake store, created an AD web application following the article here, and made sure that the account has access to the data lake store.  However, I receive the following error whenever I try to run a pipeline involving a single copy activity that uses the data lake store as a sink:

Activity Copy (copy activity name) failed: Failed to detect region of linked service 'AzureDataLakeStore' : 'LS_DataLakeStore' with error 'Cannot access the ADLS account '(data lake store account name)'. Please make sure it has been created.', please explicitly specify the location of the integration runtime referred by the connectVia property to avoid region detection if needed.

I have triple checked that the account name is correct.  I've granted the AD application 'Owner' access to the subscription just to make sure it's not a permissions issue.  And I even attempted to create an Adf Integration Runtime so I can specify it via the 'connectVia' property as suggested by the error, all with no luck.

Ideas on why ADF can't seem to see my data lake store?

Here is my Linked Service json:

```<code>{
  "name": "LS_DataLakeStore",
  "properties": {
    "type": "AzureDataLakeStore",
    "typeProperties": {
      "dataLakeStoreUri": "adl://{my adls account name}.azuredatalakestore.net/",
      "servicePrincipalId": "{the application id of the AD account I created}",
      "servicePrincipalKey": {
        "type": "SecureString",
        "value": "{the value of the key for the AD account I generated}"
      },
      "tenant": "{my tenant id (I also tried using the tenant domain name here as well)}",
      "subscriptionId": "{the subscription id in which the ADF and ADLS are located}",
      "resourceGroupName": "{the resource group name in which the ADF and ADLS are located}"
    }
  }
}
</code>```

答:
make sure the subscriptionId, resourceGroupName you provide in the linkeservice typeProperties are indeed ones that the data lake account belongs to.

make sure you have grant at least "Reader" role to the user/Serviceprincipal on the data lake account, here is how to make it:

a.     Go to Azure Portal, find the Data Lake Store account

b.     Click “Access Control (IAM)” on the blade of the Data Lake Store

c.     Click "Add" in the blade of "Access Control (IAM)"

d.     Set "Role" to "Reader", and specify the AAD app you created

If still doesn't work, please try specify an execution location.

For ADFV1, executionLocation is a property for copy activity "typeProperties";

"activities":[

  {
    "name": "SqlServertoAzureSearchIndex",
    "description": "copy activity",
    "type": "Copy",
    ...
    "typeProperties": {
      "source": {
        "type": "SqlSource”
      },
      "sink": {
        "type": "AzureSearchIndexSink"
      },
      "executionLocation": "West US",
    },
   ...
  }
]

For ADFV2, specify a connectVia on your AzureDataLakeStoreLinkedService to link to a CloudIR like this:

```<code>"integrationRuntimes": [
        {
            "name": "cloudIR",
            "properties": {
                "type": "Managed",
                "typeProperties": {
                    "computeProperties": {
                        "location": "East US 2"
                    }
                }
            }
        }
    ]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am attempting to use azure data factory v2 to copy data to an Azure data lake store sink.  I have created the data lake store, created an AD web application following the article here, and made sure that the account has access to the data lake store.  However, I receive the following error whenever I try to run a pipeline involving a single copy activity that uses the data lake store as a sink:

Activity Copy (copy activity name) failed: Failed to detect region of linked service 'AzureDataLakeStore' : 'LS_DataLakeStore' with error 'Cannot access the ADLS account '(data lake store account name)'. Please make sure it has been created.', please explicitly specify the location of the integration runtime referred by the connectVia property to avoid region detection if needed.

I have triple checked that the account name is correct.  I've granted the AD application 'Owner' access to the subscription just to make sure it's not a permissions issue.  And I even attempted to create an Adf Integration Runtime so I can specify it via the 'connectVia' property as suggested by the error, all with no luck.

Ideas on why ADF can't seem to see my data lake store?

Here is my Linked Service json:

{
  "name": "LS_DataLakeStore",
  "properties": {
    "type": "AzureDataLakeStore",
    "typeProperties": {
      "dataLakeStoreUri": "adl://{my adls account name}.azuredatalakestore.net/",
      "servicePrincipalId": "{the application id of the AD account I created}",
      "servicePrincipalKey": {
        "type": "SecureString",
        "value": "{the value of the key for the AD account I generated}"
      },
      "tenant": "{my tenant id (I also tried using the tenant domain name here as well)}",
      "subscriptionId": "{the subscription id in which the ADF and ADLS are located}",
      "resourceGroupName": "{the resource group name in which the ADF and ADLS are located}"
    }
  }
}

Body:
make sure the subscriptionId, resourceGroupName you provide in the linkeservice typeProperties are indeed ones that the data lake account belongs to.

make sure you have grant at least "Reader" role to the user/Serviceprincipal on the data lake account, here is how to make it:

a.     Go to Azure Portal, find the Data Lake Store account

b.     Click “Access Control (IAM)” on the blade of the Data Lake Store

c.     Click "Add" in the blade of "Access Control (IAM)"

d.     Set "Role" to "Reader", and specify the AAD app you created

If still doesn't work, please try specify an execution location.

For ADFV1, executionLocation is a property for copy activity "typeProperties";

"activities":[

  {
    "name": "SqlServertoAzureSearchIndex",
    "description": "copy activity",
    "type": "Copy",
    ...
    "typeProperties": {
      "source": {
        "type": "SqlSource”
      },
      "sink": {
        "type": "AzureSearchIndexSink"
      },
      "executionLocation": "West US",
    },
   ...
  }
]

For ADFV2, specify a connectVia on your AzureDataLakeStoreLinkedService to link to a CloudIR like this:

"integrationRuntimes": [
        {
            "name": "cloudIR",
            "properties": {
                "type": "Managed",
                "typeProperties": {
                    "computeProperties": {
                        "location": "East US 2"
                    }
                }
            }
        }
    ]


问:
Can I use mock data and proxy api data at the same time in my react project when using node express as a proxy server?
During my react project development process, I use express to config a proxy sever. There is a api interface invocation always fail, so I want to mock this one. I tried many times but still failed. Is anyone know how to config it? Your response will be highly appreciated.</p>

答:
I had a similar requirement where I needed to mock only a few calls and hit the original API for the others. For this, I hacked a tool Beeceptor for proxying and mocking at the same time. You can define mocking rule to decide when to mock, and the other calls are routed to original API.

This tool is language/platform agnostic as it is hosted and provides subdomain/endpoint.

(Disclaimer: I am the author of Beeceptor, and sharing here as it fulfills the precise need.)


问:
returning component inside function not working
I've a component which i'm rendering by considering some conditions. It's done as follows

```<code>const Test = () => {
    return <div className="text_align_center white_color">
        <span><i className="fa fa-exclamation-triangle" aria-hidden="true"></i>
            No internet connection. Please check your connection settings and try again
        </span>
    </div>
}

function checkInternetConnection(){

    isOnline().then(online => {

       if(online === true){

           console.log("Came in here")

            return <Test/>

        }

    });
}
</code>```

Then i'm calling my function as follows

```<code>const App = () => (
    <div className="ui container">

        {checkInternetConnection()}
);
</code>```

But the issue is eventhough i'm getting the console log inside checkInternetConnection function, the returned component is not appearing. What can be cause of this?

答:
Since isOnline() has a .then() clause I assume it is an asynchronous Promise?

If that is the case, then that is your culprit. The component will not re-render when the promise returns as React only renders when state changes, which is not the case here.

To get the behavior you describe do the rendering of the Test component based on a state variable and set it in your .then() when the promise returns.

Body:
I've a component which i'm rendering by considering some conditions. It's done as follows

const Test = () => {
    return

            No internet connection. Please check your connection settings and try again

}

function checkInternetConnection(){

    isOnline().then(online => {

       if(online === true){

           console.log("Came in here")

            return <Test/>

        }

    });
}

Then i'm calling my function as follows

const App = () => (

        {checkInternetConnection()}
);

But the issue is eventhough i'm getting the console log inside checkInternetConnection function, the returned component is not appearing. What can be cause of this?


问:
In AngularJS, why isn't a $scope variable accessible from a simple function?
My code is as shown below:

```<code>angular.module('xyz', [])
    .controller('listController', ['$scope',
        function($scope) {
            $scope.deliveryOptions = 0;
            var vm = this;

            function doTransaction() {
                console.log('delivery options is ' + vm.$scope.deliveryOptions);
            }
        }
    ]);
</code>```

Here inside console.log(delivery options), it gives me error that it is Unable to get property 'deliveryOptions' of undefined or null reference. So how can I access that variable?

答:
The problem is that the $scope is not defined on the vm object.
To solve this you should either define everything on the $scope object like this

```<code>angular.module('xyz', [])
    .controller('listController', ['$scope',
        function($scope) {
            $scope.deliveryOptions = 0;

            $scope.doTransaction = function() {
                console.log('delivery options is ' + $scope.deliveryOptions);
            }
        }
    ]);
</code>```

Or on the vm object

```<code>angular.module('xyz', [])
    .controller('listController',
        function() {
            var vm = this;
            vm.deliveryOptions = 0;

            vm.doTransaction = function() {
                console.log('delivery options is ' + vm.deliveryOptions);
            }
        }
    );
</code>```

Mixing vm and $scope is not the best way to go

Body:
My code is as shown below:

angular.module('xyz', [])
    .controller('listController', ['$scope',
        function($scope) {
            $scope.deliveryOptions = 0;
            var vm = this;

            function doTransaction() {
                console.log('delivery options is ' + vm.$scope.deliveryOptions);
            }
        }
    ]);

Here inside console.log(delivery options), it gives me error that it is Unable to get property 'deliveryOptions' of undefined or null reference. So how can I access that variable?

Body:
The problem is that the $scope is not defined on the vm object.
To solve this you should either define everything on the $scope object like this

angular.module('xyz', [])
    .controller('listController', ['$scope',
        function($scope) {
            $scope.deliveryOptions = 0;

            $scope.doTransaction = function() {
                console.log('delivery options is ' + $scope.deliveryOptions);
            }
        }
    ]);

Or on the vm object

angular.module('xyz', [])
    .controller('listController',
        function() {
            var vm = this;
            vm.deliveryOptions = 0;

            vm.doTransaction = function() {
                console.log('delivery options is ' + vm.deliveryOptions);
            }
        }
    );

Mixing vm and $scope is not the best way to go


问:
How can I sum strings in one column into one row in Microsoft SQL? Group by does not work since it is MSSQL
for example we have table with three columns

```<code>Column A |  Column B | Column C
-------------------------------
P1       |    10     |    A
P1       |    20     |    B
P1       |    30     |    C
P2       |    30     |    D
P2       |    40     |    E
</code>```

How do I have to write SELECT query in Microsoft SQL to have this kind of result

```<code>Column A |     Column B      |   Column C
------------------------------------------
P1       |    10, 20, 30     |    A, B, C
P2       |    30, 40         |    D, E
</code>```

答:
You could try xml method with stuff()  function

```<code>select t.[Column A] ,
         [Column B] =
                stuff(
                       (select  ','+cast([Column B] as varchar) from <table> where [Column A]  = t.[Column A]  for xml path('')),
                       1,1,''),
         [Column C] = stuff(
                       (select  ','+[Column C] from <table> where [Column A] = t.[Column A] for xml path('')),
                       1,1,'')
from <table> t
group by t.[Column A]
</code>```

Body:
for example we have table with three columns

Column A |  Column B | Column C
-------------------------------
P1       |    10     |    A
P1       |    20     |    B
P1       |    30     |    C
P2       |    30     |    D
P2       |    40     |    E

How do I have to write SELECT query in Microsoft SQL to have this kind of result

Column A |     Column B      |   Column C
------------------------------------------
P1       |    10, 20, 30     |    A, B, C
P2       |    30, 40         |    D, E

Body:
You could try xml method with stuff()  function

select t.[Column A] ,
         [Column B] =
                stuff(
                       (select  ','+cast([Column B] as varchar) from <table> where [Column A]  = t.[Column A]  for xml path('')),
                       1,1,''),
         [Column C] = stuff(
                       (select  ','+[Column C] from <table> where [Column A] = t.[Column A] for xml path('')),
                       1,1,'')
from <table> t
group by t.[Column A]


问:
Check if class attribute was defined or derived in given class
Example

```<code>class A:
    foo = 1

class B:
    foo = 2

class C:
    foo = 3

class D(A, B, C):
    pass

def collect_foo(cls):
    import inspect
    foos = []
    for c in inspect.getmro(cls):
        if hasattr(c, 'foo'):
            foos.append(c.foo)
    return foos
</code>```

Now collect_foo(D) returns [1, 1, 2, 3] - 1 is doubled as D derives it from A. The question is - how to get unique foos. First thing which came to my mind was checking if property is derived or declared in given class - is it possible? How to do that?

答:
I agree with the accepted answer, but a @classmethod did not match my case...

I found it useful to check the class dict from the context of a base class or mix-in, where I only want to execute some code path if it applies to the derived class, such as if a particular method is overridden.

i.e. (in Python 3.6):

if method_name in self.__class__.__dict__.keys():
    # do something

I rationalized it as follows.

self is the instance

__class__ is that instance's actual type

therefore, dict only contains the methods actually overridden in the derived class.

ContentLicense: CC BY-SA 2.5

Body:
Example

class A:
    foo = 1

class B:
    foo = 2

class C:
    foo = 3

class D(A, B, C):
    pass

def collect_foo(cls):
    import inspect
    foos = []
    for c in inspect.getmro(cls):
        if hasattr(c, 'foo'):
            foos.append(c.foo)
    return foos

Now collect_foo(D) returns [1, 1, 2, 3] - 1 is doubled as D derives it from A. The question is - how to get unique foos. First thing which came to my mind was checking if property is derived or declared in given class - is it possible? How to do that?


问:
How to keep all intermediate property variables in a deeply nested destructure
Given this:

```<code>var metadata = {
    title: 'Scratchpad',
    translations: [
       {
        title: 'JavaScript-Umgebung'
       }
    ]
};

const output = ({
  title: englishTitle,
  translations: [{
    title: localeTitle
  }]
}) => (
    console.log(englishTitle), // "Scratchpad"
    console.log(localeTitle)  // "JavaScript-Umgebung"
)

output(metadata);
</code>```

Now translations is undefined:

```<code>console.log(JSON.stringify(translations))  // ❌ "undefined"
</code>```

Question: Is there a way to create a variable translations within the params destructure expressions (e.g. within the function param parenthesis)

答:
You can destructure translations as well as it's inner members:

var metadata = {
    title: 'Scratchpad',
    translations: [
       {
        title: 'JavaScript-Umgebung'
       }
    ]
};

const output = ({
  title: englishTitle,
  translations, // get translations
  translations: [{
    title: localeTitle
  }]
}) => (
    console.log(englishTitle), // "Scratchpad"
    console.log(localeTitle),  // "JavaScript-Umgebung"
    console.log(translations)  // [{ title: 'JavaScript-Umgebung' }]
)

output(metadata);```

Body:
Given this:

var metadata = {
    title: 'Scratchpad',
    translations: [
       {
        title: 'JavaScript-Umgebung'
       }
    ]
};

const output = ({
  title: englishTitle,
  translations: [{
    title: localeTitle
  }]
}) => (
    console.log(englishTitle), // "Scratchpad"
    console.log(localeTitle)  // "JavaScript-Umgebung"
)

output(metadata);

Now translations is undefined:

console.log(JSON.stringify(translations))  // ❌ "undefined"

Question: Is there a way to create a variable translations within the params destructure expressions (e.g. within the function param parenthesis)


问:
How to use a ListView inside a ExpandableList?
I've been working with a custom ExpandableList (see example picture below) where each item always has one child. This child consists of three parts. Each part has a header (red bars) and below that an Empty item OR a list of items. The length of this list will vary.

The first way I tried to do this is by adding a ViewStub below the empty item, which I inflated with a custom view, which also contained a ViewStub at the end which I inflated in turn for the next item, thus adding items recursively to create this sort of list of items. Sadly this resulted in StackOverflowError's when the list became too long (With short lists this worked perfectly).

So on my second try I tried using a ListView with a custom adapter instead. Sadly this list only used a small part of my screen and the rest of the items where occluded behind the header of the next part (This mini list looked scrollable as a second scrollbar appeared next to it, but it did not scroll. Not that I would consider this scrolling inside a scrolling list to be a good solution, but just wanted to mention this).

Can anyone tell me how I can tell this list of items to not be scrollable and take up all the room that it needs (does it know what size it is going to be when the child node is created??) or help me with a alternative solution to my problem? (Ooh, and I have considered putting an unholy amount of ViewStubs inside my layout, but that just seems idiotic and really bad practice. Correct me if I'm wrong)

答:
If I understood you correctly, then why don't you just take an ExpandableList + Adapter that implements ExpandableListAdapter? It's a somewhat ugly approach but it works and isn't much hassle.

MyAdapter implements ExpandableListAdapter

```<code>@Override
public View getChildView(int groupPosition, int childPosition,boolean isLastChild, View convertView, ViewGroup parent) {

}
</code>```

In this method you could simply figure out if the current childPosition would be one of the headers or one of the children and inflate the appropriate View from xml.

Body:
If I understood you correctly, then why don't you just take an ExpandableList + Adapter that implements ExpandableListAdapter? It's a somewhat ugly approach but it works and isn't much hassle.

MyAdapter implements ExpandableListAdapter

@Override
public View getChildView(int groupPosition, int childPosition,boolean isLastChild, View convertView, ViewGroup parent) {

}

In this method you could simply figure out if the current childPosition would be one of the headers or one of the children and inflate the appropriate View from xml.


问:
How to persist variables between vNext phases
I'm trying to write a VSTS/vNext release process to disable release targets from F5 load-balancer pools e.g.:

```<code>Disable-PoolMembers (logfile) [run on agent phase / Powershell script]
if that will cause an outage
    ask for override          [agentless phase]
    if override
        Disable-PoolMembers   [run on agent phase / Powershell script]
Wait for Validation           [agentless phase]
Enable-PoolMembers (logfile)  [run on agent phase / Powershell script]
</code>```

When my Disable-PoolMembers.ps1 detects that disabling the requested pool members would result in a pool with no available/enabled members it will set a vsts variable with:

```<code>Write-Output ("##vso[task.setvariable variable=OutageCondition;]true")
</code>```

And then in the 'ask for override' agentless phase there is a custom condition of

```<code>and(succeeded(), eq(variables['OutageCondition'], 'true'))
</code>```

But the override agentless phase never executes.

I've put in some inline powershell scripts in the various phases to show what the variable value is.
In the Disable-PoolMembers phase I see that the OutageCondition value is set to true, but in the Enable-PoolMembers agent phase it is set to false.
So it appears that variables set using logging commands only persist in the phase that they were set.

I have tried not defining the variable at all and setting it on the fly in the powershell script with the same results (value is set, within the phase; but is not available in subsequent phases).
And I have tried setting the variable in VSTS as a Release scope and the variable is available in all phases at it's defined value, but it's Powershell-changed value is only available in the phase in which it is set.

Is this expected behavior: ##vso only effects values within the phase?
Is there something I can do to make the change persist through subsequent phases?
Is there a better approach?

答:
Variables can not be persisted in another phase for now. The variable’s value will be used the original defined for the variable not you changed by Write-Host.

There is the issue for variables not persistent between phases, you can follow up.

Body:
I'm trying to write a VSTS/vNext release process to disable release targets from F5 load-balancer pools e.g.:

Disable-PoolMembers (logfile) [run on agent phase / Powershell script]
if that will cause an outage
    ask for override          [agentless phase]
    if override
        Disable-PoolMembers   [run on agent phase / Powershell script]
Wait for Validation           [agentless phase]
Enable-PoolMembers (logfile)  [run on agent phase / Powershell script]

When my Disable-PoolMembers.ps1 detects that disabling the requested pool members would result in a pool with no available/enabled members it will set a vsts variable with:

Write-Output ("##vso[task.setvariable variable=OutageCondition;]true")

And then in the 'ask for override' agentless phase there is a custom condition of

and(succeeded(), eq(variables['OutageCondition'], 'true'))

But the override agentless phase never executes.

I've put in some inline powershell scripts in the various phases to show what the variable value is.
In the Disable-PoolMembers phase I see that the OutageCondition value is set to true, but in the Enable-PoolMembers agent phase it is set to false.
So it appears that variables set using logging commands only persist in the phase that they were set.

I have tried not defining the variable at all and setting it on the fly in the powershell script with the same results (value is set, within the phase; but is not available in subsequent phases).
And I have tried setting the variable in VSTS as a Release scope and the variable is available in all phases at it's defined value, but it's Powershell-changed value is only available in the phase in which it is set.

Is this expected behavior: ##vso only effects values within the phase?
Is there something I can do to make the change persist through subsequent phases?
Is there a better approach?


问:
change button based on previously "liked" status by usr django
I am new to Django and am trying to create a favorite application.
I would like to have the liked button change based on whether or not the user has already favorited the physician.

I pass physicians and liked list to my template but not sure what to do next to extract liked from the array, and not sure if this the most elegant way to approach this.

Any help would be much appreciated!

models.py

```<code>class Physician(models.Model):
    speciality = models.CharField(null=False, blank=False, max_length=30)
    first_name = models.CharField(null=False, blank=False, max_length=50)
    last_name = models.CharField(null=False, blank=False, max_length=50)
    title = models.CharField(null=False, blank=False, max_length=2)
    address1 = models.CharField(null=False, blank=True, max_length=50)
    address2 = models.CharField(null=True, blank=True, max_length=20)
    city = models.CharField(null=False, blank=False, max_length=50)
    state = models.CharField(null=False, blank=False, max_length=2)
    zip = models.CharField(null=False, blank=False, max_length=12)
    likes = models.IntegerField(default=1)

def __str__(self):
    template = '{0.last_name} {0.first_name} {0.speciality}'
    return template.format(self)

class Voter(models.Model):
    user = models.ForeignKey(User)
    physician = models.ForeignKey(Physician)
</code>```

My template is

```<code>    {% if physicians %}
        {% for physician in physicians  %}
            <tr>
            <td>
            <a href="/getmd/{{physician.id}}/">
                {{ physician.last_name }}, {{ physician.first_name }} </a>
            </td>
            <td>{{ physician.state }}</td>
            <td>{{ physician.speciality }}</td>
            <td>{{ physician.id}}</td>
            <td><strong id="like_count{{physician.id}}">{{ physician.likes }}</strong> </td>
            <td>
                {% if user.is_authenticated %}

                    {% if likedalready.physician].liked   %}

                        <button id="alreadyvoted" data-catid="{{physician.id}}" class="likes btn btn-secondary" type="button" title="Already faved">
                        <span class="glyphicon glyphicon-check"></span>
                        Faved
                        </button>
                    {%else%}
                        <button id="{{physician.id}}like" data-catid="{{physician.id}}" class="likes btn btn-primary" type="button" title="Fave Me">
                            <span class="glyphicon glyphicon-thumbs-up"></span>
                            Fav
                        </button>

                    {% endif %}

                {% endif %}

            </td>

            </tr>
        {% endfor %}

    {% else %}
    <p>Sign in to fave</p>
    {% endif %}
</tbody>
</code>```

my views.py
def physicians(request):

```<code>user = User;
liked = False;
args = {}
args.update(csrf(request))
physicians = Physician.objects.all().order_by('last_name')

page = request.GET.get('page', 1)
paginator = Paginator(physicians, 10)
try:
    physicians = paginator.page(page)
except PageNotAnInteger:
    physicians = paginator.page(1)
except EmptyPage:
    physicians = paginator.page(paginator.num_pages)

#Create list of already liked physicians
return_list = []

for physician in physicians:
    liked = Voter.objects.filter(physician_id=physician.id, user_id=request.user.id).exists()
    return_list.append((physician, {'liked': liked}))

args['physicians'] = physicians
return render(request, 'physicians.html', args, {'liked': return_list})
</code>```

答:
Firstly change your model design,

Remove Voter Model and add a ManyToMany Field in Physician model. Also remove likes attribute from Physician model,

```<code>class Physician(models.Model):
    ....
    #users liked the physcian
    likers = models.ManyToManyField(User, related_name='liked_physicians')
</code>```

views.py

```<code>context['physicians'] = Physician.objects.all().annotate(
    total_likes=Count('likers')
)
</code>```

Write a template tag to check (count/exists) whether loggedin user liked the physician or not

```<code>@register.filter
def is_liker(physician, user):
    return physician.likers.filter(id=user.id).exists()
</code>```

template

```<code>{% for physician in physicians  %}

    {% if physcian|is_liker:request.user == True %}
      liked
    {% else %}
      <button>Like</button>
    {% endif %}

{% endfor %}
</code>```

Body:
I am new to Django and am trying to create a favorite application.
I would like to have the liked button change based on whether or not the user has already favorited the physician.

I pass physicians and liked list to my template but not sure what to do next to extract liked from the array, and not sure if this the most elegant way to approach this.

Any help would be much appreciated!

models.py

class Physician(models.Model):
    speciality = models.CharField(null=False, blank=False, max_length=30)
    first_name = models.CharField(null=False, blank=False, max_length=50)
    last_name = models.CharField(null=False, blank=False, max_length=50)
    title = models.CharField(null=False, blank=False, max_length=2)
    address1 = models.CharField(null=False, blank=True, max_length=50)
    address2 = models.CharField(null=True, blank=True, max_length=20)
    city = models.CharField(null=False, blank=False, max_length=50)
    state = models.CharField(null=False, blank=False, max_length=2)
    zip = models.CharField(null=False, blank=False, max_length=12)
    likes = models.IntegerField(default=1)

def __str__(self):
    template = '{0.last_name} {0.first_name} {0.speciality}'
    return template.format(self)

class Voter(models.Model):
    user = models.ForeignKey(User)
    physician = models.ForeignKey(Physician)

My template is

    {% if physicians %}
        {% for physician in physicians  %}

                {{ physician.last_name }}, {{ physician.first_name }}

            {{ physician.state }}
            {{ physician.speciality }}
            {{ physician.id}}
            {{ physician.likes }}

                {% if user.is_authenticated %}

                    {% if likedalready.physician].liked   %}

                        <button id="alreadyvoted" data-catid="{{physician.id}}" class="likes btn btn-secondary" type="button" title="Already faved">

                        Faved
                        </button>
                    {%else%}
                        <button id="{{physician.id}}like" data-catid="{{physician.id}}" class="likes btn btn-primary" type="button" title="Fave Me">

                            Fav
                        </button>

                    {% endif %}

                {% endif %}

        {% endfor %}

    {% else %}

Sign in to fave

    {% endif %}

my views.py
def physicians(request):

user = User;
liked = False;
args = {}
args.update(csrf(request))
physicians = Physician.objects.all().order_by('last_name')

page = request.GET.get('page', 1)
paginator = Paginator(physicians, 10)
try:
    physicians = paginator.page(page)
except PageNotAnInteger:
    physicians = paginator.page(1)
except EmptyPage:
    physicians = paginator.page(paginator.num_pages)

#Create list of already liked physicians
return_list = []

for physician in physicians:
    liked = Voter.objects.filter(physician_id=physician.id, user_id=request.user.id).exists()
    return_list.append((physician, {'liked': liked}))

args['physicians'] = physicians
return render(request, 'physicians.html', args, {'liked': return_list})

Body:
Firstly change your model design,

Remove Voter Model and add a ManyToMany Field in Physician model. Also remove likes attribute from Physician model,

class Physician(models.Model):
    ....
    #users liked the physcian
    likers = models.ManyToManyField(User, related_name='liked_physicians')

views.py

context['physicians'] = Physician.objects.all().annotate(
    total_likes=Count('likers')
)

Write a template tag to check (count/exists) whether loggedin user liked the physician or not

@register.filter
def is_liker(physician, user):
    return physician.likers.filter(id=user.id).exists()

template

{% for physician in physicians  %}

    {% if physcian|is_liker:request.user == True %}
      liked
    {% else %}
      <button>Like</button>
    {% endif %}

{% endfor %}


问:
2D Density or Frquency Scatter Plot in python
How can I make a scatter plot colored by density in matplotlib?
When I plot a colorbar it shows density scale, I want counts/percentage instead. How to convert density estimation to frequency counts?

Expected result is Fig.3 on page 8 of this paper: https://www.atmos-meas-tech.net/9/3293/2016/amt-9-3293-2016.pdf

If anyone can guide me to draw a plot similar to one shown in paper, it will be really helpful. Thank you in advance.

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde

# Generate fake data
x = np.random.normal(size=1000)
y = x * 3 + np.random.normal(size=1000)

# Calculate the point density
xy = np.vstack([x,y])
z = gaussian_kde(xy)(xy)

fig, ax = plt.subplots()
cax=ax.scatter(x, y, c=z, s=10, cmap=plt.cm.jet)
cbar = fig.colorbar(cax)
plt.show()
</code>```

Another Method Tried:

```<code>#libraries
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import kde

# create data
x = np.random.normal(size=500)
y = x * 3 + np.random.normal(size=500)

# Evaluate a gaussian kde on a regular grid of nbins x nbins over
nbins=50
k = kde.gaussian_kde([x,y])
xi, yi = np.mgrid[min(x):max(x):nbins*1j, min(y):max(y):nbins*1j]
zi = k(np.vstack([xi.flatten(), yi.flatten()]))

# Add color bar
plt.pcolormesh(xi, yi, zi.reshape(xi.shape), cmap=plt.cm.jet)
plt.colorbar()
plt.show()
</code>```

答:
That's not a histogram, it's just sampling your kde on a grid...

Try this: plt.hist2d(x, y)

you can specify the bins using bins=whatever argument and many more options...

Body:
How can I make a scatter plot colored by density in matplotlib?
When I plot a colorbar it shows density scale, I want counts/percentage instead. How to convert density estimation to frequency counts?

Expected result is Fig.3 on page 8 of this paper: https://www.atmos-meas-tech.net/9/3293/2016/amt-9-3293-2016.pdf

If anyone can guide me to draw a plot similar to one shown in paper, it will be really helpful. Thank you in advance.

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde

# Generate fake data
x = np.random.normal(size=1000)
y = x * 3 + np.random.normal(size=1000)

# Calculate the point density
xy = np.vstack([x,y])
z = gaussian_kde(xy)(xy)

fig, ax = plt.subplots()
cax=ax.scatter(x, y, c=z, s=10, cmap=plt.cm.jet)
cbar = fig.colorbar(cax)
plt.show()

Another Method Tried:

#libraries
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import kde

# create data
x = np.random.normal(size=500)
y = x * 3 + np.random.normal(size=500)

# Evaluate a gaussian kde on a regular grid of nbins x nbins over
nbins=50
k = kde.gaussian_kde([x,y])
xi, yi = np.mgrid[min(x):max(x):nbins*1j, min(y):max(y):nbins*1j]
zi = k(np.vstack([xi.flatten(), yi.flatten()]))

# Add color bar
plt.pcolormesh(xi, yi, zi.reshape(xi.shape), cmap=plt.cm.jet)
plt.colorbar()
plt.show()


问:
How to emulate the same behaviour in kotlin
How to emulate the same behaviour using lambdas kotlin.

Java Code:

```<code>   public interface OnClickListener{
    public void onClick();
    }

    public class Sample {

            OnclickListener mOnclickListener;

            public void setOnclickListener(OnclickListener l){

                if(l!=null)
                mOnclickListener =l;
            }

            public void performClick()
            {
                mOnclickListener.onClick(5);
            }

        }

  public class SampleImpl{

     Sample sample=new Sample();
      sample.setOnClickListener(new OnClickListner(){ onClick{}});

     sample.performClick();

}
</code>```

As per kotlin, function receives parameter of interface with single method can represent in lambda, i am trying...

Kotlin code :

```<code>var sample= Sample();

    sample.setOnClickListener({Int ->  println("action performed") })
    sample.performClick(); //will call this method whenever needed.

    class Sample {

         var click=null;

        fun setOnClickListener(onClick : (Int)->Unit){

           click= onClick // trying to assign and want to use it in another
                              funciton. I know it is wrong, how to achieve
                             this.
        }

      fun performClick()
       {
           click(5)
       }
    }
</code>```

Is there any alternative to achieve this?

答:
The compiler has no way of inferring a type of (Int) -> Unit from var click = null.

You can change the declaration to something like var click : (Int) -> Unit = {}. This explicitly states the type, and uses a non-nullable type so as not to complicate performClick.

Body:
How to emulate the same behaviour using lambdas kotlin.

Java Code:

   public interface OnClickListener{
    public void onClick();
    }

    public class Sample {

            OnclickListener mOnclickListener;

            public void setOnclickListener(OnclickListener l){

                if(l!=null)
                mOnclickListener =l;
            }

            public void performClick()
            {
                mOnclickListener.onClick(5);
            }

        }

  public class SampleImpl{

     Sample sample=new Sample();
      sample.setOnClickListener(new OnClickListner(){ onClick{}});

     sample.performClick();

}

As per kotlin, function receives parameter of interface with single method can represent in lambda, i am trying...

Kotlin code :

var sample= Sample();

    sample.setOnClickListener({Int ->  println("action performed") })
    sample.performClick(); //will call this method whenever needed.

    class Sample {

         var click=null;

        fun setOnClickListener(onClick : (Int)->Unit){

           click= onClick // trying to assign and want to use it in another
                              funciton. I know it is wrong, how to achieve
                             this.
        }

      fun performClick()
       {
           click(5)
       }
    }

Is there any alternative to achieve this?


问:
Sql MAX DateTime and if clause?
My 2nd Sql question on SO today - I need to brush up my Sql skills!!!!

I have the following three tables....

Diary, Entry, and EntryType

A Diary can have many Entry(ies), each Entry is of a particular EntryType.

Entry has a created DateTime
EntryType has an Id, and SomeOtherValue (int)

EDIT

Sorry Chaps.  Thanks for response so far but I didn't explain it well enough; the requirements have changed a bit.....

I would like the Id of any Diary where its latest Entry that is greater than @lastDateTime AND EntryType.someOthervalue != 0 has a EntryType.someOthervalue == @someValue

Or to put it another way....For all those Entry rows with a created Date time > @lastDateTime, ignore the someOtherValues that equal 0, and if the top 1 left over has a someOtherValue = @someValue, return the Id of the diary!!!!

Does that make sense???  I'm not sure what I should be putting my MAX, WHERE, and HAVING (if anything at all!)

Thanks,

ETFairfax.

答:
How about something like this:</p>

```<code>select d.diary_id
  from diary       d
  join entry       e on(d.diary_id = e.diary_id)
  join entry_type et on(e.entry_type_id = et.entry_type_id)
 where et.someOthervalue = @someValue
 group by d.diary_id
having max(e.created) > @lastDateTime;
</code>```

Title: Sql MAX DateTime and if clause?

Body:
How about something like this:

select d.diary_id
  from diary       d
  join entry       e on(d.diary_id = e.diary_id)
  join entry_type et on(e.entry_type_id = et.entry_type_id)
 where et.someOthervalue = @someValue
 group by d.diary_id
having max(e.created) > @lastDateTime;


问:
Kendo Grid excel Export not working on chrome for 27K records but works for FF
I am trying to export kendo grid. It has around more than 27K records. when i try to export i get "Failed Network error" error in chrome, but this works fine on FF. I also tried to create kendo.ooxml.Workbook and tried to save it by Kendo.saveAs() but it also gives me same error. So i had to switch to server side.

Is there a limitation on Kendo.saveAs() method for file size ? It is strange that this scenario works fine on FireFox.

答:
I have just resolved my problem with Kendo Export To PDF not working with Chrome. Using Network Traffic in Developer Tools I saw that there was a 404 error - DejaVuSans.ttf font not found. This did not stop Internet Explorer working - but it was the show stopper with Chrome. I moved the DejaVuSans font from the font folder to the Content folder (in with the calling css file), and changed the css code to (no path required now):

```<code>@font-face {
font-family: "DejaVu Sans";
src: url("DejaVuSans.ttf") format("truetype");
}
</code>```

Perhaps not ideal to have a font in the Content folder when there is a font folder in the root directory, but my app works now.

Body:
I have just resolved my problem with Kendo Export To PDF not working with Chrome. Using Network Traffic in Developer Tools I saw that there was a 404 error - DejaVuSans.ttf font not found. This did not stop Internet Explorer working - but it was the show stopper with Chrome. I moved the DejaVuSans font from the font folder to the Content folder (in with the calling css file), and changed the css code to (no path required now):

@font-face {
font-family: "DejaVu Sans";
src: url("DejaVuSans.ttf") format("truetype");
}

Perhaps not ideal to have a font in the Content folder when there is a font folder in the root directory, but my app works now.


问:
Display specific length of div element pagination
I would like to know how to display specific length of an item by pagination.
with the element code below shows 20 items of div elements.

```<code><div class="group-of-element">
<div class="items">item1</div>
<div class="items">item2</div>
<div class="items">item3</div>
<div class="items">item4</div>
<div class="items">item5</div>
<div class="items">item6</div>
<div class="items">item7</div>
<div class="items">item8</div>
<div class="items">item9</div>
<div class="items">item10</div>
<div class="items">item12</div>
<div class="items">item13</div>
<div class="items">item14</div>
<div class="items">item15</div>
<div class="items">item16</div>
<div class="items">item17</div>
<div class="items">item18</div>
<div class="items">item19</div>
<div class="items">item20</div>
</div>
</code>```

As a result It would be something like this

The first 9 of div items would be displayed and when the button "Display Next 9 items" would be clicked it would display the next set of 9 items. And also when the "Display all items" would be clicked, all results should be displayed.

*Updated Also all the old items would need to hide when the "next 9 items" should be clicked

Any help would be greatly appreciated

答:
You can use a combination of :not(:visible) and :lt(9);

:not(:visible) will select elements that are not visible.

:lt(9) will select the first 9 items.

```<code>$(".next").click(function() {
  $(".group-of-element .items:not(:visible):lt(9)").show();
})
</code>```

Demo

$(".next").click(function() {
  var showele = $(".group-of-element .items:not(:visible):lt(9)");
  $(".group-of-element .items").hide();
  showele.show();
})

$(".all").click(function() {
  $(".group-of-element .items").show();
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.items {
  display: none
}</code>```

item1

item2

item3

item4

item5

item6

item7

item8

item9

item10

item12

item13

item14

item15

item16

item17

item18

item19

item20

<button class="next">show next 9</botton><button class="all">all</botton>```

Body:
I would like to know how to display specific length of an item by pagination.
with the element code below shows 20 items of div elements.

item1

item2

item3

item4

item5

item6

item7

item8

item9

item10

item12

item13

item14

item15

item16

item17

item18

item19

item20

As a result It would be something like this

The first 9 of div items would be displayed and when the button "Display Next 9 items" would be clicked it would display the next set of 9 items. And also when the "Display all items" would be clicked, all results should be displayed.

*Updated Also all the old items would need to hide when the "next 9 items" should be clicked

Any help would be greatly appreciated

Body:
You can use a combination of :not(:visible) and :lt(9);

:not(:visible) will select elements that are not visible.

:lt(9) will select the first 9 items.

$(".next").click(function() {
  $(".group-of-element .items:not(:visible):lt(9)").show();
})

Demo

$(".next").click(function() {
  var showele = $(".group-of-element .items:not(:visible):lt(9)");
  $(".group-of-element .items").hide();
  showele.show();
})

$(".all").click(function() {
  $(".group-of-element .items").show();
})

.items {
  display: none
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="group-of-element">
  <div class="items">item1</div>
  <div class="items">item2</div>
  <div class="items">item3</div>
  <div class="items">item4</div>
  <div class="items">item5</div>
  <div class="items">item6</div>
  <div class="items">item7</div>
  <div class="items">item8</div>
  <div class="items">item9</div>
  <div class="items">item10</div>
  <div class="items">item12</div>
  <div class="items">item13</div>
  <div class="items">item14</div>
  <div class="items">item15</div>
  <div class="items">item16</div>
  <div class="items">item17</div>
  <div class="items">item18</div>
  <div class="items">item19</div>
  <div class="items">item20</div>
</div>
<button class="next">show next 9</botton><button class="all">all</botton>


问:
Running Main Class from War file
I need to run class with main method from a war file. I tried java -jar test.war. It dint work. I tried by putting Main-Class entry in MANIFEST.MF file but giving error as NoClassDefFound error.

Thanks.

答:
The classes that get loaded into the classpath diffirent with war and jar. Try to change file and you can run with command line.
Suggest this link to help you:
How do I run a class in a WAR from the command line?</p>

Title: Running Main Class from War file


问:
Fetch json response inside array of array
My Json response is as follows.I want to get the individual array item from the response like static website,dynamic website.Can you help me please?</p>

```<code>{
  "data": [
    [
      "Static Website"
    ],
    [
      "Dynamic Website"
    ],
    [
      "E-Commerce Website"
    ],
    [
      "ERP"
    ],
    [
      "IOS Application"
    ],
    [
      "Social Networking"
    ],
    [
      "Web Application"
    ],
    [
      "Graphic Design"
    ]
  ],
  "status": 200
}
</code>```

答:
Try this snippet

```<code> @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);

            try {
                JSONArray jsonArray = response.getJSONArray("data");
                String status = response.getString("status");

                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                   //get Whatever you want here and add to arraylist or store somewhere//
                }
            }
            catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), R.string.exception, Toast.LENGTH_SHORT).show();

            }
        }
</code>```

Body:
My Json response is as follows.I want to get the individual array item from the response like static website,dynamic website.Can you help me please?

{
  "data": [
    [
      "Static Website"
    ],
    [
      "Dynamic Website"
    ],
    [
      "E-Commerce Website"
    ],
    [
      "ERP"
    ],
    [
      "IOS Application"
    ],
    [
      "Social Networking"
    ],
    [
      "Web Application"
    ],
    [
      "Graphic Design"
    ]
  ],
  "status": 200
}

Body:
Try this snippet

 @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);

            try {
                JSONArray jsonArray = response.getJSONArray("data");
                String status = response.getString("status");

                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                   //get Whatever you want here and add to arraylist or store somewhere//
                }
            }
            catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), R.string.exception, Toast.LENGTH_SHORT).show();

            }
        }


问:
Chrome extension not waiting for DOM to load
I am trying to access any element on YouTube from a content script.

manifest.json

```<code>"content_scripts": [
    {
      "run_at": "document_end",
      "matches": ["*://www.youtube.com/watch?v=*"],
      "js": ["content/content.js"]
    }
  ]
</code>```

However, when logging the element, I sometimes get null and sometimes the element is logged.

content.js

```<code>document.addEventListener('DOMContentLoaded', afterDOMLoaded)

function afterDOMLoaded() {
    const element = document.getElementById('top')
    console.log(element)
}
</code>```

It works when using setTimeout

```<code>setTimeout(function(){
    const element = document.getElementById('top')
    console.log(element)
}, 3000)
</code>```

I read here that this is because the element is being added later dynamically, by the page's javascript, and the only way to solve this is by using a MutationObserver/mutation-summary. This seems like a lot of hassle for just accessing an element. Isn't there any other way?

答:
By Loading asynchronously we will get the solution run at "document_idle".
In the case of "document_idle", the browser chooses a time to inject scripts between "document_end" and immediately after the window.onload event fires.

Update manifest.json

"content_scripts": [
    {
      "run_at": "document_idle",
      "matches": [
        "*://www.youtube.com/watch?v=*"
      ],
      "js": [
        "content.js"
      ]
    }
 ]

In Content script, get the document ready state and do with asynchronous way.

```<code>HTMLDocument.prototype.ready = new Promise(function (resolve) {
if (document.readyState != "loading")
    return resolve();
else
    document.addEventListener("DOMContentLoaded", function () {
        return resolve();
    });
});

document.ready.then(function () {
    const element = document.getElementById('top')
    console.log(element)
});
</code>```

Hope this helps.

Body:
I am trying to access any element on YouTube from a content script.

manifest.json

"content_scripts": [
    {
      "run_at": "document_end",
      "matches": ["*://www.youtube.com/watch?v=*"],
      "js": ["content/content.js"]
    }
  ]

However, when logging the element, I sometimes get null and sometimes the element is logged.

content.js

document.addEventListener('DOMContentLoaded', afterDOMLoaded)

function afterDOMLoaded() {
    const element = document.getElementById('top')
    console.log(element)
}

It works when using setTimeout

setTimeout(function(){
    const element = document.getElementById('top')
    console.log(element)
}, 3000)

I read here that this is because the element is being added later dynamically, by the page's javascript, and the only way to solve this is by using a MutationObserver/mutation-summary. This seems like a lot of hassle for just accessing an element. Isn't there any other way?

Body:
By Loading asynchronously we will get the solution run at "document_idle".
In the case of "document_idle", the browser chooses a time to inject scripts between "document_end" and immediately after the window.onload event fires.

Update manifest.json

"content_scripts": [
    {
      "run_at": "document_idle",
      "matches": [
        "*://www.youtube.com/watch?v=*"
      ],
      "js": [
        "content.js"
      ]
    }
 ]

In Content script, get the document ready state and do with asynchronous way.

HTMLDocument.prototype.ready = new Promise(function (resolve) {
if (document.readyState != "loading")
    return resolve();
else
    document.addEventListener("DOMContentLoaded", function () {
        return resolve();
    });
});

document.ready.then(function () {
    const element = document.getElementById('top')
    console.log(element)
});

Hope this helps.


问:
C# .NETCF - HTC Touch is not firing TextBox KeyPress event
I'm facing this strange situation: I use my own "custom soft keyboard" (just some buttons placed on screen) and then I use PostKeybdMessage do send "keys" to the TextBox.

Everything allways worked fine, but today when I installed in a HTC Touch2 devices, the Textbox's KeyPress event is not being fired. In HTC devices I'm having this same "strange" behavion: KeyDown and KeyUp events are being fired, but KeyPress is missing!

Does anybody know why is this happening?

Regards.

答:
Well, for those interested...

After some hours of researching, it appears that some HTC "flavors" have a special version of auto complete that causes the keypress to be lost.

(see: http://webcache.googleusercontent.com/search?q=cache:vIddjM7iEloJ:forums.citrix.com/thread.jspa%3FthreadID%3D238620%26tstart%3D0+htc+touch+keypress+not+being+fired&cd=5&hl=pt-BR&ct=clnk&gl=br).

What I did was just set to the "default" windows mobile keyboard.

(see: http://forum.xda-developers.com/archive/index.php/t-444641.html)

HKLM\System\CurrentControlSet\Control\Layouts\e0010409

Ime File = \windows\compime.dll

Layout Tex = COMP IME


问:
Undo in Python with a very large state. Is it possible?
This appears simple, but I can't find a good solution.

It's the old 'pass by reference'/ 'pass by value' / 'pass by object reference' problem. I understand what is happening, but I can't find a good work around.

I am aware of solutions for small problems, but my state is very large and extremely expensive to save/ recalculate. Given these constraints, I can't find a solution.

Here is some simple pseudocode to illustrate what I would like to do (if Python would let me pass by reference):

```<code>class A:
    def __init__(self,x):
        self.g=x
        self.changes=[]
    def change_something(self,what,new): # I want to pass 'what' by reference
        old=what # and then de-reference it here to read the value
        self.changes.append([what,old]) # store a reference
        what=new # dereference and change the value
    def undo_changes():
        for c in self.changes:
            c[0]=c[1] # dereference and restore old value
</code>```

Edit: Adding some more pseudocode to show how I would like the use the above

```<code>test=A(1) # initialise test.g as 1

print(test.g)
out: 1

test.change_something(test.g,2)
# if my imaginary code above functioned as described in its comments,
# this would change test.g to 2 and store the old value in the list of changes

print(test.g)
out: 2

test.undo_changes()

print(test.g)
out: 1
</code>```

Obviously the above code doesnt work in python due to being 'pass by object reference'. Also I'd like to be able to undo a single change, not just all of them as in the code above.

The thing is... I can't seem to find a good work around. There are solutions out there like these:

Do/Undo using command pattern in Python

making undo in python

Which involve storing a stack of commands. 'Undo' then involves removing the last command and then re-building the final state by taking the initial state and re-applying everything but the last command. My state is too large for this to be feasible, the issues are:

The state is very large. Saving it entirely is prohibitively expensive.

'Do' operations are costly (making recalculating from a saved state infeasible).

Do operations are also non-deterministic, relying on random input.

Undo operations are very frequent

I have one idea, which is to ensure that EVERYTHING is stored in lists, and writing my code so that everything is stored, read from and written to these lists. Then in the code above I can pass the list name and list index every time I want to read/write a variable.

Essentially this amounts to building my own memory architecture and C-style pointer system within Python!
This works, but seems a little... ridiculous? Surely there is a better way?

答:
Please check if it helps....

```<code>class A:
def __init__(self,x):
    self.g=x
    self.changes={}
    self.changes[str(x)] = {'init':x, 'old':x, 'new':x}   #or make a key by your choice(immutable)
def change_something(self,what,new): # I want to pass 'what' by reference
    self.changes[what]['new'] = new #add changed value to your dict
    what=new # dereference and change the value
def undo_changes():
    what = self.changes[what]['old'] #retrieve/changed to the old value
    self.changes[what]['new'] = self.changes[what]['old'] #change latest new val to old val as you reverted your changes
</code>```

for each change you can update the change_dictionary. Onlhy thing you have to figure out is "how to create entry for what as a key in self.change dictionary", I just made it str(x), just check the type(what) and how to make it a key in your case.

Body:
This appears simple, but I can't find a good solution.

It's the old 'pass by reference'/ 'pass by value' / 'pass by object reference' problem. I understand what is happening, but I can't find a good work around.

I am aware of solutions for small problems, but my state is very large and extremely expensive to save/ recalculate. Given these constraints, I can't find a solution.

Here is some simple pseudocode to illustrate what I would like to do (if Python would let me pass by reference):

class A:
    def __init__(self,x):
        self.g=x
        self.changes=[]
    def change_something(self,what,new): # I want to pass 'what' by reference
        old=what # and then de-reference it here to read the value
        self.changes.append([what,old]) # store a reference
        what=new # dereference and change the value
    def undo_changes():
        for c in self.changes:
            c[0]=c[1] # dereference and restore old value

Edit: Adding some more pseudocode to show how I would like the use the above

test=A(1) # initialise test.g as 1

print(test.g)
out: 1

test.change_something(test.g,2)
# if my imaginary code above functioned as described in its comments,
# this would change test.g to 2 and store the old value in the list of changes

print(test.g)
out: 2

test.undo_changes()

print(test.g)
out: 1

Obviously the above code doesnt work in python due to being 'pass by object reference'. Also I'd like to be able to undo a single change, not just all of them as in the code above.

The thing is... I can't seem to find a good work around. There are solutions out there like these:

Do/Undo using command pattern in Python

making undo in python

Which involve storing a stack of commands. 'Undo' then involves removing the last command and then re-building the final state by taking the initial state and re-applying everything but the last command. My state is too large for this to be feasible, the issues are:

The state is very large. Saving it entirely is prohibitively expensive.

'Do' operations are costly (making recalculating from a saved state infeasible).

Do operations are also non-deterministic, relying on random input.

Undo operations are very frequent

I have one idea, which is to ensure that EVERYTHING is stored in lists, and writing my code so that everything is stored, read from and written to these lists. Then in the code above I can pass the list name and list index every time I want to read/write a variable.

Essentially this amounts to building my own memory architecture and C-style pointer system within Python!
This works, but seems a little... ridiculous? Surely there is a better way?

Body:
Please check if it helps....

class A:
def __init__(self,x):
    self.g=x
    self.changes={}
    self.changes[str(x)] = {'init':x, 'old':x, 'new':x}   #or make a key by your choice(immutable)
def change_something(self,what,new): # I want to pass 'what' by reference
    self.changes[what]['new'] = new #add changed value to your dict
    what=new # dereference and change the value
def undo_changes():
    what = self.changes[what]['old'] #retrieve/changed to the old value
    self.changes[what]['new'] = self.changes[what]['old'] #change latest new val to old val as you reverted your changes

for each change you can update the change_dictionary. Onlhy thing you have to figure out is "how to create entry for what as a key in self.change dictionary", I just made it str(x), just check the type(what) and how to make it a key in your case.


问:
Why do I get an MKErrorDomain error when doing a local search?
I am trying to implement a search bar where the user can type in a string and search for an address or a business.

To find businesses I use Yelp APIs to outsource the information I need.

To find addresses I use Apple's MKLocalSearch APIs to get the information I need.

However, I do have a problem. When I hold on to the backspace button to clear out the text from the search bar or type too fast into the search bar  I get an MKErrorDomain error:

The operation couldn’t be completed. (MKErrorDomain error 3.)

When I get this error I will have to wait a few moments in order for the code to work again and retrieve information from the APIs.

The following code is what I have to implement what I am looking for:

This is the search bar delegate method:

```<code>func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    if searchBar.text == "" {
        addServiceCellToTableView()
        loadSearchHistory()
        return
    } else if searchBar.text != "" {
        removeServiceCellFromTableView()
    }

    if searchCompleter.isSearching{
        searchCompleter.cancel()
        searchCompleter.region = (delegate?.businessSearchResultTableViewControllerNeedsUpdatedMapRegion(self))!
        searchCompleter.queryFragment = searchText
    } else {
        searchCompleter.region = (delegate?.businessSearchResultTableViewControllerNeedsUpdatedMapRegion(self))!
        searchCompleter.queryFragment = searchText
    }

}
</code>```

I use MKLocalSearchCompleter to get suggestions based on what the user types into the search bar:

```<code>func completerDidUpdateResults(_ completer: MKLocalSearchCompleter){

    guard completer.results.count != 0 else {return}

    var searchTerm: String = completer.results.first!.title
    if completer.results.first!.subtitle != "" {
        searchTerm = searchTerm + ", " + completer.results.first!.subtitle
    }

    if let _ = addressDetector.firstMatch(in: searchTerm, options: [], range: NSMakeRange(0, searchTerm.utf8.count)){
        searchAddress(for: searchTerm)
    } else {
        getBusinesses(withSearchTerm: searchTerm, userCoordinates: currentUserLocation.coordinate)
    }

}
</code>```

In the code above I use NSDataDetector to see if the suggested text is an address...If so I feed it into MKLocalSearch...

Finally, In order to search for for addresses I defined a method called searchAddress(for:):

```<code>func searchAddress(for string: String){

        let localSearchRequest = MKLocalSearchRequest()
        localSearchRequest.naturalLanguageQuery = string
        localSearchRequest.region = (delegate?.businessSearchResultTableViewControllerNeedsUpdatedMapRegion(self))!

        let localSearch = MKLocalSearch(request: localSearchRequest)
        localSearch.start(completionHandler: {searchResponse, error in
            guard error == nil else {
                print(error.debugDescription)
                return
            }

            guard let mapItems = searchResponse?.mapItems else {return}

            self.tableViewDataSourceList = mapItems
            self.tableView.reloadData()
            self.delegate?.businessSearchResultTableViewStopedGettingBusiness(self, with: self.tableViewDataSourceList, at: CLLocationCoordinate2D(latitude: self.currentUserLocation.coordinate.latitude, longitude: self.currentUserLocation.coordinate.longitude))
        })
    }
</code>```

When I type too fast or hold on the backspace key I get the following error in the console:

```<code>The operation couldn’t be completed. (MKErrorDomain error 3.)
The operation couldn’t be completed. (MKErrorDomain error 3.)
The operation couldn’t be completed. (MKErrorDomain error 3.)
The operation couldn’t be completed. (MKErrorDomain error 3.)
The operation couldn’t be completed. (MKErrorDomain error 3.)
The operation couldn’t be completed. (MKErrorDomain error 3.)
The operation couldn’t be completed. (MKErrorDomain error 3.)
The operation couldn’t be completed. (MKErrorDomain error 3.)
</code>```

Any help will be much appreciated :-)

答:
What you're seeing here is the MKError.loadingThrottled error. You will have to delay requests you're sending to Apple.

You can do this by restarting a timer every time the user updates the search query. You can adjust how frequently you ping the API by extending the length of the timer. By resetting the timer each time the query is updated, you avoid sending multiple requests when the characters are changing rapidly.

```<code>// declare and store Timer somewhere

func searchAddress(with query: String) {

}

func timerDidFire(_ sender: Any) {
    let query = textField.text
    searchAddress(with: query)
}

Timer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(timerDidFire), userInfo: nil, repeats: false)
</code>```

Body:
I am trying to implement a search bar where the user can type in a string and search for an address or a business.

To find businesses I use Yelp APIs to outsource the information I need.

To find addresses I use Apple's MKLocalSearch APIs to get the information I need.

However, I do have a problem. When I hold on to the backspace button to clear out the text from the search bar or type too fast into the search bar  I get an MKErrorDomain error:

The operation couldn’t be completed. (MKErrorDomain error 3.)

When I get this error I will have to wait a few moments in order for the code to work again and retrieve information from the APIs.

The following code is what I have to implement what I am looking for:

This is the search bar delegate method:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    if searchBar.text == "" {
        addServiceCellToTableView()
        loadSearchHistory()
        return
    } else if searchBar.text != "" {
        removeServiceCellFromTableView()
    }

    if searchCompleter.isSearching{
        searchCompleter.cancel()
        searchCompleter.region = (delegate?.businessSearchResultTableViewControllerNeedsUpdatedMapRegion(self))!
        searchCompleter.queryFragment = searchText
    } else {
        searchCompleter.region = (delegate?.businessSearchResultTableViewControllerNeedsUpdatedMapRegion(self))!
        searchCompleter.queryFragment = searchText
    }

}

I use MKLocalSearchCompleter to get suggestions based on what the user types into the search bar:

func completerDidUpdateResults(_ completer: MKLocalSearchCompleter){

    guard completer.results.count != 0 else {return}

    var searchTerm: String = completer.results.first!.title
    if completer.results.first!.subtitle != "" {
        searchTerm = searchTerm + ", " + completer.results.first!.subtitle
    }

    if let _ = addressDetector.firstMatch(in: searchTerm, options: [], range: NSMakeRange(0, searchTerm.utf8.count)){
        searchAddress(for: searchTerm)
    } else {
        getBusinesses(withSearchTerm: searchTerm, userCoordinates: currentUserLocation.coordinate)
    }

}

In the code above I use NSDataDetector to see if the suggested text is an address...If so I feed it into MKLocalSearch...

Finally, In order to search for for addresses I defined a method called searchAddress(for:):

func searchAddress(for string: String){

        let localSearchRequest = MKLocalSearchRequest()
        localSearchRequest.naturalLanguageQuery = string
        localSearchRequest.region = (delegate?.businessSearchResultTableViewControllerNeedsUpdatedMapRegion(self))!

        let localSearch = MKLocalSearch(request: localSearchRequest)
        localSearch.start(completionHandler: {searchResponse, error in
            guard error == nil else {
                print(error.debugDescription)
                return
            }

            guard let mapItems = searchResponse?.mapItems else {return}

            self.tableViewDataSourceList = mapItems
            self.tableView.reloadData()
            self.delegate?.businessSearchResultTableViewStopedGettingBusiness(self, with: self.tableViewDataSourceList, at: CLLocationCoordinate2D(latitude: self.currentUserLocation.coordinate.latitude, longitude: self.currentUserLocation.coordinate.longitude))
        })
    }

When I type too fast or hold on the backspace key I get the following error in the console:

The operation couldn’t be completed. (MKErrorDomain error 3.)
The operation couldn’t be completed. (MKErrorDomain error 3.)
The operation couldn’t be completed. (MKErrorDomain error 3.)
The operation couldn’t be completed. (MKErrorDomain error 3.)
The operation couldn’t be completed. (MKErrorDomain error 3.)
The operation couldn’t be completed. (MKErrorDomain error 3.)
The operation couldn’t be completed. (MKErrorDomain error 3.)
The operation couldn’t be completed. (MKErrorDomain error 3.)

Any help will be much appreciated :-)

Body:
What you're seeing here is the MKError.loadingThrottled error. You will have to delay requests you're sending to Apple.

You can do this by restarting a timer every time the user updates the search query. You can adjust how frequently you ping the API by extending the length of the timer. By resetting the timer each time the query is updated, you avoid sending multiple requests when the characters are changing rapidly.

// declare and store Timer somewhere

func searchAddress(with query: String) {

}

func timerDidFire(_ sender: Any) {
    let query = textField.text
    searchAddress(with: query)
}

Timer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(timerDidFire), userInfo: nil, repeats: false)


问:
Performance of JOINS in SAP HANA Calculation View
For Example:
I have 4 columns (A,B,C,D).

I thought that instead of connecting each and every column in join I should make a concatenated column in both projection(CA_CONCAT-> A+B+C+D) and make a join on this, Just to check on which method performance is better.

It was working faster earlier but in few CV's this method is slower sometimes, especially at time of filtering!

Can any one suggest which is an efficient method?

答:
I don't think the JOIN conditions with concatenated fields will work better in performance.

Although we say in general there is not a need for index on column tables on HANA database, the column tables have a structure that works with an index on every column.
So if you concatenate 4 columns and produce a new calculated field, first you loose the option to use these index on 4 columns and the corresponding joining columns

I did not check the  execution plan, but it will probably make a full scan on these columns

In fact I'm surprised you have mentioned that it worked faster, and experienced problems only on a few

Because concatenation or applying a function on a database column is even only by itself a workload over the SELECT process. It might include implicit type cast operation, which might bring additional workload more than expected


问:
How to add seeded data into the mongodb using docker?
I have a mongo-seed image and mongo image set up

How can i run the mongo database up with the seeded data in docker.

答:
use docker link in-order to link 2 dependent containers

It explained here , it might helpfull

https://rominirani.com/docker-tutorial-series-part-8-linking-containers-69a4e5bf50fb

If your using docker-compose then here is the solution which you looking

https://gist.github.com/jschwarty/6f9907e2871d1ece5bde53d259c18d5f