问:
mysql query show only 1 result
i want to output the result based on todays date.
the problem is, the output only show 1 result?</p>

```<code>database report table:
id  |  r_amount | id_therapist | date | time | t_tanning | t_deep

// this query works fine echoing all the result if i use while loop
$today = date('Y-m-d');
(1) $q = $db->query("SELECT * FROM report WHERE date='$today' ORDER BY date ASC")

// this query only show 1 output result?
(2) $q = $db->query("SELECT *, SUM(IF(t_tanning LIKE 'Pro Tan%', r_amount, 0)) AS totalProTan FROM report WHERE date='$today' ORDER BY date ASC")

while($r = $q->fetch_array(MYSQLI_ASSOC)) :
     // (1) echoing all result from database
     echo $r['r_amount'].'<br>';
     // (2) echoing only 1 result????
     echo $r['totalProTan'].'<br>';
endwhile;
</code>```

答:
The use of the aggregate function SUM will result in a single result. You are asking the database to get all the rows then sum up a value and give you the value.

To see the result for many groups of values you have to add a group by clause.

Title: mysql query show only 1 result

Body:
i want to output the result based on todays date.
the problem is, the output only show 1 result?

database report table:
id  |  r_amount | id_therapist | date | time | t_tanning | t_deep

// this query works fine echoing all the result if i use while loop
$today = date('Y-m-d');
(1) $q = $db->query("SELECT * FROM report WHERE date='$today' ORDER BY date ASC")

// this query only show 1 output result?
(2) $q = $db->query("SELECT *, SUM(IF(t_tanning LIKE 'Pro Tan%', r_amount, 0)) AS totalProTan FROM report WHERE date='$today' ORDER BY date ASC")

while($r = $q->fetch_array(MYSQLI_ASSOC)) :
     // (1) echoing all result from database
     echo $r['r_amount'].'
';
     // (2) echoing only 1 result????
     echo $r['totalProTan'].'
';
endwhile;


来源: stackexchange

问:
PHP date format /Date(1365004652303-0500)/
I am calling an API from where I am getting date /Date(1365004652303-0500)/, I don't understand what format this is. How is this date format called? I was not sure what to google for such type of format.

Can anyone help me out in getting this date in Y-m-d H:i:s format?

The API I am calling is on .NET server. And when I call it using PHP's file_get_contents and json_decode it gives me the following Date format for created date: /Date(1365004652303-0500)/

答:
This is what I'm using to parse timestamps from a Xero API. It accounts for:

Negative timestamps, dates before the epoch.

Timestamps with less than 10 digits (but on the epoch - time zero - not sure what that format would even look like)

Fractions of a second.

Optional timezone offset, both positive and negative.

Code:

```<code>if (preg_match('#^(/Date\()([-]?[0-9]+)([0-9]{3})([+-][0-9]{4})?(\)/)$#', $data, $matches)) {
    // Handle Xero API DateTime formats. Examples:
    // "/Date(1436961673000)/" - unix timestamp with milliseconds
    // "/Date(1436961673000+0100)/" - with an additional timezone correction
    // "/Date(-1436961673000-0530)/" - before the epoch, 1924 here
    //
    // RE matches for "/Date(1436961673090+0100)/":
    // [1] = (/Date\()          "/Date("
    // [2] = ([-]?[0-9]+)       "1436961673"    epoch seconds
    // [3] = ([0-9]{3})         "090"           milliseconds
    // [4] = ([+-][0-9]{4})?    "+0100" or ""   optional timezone
    // [5] = (\)/)              ")"

    $result = \DateTime::createFromFormat('U u', $matches[2] . ' ' . $matches[3] . '000')
        ->setTimezone(new \DateTimeZone($matches[4] ?: '+0000'));
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is what I'm using to parse timestamps from a Xero API. It accounts for:

Negative timestamps, dates before the epoch.

Timestamps with less than 10 digits (but on the epoch - time zero - not sure what that format would even look like)

Fractions of a second.

Optional timezone offset, both positive and negative.

Code:

if (preg_match('#^(/Date\()([-]?[0-9]+)([0-9]{3})([+-][0-9]{4})?(\)/)$#', $data, $matches)) {
    // Handle Xero API DateTime formats. Examples:
    // "/Date(1436961673000)/" - unix timestamp with milliseconds
    // "/Date(1436961673000+0100)/" - with an additional timezone correction
    // "/Date(-1436961673000-0530)/" - before the epoch, 1924 here
    //
    // RE matches for "/Date(1436961673090+0100)/":
    // [1] = (/Date\()          "/Date("
    // [2] = ([-]?[0-9]+)       "1436961673"    epoch seconds
    // [3] = ([0-9]{3})         "090"           milliseconds
    // [4] = ([+-][0-9]{4})?    "+0100" or ""   optional timezone
    // [5] = (\)/)              ")"

    $result = \DateTime::createFromFormat('U u', $matches[2] . ' ' . $matches[3] . '000')
        ->setTimezone(new \DateTimeZone($matches[4] ?: '+0000'));
}

ContentLicense: CC BY-SA 4.0


问:
Spring Boot passing value / using method inside the application.properties
For example:

I have a class called Path.java

In Path.java, I have getter method "getPort()" that returns int 8080

In application.properties, I want to use     server.port = "getPort()"

How?

I want to externalize the datasource. I already have a class that grabs the information from the external .txt file. I need to use this class inside the application.properties.

Like, spring.datasource.url = ??getURL()??

答: Thinking how you get the port in your Path.java . Then just reuse that information.  There is no way to call a method in a properties file.


问:
Linux - grep -e works when invoke the script.sh from command but fails when the script.sh is called from crontab
I tested the below script.sh file. it works when I call from command prompt:

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

export file="test.txt"
export dir=$HOME
export exe_env="test"
export batch="1"
echo "info: `date` :Environment: ""$exe_env"
echo "info: inputfile: ""$dir/$file"

if [ -f $dir/$file ] ; then             # check if input file exists
        job_list=($( grep -e ':'"$batch"'$' "${dir}/${file}" ))
        for job in "${job_list[@]}"
        do
            echo ${job}
        done
fi
</code>```

But when I run from crontab as:

```<code>SHELL=/bin/ksh
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=
HOME=/
* * * * * script.sh >> nohup_1.out 2>&1
</code>```

I get the error -

syntax error at line 11 : `(' unexpected

I tried using double brase. Didn't solve. Any help.

答:
When you run tasks from cron, there is usually a small set of environment variables defined.
$HOME is probably missed. Try to run the script using absolute path to the file or command.</p>

Body:
I tested the below script.sh file. it works when I call from command prompt:

#!/bin/ksh

export file="test.txt"
export dir=$HOME
export exe_env="test"
export batch="1"
echo "info: `date` :Environment: ""$exe_env"
echo "info: inputfile: ""$dir/$file"

if [ -f $dir/$file ] ; then             # check if input file exists
        job_list=($( grep -e ':'"$batch"'$' "${dir}/${file}" ))
        for job in "${job_list[@]}"
        do
            echo ${job}
        done
fi

But when I run from crontab as:

SHELL=/bin/ksh
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=
HOME=/
* * * * * script.sh >> nohup_1.out 2>&1

I get the error -

syntax error at line 11 : `(' unexpected

I tried using double brase. Didn't solve. Any help.


问:
kube-scheduler Liveness probe failed: Get http://127.0.0.1:10251/healthz: dial tcp 127.0.0.1:10251: connect: connection refused
So I have this unhealthy cluster partially working in the datacenter.  This is probably the 10th time I have rebuilt from the instructions at:  https://kubernetes.io/docs/setup/independent/high-availability/

I can apply some pods to this cluster and it seems to work but eventually it starts slowing down and crashing as you can see below.  Here is the scheduler manifest:

```<code>apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    component: kube-scheduler
    tier: control-plane
  name: kube-scheduler
  namespace: kube-system
spec:
  containers:
  - command:
    - kube-scheduler
    - --bind-address=127.0.0.1
    - --kubeconfig=/etc/kubernetes/scheduler.conf
    - --authentication-kubeconfig=/etc/kubernetes/scheduler.conf
    - --authorization-kubeconfig=/etc/kubernetes/scheduler.conf
    - --leader-elect=true
    image: k8s.gcr.io/kube-scheduler:v1.14.2
    imagePullPolicy: IfNotPresent
    livenessProbe:
      failureThreshold: 8
      httpGet:
        host: 127.0.0.1
        path: /healthz
        port: 10251
        scheme: HTTP
      initialDelaySeconds: 15
      timeoutSeconds: 15
    name: kube-scheduler
    resources:
      requests:
        cpu: 100m
    volumeMounts:
    - mountPath: /etc/kubernetes/scheduler.conf
      name: kubeconfig
      readOnly: true
  hostNetwork: true
  priorityClassName: system-cluster-critical
  volumes:
  - hostPath:
      path: /etc/kubernetes/scheduler.conf
      type: FileOrCreate
    name: kubeconfig
status: {}
</code>```

$ kubectl -n kube-system get pods

```<code>NAME                                       READY   STATUS             RESTARTS   AGE
coredns-fb8b8dccf-42psn                    1/1     Running            9          88m
coredns-fb8b8dccf-x9mlt                    1/1     Running            11         88m
docker-registry-dqvzb                      1/1     Running            1          2d6h
kube-apiserver-kube-apiserver-1            1/1     Running            44         2d8h
kube-apiserver-kube-apiserver-2            1/1     Running            34         2d7h
kube-controller-manager-kube-apiserver-1   1/1     Running            198        2d2h
kube-controller-manager-kube-apiserver-2   0/1     CrashLoopBackOff   170        2d7h
kube-flannel-ds-amd64-4mbfk                1/1     Running            1          2d7h
kube-flannel-ds-amd64-55hc7                1/1     Running            1          2d8h
kube-flannel-ds-amd64-fvwmf                1/1     Running            1          2d7h
kube-flannel-ds-amd64-ht5wm                1/1     Running            3          2d7h
kube-flannel-ds-amd64-rjt9l                1/1     Running            4          2d8h
kube-flannel-ds-amd64-wpmkj                1/1     Running            1          2d7h
kube-proxy-2n64d                           1/1     Running            3          2d7h
kube-proxy-2pq2g                           1/1     Running            1          2d7h
kube-proxy-5fbms                           1/1     Running            2          2d8h
kube-proxy-g8gmn                           1/1     Running            1          2d7h
kube-proxy-wrdrj                           1/1     Running            1          2d8h
kube-proxy-wz6gv                           1/1     Running            1          2d7h
kube-scheduler-kube-apiserver-1            0/1     CrashLoopBackOff   198        2d2h
kube-scheduler-kube-apiserver-2            1/1     Running            5          18m
nginx-ingress-controller-dz8fm             1/1     Running            3          2d4h
nginx-ingress-controller-sdsgg             1/1     Running            3          2d4h
nginx-ingress-controller-sfrgb             1/1     Running            1          2d4h
</code>```

$ kubectl -n kube-system describe pod kube-scheduler-kube-apiserver-1

```<code>Containers:
  kube-scheduler:
    Container ID:  docker://c04f3c9061cafef8749b2018cd66e6865d102f67c4d13bdd250d0b4656d5f220
    Image:         k8s.gcr.io/kube-scheduler:v1.14.2
    Image ID:      docker-pullable://k8s.gcr.io/kube-scheduler@sha256:052e0322b8a2b22819ab0385089f202555c4099493d1bd33205a34753494d2c2
    Port:          <none>
    Host Port:     <none>
    Command:
      kube-scheduler
      --bind-address=127.0.0.1
      --kubeconfig=/etc/kubernetes/scheduler.conf
      --authentication-kubeconfig=/etc/kubernetes/scheduler.conf
      --authorization-kubeconfig=/etc/kubernetes/scheduler.conf
      --leader-elect=true
    State:          Waiting
      Reason:       CrashLoopBackOff
    Last State:     Terminated
      Reason:       Error
      Exit Code:    1
      Started:      Tue, 28 May 2019 23:16:50 -0400
      Finished:     Tue, 28 May 2019 23:19:56 -0400
    Ready:          False
    Restart Count:  195
    Requests:
      cpu:        100m
    Liveness:     http-get http://127.0.0.1:10251/healthz delay=15s timeout=15s period=10s #success=1 #failure=8
    Environment:  <none>
    Mounts:
      /etc/kubernetes/scheduler.conf from kubeconfig (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  kubeconfig:
    Type:          HostPath (bare host directory volume)
    Path:          /etc/kubernetes/scheduler.conf
    HostPathType:  FileOrCreate
QoS Class:         Burstable
Node-Selectors:    <none>
Tolerations:       :NoExecute
Events:
  Type     Reason          Age                    From                       Message
  ----     ------          ----                   ----                       -------
  Normal   Created         4h56m (x104 over 37h)  kubelet, kube-apiserver-1  Created container kube-scheduler
  Normal   Started         4h56m (x104 over 37h)  kubelet, kube-apiserver-1  Started container kube-scheduler
  Warning  Unhealthy       137m (x71 over 34h)    kubelet, kube-apiserver-1  Liveness probe failed: Get http://127.0.0.1:10251/healthz: dial tcp 127.0.0.1:10251: connect: connection refused
  Normal   Pulled          132m (x129 over 37h)   kubelet, kube-apiserver-1  Container image "k8s.gcr.io/kube-scheduler:v1.14.2" already present on machine
  Warning  BackOff         128m (x1129 over 34h)  kubelet, kube-apiserver-1  Back-off restarting failed container
  Normal   SandboxChanged  80m                    kubelet, kube-apiserver-1  Pod sandbox changed, it will be killed and re-created.
  Warning  Failed          76m                    kubelet, kube-apiserver-1  Error: context deadline exceeded
  Normal   Pulled          36m (x7 over 78m)      kubelet, kube-apiserver-1  Container image "k8s.gcr.io/kube-scheduler:v1.14.2" already present on machine
  Normal   Started         36m (x6 over 74m)      kubelet, kube-apiserver-1  Started container kube-scheduler
  Normal   Created         32m (x7 over 74m)      kubelet, kube-apiserver-1  Created container kube-scheduler
  Warning  Unhealthy       20m (x9 over 40m)      kubelet, kube-apiserver-1  Liveness probe failed: Get http://127.0.0.1:10251/healthz: dial tcp 127.0.0.1:10251: connect: connection refused
  Warning  BackOff         2m56s (x85 over 69m)   kubelet, kube-apiserver-1  Back-off restarting failed container
</code>```

I feel like I am overlooking a simple option or configuration but I can't find it and after days of dealing with this problem and reading documentation I am at my wits end.

The load balancer is a TCP load balancer and seems to be working as expected as I can query the cluster from my desktop.

Any suggestions or troubleshooting tips are definitely welcome at this time.

Thank you.

答: The problem with our configuration was that a well intended technician decided to eliminate one of the rules on the kubernetes master firewall which prevented the master from looping back to ports it needed to probe.  This caused all kinds of weird issues and misdiagnosed problems which was definitely the wrong direction.  After we allowed all ports on the servers Kubernetes was back to its normal behavior.</p>

Body:
So I have this unhealthy cluster partially working in the datacenter.  This is probably the 10th time I have rebuilt from the instructions at:  https://kubernetes.io/docs/setup/independent/high-availability/

I can apply some pods to this cluster and it seems to work but eventually it starts slowing down and crashing as you can see below.  Here is the scheduler manifest:

apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    component: kube-scheduler
    tier: control-plane
  name: kube-scheduler
  namespace: kube-system
spec:
  containers:
  - command:
    - kube-scheduler
    - --bind-address=127.0.0.1
    - --kubeconfig=/etc/kubernetes/scheduler.conf
    - --authentication-kubeconfig=/etc/kubernetes/scheduler.conf
    - --authorization-kubeconfig=/etc/kubernetes/scheduler.conf
    - --leader-elect=true
    image: k8s.gcr.io/kube-scheduler:v1.14.2
    imagePullPolicy: IfNotPresent
    livenessProbe:
      failureThreshold: 8
      httpGet:
        host: 127.0.0.1
        path: /healthz
        port: 10251
        scheme: HTTP
      initialDelaySeconds: 15
      timeoutSeconds: 15
    name: kube-scheduler
    resources:
      requests:
        cpu: 100m
    volumeMounts:
    - mountPath: /etc/kubernetes/scheduler.conf
      name: kubeconfig
      readOnly: true
  hostNetwork: true
  priorityClassName: system-cluster-critical
  volumes:
  - hostPath:
      path: /etc/kubernetes/scheduler.conf
      type: FileOrCreate
    name: kubeconfig
status: {}

$ kubectl -n kube-system get pods

NAME                                       READY   STATUS             RESTARTS   AGE
coredns-fb8b8dccf-42psn                    1/1     Running            9          88m
coredns-fb8b8dccf-x9mlt                    1/1     Running            11         88m
docker-registry-dqvzb                      1/1     Running            1          2d6h
kube-apiserver-kube-apiserver-1            1/1     Running            44         2d8h
kube-apiserver-kube-apiserver-2            1/1     Running            34         2d7h
kube-controller-manager-kube-apiserver-1   1/1     Running            198        2d2h
kube-controller-manager-kube-apiserver-2   0/1     CrashLoopBackOff   170        2d7h
kube-flannel-ds-amd64-4mbfk                1/1     Running            1          2d7h
kube-flannel-ds-amd64-55hc7                1/1     Running            1          2d8h
kube-flannel-ds-amd64-fvwmf                1/1     Running            1          2d7h
kube-flannel-ds-amd64-ht5wm                1/1     Running            3          2d7h
kube-flannel-ds-amd64-rjt9l                1/1     Running            4          2d8h
kube-flannel-ds-amd64-wpmkj                1/1     Running            1          2d7h
kube-proxy-2n64d                           1/1     Running            3          2d7h
kube-proxy-2pq2g                           1/1     Running            1          2d7h
kube-proxy-5fbms                           1/1     Running            2          2d8h
kube-proxy-g8gmn                           1/1     Running            1          2d7h
kube-proxy-wrdrj                           1/1     Running            1          2d8h
kube-proxy-wz6gv                           1/1     Running            1          2d7h
kube-scheduler-kube-apiserver-1            0/1     CrashLoopBackOff   198        2d2h
kube-scheduler-kube-apiserver-2            1/1     Running            5          18m
nginx-ingress-controller-dz8fm             1/1     Running            3          2d4h
nginx-ingress-controller-sdsgg             1/1     Running            3          2d4h
nginx-ingress-controller-sfrgb             1/1     Running            1          2d4h

$ kubectl -n kube-system describe pod kube-scheduler-kube-apiserver-1

Containers:
  kube-scheduler:
    Container ID:  docker://c04f3c9061cafef8749b2018cd66e6865d102f67c4d13bdd250d0b4656d5f220
    Image:         k8s.gcr.io/kube-scheduler:v1.14.2
    Image ID:      docker-pullable://k8s.gcr.io/kube-scheduler@sha256:052e0322b8a2b22819ab0385089f202555c4099493d1bd33205a34753494d2c2
    Port:          <none>
    Host Port:     <none>
    Command:
      kube-scheduler
      --bind-address=127.0.0.1
      --kubeconfig=/etc/kubernetes/scheduler.conf
      --authentication-kubeconfig=/etc/kubernetes/scheduler.conf
      --authorization-kubeconfig=/etc/kubernetes/scheduler.conf
      --leader-elect=true
    State:          Waiting
      Reason:       CrashLoopBackOff
    Last State:     Terminated
      Reason:       Error
      Exit Code:    1
      Started:      Tue, 28 May 2019 23:16:50 -0400
      Finished:     Tue, 28 May 2019 23:19:56 -0400
    Ready:          False
    Restart Count:  195
    Requests:
      cpu:        100m
    Liveness:     http-get http://127.0.0.1:10251/healthz delay=15s timeout=15s period=10s #success=1 #failure=8
    Environment:  <none>
    Mounts:
      /etc/kubernetes/scheduler.conf from kubeconfig (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  kubeconfig:
    Type:          HostPath (bare host directory volume)
    Path:          /etc/kubernetes/scheduler.conf
    HostPathType:  FileOrCreate
QoS Class:         Burstable
Node-Selectors:    <none>
Tolerations:       :NoExecute
Events:
  Type     Reason          Age                    From                       Message
  ----     ------          ----                   ----                       -------
  Normal   Created         4h56m (x104 over 37h)  kubelet, kube-apiserver-1  Created container kube-scheduler
  Normal   Started         4h56m (x104 over 37h)  kubelet, kube-apiserver-1  Started container kube-scheduler
  Warning  Unhealthy       137m (x71 over 34h)    kubelet, kube-apiserver-1  Liveness probe failed: Get http://127.0.0.1:10251/healthz: dial tcp 127.0.0.1:10251: connect: connection refused
  Normal   Pulled          132m (x129 over 37h)   kubelet, kube-apiserver-1  Container image "k8s.gcr.io/kube-scheduler:v1.14.2" already present on machine
  Warning  BackOff         128m (x1129 over 34h)  kubelet, kube-apiserver-1  Back-off restarting failed container
  Normal   SandboxChanged  80m                    kubelet, kube-apiserver-1  Pod sandbox changed, it will be killed and re-created.
  Warning  Failed          76m                    kubelet, kube-apiserver-1  Error: context deadline exceeded
  Normal   Pulled          36m (x7 over 78m)      kubelet, kube-apiserver-1  Container image "k8s.gcr.io/kube-scheduler:v1.14.2" already present on machine
  Normal   Started         36m (x6 over 74m)      kubelet, kube-apiserver-1  Started container kube-scheduler
  Normal   Created         32m (x7 over 74m)      kubelet, kube-apiserver-1  Created container kube-scheduler
  Warning  Unhealthy       20m (x9 over 40m)      kubelet, kube-apiserver-1  Liveness probe failed: Get http://127.0.0.1:10251/healthz: dial tcp 127.0.0.1:10251: connect: connection refused
  Warning  BackOff         2m56s (x85 over 69m)   kubelet, kube-apiserver-1  Back-off restarting failed container

I feel like I am overlooking a simple option or configuration but I can't find it and after days of dealing with this problem and reading documentation I am at my wits end.

The load balancer is a TCP load balancer and seems to be working as expected as I can query the cluster from my desktop.

Any suggestions or troubleshooting tips are definitely welcome at this time.

Thank you.


问:
Calculate bearing between two locations (lat, long)
I'm trying to develop my own augmented reality engine.

Searching on internet, I've found this useful tutorial. Reading it I see that the important thing is bearing between user location, point location and north.

The following picture is from that tutorial.

Following it, I wrote an Objective-C method to obtain beta:

```<code>+ (float) calculateBetaFrom:(CLLocationCoordinate2D)user to:(CLLocationCoordinate2D)destination
{
    double beta = 0;
    double a, b = 0;

    a = destination.latitude - user.latitude;
    b = destination.longitude - user.longitude;

    beta = atan2(a, b) * 180.0 / M_PI;
    if (beta < 0.0)
        beta += 360.0;
    else if (beta > 360.0)
        beta -= 360;

    return beta;
}
</code>```

But, when I try it, it doesn't work very well.

So, I checked iPhone AR Toolkit, to see how it works (I've been working with this toolkit, but it is so big for me).

And, in ARGeoCoordinate.m there is another implementation of how to obtain beta:

```<code>- (float)angleFromCoordinate:(CLLocationCoordinate2D)first toCoordinate:(CLLocationCoordinate2D)second {

    float longitudinalDifference    = second.longitude - first.longitude;
    float latitudinalDifference     = second.latitude  - first.latitude;
    float possibleAzimuth           = (M_PI * .5f) - atan(latitudinalDifference / longitudinalDifference);

    if (longitudinalDifference > 0)
        return possibleAzimuth;
    else if (longitudinalDifference < 0)
        return possibleAzimuth + M_PI;
    else if (latitudinalDifference < 0)
        return M_PI;

    return 0.0f;
}
</code>```

It uses this formula:

```<code>float possibleAzimuth = (M_PI * .5f) - atan(latitudinalDifference / longitudinalDifference);
</code>```

Why is (M_PI * .5f) in this formula? I don't understand it.

And continue searching, I've found another page talking about how to calculate distance and bearing of 2 locations. In this page there is another implementation:

```<code>/**
 * Returns the (initial) bearing from this point to the supplied point, in degrees
 *   see http://williams.best.vwh.net/avform.htm#Crs
 *
 * @param   {LatLon} point: Latitude/longitude of destination point
 * @returns {Number} Initial bearing in degrees from North
 */
LatLon.prototype.bearingTo = function(point) {
  var lat1 = this._lat.toRad(), lat2 = point._lat.toRad();
  var dLon = (point._lon-this._lon).toRad();

  var y = Math.sin(dLon) * Math.cos(lat2);
  var x = Math.cos(lat1)*Math.sin(lat2) -
          Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon);
  var brng = Math.atan2(y, x);

  return (brng.toDeg()+360) % 360;
}
</code>```

Which one is the right one?

答:
/*
        Kirit vaghela answer has been modified..
        Math.sin gives the radian value so to get degree value we need to pass Math.toRadians(value) inside Math.sin() or Math.cos()
      */

```<code>    double lat1 = 39.099912;
    double lat2 = 38.627089;
    double lng1 = -94.581213;
    double lng2 = -90.200203;

    double dLon = (lng2-lng1);
    double x = Math.sin(Math.toRadians(dLon)) * Math.cos(Math.toRadians(lat2));
    double y = Math.cos(Math.toRadians(lat1))*Math.sin(Math.toRadians(lat2)) - Math.sin(Math.toRadians(lat1))*Math.cos(Math.toRadians(lat2))*Math.cos(Math.toRadians(dLon));
    double bearing = Math.toDegrees((Math.atan2(x, y)));
    System.out.println("BearingAngle : "+bearing);
</code>```

Body:
I'm trying to develop my own augmented reality engine.

Searching on internet, I've found this useful tutorial. Reading it I see that the important thing is bearing between user location, point location and north.

The following picture is from that tutorial.

Following it, I wrote an Objective-C method to obtain beta:

+ (float) calculateBetaFrom:(CLLocationCoordinate2D)user to:(CLLocationCoordinate2D)destination
{
    double beta = 0;
    double a, b = 0;

    a = destination.latitude - user.latitude;
    b = destination.longitude - user.longitude;

    beta = atan2(a, b) * 180.0 / M_PI;
    if (beta < 0.0)
        beta += 360.0;
    else if (beta > 360.0)
        beta -= 360;

    return beta;
}

But, when I try it, it doesn't work very well.

So, I checked iPhone AR Toolkit, to see how it works (I've been working with this toolkit, but it is so big for me).

And, in ARGeoCoordinate.m there is another implementation of how to obtain beta:

- (float)angleFromCoordinate:(CLLocationCoordinate2D)first toCoordinate:(CLLocationCoordinate2D)second {

    float longitudinalDifference    = second.longitude - first.longitude;
    float latitudinalDifference     = second.latitude  - first.latitude;
    float possibleAzimuth           = (M_PI * .5f) - atan(latitudinalDifference / longitudinalDifference);

    if (longitudinalDifference > 0)
        return possibleAzimuth;
    else if (longitudinalDifference < 0)
        return possibleAzimuth + M_PI;
    else if (latitudinalDifference < 0)
        return M_PI;

    return 0.0f;
}

It uses this formula:

float possibleAzimuth = (M_PI * .5f) - atan(latitudinalDifference / longitudinalDifference);

Why is (M_PI * .5f) in this formula? I don't understand it.

And continue searching, I've found another page talking about how to calculate distance and bearing of 2 locations. In this page there is another implementation:

/**
 * Returns the (initial) bearing from this point to the supplied point, in degrees
 *   see http://williams.best.vwh.net/avform.htm#Crs
 *
 * @param   {LatLon} point: Latitude/longitude of destination point
 * @returns {Number} Initial bearing in degrees from North
 */
LatLon.prototype.bearingTo = function(point) {
  var lat1 = this._lat.toRad(), lat2 = point._lat.toRad();
  var dLon = (point._lon-this._lon).toRad();

  var y = Math.sin(dLon) * Math.cos(lat2);
  var x = Math.cos(lat1)*Math.sin(lat2) -
          Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon);
  var brng = Math.atan2(y, x);

  return (brng.toDeg()+360) % 360;
}

Which one is the right one?

Body:
/*
        Kirit vaghela answer has been modified..
        Math.sin gives the radian value so to get degree value we need to pass Math.toRadians(value) inside Math.sin() or Math.cos()
      */

    double lat1 = 39.099912;
    double lat2 = 38.627089;
    double lng1 = -94.581213;
    double lng2 = -90.200203;

    double dLon = (lng2-lng1);
    double x = Math.sin(Math.toRadians(dLon)) * Math.cos(Math.toRadians(lat2));
    double y = Math.cos(Math.toRadians(lat1))*Math.sin(Math.toRadians(lat2)) - Math.sin(Math.toRadians(lat1))*Math.cos(Math.toRadians(lat2))*Math.cos(Math.toRadians(dLon));
    double bearing = Math.toDegrees((Math.atan2(x, y)));
    System.out.println("BearingAngle : "+bearing);


问:
How to extract numbers from a string and dumping them as a comma separated values?
I have a test_file in bash which outputs following on screen . I have no control on the upstream code to print them in a certain way. So, I need to do parse some values from the screen output.
Here is what I'm doing:

```<code>MyOut=$(./my_test_file.sh)    # this is my example script which echo's the
                                 #output
echo $MyOut
</code>```

shows me the following

```<code>output for different segments IP address: 192.168.0.12 Segment :0xfff Segment Data: 123 23 42 23 4 444 1121 8676 34 530 323 564 523 7878 7328 96
</code>```

my expected results would be a string variable

```<code>123,23,42,23,4,444,1121,8676,34,530,323,564,523,7878,7328,96
</code>```

comma-separated 16 values getting stored in some variable which I can dump in a text file for further processing.

I tried playing with regular expressions and would like to only extract last 16 numbers in the following output

I did this

```<code>numbers=$(echo $MyOut | grep -o -E '[0-9]+')
</code>```

gives me

```<code>192 168 0 12 0 123 23 42 23 4 444 1121 8676 34 530 323 564 523 7878 7328 96
</code>```

I need to extract the last 16 numbers. Since it is not a array format , Can I add something in regular expression which only spits out only last 16 numbers delimited by commma ???

btw If you need to look into my_test_file.sh , its just echoing the statements

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

echo "output for different segments "
echo "IP address: 192.168.0.12 Segment :0xfff"
echo "Segment Data:"
echo "123"
echo "23"
echo "42"
echo "23"
echo "4"
echo "444"
echo "1121"
echo "8676"
echo "34"
echo "530"
echo "323"
echo "564"
echo "523"
echo "7878"
echo "7328"
echo "96"

</code>```

Thanks
Ash

答:
here is a sample awk script:

```<code> text="output for different segments IP address: 192.168.0.12 Segment :0xfff Segment Data: 123 23 42 23 4 444 1121 8676 34 530 323 564 523 7878 7328 96"
 echo $text |awk '{sub(/^.*Segment Data: /,"");gsub(/ /,",")}1'
</code>```

output:

```<code>123,23,42,23,4,444,1121,8676,34,530,323,564,523,7878,7328,96
</code>```

explantion:

sub(/^.*Segment Data: /,"") remove text from line begining to Segment Data:

gsub(/ /,",") replace all  with ,

1 print modified line

Body:
I have a test_file in bash which outputs following on screen . I have no control on the upstream code to print them in a certain way. So, I need to do parse some values from the screen output.
Here is what I'm doing:

MyOut=$(./my_test_file.sh)    # this is my example script which echo's the
                                 #output
echo $MyOut

shows me the following

output for different segments IP address: 192.168.0.12 Segment :0xfff Segment Data: 123 23 42 23 4 444 1121 8676 34 530 323 564 523 7878 7328 96

my expected results would be a string variable

123,23,42,23,4,444,1121,8676,34,530,323,564,523,7878,7328,96

comma-separated 16 values getting stored in some variable which I can dump in a text file for further processing.

I tried playing with regular expressions and would like to only extract last 16 numbers in the following output

I did this

numbers=$(echo $MyOut | grep -o -E '[0-9]+')

gives me

192 168 0 12 0 123 23 42 23 4 444 1121 8676 34 530 323 564 523 7878 7328 96

I need to extract the last 16 numbers. Since it is not a array format , Can I add something in regular expression which only spits out only last 16 numbers delimited by commma ???

btw If you need to look into my_test_file.sh , its just echoing the statements

#!/bin/bash

echo "output for different segments "
echo "IP address: 192.168.0.12 Segment :0xfff"
echo "Segment Data:"
echo "123"
echo "23"
echo "42"
echo "23"
echo "4"
echo "444"
echo "1121"
echo "8676"
echo "34"
echo "530"
echo "323"
echo "564"
echo "523"
echo "7878"
echo "7328"
echo "96"

Thanks
Ash

Body:
here is a sample awk script:

 text="output for different segments IP address: 192.168.0.12 Segment :0xfff Segment Data: 123 23 42 23 4 444 1121 8676 34 530 323 564 523 7878 7328 96"
 echo $text |awk '{sub(/^.*Segment Data: /,"");gsub(/ /,",")}1'

output:

123,23,42,23,4,444,1121,8676,34,530,323,564,523,7878,7328,96

explantion:

sub(/^.*Segment Data: /,"") remove text from line begining to Segment Data:

gsub(/ /,",") replace all  with ,

1 print modified line


问:
How to deploy a Flask REST API containing MySQLdb code on Heroku?
Most of the tutorials only show how to deploy a simple Flask hello world app on Heroku. But I have a Flask app which contains URLs with both GET and POST requests and they use MySQLdb library for fetching data from database.

How to set up such apps on Heroku? Currently I have a MySQL database on my local machine which is used by the code to fetch data. The Flask code contains many functions which are invoked by API calls. For example:

```<code>@app.route('/display_table', methods=['POST'])
def display_webstats():
    db = MySQLdb.connect("localhost", "root", "root", "db_name")
    cursor = db.cursor()
    cursor.execute("select * from table_name")
    ws = cursor.fetchall()
    return jsonify(ws), 200
</code>```

How to deploy such apps on Heroku?

答:
Make sure your dependencies are listed in your requirements.txt or Pipfile and Pipfile.lock.

Select a MySQL addon and provision it, e.g.

```<code>heroku addons:create cleardb:ignite
</code>```

Update your code to connect to the database provided by whatever environment variables the addon provides, e.g. CLEARDB_DATABASE_URL. You can use os.getenv() with a default argument to fall back in your development environment:

```<code>import os

database_url = os.getenv(
    'CLEARDB_DATABASE_URL',
    default='mysql://root:root@localhost/db_name',  # For local development
)
</code>```

It's probably also a good idea to centralize your database connection logic so it's not done in every controller. Something like Flask-SQLAlchemy might be helpful to simplify connecting and querying your database. It also provides an ORM if you want one of those.

Deploy.

Assuming you have them, run your migrations on Heroku via heroku run. If you're not using a migrations library I urge you to start. Flask-Migrate might be a good fit.

The alternative is manually creating and maintaining your schema across environments, and that's time-consuming, error prone, and frustrating.

Body:
Most of the tutorials only show how to deploy a simple Flask hello world app on Heroku. But I have a Flask app which contains URLs with both GET and POST requests and they use MySQLdb library for fetching data from database.

How to set up such apps on Heroku? Currently I have a MySQL database on my local machine which is used by the code to fetch data. The Flask code contains many functions which are invoked by API calls. For example:

@app.route('/display_table', methods=['POST'])
def display_webstats():
    db = MySQLdb.connect("localhost", "root", "root", "db_name")
    cursor = db.cursor()
    cursor.execute("select * from table_name")
    ws = cursor.fetchall()
    return jsonify(ws), 200

How to deploy such apps on Heroku?

Body:
Make sure your dependencies are listed in your requirements.txt or Pipfile and Pipfile.lock.

Select a MySQL addon and provision it, e.g.

heroku addons:create cleardb:ignite

Update your code to connect to the database provided by whatever environment variables the addon provides, e.g. CLEARDB_DATABASE_URL. You can use os.getenv() with a default argument to fall back in your development environment:

import os

database_url = os.getenv(
    'CLEARDB_DATABASE_URL',
    default='mysql://root:root@localhost/db_name',  # For local development
)

It's probably also a good idea to centralize your database connection logic so it's not done in every controller. Something like Flask-SQLAlchemy might be helpful to simplify connecting and querying your database. It also provides an ORM if you want one of those.

Deploy.

Assuming you have them, run your migrations on Heroku via heroku run. If you're not using a migrations library I urge you to start. Flask-Migrate might be a good fit.

The alternative is manually creating and maintaining your schema across environments, and that's time-consuming, error prone, and frustrating.


问:
How do to configure Karma to NOT restart the browser when it is closed?
I'm using the following command to run my unit tests in sort of a "debug" mode (where --debug is a custom key I added for my own purposes).

karma start ./.config/karma.conf.js --browsers=Chrome --debug

The command works fine -- it runs the tests and keeps it's instance of the Chrome browser open indefinitely. However, when I'm attempting to kill the browser by closing it, the test runner restarts it (up to 2 times).

```<code>05 01 2018 13:00:56.024:ERROR [launcher]: Chrome crashed.

05 01 2018 13:00:56.024:ERROR [launcher]: Chrome stdout:
05 01 2018 13:00:56.024:ERROR [launcher]: Chrome stderr:
05 01 2018 13:00:56.256:INFO [launcher]: Trying to start Chrome again (1/2).
</code>```

Is there a way to instruct Karma to NOT restart Chrome when it's closed/crashed?

答:
Set the retryLimit in your karma config to -1:

retryLimit

Type: Number

Default: 2

Description: When a browser crashes, karma will try to relaunch. This defines how many times karma should relaunch
  a browser before giving up.

https://github.com/karma-runner/karma/blob/master/docs/config/01-configuration-file.md#retrylimit

Body:
I'm using the following command to run my unit tests in sort of a "debug" mode (where --debug is a custom key I added for my own purposes).

karma start ./.config/karma.conf.js --browsers=Chrome --debug

The command works fine -- it runs the tests and keeps it's instance of the Chrome browser open indefinitely. However, when I'm attempting to kill the browser by closing it, the test runner restarts it (up to 2 times).

05 01 2018 13:00:56.024:ERROR [launcher]: Chrome crashed.

05 01 2018 13:00:56.024:ERROR [launcher]: Chrome stdout:
05 01 2018 13:00:56.024:ERROR [launcher]: Chrome stderr:
05 01 2018 13:00:56.256:INFO [launcher]: Trying to start Chrome again (1/2).

Is there a way to instruct Karma to NOT restart Chrome when it's closed/crashed?


问:
Pandas, groupby where column value is greater than x
I have a table like this

```<code>    timestamp   avg_hr  hr_quality  avg_rr  rr_quality  activity    sleep_summary_id

    1422404668  66      229             0       0           13              78
    1422404670  64      223             0       0           20              78
    1422404672  64      216             0       0           11              78
    1422404674  66      198             0       40          9               78
    1422404676  65      184             0       30          3               78
    1422404678  64      173             0       10          17              78
    1422404680  66      199             0       20          118             78
</code>```

I'm trying to group the data by timestamp,sleep id and rr_quality, where rr_quality is > 0

I've tried the following and none of them seems to work

```<code> df3 = df2.groupby([df2.index.hour,'sleep_summary_id',df2['rr_quality']>0])

 df3 = df2.groupby([df2.index.hour,'sleep_summary_id','rr_quality'>0])

 df3 = df2.groupby([df2.index.hour,'sleep_summary_id',['rr_quality']>0])
</code>```

All of them returns a keyerror.

EDIT:

Also can't seem to be able to pass more than one filter at a time.
I tried the following:

```<code>df2[df2['rr_quality'] >= 150, df2['hr_quality'] > 200]
df2[df2['rr_quality'] >= 150, ['hr_quality'] > 200]
df2[[df2['rr_quality'] >= 150, ['hr_quality'] > 200]]
</code>```

returns: TypeError: 'Series' objects are mutable, thus they cannot be hashed

答:
I know this is old but I wanted to add that there is an official function to do exactly this. Transforming the example from pandas to your case:</p>

```<code>grouped_df2= df2.groupby([df2.index.hour,'sleep_summary_id','rr_quality'])
grouped_df2.filter(lambda x: x['rr_quality'] > 0.)
</code>```

Body:
I have a table like this

    timestamp   avg_hr  hr_quality  avg_rr  rr_quality  activity    sleep_summary_id

    1422404668  66      229             0       0           13              78
    1422404670  64      223             0       0           20              78
    1422404672  64      216             0       0           11              78
    1422404674  66      198             0       40          9               78
    1422404676  65      184             0       30          3               78
    1422404678  64      173             0       10          17              78
    1422404680  66      199             0       20          118             78

I'm trying to group the data by timestamp,sleep id and rr_quality, where rr_quality is > 0

I've tried the following and none of them seems to work

 df3 = df2.groupby([df2.index.hour,'sleep_summary_id',df2['rr_quality']>0])

 df3 = df2.groupby([df2.index.hour,'sleep_summary_id','rr_quality'>0])

 df3 = df2.groupby([df2.index.hour,'sleep_summary_id',['rr_quality']>0])

All of them returns a keyerror.

EDIT:

Also can't seem to be able to pass more than one filter at a time.
I tried the following:

df2[df2['rr_quality'] >= 150, df2['hr_quality'] > 200]
df2[df2['rr_quality'] >= 150, ['hr_quality'] > 200]
df2[[df2['rr_quality'] >= 150, ['hr_quality'] > 200]]

returns: TypeError: 'Series' objects are mutable, thus they cannot be hashed

Body:
I know this is old but I wanted to add that there is an official function to do exactly this. Transforming the example from pandas to your case:

grouped_df2= df2.groupby([df2.index.hour,'sleep_summary_id','rr_quality'])
grouped_df2.filter(lambda x: x['rr_quality'] > 0.)


问:
Animation when user go into site, but not when he travels
I have a website, where i wanna use some simple animations when the page is loaded. The animation code is not a problem. This animation is some fading in of menu and other elements. I will call this an intro of my page. I want the end-user to see this animation ONLY when he visit a site, and dont see when he clicks some links in menu and travel around my website. I worked it out for now by putting the animation code only on fron page, but for example: what if someone gives a link to mywebsite.com/news to someone. He will go into site and he will not see the animation cause its only on the front page. Any solutions? I think about some session & cookies "if" statements with php maybe, but I'm a begginer and I dont know how to work it out.</p>

答: Make your home page always the same, and just load the code of the other pages. I mean, you can use frames, or php code with include('file.php'); for example. Then your animation will be always on the same page, or just load a frame in every page of your site, and the anim in that frame.</p>


问:
Using Dense Rank to simulate Count(Distinct) but running into a problem
Since SQL doesn't allow me to do count Distinct over Window functions, I have to use dense rank to achieve what I am trying to do.

My statement is:

```<code>,DENSE_RANK() over (partition by CustomerEmail order by Date_Created asc)
+DENSE_RANK() over (partition by CustomerEmail order by Date_Created desc)
-1 as AmountOrdersOverRangeByCustomer
</code>```

This gives me how much time a customer (using email to identify) places an order. So if he places 5 orders over a period of time, it would go 5,5,5,5, and 5.

The problem is, if he places two orders on the same day (Date_Created). Then instead of counting it as 2,2,  Dense_Rank counts it as 1,1... which I think is how it is supposed to act, but not how I want it. Does anyone know a fix? Would using Row_Number instead of Dense_Rank fix this?

答:
Your query is counting DISTINCT Date_Created for each customer email.

If you want to count "how much times a customer places an order" you should use regular count, like:

```<code>COUNT(*) over (partition by CustomerEmail)
</code>```

Body:
Since SQL doesn't allow me to do count Distinct over Window functions, I have to use dense rank to achieve what I am trying to do.

My statement is:

,DENSE_RANK() over (partition by CustomerEmail order by Date_Created asc)
+DENSE_RANK() over (partition by CustomerEmail order by Date_Created desc)
-1 as AmountOrdersOverRangeByCustomer

This gives me how much time a customer (using email to identify) places an order. So if he places 5 orders over a period of time, it would go 5,5,5,5, and 5.

The problem is, if he places two orders on the same day (Date_Created). Then instead of counting it as 2,2,  Dense_Rank counts it as 1,1... which I think is how it is supposed to act, but not how I want it. Does anyone know a fix? Would using Row_Number instead of Dense_Rank fix this?

Body:
Your query is counting DISTINCT Date_Created for each customer email.

If you want to count "how much times a customer places an order" you should use regular count, like:

COUNT(*) over (partition by CustomerEmail)


答:
```<code>MyOut=$(./my_test_file.sh | tail -n +4 | paste -sd ",")
</code>```

The tail -n +4 will skip to the 4th line of your output and the paste will join the lines with a comma instead of a space.

In comments you mention you don't have access to paste - what about tr?

```<code>MyOut=$(./my_test_file.sh | tail -n +4 | tr '\n' ',')
</code>```

Title: How to extract numbers from a string and dumping them as a comma separated values?

Body:
MyOut=$(./my_test_file.sh | tail -n +4 | paste -sd ",")

The tail -n +4 will skip to the 4th line of your output and the paste will join the lines with a comma instead of a space.

In comments you mention you don't have access to paste - what about tr?

MyOut=$(./my_test_file.sh | tail -n +4 | tr '\n' ',')


问:
QNA chatbot "say the feedback" with Cortana
I created a QNA (qnamaker.ai) and a chatbot in Azure. They connected and doing what they should do. I activated Cortana channel on azure than if I use the right invocation method its giving the right feedback just it doesn’t talk at all. I saw that Cortana will answer verbally if you invoked or queried with speech but seems not working.

I tried to recreate the whole app but it doesn’t resolve my issue.
I have created a basic C# UWP app with basic question and with that Cortana talks.

The code now is the default chatbot code from Microsoft.

I would ask your advice that if I miss some setting or I just need to modify the code?

Thanks for your help.

Gabor

```<code>    protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
    {
        var httpClient = _httpClientFactory.CreateClient();

        var qnaMaker = new QnAMaker(new QnAMakerEndpoint
        {
            KnowledgeBaseId = _configuration["QnAKnowledgebaseId"],
            EndpointKey = _configuration["QnAAuthKey"],
            Host = GetHostname()
        },
        null,
        httpClient);

        _logger.LogInformation("Calling QnA Maker");

        // The actual call to the QnA Maker service.
        var response = await qnaMaker.GetAnswersAsync(turnContext);
        if (response != null && response.Length > 0)
        {
            await turnContext.SendActivityAsync(MessageFactory.Text(response[0].Answer), cancellationToken);
        }
        else
        {
            await turnContext.SendActivityAsync(MessageFactory.Text("No QnA Maker answers were found."), cancellationToken);
        }
</code>```

答:
Bot samples do not call the appropriate API to speak results.  You need to add parameters for speech and input hints.  Please see

https://github.com/microsoft/cortana-skills-samples/blob/master/Consumer/CSharp/V4Patches/11.qnamaker.diff

That shows a change to do this

```<code>                 await turnContext.SendActivityAsync(msg, speak: msg, inputHint: InputHints.AcceptingInput, cancellationToken: cancellationToken);
</code>```

Body:
I created a QNA (qnamaker.ai) and a chatbot in Azure. They connected and doing what they should do. I activated Cortana channel on azure than if I use the right invocation method its giving the right feedback just it doesn’t talk at all. I saw that Cortana will answer verbally if you invoked or queried with speech but seems not working.

I tried to recreate the whole app but it doesn’t resolve my issue.
I have created a basic C# UWP app with basic question and with that Cortana talks.

The code now is the default chatbot code from Microsoft.

I would ask your advice that if I miss some setting or I just need to modify the code?

Thanks for your help.

Gabor

    protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
    {
        var httpClient = _httpClientFactory.CreateClient();

        var qnaMaker = new QnAMaker(new QnAMakerEndpoint
        {
            KnowledgeBaseId = _configuration["QnAKnowledgebaseId"],
            EndpointKey = _configuration["QnAAuthKey"],
            Host = GetHostname()
        },
        null,
        httpClient);

        _logger.LogInformation("Calling QnA Maker");

        // The actual call to the QnA Maker service.
        var response = await qnaMaker.GetAnswersAsync(turnContext);
        if (response != null && response.Length > 0)
        {
            await turnContext.SendActivityAsync(MessageFactory.Text(response[0].Answer), cancellationToken);
        }
        else
        {
            await turnContext.SendActivityAsync(MessageFactory.Text("No QnA Maker answers were found."), cancellationToken);
        }

Body:
Bot samples do not call the appropriate API to speak results.  You need to add parameters for speech and input hints.  Please see

https://github.com/microsoft/cortana-skills-samples/blob/master/Consumer/CSharp/V4Patches/11.qnamaker.diff

That shows a change to do this

                 await turnContext.SendActivityAsync(msg, speak: msg, inputHint: InputHints.AcceptingInput, cancellationToken: cancellationToken);


问:
Do django db_index migrations run concurrently?
I'm looking to add a multi-column index to a postgres database.  I have a non blocking SQL command to do this which looks like this:

```<code>CREATE INDEX CONCURRENTLY shop_product_fields_index ON shop_product (id, ...);
</code>```

When I add db_index to my model and run the migration, will it also run concurrently or will it block writes?  Is a concurrent migration possible in django?

答:
You could use the SeparateDatabaseAndState migration operation to provide a custom SQL command for creating the index. The operation accepts two lists of operations:

state_operations are operations to apply on the Django model state.
They do not affect the database.

database_operations are operations to apply to the database.

An example migration may look like this:

```<code>from django.db import migrations, models

class Migration(migrations.Migration):
    atomic = False

    dependencies = [
        ('myapp', '0001_initial'),
    ]

    operations = [
        migrations.SeparateDatabaseAndState(
            state_operations=[
                # operation generated by `makemigrations` to create an ordinary index
                migrations.AlterField(
                    # ...
                ),
            ],

            database_operations=[
                # operation to run custom SQL command (check the output of `sqlmigrate`
                # to see the auto-generated SQL, edit as needed)
                migrations.RunSQL(sql='CREATE INDEX CONCURRENTLY ...',
                                  reverse_sql='DROP INDEX ...'),
            ],
        ),
    ]
</code>```

Body:
I'm looking to add a multi-column index to a postgres database.  I have a non blocking SQL command to do this which looks like this:

CREATE INDEX CONCURRENTLY shop_product_fields_index ON shop_product (id, ...);

When I add db_index to my model and run the migration, will it also run concurrently or will it block writes?  Is a concurrent migration possible in django?

Body:
You could use the SeparateDatabaseAndState migration operation to provide a custom SQL command for creating the index. The operation accepts two lists of operations:

state_operations are operations to apply on the Django model state.
They do not affect the database.

database_operations are operations to apply to the database.

An example migration may look like this:

from django.db import migrations, models

class Migration(migrations.Migration):
    atomic = False

    dependencies = [
        ('myapp', '0001_initial'),
    ]

    operations = [
        migrations.SeparateDatabaseAndState(
            state_operations=[
                # operation generated by `makemigrations` to create an ordinary index
                migrations.AlterField(
                    # ...
                ),
            ],

            database_operations=[
                # operation to run custom SQL command (check the output of `sqlmigrate`
                # to see the auto-generated SQL, edit as needed)
                migrations.RunSQL(sql='CREATE INDEX CONCURRENTLY ...',
                                  reverse_sql='DROP INDEX ...'),
            ],
        ),
    ]


问:
Laravel displaying/updating data from DB show data in view only status "active" and "deactive" find by $id
I tried below code, but it is not working.

In this code, when I entered "DELETED", "id" number in browser "URL" it showing "DELETED" status users details also, I want to show and access only "ACTIVATE" AND "DEACTIVATE" users only if I entered "DELETED" Users "id" in "URL" it should show an error:

public function staff_status($id)
{
    $user = User::where('status', '=', 'ACTIVATE')->orWhere('status', '=', 'DEACTIVATE')->find($id);

    return view('home', compact('user'));
}

public function status_update(Request $request, $id)
{
    $user = User::where('status', '=', 'ACTIVATE') > orWhere('status', '=', 'DEACTIVATE')->find($id);

    $user['status'] = $request->status;

    $user->save();

    return back()->with('success', 'SUBMITED SUCCESSFULLY .');
}
```

答:
As @Chay22 mentioned you're supposed to add another where condition

just replace your code with this

```<code>public function staff_status($id)
{
    $user = User::where('status', '!=', 'DELETED')
                  ->where(function($query){
                      $query->where('status','=','ACTIVATE');
                      $query->orWhere('status','=','DEACTIVATE');
                  })->find($id);
    if (! $user) {
        return // return your error here
    }

    return view('home',compact('user'));
}

public function status_update(Request $request, $id)
{
    $user = User::where('status', '!=', 'DELETED')
                  ->where(function($query){
                      $query->where('status','=','ACTIVATE');
                      $query->orWhere('status','=','DEACTIVATE');
                  })->find($id);

    if ($user) {
        $user->status = $request->status;
        $user->save();

        return back()->with('success','SUBMITED SUCCESSFULLY .');
    } else {
        return // return your error here
    }
}
</code>```

Body:
As @Chay22 mentioned you're supposed to add another where condition

just replace your code with this

public function staff_status($id)
{
    $user = User::where('status', '!=', 'DELETED')
                  ->where(function($query){
                      $query->where('status','=','ACTIVATE');
                      $query->orWhere('status','=','DEACTIVATE');
                  })->find($id);
    if (! $user) {
        return // return your error here
    }

    return view('home',compact('user'));
}

public function status_update(Request $request, $id)
{
    $user = User::where('status', '!=', 'DELETED')
                  ->where(function($query){
                      $query->where('status','=','ACTIVATE');
                      $query->orWhere('status','=','DEACTIVATE');
                  })->find($id);

    if ($user) {
        $user->status = $request->status;
        $user->save();

        return back()->with('success','SUBMITED SUCCESSFULLY .');
    } else {
        return // return your error here
    }
}


问:
Angular *ngIf for nested formgroup value
I want to implement *ngIf for some div...

Doesn't work:

```<code>*ngIf="postForm.value.osnovne.sekcija === vozila"
</code>```

also

```<code>*ngIf="postForm.controls['osnovne'].value.sekcija === vozila
</code>```

This is my form:

```<code>this.postForm = this.fb.group({
      osnovne: this.fb.group({
        sekcija: vozila,
        cena: "",
        dogovor: "",
        opis: ""
      }),
      detaljne: this.fb.group({
        name: "",
        value: ""
      }),
      imagePath: this.fb.group({
        data: ""
      })
    });
</code>```

How to to that?

答:
You will need to use .get() better, something like this:

*ngIf="postForm.get('osnovne').get('sekcija').value === vozila"

.get() will insure you will always get the value even if the Control is disabled

Body:
I want to implement *ngIf for some div...

Doesn't work:

*ngIf="postForm.value.osnovne.sekcija === vozila"

also

*ngIf="postForm.controls['osnovne'].value.sekcija === vozila

This is my form:

this.postForm = this.fb.group({
      osnovne: this.fb.group({
        sekcija: vozila,
        cena: "",
        dogovor: "",
        opis: ""
      }),
      detaljne: this.fb.group({
        name: "",
        value: ""
      }),
      imagePath: this.fb.group({
        data: ""
      })
    });

How to to that?


问:
c++ vectors and pointers
As i understand if i dont store pointers, everything in c++ gets copied, which can lead to bad performance (ignore the simplicity of my example). So i thought i store my objects as pointers instead of string object inside my vector, thats better for performance right? (assumining i have very long strings and lots of them).

The problem when i try to iterate over my vector of string pointers is i cant extract the actual value from them

```<code>string test = "my-name";
vector<string*> names(20);
names.push_back(&test);

vector<string*>::iterator iterator = names.begin();
while (iterator != names.end())
{
    std::cout << (*iterator) << ":" << std::endl;
    // std::cout << *(*iterator); // fails

    iterator++;
}
</code>```

See the commented line, i have no problem in receiving the string pointer. But when i try to get the string pointers value i get an error (i couldnt find what excatly the error is but the program just fails).

I also tried storing (iterator) in a new string variable and but it didnt help?

答:
You've created the vector and initialized it to contain 20 items. Those items are being default initialized, which in the case of a pointer is a null pointer. The program is having trouble dereferencing those null pointers.

One piece of advice is to not worry about what's most efficient until you have a demonstrated problem. This code would certainly work much better with a vector<string> versus a vector<string*>.

Title: c++ vectors and pointers

Body:
As i understand if i dont store pointers, everything in c++ gets copied, which can lead to bad performance (ignore the simplicity of my example). So i thought i store my objects as pointers instead of string object inside my vector, thats better for performance right? (assumining i have very long strings and lots of them).

The problem when i try to iterate over my vector of string pointers is i cant extract the actual value from them

string test = "my-name";
vector<string*> names(20);
names.push_back(&test);

vector<string*>::iterator iterator = names.begin();
while (iterator != names.end())
{
    std::cout << (*iterator) << ":" << std::endl;
    // std::cout << *(*iterator); // fails

    iterator++;
}

See the commented line, i have no problem in receiving the string pointer. But when i try to get the string pointers value i get an error (i couldnt find what excatly the error is but the program just fails).

I also tried storing (iterator) in a new string variable and but it didnt help?


问:
How can I change color of items on Toolbar
I have a Toolbar, I want to change background to Black but by default items color is black and I want to change their color to gray, how can I do that ? Thanks you so much:
My Image about Toolbar

And this is my toolbar.xml

```<code><android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#2196F3"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
</code>```

My styles.xml

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
</code>```

答:
While creating an icon or vector asset, you can select the color

Click on the color selector.

If you want to change color in code then add app:iconTint="@color/yourcolor" in your MenuItem for change the Icon color.

```<code><item
android:icon="@drawable/ic_share_white_24dp"
android:id="@+id/action_share"
android:title="@string/action_share"
android:orderInCategory="200"
app:iconTint="@color/yourcolor"
app:showAsAction="ifRoom"
app:actionProviderClass="android.support.v7.widget.ShareActionProvider"/>
</code>```

For changing the 3 dots icon color, try adding this in styles.xml

```<code><style name="YourCustomTheme.OverFlow">
    <item name="android:src">@drawable/my_overflow_image</item>
</style>
</code>```

Body:
I have a Toolbar, I want to change background to Black but by default items color is black and I want to change their color to gray, how can I do that ? Thanks you so much:
My Image about Toolbar

And this is my toolbar.xml

<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#2196F3"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

My styles.xml

Body:
While creating an icon or vector asset, you can select the color

Click on the color selector.

If you want to change color in code then add app:iconTint="@color/yourcolor" in your MenuItem for change the Icon color.

<item
android:icon="@drawable/ic_share_white_24dp"
android:id="@+id/action_share"
android:title="@string/action_share"
android:orderInCategory="200"
app:iconTint="@color/yourcolor"
app:showAsAction="ifRoom"
app:actionProviderClass="android.support.v7.widget.ShareActionProvider"/>

For changing the 3 dots icon color, try adding this in styles.xml

<style name="YourCustomTheme.OverFlow">
    <item name="android:src">@drawable/my_overflow_image</item>
</style>


问:
Making a ffmpeg screen capture on Mac OS X using YUV 4:2:0 Planar color model
I make screen recordings with ffmpeg, using avfoundation on Mac OS X, x11grab on Linux and gdigrab on Windows.

The resulting files should be compatible with modern web browsers (<video/>), so I use H.264 codec and request YUV 4:2:0 Planar pixel format.

On Mac OS X, however (unlike Linux and Windows), I receive the following logging:

```<code>/usr/local/bin/ffmpeg -y -v error -f avfoundation -threads 0 -hide_banner -i 1:none -f mp4 -vcodec h264 -pix_fmt yuv420p -r 25/1 -qscale:v 1 -vf scale=-1:1080 target.mp4
[avfoundation @ 0x7fdba2003a00] Selected pixel format (yuv420p) is not supported by the input device.
[avfoundation @ 0x7fdba2003a00] Supported pixel formats:
[avfoundation @ 0x7fdba2003a00]   uyvy422
[avfoundation @ 0x7fdba2003a00]   yuyv422
[avfoundation @ 0x7fdba2003a00]   nv12
[avfoundation @ 0x7fdba2003a00]   0rgb
[avfoundation @ 0x7fdba2003a00]   bgr0
</code>```

Still, according to mplayer, the resulting MP4 file seems to have YUV 4:2:0 Planar color model:

```<code>[h264 @ 0x1048a8ac0]Format yuv420p chosen by get_format().
[h264 @ 0x1048a8ac0]Reinit context to 1728x1088, pix_fmt: yuv420p
[h264 @ 0x1048a8ac0]Format yuv420p chosen by get_format().
[h264 @ 0x1048a8ac0]Reinit context to 1728x1088, pix_fmt: yuv420p
[swscaler @ 0x1048c3cc0]bicubic scaler, from yuv420p to yuyv422 using MMXEXT
*** [scale] Exporting mp_image_t, 1728x1080x12bpp YUV planar, 2799360 bytes
*** [vo] Allocating mp_image_t, 1728x1080x16bpp YUV packed, 3732480 bytes
</code>```

the same confirmed by ffmpeg:

```<code>$ ffmpeg -i target.mp4 -hide_banner
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'target.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.20.100
  Duration: 00:00:04.72, start: 0.000000, bitrate: 201 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1728x1080, 197 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
</code>```

Questions:

Can someone explain the above ffmpeg logging?

If I still need to convert the avfoundation video stream to yuv420p, how do I make it on the fly (in a single ffmpeg pass)?

答:
The avfoundation module has its pixel format default set to yuv420p. When not available, it will print that warning and attempt to select another format. You should see a line below that warning starting with Overriding selected pixel format to use ..

If the output's fine, this can be ignored. You don't need a second pass or any other change.

Body:
I make screen recordings with ffmpeg, using avfoundation on Mac OS X, x11grab on Linux and gdigrab on Windows.

The resulting files should be compatible with modern web browsers (<video/>), so I use H.264 codec and request YUV 4:2:0 Planar pixel format.

On Mac OS X, however (unlike Linux and Windows), I receive the following logging:

/usr/local/bin/ffmpeg -y -v error -f avfoundation -threads 0 -hide_banner -i 1:none -f mp4 -vcodec h264 -pix_fmt yuv420p -r 25/1 -qscale:v 1 -vf scale=-1:1080 target.mp4
[avfoundation @ 0x7fdba2003a00] Selected pixel format (yuv420p) is not supported by the input device.
[avfoundation @ 0x7fdba2003a00] Supported pixel formats:
[avfoundation @ 0x7fdba2003a00]   uyvy422
[avfoundation @ 0x7fdba2003a00]   yuyv422
[avfoundation @ 0x7fdba2003a00]   nv12
[avfoundation @ 0x7fdba2003a00]   0rgb
[avfoundation @ 0x7fdba2003a00]   bgr0

Still, according to mplayer, the resulting MP4 file seems to have YUV 4:2:0 Planar color model:

[h264 @ 0x1048a8ac0]Format yuv420p chosen by get_format().
[h264 @ 0x1048a8ac0]Reinit context to 1728x1088, pix_fmt: yuv420p
[h264 @ 0x1048a8ac0]Format yuv420p chosen by get_format().
[h264 @ 0x1048a8ac0]Reinit context to 1728x1088, pix_fmt: yuv420p
[swscaler @ 0x1048c3cc0]bicubic scaler, from yuv420p to yuyv422 using MMXEXT
*** [scale] Exporting mp_image_t, 1728x1080x12bpp YUV planar, 2799360 bytes
*** [vo] Allocating mp_image_t, 1728x1080x16bpp YUV packed, 3732480 bytes

the same confirmed by ffmpeg:

$ ffmpeg -i target.mp4 -hide_banner
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'target.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.20.100
  Duration: 00:00:04.72, start: 0.000000, bitrate: 201 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1728x1080, 197 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler

Questions:

Can someone explain the above ffmpeg logging?

If I still need to convert the avfoundation video stream to yuv420p, how do I make it on the fly (in a single ffmpeg pass)?


问:
Filter by a property that has a value of true in a collection of error objects
I have an object that has a few different errors in it that are boolean. I would like to loop over this object and find out which errors are true and display their message that is also in the object, but not display the ones that are false.

I have tried to use the .some() and .reduce() functions but can't seem to get them to work.

```<code>const Errors = home => {
  const errors = [
    {
      message: 'This home requires an image.',
      error: true,
      buttonText: 'Add Image',
    },
    {
      message: 'This home requires two images.',
      error: false,
      buttonText: 'Add Image',
    },
    {
      message: 'This home was unpublished by the dealer.',
      error: true,
      buttonText: 'Publish Home',
    },
  ];

  return errors.some(error => error.message);
};

const MainComponent = () => {
  return(
    <Errors />
  );
}
</code>```

I just want to display the errors that are true.

答:
Use .filter to filter only the errors that are true and .map to show only the message

```<code>return errors.filter(e => e.error).map(e => e.message)
</code>```

Body:
I have an object that has a few different errors in it that are boolean. I would like to loop over this object and find out which errors are true and display their message that is also in the object, but not display the ones that are false.

I have tried to use the .some() and .reduce() functions but can't seem to get them to work.

const Errors = home => {
  const errors = [
    {
      message: 'This home requires an image.',
      error: true,
      buttonText: 'Add Image',
    },
    {
      message: 'This home requires two images.',
      error: false,
      buttonText: 'Add Image',
    },
    {
      message: 'This home was unpublished by the dealer.',
      error: true,
      buttonText: 'Publish Home',
    },
  ];

  return errors.some(error => error.message);
};

const MainComponent = () => {
  return(
    <Errors />
  );
}

I just want to display the errors that are true.

Body:
Use .filter to filter only the errors that are true and .map to show only the message

return errors.filter(e => e.error).map(e => e.message)


问:
How to determine when a custom UICollectionViewCell is 100% on the screen

From the diagram above I have UICollectionView with 4 custom cells.  At any time 2 or three cells can be on the screen.  How can I tell when "cell 1" or "cell 2" is 100% on the screen?

Both

```<code>collectionView.visibleCells
collectionView.indexPathsForVisibleItems
</code>```

return arrays and doesn't tell you if what cell 100% on the screen.

In the case of the image, the following will be display on didSelectItemAt

collectionView.visibleCells

```<code>[<Shot_On_Goal.MainCollectionViewCell: 0x101f525c0; baseClass = UICollectionViewCell; frame = (190 7.66667; 454 350); clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x1c0237300>>, <Shot_On_Goal.HeaderCollectionViewCell: 0x101f4d580; baseClass = UICollectionViewCell; frame = (10 0; 170 365); clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x1c0236800>>, <Shot_On_Goal.TheirHockeyNetCollectionViewCell: 0x101f55520; baseClass = UICollectionViewCell; frame = (654 7.66667; 454 350); clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x1c0238fe0>>]
</code>```

collectionView.indexPathsForVisibleItems

```<code>[[0, 1], [0, 0], [0, 2]]
</code>```

答:
Here's an extension for it, based don DonMag's answer:</p>

```<code>extension UICollectionView {
    var fullyVisibleCells : [UICollectionViewCell] {
        return self.visibleCells.filter { cell in
            let cellRect = self.convert(cell.frame, to: self.superview)
            return self.frame.contains(cellRect) }
    }
}
</code>```

Body:
From the diagram above I have UICollectionView with 4 custom cells.  At any time 2 or three cells can be on the screen.  How can I tell when "cell 1" or "cell 2" is 100% on the screen?

Both

collectionView.visibleCells
collectionView.indexPathsForVisibleItems

return arrays and doesn't tell you if what cell 100% on the screen.

In the case of the image, the following will be display on didSelectItemAt

collectionView.visibleCells

[<Shot_On_Goal.MainCollectionViewCell: 0x101f525c0; baseClass = UICollectionViewCell; frame = (190 7.66667; 454 350); clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x1c0237300>>, <Shot_On_Goal.HeaderCollectionViewCell: 0x101f4d580; baseClass = UICollectionViewCell; frame = (10 0; 170 365); clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x1c0236800>>, <Shot_On_Goal.TheirHockeyNetCollectionViewCell: 0x101f55520; baseClass = UICollectionViewCell; frame = (654 7.66667; 454 350); clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x1c0238fe0>>]

collectionView.indexPathsForVisibleItems

[[0, 1], [0, 0], [0, 2]]

Body:
Here's an extension for it, based don DonMag's answer:

extension UICollectionView {
    var fullyVisibleCells : [UICollectionViewCell] {
        return self.visibleCells.filter { cell in
            let cellRect = self.convert(cell.frame, to: self.superview)
            return self.frame.contains(cellRect) }
    }
}


问:
jQuery Transparent Countdown
I have seen many countdown's in JS and jQuery so I wanted it to be transparent i.e to match with the Page BG color ? If anyone knows such a countdown please reply and I need it to be in sorta Big FOnts and Vertical ...</p>

答:
This plugin is pretty good.
http://keith-wood.name/countdown.html

you can always set the css to whatever you want.

Title: jQuery Transparent Countdown


问:
Inserting multiple buttons onto a page in one line
I'm trying to insert a few buttons onto a page using a Chrome Extension. I don't own the page and can't control the CSS.

I want them all in one line. Right now they are all appearing on their own line and taking up the entire width.

```<code>var inMailButton = $('<button  type="button">Add to Response</button>')
var notInterested = $('<button class="column" type=button>Not Interested</button>')
var noRelo = $('<button class="column" type=button">No Relo</button>')
var interested = $('<button class="column" type=button">Interested</button>')

var responseLocation = $('#mailbox-main')

responseLocation.prepend(notInterested)
responseLocation.prepend(noRelo)
responseLocation.prepend(interested)
responseLocation.prepend(inMailButton)
</code>```

This appears on the page like:

```<code>Add To Response
Not Interested
No Relo
Interested
</code>```

Whereas I want them to be side by side

```<code>Add to Response | Not Interested | No Relo | Interested
</code>```

I was trying to add them to a  first, and then add that to responseLocation but I can't get it working as I wanted.

How would I do this?

答:
Add to your CSS:</p>

```<code>#mailbox-main button {
   display: inline-block;
}
</code>```

Body:
I'm trying to insert a few buttons onto a page using a Chrome Extension. I don't own the page and can't control the CSS.

I want them all in one line. Right now they are all appearing on their own line and taking up the entire width.

var inMailButton = $('<button  type="button">Add to Response</button>')
var notInterested = $('<button class="column" type=button>Not Interested</button>')
var noRelo = $('<button class="column" type=button">No Relo</button>')
var interested = $('<button class="column" type=button">Interested</button>')

var responseLocation = $('#mailbox-main')

responseLocation.prepend(notInterested)
responseLocation.prepend(noRelo)
responseLocation.prepend(interested)
responseLocation.prepend(inMailButton)

This appears on the page like:

Add To Response
Not Interested
No Relo
Interested

Whereas I want them to be side by side

Add to Response | Not Interested | No Relo | Interested

I was trying to add them to a  first, and then add that to responseLocation but I can't get it working as I wanted.

How would I do this?

Body:
Add to your CSS:

#mailbox-main button {
   display: inline-block;
}


问:
How to trigger modal when div element is dragged to specific location?
I am making a a boardgame website for a schoolproject. I have a div element(image) that can be dragged. The goal is to reach to the finish line. So my main problem is that how can I trigger a modal when the image is dragged to the finish point? Here below is my code that i have written to drag the element across the canvas.</p>

```<code>    var canvas = new fabric.Canvas('c', { selection: false });
    var grid = 35;

    // create grid

    for (var i = 0; i < (3000 / grid); i++) {
        canvas.add(new fabric.Line([ i * grid, 0, i * grid, 3000], { stroke: '#ccc', selectable: false }));
        canvas.add(new fabric.Line([ 0, i * grid, 3000, i * grid], { stroke: '#ccc', selectable: false }))
    }

    const url = 'https://oege.ie.hva.nl/~delawai/assets/images/Photos/bus_geel.png';
    const url1 = 'https://oege.ie.hva.nl/~delawai/assets/images/Photos/bus_blauw.png';
    const url2 = 'https://oege.ie.hva.nl/~delawai/assets/images/Photos/bus_lichtblauw.png';
    const url3 = 'https://oege.ie.hva.nl/~delawai/assets/images/Photos/bus_lichtgroen.png';
    const url4 = 'https://oege.ie.hva.nl/~delawai/assets/images/Photos/bus_paars.png';
    const url5 = 'https://oege.ie.hva.nl/~delawai/assets/images/Photos/bus_rood.png';
    const url6 = 'https://oege.ie.hva.nl/~delawai/assets/images/Photos/bus_roze.png';

    fabric.Image.fromURL(url, (img) => {
//scale down the image but keeping the aspect ratio
        const width = 100;
        const height = 80;
        const widthFactor = width / img.width;
        const heightFactor = height/ img.height;
        const minFactor = Math.min(widthFactor, heightFactor);
        img.scale(minFactor);
        canvas.add(img)
    }, {
//here you can set the positioning
        left: 1790,
        top: 40,
    });
    fabric.Image.fromURL(url1, (img) => {
//scale down the image but keeping the aspect ratio
        const width = 100;
        const height = 80;
        const widthFactor = width / img.width;
        const heightFactor = height/ img.height;
        const minFactor = Math.min(widthFactor, heightFactor);
        img.scale(minFactor);
        canvas.add(img)
    }, {
//here you can set the positioning
        left: 1790,
        top: 100,
    });
    fabric.Image.fromURL(url2, (img) => {
//scale down the image but keeping the aspect ratio
        const width = 100;
        const height = 80;
        const widthFactor = width / img.width;
        const heightFactor = height/ img.height;
        const minFactor = Math.min(widthFactor, heightFactor);
        img.scale(minFactor);
        canvas.add(img)
    }, {
//here you can set the positioning
        left: 1790,
        top: 150,
    });
    fabric.Image.fromURL(url3, (img) => {
//scale down the image but keeping the aspect ratio
        const width = 100;
        const height = 80;
        const widthFactor = width / img.width;
        const heightFactor = height/ img.height;
        const minFactor = Math.min(widthFactor, heightFactor);
        img.scale(minFactor);
        canvas.add(img)
    }, {
//here you can set the positioning
        left: 1790,
        top: 200,
    });
    fabric.Image.fromURL(url4, (img) => {
//scale down the image but keeping the aspect ratio
        const width = 100;
        const height = 80;
        const widthFactor = width / img.width;
        const heightFactor = height/ img.height;
        const minFactor = Math.min(widthFactor, heightFactor);
        img.scale(minFactor);
        canvas.add(img)
    }, {
//here you can set the positioning
        left: 1790,
        top: 250,
    });
    fabric.Image.fromURL(url5, (img) => {
//scale down the image but keeping the aspect ratio
        const width = 100;
        const height = 80;
        const widthFactor = width / img.width;
        const heightFactor = height/ img.height;
        const minFactor = Math.min(widthFactor, heightFactor);
        img.scale(minFactor);
        canvas.add(img)
    }, {
//here you can set the positioning
        left: 1790,
        top: 300,
    });
    fabric.Image.fromURL(url6, (img) => {
//scale down the image but keeping the aspect ratio
        const width = 100;
        const height = 80;
        const widthFactor = width / img.width;
        const heightFactor = height/ img.height;
        const minFactor = Math.min(widthFactor, heightFactor);
        img.scale(minFactor);
        canvas.add(img)
    }, {
//here you can set the positioning
        left: 1790,
        top: 350,
    });
    canvas.on('object:moving', function(options) {
        options.target.set({
            left: Math.round(options.target.left / grid) * grid,
            top: Math.round(options.target.top / grid) * grid
        });
    });

})
</code>```

答: Start here with collision detection and write a function that launches the modal after detection happens.</p>

Body:
I am making a a boardgame website for a schoolproject. I have a div element(image) that can be dragged. The goal is to reach to the finish line. So my main problem is that how can I trigger a modal when the image is dragged to the finish point? Here below is my code that i have written to drag the element across the canvas.

    var canvas = new fabric.Canvas('c', { selection: false });
    var grid = 35;

    // create grid

    for (var i = 0; i < (3000 / grid); i++) {
        canvas.add(new fabric.Line([ i * grid, 0, i * grid, 3000], { stroke: '#ccc', selectable: false }));
        canvas.add(new fabric.Line([ 0, i * grid, 3000, i * grid], { stroke: '#ccc', selectable: false }))
    }

    const url = 'https://oege.ie.hva.nl/~delawai/assets/images/Photos/bus_geel.png';
    const url1 = 'https://oege.ie.hva.nl/~delawai/assets/images/Photos/bus_blauw.png';
    const url2 = 'https://oege.ie.hva.nl/~delawai/assets/images/Photos/bus_lichtblauw.png';
    const url3 = 'https://oege.ie.hva.nl/~delawai/assets/images/Photos/bus_lichtgroen.png';
    const url4 = 'https://oege.ie.hva.nl/~delawai/assets/images/Photos/bus_paars.png';
    const url5 = 'https://oege.ie.hva.nl/~delawai/assets/images/Photos/bus_rood.png';
    const url6 = 'https://oege.ie.hva.nl/~delawai/assets/images/Photos/bus_roze.png';

    fabric.Image.fromURL(url, (img) => {
//scale down the image but keeping the aspect ratio
        const width = 100;
        const height = 80;
        const widthFactor = width / img.width;
        const heightFactor = height/ img.height;
        const minFactor = Math.min(widthFactor, heightFactor);
        img.scale(minFactor);
        canvas.add(img)
    }, {
//here you can set the positioning
        left: 1790,
        top: 40,
    });
    fabric.Image.fromURL(url1, (img) => {
//scale down the image but keeping the aspect ratio
        const width = 100;
        const height = 80;
        const widthFactor = width / img.width;
        const heightFactor = height/ img.height;
        const minFactor = Math.min(widthFactor, heightFactor);
        img.scale(minFactor);
        canvas.add(img)
    }, {
//here you can set the positioning
        left: 1790,
        top: 100,
    });
    fabric.Image.fromURL(url2, (img) => {
//scale down the image but keeping the aspect ratio
        const width = 100;
        const height = 80;
        const widthFactor = width / img.width;
        const heightFactor = height/ img.height;
        const minFactor = Math.min(widthFactor, heightFactor);
        img.scale(minFactor);
        canvas.add(img)
    }, {
//here you can set the positioning
        left: 1790,
        top: 150,
    });
    fabric.Image.fromURL(url3, (img) => {
//scale down the image but keeping the aspect ratio
        const width = 100;
        const height = 80;
        const widthFactor = width / img.width;
        const heightFactor = height/ img.height;
        const minFactor = Math.min(widthFactor, heightFactor);
        img.scale(minFactor);
        canvas.add(img)
    }, {
//here you can set the positioning
        left: 1790,
        top: 200,
    });
    fabric.Image.fromURL(url4, (img) => {
//scale down the image but keeping the aspect ratio
        const width = 100;
        const height = 80;
        const widthFactor = width / img.width;
        const heightFactor = height/ img.height;
        const minFactor = Math.min(widthFactor, heightFactor);
        img.scale(minFactor);
        canvas.add(img)
    }, {
//here you can set the positioning
        left: 1790,
        top: 250,
    });
    fabric.Image.fromURL(url5, (img) => {
//scale down the image but keeping the aspect ratio
        const width = 100;
        const height = 80;
        const widthFactor = width / img.width;
        const heightFactor = height/ img.height;
        const minFactor = Math.min(widthFactor, heightFactor);
        img.scale(minFactor);
        canvas.add(img)
    }, {
//here you can set the positioning
        left: 1790,
        top: 300,
    });
    fabric.Image.fromURL(url6, (img) => {
//scale down the image but keeping the aspect ratio
        const width = 100;
        const height = 80;
        const widthFactor = width / img.width;
        const heightFactor = height/ img.height;
        const minFactor = Math.min(widthFactor, heightFactor);
        img.scale(minFactor);
        canvas.add(img)
    }, {
//here you can set the positioning
        left: 1790,
        top: 350,
    });
    canvas.on('object:moving', function(options) {
        options.target.set({
            left: Math.round(options.target.left / grid) * grid,
            top: Math.round(options.target.top / grid) * grid
        });
    });

})


问:
error: value split is not a member of (String, Int)
I have to use foldByKey on a List to find the max price of each item.
The data, I am using is:

```<code>val itemPrice= List(("Soap",10),("Toaster",200),("Tshirt",400),("Tshirt",1000),("Suits",8000),("Suits",17000),("Soap",100))
</code>```

When I am trying to split the list into separate small items, it is giving the error:

```<code> error: value split is not a member of (String, Int)
</code>```

I want to split the List into inividual small lists and then apply foldbykey on  it like

```<code>val a = itemPrice.map(st =>st.split(",")).foldByKey(("dummy",0.0))((acc,element)=> if (acc._2>element._2) acc else element)
</code>```

Please help me find the resolution.
Code review and correction will be much helpful.

答:
Looks like you want to make it work by this example.

As you can see, you don't need split. You have 2 options:

1) Use fold -

```<code>itemPrice.fold(("dummy", 0.0))((acc, element) => {
  (acc,element)=> if (acc._2>element._2) acc else element
})
</code>```

2) Use foldByKey, but in that case, you need your to have tuples like:
List(("a", ("Soap",10)), ("b", ("Toaster", 200))) ..

and then:

```<code>`itemPrice.foldByKey(("dummy", 0.0))((acc, element) => {
  (acc,element)=> if (acc._2>element._2) acc else element
})
</code>```

Again, no need to use split at all.

Body:
I have to use foldByKey on a List to find the max price of each item.
The data, I am using is:

val itemPrice= List(("Soap",10),("Toaster",200),("Tshirt",400),("Tshirt",1000),("Suits",8000),("Suits",17000),("Soap",100))

When I am trying to split the list into separate small items, it is giving the error:

 error: value split is not a member of (String, Int)

I want to split the List into inividual small lists and then apply foldbykey on  it like

val a = itemPrice.map(st =>st.split(",")).foldByKey(("dummy",0.0))((acc,element)=> if (acc._2>element._2) acc else element)

Please help me find the resolution.
Code review and correction will be much helpful.

Body:
Looks like you want to make it work by this example.

As you can see, you don't need split. You have 2 options:

1) Use fold -

itemPrice.fold(("dummy", 0.0))((acc, element) => {
  (acc,element)=> if (acc._2>element._2) acc else element
})

2) Use foldByKey, but in that case, you need your to have tuples like:
List(("a", ("Soap",10)), ("b", ("Toaster", 200))) ..

and then:

`itemPrice.foldByKey(("dummy", 0.0))((acc, element) => {
  (acc,element)=> if (acc._2>element._2) acc else element
})

Again, no need to use split at all.


答:
you could do this a few ways...

the inline-block way:

```<code>button {
    display: inline-block
}
</code>```

Or use flex box, but that would require a housing div like so...

```<code><div class="buttonContainer">
    <button>button 1</button>
    <button>button 2</button>
    <button>button 3</button>
</div>

//CSS
.buttonContainer {
   display: flex;
}
</code>```

Title: Inserting multiple buttons onto a page in one line

Body:
you could do this a few ways...

the inline-block way:

button {
    display: inline-block
}

Or use flex box, but that would require a housing div like so...

<div class="buttonContainer">
    <button>button 1</button>
    <button>button 2</button>
    <button>button 3</button>
</div>

//CSS
.buttonContainer {
   display: flex;
}


问:
vba getElementById generated by javascript
I am currently trying to download the value of a div on the following page: http://www.banrep.gov.co/es/tasa-cambio-del-peso-colombiano-trm   this value of the div is generated with a javascript. Can someone tell me if it is possible to download that value that is generated with javascript with VBA?

Page image

this is my code:

```<code>Sub Basics_Of_Web_Macro()

    Dim myIE As Object
    Dim myIEDoc As Object

    Set myIE = CreateObject("InternetExplorer.Application")

    myIE.Visible = True

    myIE.navigate "http://www.banrep.gov.co/es/tasa-cambio-del-peso-colombiano-trm"

    While myIE.Busy
        DoEvents
    Wend

    Set myIEDoc = myIE.document

    MsgBox myIEDoc.Title

    MsgBox myIEDoc.getElementById("div_datos").innerText

End Sub
</code>```

答:
There is an alternative url that the page uses to get that content. You can regex out the value from the response. You could generalise the regex more according to use cases.

Try regex here

```<code>Option Explicit
Public Sub Test()
    Dim s As String, re As Object, p As String
    p = "new Array\(.*, ""\d+,\d+"",""(\d+\.\d+,\d+)""\);"
    Set re = CreateObject("VBScript.RegExp")

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "http://obieebr.banrep.gov.co/analytics/saw.dll?Go&path=%2Fshared%2fSeries%20Estad%c3%adsticas_T%2F1.%20Tasa%20de%20Cambio%20Peso%20Colombiano%2F1.1%20TRM%20-%20Disponible%20desde%20el%2027%20de%20noviembre%20de%201991%2F1.1.6.TCM_TRM%20para%20un%20d%C3%ADa&lang=es&options=rdf&NQUser=publico&NQPassword=publico", False
        .send
        s = .responseText
        Debug.Print GetValue(re, s, p)
    End With
End Sub

Public Function GetValue(ByVal re As Object, inputString As String, ByVal pattern As String) As String
    With re
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .pattern = pattern
        If .Test(inputString) Then
            GetValue = .Execute(inputString)(0).SubMatches(0)
        Else
            GetValue = "Not found"
        End If
    End With
End Function
</code>```

Regex explanation:

Body:
I am currently trying to download the value of a div on the following page: http://www.banrep.gov.co/es/tasa-cambio-del-peso-colombiano-trm   this value of the div is generated with a javascript. Can someone tell me if it is possible to download that value that is generated with javascript with VBA?

Page image

this is my code:

Sub Basics_Of_Web_Macro()

    Dim myIE As Object
    Dim myIEDoc As Object

    Set myIE = CreateObject("InternetExplorer.Application")

    myIE.Visible = True

    myIE.navigate "http://www.banrep.gov.co/es/tasa-cambio-del-peso-colombiano-trm"

    While myIE.Busy
        DoEvents
    Wend

    Set myIEDoc = myIE.document

    MsgBox myIEDoc.Title

    MsgBox myIEDoc.getElementById("div_datos").innerText

End Sub

Body:
There is an alternative url that the page uses to get that content. You can regex out the value from the response. You could generalise the regex more according to use cases.

Try regex here

Option Explicit
Public Sub Test()
    Dim s As String, re As Object, p As String
    p = "new Array\(.*, ""\d+,\d+"",""(\d+\.\d+,\d+)""\);"
    Set re = CreateObject("VBScript.RegExp")

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "http://obieebr.banrep.gov.co/analytics/saw.dll?Go&path=%2Fshared%2fSeries%20Estad%c3%adsticas_T%2F1.%20Tasa%20de%20Cambio%20Peso%20Colombiano%2F1.1%20TRM%20-%20Disponible%20desde%20el%2027%20de%20noviembre%20de%201991%2F1.1.6.TCM_TRM%20para%20un%20d%C3%ADa&lang=es&options=rdf&NQUser=publico&NQPassword=publico", False
        .send
        s = .responseText
        Debug.Print GetValue(re, s, p)
    End With
End Sub

Public Function GetValue(ByVal re As Object, inputString As String, ByVal pattern As String) As String
    With re
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .pattern = pattern
        If .Test(inputString) Then
            GetValue = .Execute(inputString)(0).SubMatches(0)
        Else
            GetValue = "Not found"
        End If
    End With
End Function

Regex explanation:


问:
XStream returns attribute value as null
Today I faced strange behavior of XStream. So, XML:

```<code><AddressObjectType KOD_T_ST="0" LEVEL="0" SOCRNAME="blabla"/>
</code>```

Java class:

```<code>@XStreamAlias("AddressObjectType")
public class AddressObjectType {

    @XStreamAsAttribute
    @XStreamAlias("KOD_T_ST")
    private Integer id;

    @XStreamAsAttribute
    @XStreamAlias("SOCRNAME")
    private String name;

    @XStreamAsAttribute
    @XStreamAlias("SCNAME")
    private String shortName;

    @XStreamAsAttribute
    @XStreamAlias("LEVEL")
    private int level;
    // . . . getters, setters
}
</code>```

I have problem with only attribute KOD_T_ST. During deserialization always throws com.thoughtworks.xstream.converters.ConversionException and cause is NullPointerException. Attribute value is always null. Even I switch type from Integer to String.
What is going on? Does XStream has any limitations for alias names? How to read value?

XStream version 1.4.11.1.

Many thanks for your help and best regards.

答:
There is a problem with your existing xml string

```<code><AddressObjectType KOD_T_ST="0" LEVEL="0" SOCRNAME="blabla"/>
</code>```

Instead of using the above, use the below one, it will work, there is no change in the AddressObjectType object model. Mark the difference, there is double underscore(__) in the xml which I provided.

```<code><AddressObjectType KOD__T__ST="0" LEVEL="0" SOCRNAME="blabla"/>
</code>```

To understand, refer below the link.
http://x-stream.github.io/faq.html#XML_double_underscores

To quote,

Why do field names suddenly have double underscores in the generated
  XML? XStream maps Java class names and field names to XML tags or
  attributes. Unfortunately this mapping cannot be 1:1, since some
  characters used for identifiers in Java are invalid in XML names.
  Therefore XStream uses an XmlFriendlyNameCoder to replace these
  characters with a replacement. By default this NameCoder uses an
  underscore as escape character and has therefore to escape the
  underscore itself also. You may provide a different configured
  instance of the XmlFriendlyNameCoder or a complete different
  implementation like the NoNameCoder to prevent name coding at all.
  However it is your responsibility then to ensure, that the resulting
  names are valid for XML.

Title: XStream returns attribute value as null

Body:
Today I faced strange behavior of XStream. So, XML:

<AddressObjectType KOD_T_ST="0" LEVEL="0" SOCRNAME="blabla"/>

Java class:

@XStreamAlias("AddressObjectType")
public class AddressObjectType {

    @XStreamAsAttribute
    @XStreamAlias("KOD_T_ST")
    private Integer id;

    @XStreamAsAttribute
    @XStreamAlias("SOCRNAME")
    private String name;

    @XStreamAsAttribute
    @XStreamAlias("SCNAME")
    private String shortName;

    @XStreamAsAttribute
    @XStreamAlias("LEVEL")
    private int level;
    // . . . getters, setters
}

I have problem with only attribute KOD_T_ST. During deserialization always throws com.thoughtworks.xstream.converters.ConversionException and cause is NullPointerException. Attribute value is always null. Even I switch type from Integer to String.
What is going on? Does XStream has any limitations for alias names? How to read value?

XStream version 1.4.11.1.

Many thanks for your help and best regards.

Body:
There is a problem with your existing xml string

<AddressObjectType KOD_T_ST="0" LEVEL="0" SOCRNAME="blabla"/>

Instead of using the above, use the below one, it will work, there is no change in the AddressObjectType object model. Mark the difference, there is double underscore(__) in the xml which I provided.

<AddressObjectType KOD__T__ST="0" LEVEL="0" SOCRNAME="blabla"/>

To understand, refer below the link.
http://x-stream.github.io/faq.html#XML_double_underscores

To quote,

Why do field names suddenly have double underscores in the generated
  XML? XStream maps Java class names and field names to XML tags or
  attributes. Unfortunately this mapping cannot be 1:1, since some
  characters used for identifiers in Java are invalid in XML names.
  Therefore XStream uses an XmlFriendlyNameCoder to replace these
  characters with a replacement. By default this NameCoder uses an
  underscore as escape character and has therefore to escape the
  underscore itself also. You may provide a different configured
  instance of the XmlFriendlyNameCoder or a complete different
  implementation like the NoNameCoder to prevent name coding at all.
  However it is your responsibility then to ensure, that the resulting
  names are valid for XML.