问:
Check if string contains a character with for loop?
I am currently working on a simple code that will check if an user inputted String contains character(s) that are specified in the for loop.

My current code

```<code>import java.util.Scanner;
public class AutumnLeaves {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int G = 0;
    int R = 0;
    int Y = 0;
    int B = 0;
    String S = sc.nextLine();
    for (int i = 0; i < S.length(); i++) {
        if (S.contains("G")) {
            G++;
        } else {
            if (S.contains("R")) {
                R++;
            } else {
                if (S.contains("Y")) {
                    Y++;
                } else {
                    if (S.contains("B")) {
                        B++;
                    }
                }
            }
        }
    }
    int total = G + R + Y + B;
    System.out.println(G/total);
    System.out.println(R/total);
    System.out.println(Y/total);
    System.out.println(B/total);
}
</code>```

}

As you can see, it checks if the string contains such characters and it will increase the counter of the character by one. However when I run it, I don't receive the results I predicted.
If I input GGRY, it outputs 1 0 0 0. When the desired out put is

0.5
0.25
0.25
0.0

Any help would be appreciated!

答:
Your earlier code S.contains("some character") was finding the index of the character in the entire string. Use S.charAt(i) to specifically find the index at ith location in the string.
Finally, you need to convert the integer to floating point in order to print output as floating values.

```<code>public class AutumnLeaves {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int G = 0;
        int R = 0;
        int Y = 0;
        int B = 0;
        String S = sc.nextLine();
        for (int i = 0; i < S.length(); i++) {
            if (S.charAt(i) == 'G') {
                G++;
            } else {
                if (S.charAt(i) == 'R') {
                    R++;
                } else {
                    if (S.charAt(i) == 'Y') {
                        Y++;
                    } else {
                        if (S.charAt(i) == 'B') {
                            B++;
                        }
                    }
                }
            }
        }
        int total = G + R + Y + B;
        System.out.println(G * 1.0 / total);
        System.out.println(R * 1.0 / total);
        System.out.println(Y * 1.0 / total);
        System.out.println(B * 1.0 / total);
    }
}
</code>```

Body:
I am currently working on a simple code that will check if an user inputted String contains character(s) that are specified in the for loop.

My current code

import java.util.Scanner;
public class AutumnLeaves {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int G = 0;
    int R = 0;
    int Y = 0;
    int B = 0;
    String S = sc.nextLine();
    for (int i = 0; i < S.length(); i++) {
        if (S.contains("G")) {
            G++;
        } else {
            if (S.contains("R")) {
                R++;
            } else {
                if (S.contains("Y")) {
                    Y++;
                } else {
                    if (S.contains("B")) {
                        B++;
                    }
                }
            }
        }
    }
    int total = G + R + Y + B;
    System.out.println(G/total);
    System.out.println(R/total);
    System.out.println(Y/total);
    System.out.println(B/total);
}

}

As you can see, it checks if the string contains such characters and it will increase the counter of the character by one. However when I run it, I don't receive the results I predicted.
If I input GGRY, it outputs 1 0 0 0. When the desired out put is

0.5
0.25
0.25
0.0

Any help would be appreciated!

Body:
Your earlier code S.contains("some character") was finding the index of the character in the entire string. Use S.charAt(i) to specifically find the index at ith location in the string.
Finally, you need to convert the integer to floating point in order to print output as floating values.

public class AutumnLeaves {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int G = 0;
        int R = 0;
        int Y = 0;
        int B = 0;
        String S = sc.nextLine();
        for (int i = 0; i < S.length(); i++) {
            if (S.charAt(i) == 'G') {
                G++;
            } else {
                if (S.charAt(i) == 'R') {
                    R++;
                } else {
                    if (S.charAt(i) == 'Y') {
                        Y++;
                    } else {
                        if (S.charAt(i) == 'B') {
                            B++;
                        }
                    }
                }
            }
        }
        int total = G + R + Y + B;
        System.out.println(G * 1.0 / total);
        System.out.println(R * 1.0 / total);
        System.out.println(Y * 1.0 / total);
        System.out.println(B * 1.0 / total);
    }
}


来源: stackexchange

问:
How to get access to the Heapster's Grafana dashboard after clean Kubernetes 1.5.0 installation using Rancher 1.5.1
I'm deploying my test Kubernetes cluster on AWS using Rancher 1.5.1.

I first deploy Rancher and ensure that there are no errors after hosts registration.
I then install Kubernetes using "Kubernetes" entry in the Rancher's catalog.
That succeeds seemingly without any errors and I get access to my 1.5.0 Kubernetes:

```<code>kubectl version
Client Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.4", GitCommit:"7243c69eb523aa4377bce883e7c0dd76b84709a1", GitTreeState:"clean", BuildDate:"2017-03-08T02:50:34Z", GoVersion:"go1.8", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"5+", GitVersion:"v1.5.0-115+611cbb22703182", GitCommit:"611cbb22703182611863beda17bf9f3e90afa148", GitTreeState:"clean", BuildDate:"2017-01-13T18:03:00Z", GoVersion:"go1.7.4", Compiler:"gc", Platform:"linux/amd64"}
</code>```

As I understand, the Heapster with InfluxDB and Grafana dashboard is part of the default Kubernetes installation now. All Heapster, InfluxDB and Grafana related pods show no errors nether in logs nor in status and seem to run successfully:

```<code>kubectl -n kube-system describe rs heapster-3467702493
Name:       heapster-3467702493
Namespace:  kube-system
Image(s):   gcr.io/google_containers/heapster:v1.2.0
Selector:   k8s-app=heapster,pod-template-hash=3467702493,version=v6
Labels:     k8s-app=heapster
        pod-template-hash=3467702493
        version=v6
Replicas:   1 current / 1 desired
Pods Status:    1 Running / 0 Waiting / 0 Succeeded / 0 Failed
No volumes.
No events.

kubectl -n kube-system get pods
NAME                                    READY     STATUS             RESTARTS   AGE
default-http-backend-w9td0              1/1       Running            0          1d
heapster-3467702493-b28jm               1/1       Running            0          1d
influxdb-grafana-876329878-5qpsd        2/2       Running            0          1d
kube-dns-1208858260-zb7d9               4/4       Running            0          1d
kubernetes-dashboard-2492700511-8g3bj   1/1       Running            0          1d

kubectl -n kube-system describe pod influxdb-grafana-876329878-5qpsd
Name:       influxdb-grafana-876329878-5qpsd
Namespace:  kube-system
Node:       euir1a-dclus11.qiotec-internal.com/10.11.4.172
Start Time: Tue, 14 Mar 2017 14:48:05 +0100
Labels:     name=influx-grafana
        pod-template-hash=876329878
Status:     Running
IP:     10.42.35.83
Controllers:    ReplicaSet/influxdb-grafana-876329878
Containers:
  influxdb:
    Container ID:   docker://49ad7e2033d9116cc98d1e7c8cd6e20c305179d68804b762bb19592fefa59b3e
    Image:      docker.io/kubernetes/heapster_influxdb:v0.5
    Image ID:       docker-pullable://kubernetes/heapster_influxdb@sha256:24de37030e0da01c39b8863231b70f359e1fe6d4449505da03e2e7543bb068cb
    Port:
    State:      Running
      Started:      Tue, 14 Mar 2017 14:48:29 +0100
    Ready:      True
    Restart Count:  0
    Volume Mounts:
      /data from influxdb-storage (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from io-rancher-system-token-zgrrs (ro)
    Environment Variables:  <none>
  grafana:
    Container ID:   docker://bdb4e381f0cd05df0a2d1c7dffb52b3e6e724a27999e039c5399fef391fd6d32
    Image:      gcr.io/google_containers/heapster_grafana:v2.6.0-2
    Image ID:       docker-pullable://gcr.io/google_containers/heapster_grafana@sha256:208c98b77d4e18ad7759c0958bf87d467a3243bf75b76f1240a577002e9de277
    Port:
    State:      Running
      Started:      Tue, 14 Mar 2017 14:48:41 +0100
    Ready:      True
    Restart Count:  0
    Volume Mounts:
      /var from grafana-storage (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from io-rancher-system-token-zgrrs (ro)
    Environment Variables:
      INFLUXDB_SERVICE_URL:     http://monitoring-influxdb.kube-system.svc.cluster.local:8086
      GF_AUTH_BASIC_ENABLED:        false
      GF_AUTH_ANONYMOUS_ENABLED:    true
      GF_AUTH_ANONYMOUS_ORG_ROLE:   Admin
      GF_SERVER_ROOT_URL:       /
Conditions:
  Type      Status
  Initialized   True
  Ready     True
  PodScheduled  True
Volumes:
  influxdb-storage:
    Type:   EmptyDir (a temporary directory that shares a pod's lifetime)
    Medium:
  grafana-storage:
    Type:   EmptyDir (a temporary directory that shares a pod's lifetime)
    Medium:
  io-rancher-system-token-zgrrs:
    Type:   Secret (a volume populated by a Secret)
    SecretName: io-rancher-system-token-zgrrs
QoS Class:  BestEffort
Tolerations:    <none>
No events.
</code>```

The strange thing I can only see here, is that "Port:" entries are empty (instead of having some value as I'd expected).

Here is part of the influxdb-grafana-876329878-5qpsd log. It seems that it starts successfully on port 3000:

```<code>....
2017/03/14 13:48:42 [I] Migrator: exec migration id: create index UQE_dashboard_snapshot_delete_key - v5
2017/03/14 13:48:42 [I] Migrator: exec migration id: create index IDX_dashboard_snapshot_user_id - v5
2017/03/14 13:48:42 [I] Migrator: exec migration id: alter dashboard_snapshot to mediumtext v2
2017/03/14 13:48:42 [I] Migrator: exec migration id: create quota table v1
2017/03/14 13:48:42 [I] Migrator: exec migration id: create index UQE_quota_org_id_user_id_target - v1
2017/03/14 13:48:42 [I] Created default admin user: admin
2017/03/14 13:48:42 [I] Listen: http://0.0.0.0:3000
.Grafana is up and running.
Creating default influxdb datasource...
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   272  100    37  100   235   2972  18877 --:--:-- --:--:-- --:--:-- 19583
HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
Set-Cookie: grafana_sess=3063bf504a9ec00a; Path=/; HttpOnly
Date: Tue, 14 Mar 2017 13:48:43 GMT
Content-Length: 37

{"id":1,"message":"Datasource added"}
Importing default dashboards...
...
</code>```

The services are also up:

```<code>kubectl -n kube-system get services
NAME                       CLUSTER-IP      EXTERNAL-IP   PORT(S)             AGE
default-http-backend       10.43.159.75    <none>        80/TCP              1d
heapster                   10.43.77.135    <none>        80/TCP              1d
kube-dns                   10.43.0.10      <none>        53/UDP,53/TCP       1d
kubernetes-dashboard       10.43.202.63    <none>        9090/TCP            1d
monitoring-grafana         10.43.186.82    <none>        80/TCP              1d
monitoring-influxdb        10.43.61.17     <none>        8086/TCP,8083/TCP   1d
</code>```

At the end, I cannot connect to the Grafana dashboard neither via Rancher load balancer mapping to the monitoring-grafana port 80 (I get 503 "Service not found" error) nor via Kubernetes port forwarding (connection times out)

My cluster-info output:

```<code>kubectl cluster-info
Kubernetes master is running at https://my-rancher-host:8080/r/projects/1a5/kubernetes
KubeDNS is running at https://my-rancher-host:8080/r/projects/1a5/kubernetes/api/v1/proxy/namespaces/kube-system/services/kube-dns
kubernetes-dashboard is running at https://my-rancher-host:8080/r/projects/1a5/kubernetes/api/v1/proxy/namespaces/kube-system/services/kubernetes-dashboard
</code>```

is different from the one demonstrated in this Heapster video:
https://www.youtube.com/watch?v=xSMNR2fcoLs

Can anybody give a hint about what can be wrong and how can I connect to the Heapster's Grafana dashboard?

答: Yes, almost always all HTTP services should have an ingress resource</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm deploying my test Kubernetes cluster on AWS using Rancher 1.5.1.

I first deploy Rancher and ensure that there are no errors after hosts registration.
I then install Kubernetes using "Kubernetes" entry in the Rancher's catalog.
That succeeds seemingly without any errors and I get access to my 1.5.0 Kubernetes:

kubectl version
Client Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.4", GitCommit:"7243c69eb523aa4377bce883e7c0dd76b84709a1", GitTreeState:"clean", BuildDate:"2017-03-08T02:50:34Z", GoVersion:"go1.8", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"5+", GitVersion:"v1.5.0-115+611cbb22703182", GitCommit:"611cbb22703182611863beda17bf9f3e90afa148", GitTreeState:"clean", BuildDate:"2017-01-13T18:03:00Z", GoVersion:"go1.7.4", Compiler:"gc", Platform:"linux/amd64"}

As I understand, the Heapster with InfluxDB and Grafana dashboard is part of the default Kubernetes installation now. All Heapster, InfluxDB and Grafana related pods show no errors nether in logs nor in status and seem to run successfully:

kubectl -n kube-system describe rs heapster-3467702493
Name:       heapster-3467702493
Namespace:  kube-system
Image(s):   gcr.io/google_containers/heapster:v1.2.0
Selector:   k8s-app=heapster,pod-template-hash=3467702493,version=v6
Labels:     k8s-app=heapster
        pod-template-hash=3467702493
        version=v6
Replicas:   1 current / 1 desired
Pods Status:    1 Running / 0 Waiting / 0 Succeeded / 0 Failed
No volumes.
No events.

kubectl -n kube-system get pods
NAME                                    READY     STATUS             RESTARTS   AGE
default-http-backend-w9td0              1/1       Running            0          1d
heapster-3467702493-b28jm               1/1       Running            0          1d
influxdb-grafana-876329878-5qpsd        2/2       Running            0          1d
kube-dns-1208858260-zb7d9               4/4       Running            0          1d
kubernetes-dashboard-2492700511-8g3bj   1/1       Running            0          1d

kubectl -n kube-system describe pod influxdb-grafana-876329878-5qpsd
Name:       influxdb-grafana-876329878-5qpsd
Namespace:  kube-system
Node:       euir1a-dclus11.qiotec-internal.com/10.11.4.172
Start Time: Tue, 14 Mar 2017 14:48:05 +0100
Labels:     name=influx-grafana
        pod-template-hash=876329878
Status:     Running
IP:     10.42.35.83
Controllers:    ReplicaSet/influxdb-grafana-876329878
Containers:
  influxdb:
    Container ID:   docker://49ad7e2033d9116cc98d1e7c8cd6e20c305179d68804b762bb19592fefa59b3e
    Image:      docker.io/kubernetes/heapster_influxdb:v0.5
    Image ID:       docker-pullable://kubernetes/heapster_influxdb@sha256:24de37030e0da01c39b8863231b70f359e1fe6d4449505da03e2e7543bb068cb
    Port:
    State:      Running
      Started:      Tue, 14 Mar 2017 14:48:29 +0100
    Ready:      True
    Restart Count:  0
    Volume Mounts:
      /data from influxdb-storage (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from io-rancher-system-token-zgrrs (ro)
    Environment Variables:  <none>
  grafana:
    Container ID:   docker://bdb4e381f0cd05df0a2d1c7dffb52b3e6e724a27999e039c5399fef391fd6d32
    Image:      gcr.io/google_containers/heapster_grafana:v2.6.0-2
    Image ID:       docker-pullable://gcr.io/google_containers/heapster_grafana@sha256:208c98b77d4e18ad7759c0958bf87d467a3243bf75b76f1240a577002e9de277
    Port:
    State:      Running
      Started:      Tue, 14 Mar 2017 14:48:41 +0100
    Ready:      True
    Restart Count:  0
    Volume Mounts:
      /var from grafana-storage (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from io-rancher-system-token-zgrrs (ro)
    Environment Variables:
      INFLUXDB_SERVICE_URL:     http://monitoring-influxdb.kube-system.svc.cluster.local:8086
      GF_AUTH_BASIC_ENABLED:        false
      GF_AUTH_ANONYMOUS_ENABLED:    true
      GF_AUTH_ANONYMOUS_ORG_ROLE:   Admin
      GF_SERVER_ROOT_URL:       /
Conditions:
  Type      Status
  Initialized   True
  Ready     True
  PodScheduled  True
Volumes:
  influxdb-storage:
    Type:   EmptyDir (a temporary directory that shares a pod's lifetime)
    Medium:
  grafana-storage:
    Type:   EmptyDir (a temporary directory that shares a pod's lifetime)
    Medium:
  io-rancher-system-token-zgrrs:
    Type:   Secret (a volume populated by a Secret)
    SecretName: io-rancher-system-token-zgrrs
QoS Class:  BestEffort
Tolerations:    <none>
No events.

The strange thing I can only see here, is that "Port:" entries are empty (instead of having some value as I'd expected).

Here is part of the influxdb-grafana-876329878-5qpsd log. It seems that it starts successfully on port 3000:

....
2017/03/14 13:48:42 [I] Migrator: exec migration id: create index UQE_dashboard_snapshot_delete_key - v5
2017/03/14 13:48:42 [I] Migrator: exec migration id: create index IDX_dashboard_snapshot_user_id - v5
2017/03/14 13:48:42 [I] Migrator: exec migration id: alter dashboard_snapshot to mediumtext v2
2017/03/14 13:48:42 [I] Migrator: exec migration id: create quota table v1
2017/03/14 13:48:42 [I] Migrator: exec migration id: create index UQE_quota_org_id_user_id_target - v1
2017/03/14 13:48:42 [I] Created default admin user: admin
2017/03/14 13:48:42 [I] Listen: http://0.0.0.0:3000
.Grafana is up and running.
Creating default influxdb datasource...
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   272  100    37  100   235   2972  18877 --:--:-- --:--:-- --:--:-- 19583
HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
Set-Cookie: grafana_sess=3063bf504a9ec00a; Path=/; HttpOnly
Date: Tue, 14 Mar 2017 13:48:43 GMT
Content-Length: 37

{"id":1,"message":"Datasource added"}
Importing default dashboards...
...

The services are also up:

kubectl -n kube-system get services
NAME                       CLUSTER-IP      EXTERNAL-IP   PORT(S)             AGE
default-http-backend       10.43.159.75    <none>        80/TCP              1d
heapster                   10.43.77.135    <none>        80/TCP              1d
kube-dns                   10.43.0.10      <none>        53/UDP,53/TCP       1d
kubernetes-dashboard       10.43.202.63    <none>        9090/TCP            1d
monitoring-grafana         10.43.186.82    <none>        80/TCP              1d
monitoring-influxdb        10.43.61.17     <none>        8086/TCP,8083/TCP   1d

At the end, I cannot connect to the Grafana dashboard neither via Rancher load balancer mapping to the monitoring-grafana port 80 (I get 503 "Service not found" error) nor via Kubernetes port forwarding (connection times out)

My cluster-info output:

kubectl cluster-info
Kubernetes master is running at https://my-rancher-host:8080/r/projects/1a5/kubernetes
KubeDNS is running at https://my-rancher-host:8080/r/projects/1a5/kubernetes/api/v1/proxy/namespaces/kube-system/services/kube-dns
kubernetes-dashboard is running at https://my-rancher-host:8080/r/projects/1a5/kubernetes/api/v1/proxy/namespaces/kube-system/services/kubernetes-dashboard

is different from the one demonstrated in this Heapster video:
https://www.youtube.com/watch?v=xSMNR2fcoLs

Can anybody give a hint about what can be wrong and how can I connect to the Heapster's Grafana dashboard?


问:
Call to function's are not responding
HTML CODE of the slider

```<code><body>
<button id="l"  onClick="imagem()"><b><</b></button>

<img  id="aaa">

<button id="r" onClick="image()"><b>></b></button>
</body>
</html>
</code>```

JavaScript Code Of the slider

```<code><script type="text/javascript">
    var aa = ["im1.jpg", "im2.jpg", "im3.jpg", "im4.jpg", "im5.jpg", "im6.jpg"];
    var a = 1;

    function image(n) {
        a = a + 1;
        imageShow(a);
    }

    function imagem(n) {
        a--;
        imageShow(a);
    }

    function imageShow(r) {
        if (r > aa.length) {
            a = 1;
        }
        if (r < 1) {
            a = aa.length;
        }
        document.getElementById("aaa").src = aa[a - 1];
    }

    imageShow(1); // Call to imageShow function not responding.

    auto(); // Call to auto function not responding.

    function auto() {
        if (a > aa.length) {
            a = 1;
        }
        document.getElementById("aaa").src = aa[a - 1];
        a++;
        setTimeout(auto, 5000);
    }
</script>
</code>```

Kindly someone help me to figure out this problem. The call to function auto() and call to "function imageShow" is not responding.

答:
You should call auto() function after define it.

```<code>var aa = ["im1.jpg", "im2.jpg", "im3.jpg", "im4.jpg", "im5.jpg", "im6.jpg"];
var a = 1;

function image() {
    a++;
    imageShow(a);
}

function imagem() {
    a--;
    imageShow(a);
}

function imageShow(r) {
    if (r > aa.length) {
        a = 1;
    }
    if (r < 1) {
        a = aa.length;
    }
    document.getElementById("aaa").src = aa[a - 1];
}

function auto() {
    if (a > aa.length) {
        a = 1;
    }
   document.getElementById("aaa").src = aa[a - 1];
   a++;
   setTimeout(auto, 5000);
}
auto();
</code>```

Title: Call to function's are not responding

Body:
HTML CODE of the slider

<button id="l"  onClick="imagem()"><</button>

<button id="r" onClick="image()">></button>

JavaScript Code Of the slider

Kindly someone help me to figure out this problem. The call to function auto() and call to "function imageShow" is not responding.

Body:
You should call auto() function after define it.

var aa = ["im1.jpg", "im2.jpg", "im3.jpg", "im4.jpg", "im5.jpg", "im6.jpg"];
var a = 1;

function image() {
    a++;
    imageShow(a);
}

function imagem() {
    a--;
    imageShow(a);
}

function imageShow(r) {
    if (r > aa.length) {
        a = 1;
    }
    if (r < 1) {
        a = aa.length;
    }
    document.getElementById("aaa").src = aa[a - 1];
}

function auto() {
    if (a > aa.length) {
        a = 1;
    }
   document.getElementById("aaa").src = aa[a - 1];
   a++;
   setTimeout(auto, 5000);
}
auto();


问:
Troubles in text adventure python game
In my computer's class we were tasked with creating a text adventure game in python. I've gotten something down already, but I could only get so far with my knowledge. I'm probably missing something super simple, but I'm just stuck right now.
It's a multiple choice deal where the character is presented with 3 options, look around, move or access inventory. I'm stumped at how to make the code go off on it's own tangent.

I have it to where the player can get a description of their surroundings, but if they do and the options come back up, it sort of bugs out and displays the options again and then the next player input stops the code all together. So if the player "Looks around" and then decides they want to "Move" the code stops.

And, in the first area, there are two directions you can go, north and east. Even if you go East and then look around you get the description of what the Northern room looks like.

Also, I need help getting an inventory system fleshed out. I have no idea how i'd do that.

And there are certain times in the game (at least I planned to have them included) where the player could make statements like "Get insert item here" how would I create those actions?

Here's the code.

```<code>import random
import time
print ("You awake in what looks like an adandoned diner with a pounding headache.")

d1a = input ("""What would you like to do?:
  1. Look around
  2. Move
  3. Inventory """)
while d1a != "1" and d1a != "2":
  #add option 3 to the loop

  d1a = input ("What would you like to do?")

if d1a == "1":
    print()
    print ("It looks like an old diner. Dust and grime coat the tables, chairs and counter tops. You see a door to the North and another to the East.")
    print()
    time.sleep(1.5)
    d1a = input ("""What would you like to do?:
  1. Look around
  2. Move
  3. Inventory """)

elif d1a == "2":
    d2a = input ("""Where?
    North
    West
    South
    East""")

    while d2a != "North" and d2a != "north" and d2a != "West" and d2a != "west" and d2a != "South" and d2a != "south" and d2a != "East" and d2a != "east":
      d2a = input ("Where?")

    if d2a == "North" or d2a == "north":
      print()
      print ("You go through through the door to the North")
      print ("which has lead to you what looks to be the kitchen")
      print()
      time.sleep(1)

    elif d2a == "East" or d2a == "east":
      print()
      print("You step through the door to the east which")
      print ("takes you out to the streets. They look")
      print ("musty and old, cracks ravaging the asphalt.")
      print()
      time.sleep(1)

    elif d2a == "West" or d2a == "west":
      print()
      print ("I can't move there.")
      print()
      time.sleep(1)

    elif d2a == "South" or d2a == "south":
      print()
      print ("I can't move there.")
      print()
      time.sleep(1)

d1a = input ("""What would you like to do?:
  1. Look around
  2. Move
  3. Inventory """)
while d1a != "1" and d1a != "2":
  #add option 3 to the loop

  d1a = input ("What would you like to do?")

if d1a == "1":
    print()
    print ("Must be the kitchen area. You can see stoves, ovens, cabinets containing pots and pans. A dishwasher is open exposing a group of knives. If they're clean or not is unknown.")
    print()
    time.sleep(1.5)
    d1a = input ("""What would you like to do?:
  1. Look around
  2. Move
  3. Inventory """)

elif d1a == "2":
  d2a = input ("""Where?:
  North
  west
  south
  East""")
</code>```

Sorry, I'm relatively new to coding, my class just started delving into it but I wanted to test what I could do with this game.

答: I think that when you move North/east, you should assign a variable, 'location', for example, to the place you move to. then, when you look around, you should use an if statement to see what the location is and then write the correct description.</p>

Title: Troubles in text adventure python game

Body:
In my computer's class we were tasked with creating a text adventure game in python. I've gotten something down already, but I could only get so far with my knowledge. I'm probably missing something super simple, but I'm just stuck right now.
It's a multiple choice deal where the character is presented with 3 options, look around, move or access inventory. I'm stumped at how to make the code go off on it's own tangent.

I have it to where the player can get a description of their surroundings, but if they do and the options come back up, it sort of bugs out and displays the options again and then the next player input stops the code all together. So if the player "Looks around" and then decides they want to "Move" the code stops.

And, in the first area, there are two directions you can go, north and east. Even if you go East and then look around you get the description of what the Northern room looks like.

Also, I need help getting an inventory system fleshed out. I have no idea how i'd do that.

And there are certain times in the game (at least I planned to have them included) where the player could make statements like "Get insert item here" how would I create those actions?

Here's the code.

import random
import time
print ("You awake in what looks like an adandoned diner with a pounding headache.")

d1a = input ("""What would you like to do?:
  1. Look around
  2. Move
  3. Inventory """)
while d1a != "1" and d1a != "2":
  #add option 3 to the loop

  d1a = input ("What would you like to do?")

if d1a == "1":
    print()
    print ("It looks like an old diner. Dust and grime coat the tables, chairs and counter tops. You see a door to the North and another to the East.")
    print()
    time.sleep(1.5)
    d1a = input ("""What would you like to do?:
  1. Look around
  2. Move
  3. Inventory """)

elif d1a == "2":
    d2a = input ("""Where?
    North
    West
    South
    East""")

    while d2a != "North" and d2a != "north" and d2a != "West" and d2a != "west" and d2a != "South" and d2a != "south" and d2a != "East" and d2a != "east":
      d2a = input ("Where?")

    if d2a == "North" or d2a == "north":
      print()
      print ("You go through through the door to the North")
      print ("which has lead to you what looks to be the kitchen")
      print()
      time.sleep(1)

    elif d2a == "East" or d2a == "east":
      print()
      print("You step through the door to the east which")
      print ("takes you out to the streets. They look")
      print ("musty and old, cracks ravaging the asphalt.")
      print()
      time.sleep(1)

    elif d2a == "West" or d2a == "west":
      print()
      print ("I can't move there.")
      print()
      time.sleep(1)

    elif d2a == "South" or d2a == "south":
      print()
      print ("I can't move there.")
      print()
      time.sleep(1)

d1a = input ("""What would you like to do?:
  1. Look around
  2. Move
  3. Inventory """)
while d1a != "1" and d1a != "2":
  #add option 3 to the loop

  d1a = input ("What would you like to do?")

if d1a == "1":
    print()
    print ("Must be the kitchen area. You can see stoves, ovens, cabinets containing pots and pans. A dishwasher is open exposing a group of knives. If they're clean or not is unknown.")
    print()
    time.sleep(1.5)
    d1a = input ("""What would you like to do?:
  1. Look around
  2. Move
  3. Inventory """)

elif d1a == "2":
  d2a = input ("""Where?:
  North
  west
  south
  East""")

Sorry, I'm relatively new to coding, my class just started delving into it but I wanted to test what I could do with this game.


问:
Messaging system in Rails
I want to set up a whitelist messaging system in rails where users can select which other users they want to send the comment. The message could be visible to everyone or just one person. How would I set this up and what would the message form look like?</p>

答:
Either add a join table with only a message_id and recipient_id.

```<code>class Message
  has_and_belongs_to_many :recipients
end

class Recipient
  has_and_belongs_to_many :messages
end

m = Message.new
m.recipients = list_of_recipients
m.save
</code>```

Option is duplicating the message for each recipient. This is a great solution is each recipient has full control over their message inbox (e.g. delete the message).

```<code>class Message
  belongs_to :recipient

  def self.post_message(recipients, text)
     recipients.each { |r| Message.create(:recipient => r, :text => text) }
  end
end

class Recipient
  has_many :messages
end
</code>```

ContentLicense: CC BY-SA 2.5

Title: Messaging system in Rails

Body:
Either add a join table with only a message_id and recipient_id.

class Message
  has_and_belongs_to_many :recipients
end

class Recipient
  has_and_belongs_to_many :messages
end

m = Message.new
m.recipients = list_of_recipients
m.save

Option is duplicating the message for each recipient. This is a great solution is each recipient has full control over their message inbox (e.g. delete the message).

class Message
  belongs_to :recipient

  def self.post_message(recipients, text)
     recipients.each { |r| Message.create(:recipient => r, :text => text) }
  end
end

class Recipient
  has_many :messages
end


问:
Json and multiple User defined objects error
I have the following JSON database:

```<code>{"houses":[{"doors":[{"state":false,"requests":[]}],"users":[{"username":"blucas","password":"Phantom1"}],"passcode":"1324"},null,null,null,null,null,null,null,null,null]}
</code>```

which I have generated using this code:

```<code>File database = new File("database.json");
Door door1 = new Door();
ArrayList<Door> doors = new ArrayList<Door>();
doors.add(door1);

User blucas = new User("blucas", "Phantom1");
ArrayList<User> users= new ArrayList<User>();
users.add(blucas);
House house1 = new House(doors, users);

ArrayList<House> houseList = new ArrayList<House>();
houseList.add(house1);
Houses houses = new Houses(houseList);
objMapper.writeValue(database, houses);
</code>```

when I try to access the database in the simplest way that I can find:

```<code>byte[] jsonData = null;
try {
    jsonData = Files.readAllBytes(Paths.get("database.json"));
} catch (IOException e) {
    e.printStackTrace();
}
ObjectMapper objectMapper = new ObjectMapper();

try {
    houses = objectMapper.readValue(jsonData, Houses.class);
} catch (IOException e) {
    e.printStackTrace();
}
House[] myHouses = houses.getHouses();
House house1 = myHouses[0];
System.out.println(house1.checkPasscode("1324"));
System.exit(1);
</code>```

I get the error:

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of Server.House: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)
 at [Source: database.json; line: 1, column: 13] (through reference chain: Server.Houses["houses"]->java.lang.Object[][0])

Door, House, Users, and Houses are all user defined classes that exist in the same package as each other along with the code that generates the database, and the code that attempts to open and process the database.

I have looked thoroughly for a solution to this problem, but I cannot seem to find why I would be getting this error, I am very new to JSON and databases so any advice is greatly appreciated.

答: In House class there is no default constructor. Add default constructor in House class with no parameter.</p>

Body:
I have the following JSON database:

{"houses":[{"doors":[{"state":false,"requests":[]}],"users":[{"username":"blucas","password":"Phantom1"}],"passcode":"1324"},null,null,null,null,null,null,null,null,null]}

which I have generated using this code:

File database = new File("database.json");
Door door1 = new Door();
ArrayList<Door> doors = new ArrayList<Door>();
doors.add(door1);

User blucas = new User("blucas", "Phantom1");
ArrayList<User> users= new ArrayList<User>();
users.add(blucas);
House house1 = new House(doors, users);

ArrayList<House> houseList = new ArrayList<House>();
houseList.add(house1);
Houses houses = new Houses(houseList);
objMapper.writeValue(database, houses);

when I try to access the database in the simplest way that I can find:

byte[] jsonData = null;
try {
    jsonData = Files.readAllBytes(Paths.get("database.json"));
} catch (IOException e) {
    e.printStackTrace();
}
ObjectMapper objectMapper = new ObjectMapper();

try {
    houses = objectMapper.readValue(jsonData, Houses.class);
} catch (IOException e) {
    e.printStackTrace();
}
House[] myHouses = houses.getHouses();
House house1 = myHouses[0];
System.out.println(house1.checkPasscode("1324"));
System.exit(1);

I get the error:

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of Server.House: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)
 at [Source: database.json; line: 1, column: 13] (through reference chain: Server.Houses["houses"]->java.lang.Object[][0])

Door, House, Users, and Houses are all user defined classes that exist in the same package as each other along with the code that generates the database, and the code that attempts to open and process the database.

I have looked thoroughly for a solution to this problem, but I cannot seem to find why I would be getting this error, I am very new to JSON and databases so any advice is greatly appreciated.


问:
CSS: keep image aspect ratio as viewport width decreases
At this page, there are 3 "doorway" graphics:

```<code><div class="textwidget">
    <div class="one-third first">
        <div id="doorway1" class="doorway">
            <h3>The Best Core Exercise Ever</h3>
            <div class="doorway-action">
                <a href="http://vmpersonal.com/product/core-strength-level-1/"><img src="http://vmpersonal.com/wp-content/themes/vmpersonal/images/doorway-action.png" alt="Watch Video Now" title="Watch Video Now" /> Watch Video Now</a>
            </div>
        </div>
    </div>
    <div class="one-third">
        <div id="doorway2" class="doorway">
            <h3>Core Strength Level 1 Program</h3>
            <div class="doorway-action">
                <a href="http://vmpersonal.com/product/core-strength-level-1/"><img src="http://vmpersonal.com/wp-content/themes/vmpersonal/images/doorway-action.png" alt="Watch Video Now" title="Watch Video Now" /> Watch Video Now</a>
            </div>
        </div>
    </div>
    <div class="one-third">
        <div id="doorway3" class="doorway">
            <h3>Cardio Program</h3>
            <div class="doorway-action">
                <a href="http://vmpersonal.com/product/cardio-fitness-level-1/"><img src="http://vmpersonal.com/wp-content/themes/vmpersonal/images/doorway-action.png" alt="Watch Video Now" title="Watch Video Now" /> Watch Video Now</a>
            </div>
        </div>
    </div>
</div>
</code>```

I'd like to make the graphics and the divs that contain them responsive.

They are contained in div.one-third containers.

The images are 409px x 292px, meaning the height is 71.39364303% of the width.

I thought if I used CSS:

```<code>#doorway1 {background-image: url('images/doorway1.png'); height: 71.39364303%;}
#doorway2 {background-image: url('images/doorway2.png'); height: 71.39364303%;}
#doorway3 {background-image: url('images/doorway3.png'); height: 71.39364303%;}
</code>```

they would scale down with the div.one-third as the viewport decreased in width, but they don't, the images are cut off.

How can I keep the images aspect ration consistent as the viewport width decreases?

Help appreciated.

Update: AJ Funk has helped me make the background images scale down, but how do I make the divs that contain them scale down proportionally too?

答:
I believe that you can use img {max-width:100%} to make the images scale down responsively. Then as for scaling down the divs, I cannot see why it would be necessary. div tags don't serve a purpose on their own, and are only important because of the content you put inside of it. The links will remain the size of the image, no matter what size the image is. This is because the link is represented by the image.

But, if you displayed the content you need to manipulate, h3, etc. as block elements, which should allow you to set the dimensions using

```<code>.doorway h3{ //h3 is a child element of the class doorway
     display: block;//Or "inline-block", if you are using inline currently
     //Then you should be able to set the max-width or max-height whatever the case may be
     max-height: xx%;
}
</code>```

The reason that using the percentage value you wer using is because saying height: 71% does not mean height: 71% of width It actually means height: 71% of the viewport or the size of the device screen / window (depending on the way you set the viewport) so you could calculate what the amount of viewport you want the content to take up is, 3 images so roughly 33.33% for all 3 to take up all of the screen or you can use different units like pixels, which works less kindly with RWD (Responsive Web Design) but it can work if you use 'max' and 'min' for the width, as well as make some other accommodations, such as using percentages everywhere where it can be used.

I truly hope this helped or at least points you toward the answers you are looking for.

Body:
At this page, there are 3 "doorway" graphics:

The Best Core Exercise Ever

                 Watch Video Now

Core Strength Level 1 Program

                 Watch Video Now

Cardio Program

                 Watch Video Now

I'd like to make the graphics and the divs that contain them responsive.

They are contained in div.one-third containers.

The images are 409px x 292px, meaning the height is 71.39364303% of the width.

I thought if I used CSS:

#doorway1 {background-image: url('images/doorway1.png'); height: 71.39364303%;}
#doorway2 {background-image: url('images/doorway2.png'); height: 71.39364303%;}
#doorway3 {background-image: url('images/doorway3.png'); height: 71.39364303%;}

they would scale down with the div.one-third as the viewport decreased in width, but they don't, the images are cut off.

How can I keep the images aspect ration consistent as the viewport width decreases?

Help appreciated.

Update: AJ Funk has helped me make the background images scale down, but how do I make the divs that contain them scale down proportionally too?

Body:
I believe that you can use img {max-width:100%} to make the images scale down responsively. Then as for scaling down the divs, I cannot see why it would be necessary. div tags don't serve a purpose on their own, and are only important because of the content you put inside of it. The links will remain the size of the image, no matter what size the image is. This is because the link is represented by the image.

But, if you displayed the content you need to manipulate, h3, etc. as block elements, which should allow you to set the dimensions using

.doorway h3{ //h3 is a child element of the class doorway
     display: block;//Or "inline-block", if you are using inline currently
     //Then you should be able to set the max-width or max-height whatever the case may be
     max-height: xx%;
}

The reason that using the percentage value you wer using is because saying height: 71% does not mean height: 71% of width It actually means height: 71% of the viewport or the size of the device screen / window (depending on the way you set the viewport) so you could calculate what the amount of viewport you want the content to take up is, 3 images so roughly 33.33% for all 3 to take up all of the screen or you can use different units like pixels, which works less kindly with RWD (Responsive Web Design) but it can work if you use 'max' and 'min' for the width, as well as make some other accommodations, such as using percentages everywhere where it can be used.

I truly hope this helped or at least points you toward the answers you are looking for.


问:
How to make function parameter constant in JavaScript?
What I want to do is to use as many immutable variables as possible, thus reducing the number of moving parts in my code. I want to use "var" and "let" only when it's necessary.

This won't work:

```<code>function constParam(const a){
    alert('You want me to '+a+'!');
}
</code>```

Any ideas?

答:
This is what I do:

Instead of:

```<code>function F(const a, const b, const c, const d, const e, const f, const g){ // Invalid Code
    // lorem
    // ipsum
}
</code>```

..Use:

```<code>function F(){const[a, b, c, d, e, f, g] = arguments;
    // lorem
    // ipsum
}
</code>```

Body:
What I want to do is to use as many immutable variables as possible, thus reducing the number of moving parts in my code. I want to use "var" and "let" only when it's necessary.

This won't work:

function constParam(const a){
    alert('You want me to '+a+'!');
}

Any ideas?

Body:
This is what I do:

Instead of:

function F(const a, const b, const c, const d, const e, const f, const g){ // Invalid Code
    // lorem
    // ipsum
}

..Use:

function F(){const[a, b, c, d, e, f, g] = arguments;
    // lorem
    // ipsum
}


问:
Don't collapse Toolbar when RecyclerView fits the screen

I've made an app using Android Design Library, with a Toolbar and TabLayout.
 Actually 2 tabs are present, both with 2 RecyclerView, that automatically collapse the Toolbar when scrolled.

My question is: can I disable Toolbar collapsing when RecyclerView has few items and completely fits the screen (like in TAB 2)?

I've seen a lot of examples like CheeseSquare, made by a Google employee where the issue is still present: even if the RecyclerView has just 1 item, the toolbar keeps hiding on scroll.

I think I can just find out if the first item of the RecyclerView is visible on screen and if yes disable toolbar collapsing. The former is easy to implement, what about the latter?

This is my layout:

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinator_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_scrollFlags="scroll|enterAlwaysCollapsed"
            android:background="?attr/colorPrimary"
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/glucosio_pink"
            app:tabSelectedTextColor="@android:color/white"
            app:tabIndicatorColor="@color/glucosio_accent"
            app:tabTextColor="#80ffffff"/>
        </android.support.design.widget.AppBarLayout>

        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/main_fab"
        android:layout_margin="16dp"
        android:onClick="onFabClicked"
        app:backgroundTint="@color/glucosio_accent"
        android:src="@drawable/ic_add_black_24dp"
        android:layout_gravity="bottom|right"
        />
    </android.support.design.widget.CoordinatorLayout>
</code>```

答:
Just remove scroll from

```<code>app:layout_scrollFlags="scroll|enterAlways"
</code>```

So it should be

```<code>app:layout_scrollFlags="enterAlways"
</code>```

Body:
I've made an app using Android Design Library, with a Toolbar and TabLayout.
 Actually 2 tabs are present, both with 2 RecyclerView, that automatically collapse the Toolbar when scrolled.

My question is: can I disable Toolbar collapsing when RecyclerView has few items and completely fits the screen (like in TAB 2)?

I've seen a lot of examples like CheeseSquare, made by a Google employee where the issue is still present: even if the RecyclerView has just 1 item, the toolbar keeps hiding on scroll.

I think I can just find out if the first item of the RecyclerView is visible on screen and if yes disable toolbar collapsing. The former is easy to implement, what about the latter?

This is my layout:

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinator_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_scrollFlags="scroll|enterAlwaysCollapsed"
            android:background="?attr/colorPrimary"
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/glucosio_pink"
            app:tabSelectedTextColor="@android:color/white"
            app:tabIndicatorColor="@color/glucosio_accent"
            app:tabTextColor="#80ffffff"/>
        </android.support.design.widget.AppBarLayout>

        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/main_fab"
        android:layout_margin="16dp"
        android:onClick="onFabClicked"
        app:backgroundTint="@color/glucosio_accent"
        android:src="@drawable/ic_add_black_24dp"
        android:layout_gravity="bottom|right"
        />
    </android.support.design.widget.CoordinatorLayout>

Body:
Just remove scroll from

app:layout_scrollFlags="scroll|enterAlways"

So it should be

app:layout_scrollFlags="enterAlways"


问:
R how to get the third and last row for each user
I have a table that has information about certain users. What I'm trying to do is extract the third and last row of each user...How would I do that? So for example:

```<code>User | num |

use1 | 3 |

use1 | 2 |

use1 | 5 |

use1 | 8 |

use1 | 6 |

use2 | 1 |

..
</code>```

So in this example, I'd want the row with num = 5 and num = 6 and this would continue for each different user in the table.

答:
For variety, here is a plyr solution:

```<code>library(plyr)

#group by user and return 3rd and last row
ddply(df, .(User), function(x) x[c(3, nrow(x)),])
</code>```

Body:
I have a table that has information about certain users. What I'm trying to do is extract the third and last row of each user...How would I do that? So for example:

User | num |

use1 | 3 |

use1 | 2 |

use1 | 5 |

use1 | 8 |

use1 | 6 |

use2 | 1 |

..

So in this example, I'd want the row with num = 5 and num = 6 and this would continue for each different user in the table.

Body:
For variety, here is a plyr solution:

library(plyr)

#group by user and return 3rd and last row
ddply(df, .(User), function(x) x[c(3, nrow(x)),])


问:
Creating a Dummy Variable
I am working on birthweight data with categories cigs smoked per day, male, white.

I am trying to create dummy variable for nonsmoker which I used nonsmoker<-ifelse(data$cig==0,1,0), but for light smokers, which would be between 1-5 cigarettes per day, I'm not sure on how to set a series.

I thought maybe light smoker<-ifelse(data$cigs==1-5,1,0) would work, but guess not.

答:
You would need to use a boolean to select values greater than 1 and less than 5. So something like:

smoker<-ifelse((data$cigs>=1) & (data$cigs<=5),1,0)

You could also use the cut method to create a factor, the levels of which you could then rename:

```<code>cig <- 0:10  # your original data
smoker <- cut(cig , c(-1, 0, 5, 10))
levels(smoker) <- c("0", "1-5", "6-10")  # rename the levels
</code>```

which will then give you a factor that looks like this:

```<code>> smoker
 [1] 0    1-5  1-5  1-5  1-5  1-5  6-10 6-10 6-10 6-10 6-10
</code>```

You can set your cut boundaries (i.e. is the range inclusive/exclusive of the end points?) by playing with the include.lowest and right arguments of the cut method

Title: Creating a Dummy Variable

Body:
You would need to use a boolean to select values greater than 1 and less than 5. So something like:

smoker<-ifelse((data$cigs>=1) & (data$cigs<=5),1,0)

You could also use the cut method to create a factor, the levels of which you could then rename:

cig <- 0:10  # your original data
smoker <- cut(cig , c(-1, 0, 5, 10))
levels(smoker) <- c("0", "1-5", "6-10")  # rename the levels

which will then give you a factor that looks like this:

> smoker
 [1] 0    1-5  1-5  1-5  1-5  1-5  6-10 6-10 6-10 6-10 6-10

You can set your cut boundaries (i.e. is the range inclusive/exclusive of the end points?) by playing with the include.lowest and right arguments of the cut method


问:
Why do you have to cast objects when calling particular methods of a subclass?
So, for example,

```<code>Person p = New Person()

Person z = New Adult()
</code>```

Let's say the Adult Class had it's own method called drive(), why couldn't I do:

z.drive()

I know this won't work, but what is the logic behind this not working? When you say: Person z = New Adult(), aren't you specifying it is an Adult instance?

答:
You asked this, I quote:

When you say: Person z = New Adult(), aren't you specifying it is an
  Adult instance?

No, just the opposite, more precisely:

```<code>//Main.java, first version.
class Person {
    public void drive() {
        System.out.println("Person.drive");
    }
}

class Adult extends Person {

    @Override
    public void drive() {
        System.out.println("Adult.drive");
    }
}

public class Main {
    public static void main(String[] args) {
        Person p = new Person();
        p.drive();  // Person.drive

        Person a = new Adult();
        a.drive();  // Adult.drive
    }
}
</code>```

Second Variation, this time Person has NO drive() method:

```<code>//Main.java, second version.
class Person {}

class Adult extends Person {

    // NO overriding here ..
    public void drive() {
        System.out.println("Adult.drive");
    }
}

public class Main {
    public static void main(String[] args) {
        Person p = new Adult(); // 1

        // Now this cast is needed:
        Adult  a = (Adult) p;   // 2

        a.drive();  // Adult.drive(), as before  // 3
    }
}
</code>```

Put these two separate programs in a Main.java, respectively, compile and run.

Let's consider the second version. Behold the lines marked with //1 and //2.
In //1 what's happening is the so-called slicing of class Adult. Adult is an extension of Person and therefore has the privilege to claim more memory than a Person object. But you assign a Person to an Adult object, so not all the memory of the bigger Adult object might be initialzed.

Therefore, Jave urges you to cast the Person to an real Adult object in //2, so that you show it that you know what you're doing. Only then are you permitted to call a.drive() in //3.

Hope, that helps to clarify things a bit.

Regards, Micha

Body:
So, for example,

Person p = New Person()

Person z = New Adult()

Let's say the Adult Class had it's own method called drive(), why couldn't I do:

z.drive()

I know this won't work, but what is the logic behind this not working? When you say: Person z = New Adult(), aren't you specifying it is an Adult instance?

Body:
You asked this, I quote:

When you say: Person z = New Adult(), aren't you specifying it is an
  Adult instance?

No, just the opposite, more precisely:

//Main.java, first version.
class Person {
    public void drive() {
        System.out.println("Person.drive");
    }
}

class Adult extends Person {

    @Override
    public void drive() {
        System.out.println("Adult.drive");
    }
}

public class Main {
    public static void main(String[] args) {
        Person p = new Person();
        p.drive();  // Person.drive

        Person a = new Adult();
        a.drive();  // Adult.drive
    }
}

Second Variation, this time Person has NO drive() method:

//Main.java, second version.
class Person {}

class Adult extends Person {

    // NO overriding here ..
    public void drive() {
        System.out.println("Adult.drive");
    }
}

public class Main {
    public static void main(String[] args) {
        Person p = new Adult(); // 1

        // Now this cast is needed:
        Adult  a = (Adult) p;   // 2

        a.drive();  // Adult.drive(), as before  // 3
    }
}

Put these two separate programs in a Main.java, respectively, compile and run.

Let's consider the second version. Behold the lines marked with //1 and //2.
In //1 what's happening is the so-called slicing of class Adult. Adult is an extension of Person and therefore has the privilege to claim more memory than a Person object. But you assign a Person to an Adult object, so not all the memory of the bigger Adult object might be initialzed.

Therefore, Jave urges you to cast the Person to an real Adult object in //2, so that you show it that you know what you're doing. Only then are you permitted to call a.drive() in //3.

Hope, that helps to clarify things a bit.

Regards, Micha


问:
JavaScript for loop increment not working
I'm trying to use this timeline
But currently it calculate Navigation 'left' value based on the date difference.

I'm trying to make the left value increment by 25, so nav items will have 'left' value 25, 50, 75...

Here what I tried, but it's not working-

```<code>function setDatePosition(timelineComponents, min) {
        for (i = 0; i < timelineComponents['timelineDates'].length; i++) {
            var distance = daydiff(timelineComponents['timelineDates'][0], timelineComponents['timelineDates'][i]),
                distanceNorm = Math.round(distance/timelineComponents['eventsMinLapse']) + 2;
            timelineComponents['timelineEvents'].eq(i).css('left', distanceNorm*min+'px');
        }
    }
</code>```

to

```<code>function setDatePosition(timelineComponents, min) {
        for (i = 0; i < timelineComponents['timelineDates'].length; i += 25) {
            var distance = daydiff(timelineComponents['timelineDates'][0], timelineComponents['timelineDates'][i]),
                distanceNorm = Math.round(distance/timelineComponents['eventsMinLapse']) + 2;
            timelineComponents['timelineEvents'].eq(i).css('left', i +'%');
        }
    }
</code>```

How can I make the left value increment by 25 instead of current date difference calculation?

答:
The problem is, that you are trying to access i-th element of timelineComponents['timelineEvents'] (by using  timelineComponents['timelineEvents'].eq(i)). As you specified that i increases for 25 each loop, this means that you'll access element 0, element 25, element 50, etc. What I believe you're trying to do is access every element, just make the 'left' property increase by i (in px?)

So your function would look something like this:

```<code>  function setDatePosition(timelineComponents, min) {
            var position = 0;
            for (i = 0; i < timelineComponents['timelineDates'].length; i++) {
                var distance = daydiff(timelineComponents['timelineDates'][0], timelineComponents['timelineDates'][i]),
                    distanceNorm = Math.round(distance/timelineComponents['eventsMinLapse']) + 2;
                timelineComponents['timelineEvents'].eq(i).css('left', position +'px');
                position += 25;
            }
        }
</code>```

if you need it to increase by 25%  each time, just change the position + 'px' part to position + '%'

Body:
I'm trying to use this timeline
But currently it calculate Navigation 'left' value based on the date difference.

I'm trying to make the left value increment by 25, so nav items will have 'left' value 25, 50, 75...

Here what I tried, but it's not working-

function setDatePosition(timelineComponents, min) {
        for (i = 0; i < timelineComponents['timelineDates'].length; i++) {
            var distance = daydiff(timelineComponents['timelineDates'][0], timelineComponents['timelineDates'][i]),
                distanceNorm = Math.round(distance/timelineComponents['eventsMinLapse']) + 2;
            timelineComponents['timelineEvents'].eq(i).css('left', distanceNorm*min+'px');
        }
    }

to

function setDatePosition(timelineComponents, min) {
        for (i = 0; i < timelineComponents['timelineDates'].length; i += 25) {
            var distance = daydiff(timelineComponents['timelineDates'][0], timelineComponents['timelineDates'][i]),
                distanceNorm = Math.round(distance/timelineComponents['eventsMinLapse']) + 2;
            timelineComponents['timelineEvents'].eq(i).css('left', i +'%');
        }
    }

How can I make the left value increment by 25 instead of current date difference calculation?

Body:
The problem is, that you are trying to access i-th element of timelineComponents['timelineEvents'] (by using  timelineComponents['timelineEvents'].eq(i)). As you specified that i increases for 25 each loop, this means that you'll access element 0, element 25, element 50, etc. What I believe you're trying to do is access every element, just make the 'left' property increase by i (in px?)

So your function would look something like this:

  function setDatePosition(timelineComponents, min) {
            var position = 0;
            for (i = 0; i < timelineComponents['timelineDates'].length; i++) {
                var distance = daydiff(timelineComponents['timelineDates'][0], timelineComponents['timelineDates'][i]),
                    distanceNorm = Math.round(distance/timelineComponents['eventsMinLapse']) + 2;
                timelineComponents['timelineEvents'].eq(i).css('left', position +'px');
                position += 25;
            }
        }

if you need it to increase by 25%  each time, just change the position + 'px' part to position + '%'


问:
Database says missing column even though column is there
EDIT: I found the cause to be the error of not having a column in my database called Col_Name, however I did code the column into the database and yet it tells me it isnt there.

Error message:
Error Code : 1 (SQLITE_ERROR)
                                                                       Caused By : SQL(query) error or missing database.
                                                                        (table Expense_Table has no column named Name (code 1): , while compiling: INSERT INTO Expense_Table(Am,Name) VALUES (?,?))

I have a database with 2 Columns. I save inputs into the 2 columns then load them into a listview. I have successfully done 1 column and it works perfectly. When I add the 2nd column and I load the app, my Toast message tells me my database is empty. Any help on why this happens?

My MainActivity(Only relevant parts):

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    listView = (ListView)findViewById(R.id.listView);
    if (android.os.Build.VERSION.SDK_INT >= 21) {
        Window window = this.getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.setStatusBarColor(this.getResources().getColor(R.color.colorPrimary));
    }
    //Code for Ads
    mAdView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);

    nameList = new ArrayList<>();
    expenseList = new ArrayList<>();
    Row = new ArrayList<>();
    adapter = new CustomAdapter(this, Row);
    listView.setAdapter(adapter);

    //Get Database to populate Listview
    myDb = new DBHelper(this);
    Cursor data = myDb.getListContent();
    if(data.getCount() == 0){
        Toast.makeText(this, "Data NOT loaded", Toast.LENGTH_SHORT).show();
    } else{
        while(data.moveToNext()){
            String dbAmount = data.getString(1);
            String dbName = data.getString(2);
            ExRow exRow = new ExRow(dbAmount, dbName);
            expenseList.add(dbAmount);
            Row.add(exRow);
            adapter.notifyDataSetChanged();
            Toast.makeText(this, "Data loaded", Toast.LENGTH_SHORT).show();
        }
    }
</code>```

And here is my Database class for retrieving and saving data:

```<code>private static final String DATABASE_NAME = "Expenses.db";
    public static final String TABLE_NAME = "Expense_Table";
    public static final String Col_ID = "id";
    public static final String Col_AMOUNT = "Am";
    public static final String Col_NAME = "Name";

   //public  static final String Col_Date = "date";

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);

    }

    @Override
    //Set up database here
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("Create table " + TABLE_NAME +
                "(ID INTEGER PRIMARY KEY AUTOINCREMENT, AM TEXT, Name TEXT)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

    }

public boolean saveData(String Am, String Name) {
   SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(Col_AMOUNT, Am);
    contentValues.put(Col_NAME, Name);

    long result = db.insert(TABLE_NAME, null, contentValues);
    if(result == -1){
        return false;
    }else {
        return true;
    }
}
public Cursor getListContent(){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
    return data;
}
</code>```

There is more to my MainActivity that adds the inputs into the database. I figured it's too simple to paste the code. It's simply saveData(String, String);

答:
I think you should have to use do while loop to iterate data from your database.

```<code>if (cursor.moveToFirst()) {
        do {
           String dbAmount = cursor.getString(1);
           String dbName = cursor.getString(2);
            // Adding your data to holder
            ExRow exRow = new ExRow(dbAmount, dbName);
        expenseList.add(dbAmount);
        Row.add(exRow);
        } while (cursor.moveToNext());
    }
</code>```

also there is no need to notify your list all the time so remove that code.

happy coding. :-) i hope it works for you.

Body:
EDIT: I found the cause to be the error of not having a column in my database called Col_Name, however I did code the column into the database and yet it tells me it isnt there.

Error message:
Error Code : 1 (SQLITE_ERROR)
                                                                       Caused By : SQL(query) error or missing database.
                                                                        (table Expense_Table has no column named Name (code 1): , while compiling: INSERT INTO Expense_Table(Am,Name) VALUES (?,?))

I have a database with 2 Columns. I save inputs into the 2 columns then load them into a listview. I have successfully done 1 column and it works perfectly. When I add the 2nd column and I load the app, my Toast message tells me my database is empty. Any help on why this happens?

My MainActivity(Only relevant parts):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    listView = (ListView)findViewById(R.id.listView);
    if (android.os.Build.VERSION.SDK_INT >= 21) {
        Window window = this.getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.setStatusBarColor(this.getResources().getColor(R.color.colorPrimary));
    }
    //Code for Ads
    mAdView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);

    nameList = new ArrayList<>();
    expenseList = new ArrayList<>();
    Row = new ArrayList<>();
    adapter = new CustomAdapter(this, Row);
    listView.setAdapter(adapter);

    //Get Database to populate Listview
    myDb = new DBHelper(this);
    Cursor data = myDb.getListContent();
    if(data.getCount() == 0){
        Toast.makeText(this, "Data NOT loaded", Toast.LENGTH_SHORT).show();
    } else{
        while(data.moveToNext()){
            String dbAmount = data.getString(1);
            String dbName = data.getString(2);
            ExRow exRow = new ExRow(dbAmount, dbName);
            expenseList.add(dbAmount);
            Row.add(exRow);
            adapter.notifyDataSetChanged();
            Toast.makeText(this, "Data loaded", Toast.LENGTH_SHORT).show();
        }
    }

And here is my Database class for retrieving and saving data:

private static final String DATABASE_NAME = "Expenses.db";
    public static final String TABLE_NAME = "Expense_Table";
    public static final String Col_ID = "id";
    public static final String Col_AMOUNT = "Am";
    public static final String Col_NAME = "Name";

   //public  static final String Col_Date = "date";

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);

    }

    @Override
    //Set up database here
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("Create table " + TABLE_NAME +
                "(ID INTEGER PRIMARY KEY AUTOINCREMENT, AM TEXT, Name TEXT)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

    }

public boolean saveData(String Am, String Name) {
   SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(Col_AMOUNT, Am);
    contentValues.put(Col_NAME, Name);

    long result = db.insert(TABLE_NAME, null, contentValues);
    if(result == -1){
        return false;
    }else {
        return true;
    }
}
public Cursor getListContent(){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
    return data;
}

There is more to my MainActivity that adds the inputs into the database. I figured it's too simple to paste the code. It's simply saveData(String, String);

Body:
I think you should have to use do while loop to iterate data from your database.

if (cursor.moveToFirst()) {
        do {
           String dbAmount = cursor.getString(1);
           String dbName = cursor.getString(2);
            // Adding your data to holder
            ExRow exRow = new ExRow(dbAmount, dbName);
        expenseList.add(dbAmount);
        Row.add(exRow);
        } while (cursor.moveToNext());
    }

also there is no need to notify your list all the time so remove that code.

happy coding. :-) i hope it works for you.


问:
I'm trying to create a Java program to create and write a text file, but
```<code>public static void main(String[] args) {
    File newTxt = new File("C:/Users/cauan/Desktop/newTxt.txt");

    if(newTxt.exists()) System.out.println("The file already exists!");
    else {
        try{
            newTxt.createNewFile();
            FileWriter fw=new FileWriter(newTxt);
            BufferedWriter bw = new BufferedWriter(fw);

            bw.write("This is my Prog");
        }
        catch(Exception e){e.printStackTrace();}
    }
}
</code>```

This is my code.... But i dunno why am i getting an error :/

答:
You need to close the BufferedWriter and FileWriter in order to save the contents of the file.

```<code>bw.close();
fw.close();
</code>```

Complete program link

Body:
public static void main(String[] args) {
    File newTxt = new File("C:/Users/cauan/Desktop/newTxt.txt");

    if(newTxt.exists()) System.out.println("The file already exists!");
    else {
        try{
            newTxt.createNewFile();
            FileWriter fw=new FileWriter(newTxt);
            BufferedWriter bw = new BufferedWriter(fw);

            bw.write("This is my Prog");
        }
        catch(Exception e){e.printStackTrace();}
    }
}

This is my code.... But i dunno why am i getting an error :/

Body:
You need to close the BufferedWriter and FileWriter in order to save the contents of the file.

bw.close();
fw.close();

Complete program link


问:
nginx wordpress wp-admin redirecting to home
On my nginx server when i visit example.com/wp-admin or example.com/login i always see the home page of my site, but when i visit example.com/wp-login.php everything works (and login screen is showed).

Is there some config to do in nginx to make these urls (/wp-admin or wp-login) work again?

Note: Other posts permalinks like example.com/hello-world is working.

My configs files are:

1. /etc/nginx/nginx.conf

```<code>user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}
</code>```

2. /etc/nginx/sites-available/worpdress.conf

```<code>##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# http://wiki.nginx.org/Pitfalls
# http://wiki.nginx.org/QuickStart
# http://wiki.nginx.org/Configuration
#
# Generally, you will want to move this file somewhere, and start with a clean
# file but keep this around for reference. Or just disable in sites-enabled.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    #
    # Read up on ssl_ciphers to ensure a secure configuration.
    # See: https://bugs.debian.org/765782
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;

    root /var/www/example.com/html;

    # Add index.php to the list if you are using PHP
    index index.php index.html index.htm index.nginx-debian.html;

    #server_name 127.0.0.1;
        server_name example.com www.example.com;

        location /favicon.ico {
                log_not_found off;
                access_log off;
        }

        location /robots.tx {
                allow all;
                log_not_found off;
                access_log off;
        }

        location ~* /(?:uploads|files)/.*\.php$ {
                 deny all;
        }

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        #try_files $uri $uri/ =404;
                try_files $uri $uri /index.php?$args;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;

    #   # With php7.0-cgi alone:
    #   fastcgi_pass 127.0.0.1:9000;

    #   # With php7.0-fpm:
                fastcgi_pass unix:/run/php/php7.0-fpm.sock;
                fastcgi_intercept_errors on;
        }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny all;
    }
}
</code>```

3. /etc/nginx/snippets/fastcgi-php.conf

```<code># regex to split $uri to $fastcgi_script_name and $fastcgi_path
fastcgi_split_path_info ^(.+\.php)(/.+)$;

# Check that the PHP script exists before passing it
try_files $fastcgi_script_name =404;

# Bypass the fact that try_files resets $fastcgi_path_info
# see: http://trac.nginx.org/nginx/ticket/321
set $path_info $fastcgi_path_info;
fastcgi_param PATH_INFO $path_info;

fastcgi_index index.php;
include fastcgi.conf;
</code>```

答:
You appear to have a missing / in your try_files statement. It should be:

```<code>location / {
    try_files $uri $uri/ /index.php?$args;
}
</code>```

The second term ($uri/) should cause the URI /wp-admin to be redirected to /wp-admin/ and then invoke the file /wp-admin/index.php.

See this document for more.

Body:
On my nginx server when i visit example.com/wp-admin or example.com/login i always see the home page of my site, but when i visit example.com/wp-login.php everything works (and login screen is showed).

Is there some config to do in nginx to make these urls (/wp-admin or wp-login) work again?

Note: Other posts permalinks like example.com/hello-world is working.

My configs files are:

1. /etc/nginx/nginx.conf

user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

2. /etc/nginx/sites-available/worpdress.conf

##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# http://wiki.nginx.org/Pitfalls
# http://wiki.nginx.org/QuickStart
# http://wiki.nginx.org/Configuration
#
# Generally, you will want to move this file somewhere, and start with a clean
# file but keep this around for reference. Or just disable in sites-enabled.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    #
    # Read up on ssl_ciphers to ensure a secure configuration.
    # See: https://bugs.debian.org/765782
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;

    root /var/www/example.com/html;

    # Add index.php to the list if you are using PHP
    index index.php index.html index.htm index.nginx-debian.html;

    #server_name 127.0.0.1;
        server_name example.com www.example.com;

        location /favicon.ico {
                log_not_found off;
                access_log off;
        }

        location /robots.tx {
                allow all;
                log_not_found off;
                access_log off;
        }

        location ~* /(?:uploads|files)/.*\.php$ {
                 deny all;
        }

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        #try_files $uri $uri/ =404;
                try_files $uri $uri /index.php?$args;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;

    #   # With php7.0-cgi alone:
    #   fastcgi_pass 127.0.0.1:9000;

    #   # With php7.0-fpm:
                fastcgi_pass unix:/run/php/php7.0-fpm.sock;
                fastcgi_intercept_errors on;
        }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny all;
    }
}

3. /etc/nginx/snippets/fastcgi-php.conf

# regex to split $uri to $fastcgi_script_name and $fastcgi_path
fastcgi_split_path_info ^(.+\.php)(/.+)$;

# Check that the PHP script exists before passing it
try_files $fastcgi_script_name =404;

# Bypass the fact that try_files resets $fastcgi_path_info
# see: http://trac.nginx.org/nginx/ticket/321
set $path_info $fastcgi_path_info;
fastcgi_param PATH_INFO $path_info;

fastcgi_index index.php;
include fastcgi.conf;

Body:
You appear to have a missing / in your try_files statement. It should be:

location / {
    try_files $uri $uri/ /index.php?$args;
}

The second term ($uri/) should cause the URI /wp-admin to be redirected to /wp-admin/ and then invoke the file /wp-admin/index.php.

See this document for more.


问:
ArrayList issues: One Value Resetting all values
I have an application that contains an ArrayList of ArrayLists (ArrayList<ArrayList<Element>>). Basically, each element is an item that a user can interact with. Every time an element is interacted with, that element is updated and then the whole container object is resaved to the file system. One type of element (extends Element) is the EBoolean which can contain an element title, true or false value, and several other general parameters. When the updateBoolean method is called, a tab, ID, and boolean value are passed into it. The method scans for the correct element (matching IDs) and updates its value. However, I'm getting some weird behavior, modifying one element modifies every element in the entire array.

Here's the code w/ output:

```<code>    public void updateBoolean(int index, int ID, boolean b) {
    // Data that is gonna be saved
    System.out.println("Statistics: Index: "+index+" Array # "+elements.size()+" Elements in array #: "+elements.get(index).size());
    for (int i = 1; i < elements.size(); i++) {
        System.out.println("TAB " + i + " Title: " + elements.get(i).get(0).getTitle() + "Boolean value: " + ((EBoolean) elements.get(i).get(0)).getValue());
    }

    for (int j = 0; j < elements.get(index).size(); j++) {
        if (elements.get(index).get(j).getID() == ID) {
            EBoolean ent = (EBoolean) elements.get(index).get(0);
            ent.setValue(b);
            ent.setModified(true);
            elements.get(index).set(j, ent);
            System.out.println("Updated booleans, here's what we have now: ");
            for (int i = 1; i < elements.size(); i++) {
                System.out.println("TAB " + i + " Title: " + elements.get(i).get(0).getTitle() + "Boolean value: " + ((EBoolean) elements.get(i).get(0)).getValue());

            }
            return;
        }
    }

}
</code>```

Output:

```<code>04-02 16:01:05.441 15442-15442/? I/System.out: Statistics: Index: 4 Array #         13 Elements in array #: 4
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 1 Title: BooleanBoolean    value: true
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 2 Title: BooleanBoolean value: false
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 3 Title: BooleanBoolean value: false
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 4 Title: BooleanBoolean value: false
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 5 Title: BooleanBoolean value: false
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 6 Title: BooleanBoolean value: false
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 7 Title: BooleanBoolean value: false
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 8 Title: BooleanBoolean value: false
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 9 Title: BooleanBoolean value: false
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 10 Title: BooleanBoolean value: false
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 11 Title: BooleanBoolean value: false
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 12 Title: BooleanBoolean value: false
04-02 16:01:05.441 15442-15442/? I/System.out: Updated booleans, here's what we have now:
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 1 Title: BooleanBoolean value: true
 04-02 16:01:05.441 15442-15442/? I/System.out: TAB 2 Title: BooleanBoolean value: true
 04-02 16:01:05.441 15442-15442/? I/System.out: TAB 3 Title: BooleanBoolean value: true
 04-02 16:01:05.441 15442-15442/? I/System.out: TAB 4 Title: BooleanBoolean value: true
 04-02 16:01:05.441 15442-15442/? I/System.out: TAB 5 Title: BooleanBoolean value: true
 04-02 16:01:05.441 15442-15442/? I/System.out: TAB 6 Title: BooleanBoolean value: true
 04-02 16:01:05.441 15442-15442/? I/System.out: TAB 7 Title: BooleanBoolean value: true
 04-02 16:01:05.441 15442-15442/? I/System.out: TAB 8 Title: BooleanBoolean value: true
 04-02 16:01:05.441 15442-15442/? I/System.out: TAB 9 Title: BooleanBoolean value: true
 04-02 16:01:05.441 15442-15442/? I/System.out: TAB 10 Title: BooleanBoolean value: true
 04-02 16:01:05.441 15442-15442/? I/System.out: TAB 11 Title: BooleanBoolean value: true
 04-02 16:01:05.441 15442-15442/? I/System.out: TAB 12 Title: BooleanBoolean value: true
</code>```

答: New instances were not being created when added to the array. Make sure every object within the ArrayList<ArrayList<Element>> is its own instance.

Body:
I have an application that contains an ArrayList of ArrayLists (ArrayList<ArrayList<Element>>). Basically, each element is an item that a user can interact with. Every time an element is interacted with, that element is updated and then the whole container object is resaved to the file system. One type of element (extends Element) is the EBoolean which can contain an element title, true or false value, and several other general parameters. When the updateBoolean method is called, a tab, ID, and boolean value are passed into it. The method scans for the correct element (matching IDs) and updates its value. However, I'm getting some weird behavior, modifying one element modifies every element in the entire array.

Here's the code w/ output:

    public void updateBoolean(int index, int ID, boolean b) {
    // Data that is gonna be saved
    System.out.println("Statistics: Index: "+index+" Array # "+elements.size()+" Elements in array #: "+elements.get(index).size());
    for (int i = 1; i < elements.size(); i++) {
        System.out.println("TAB " + i + " Title: " + elements.get(i).get(0).getTitle() + "Boolean value: " + ((EBoolean) elements.get(i).get(0)).getValue());
    }

    for (int j = 0; j < elements.get(index).size(); j++) {
        if (elements.get(index).get(j).getID() == ID) {
            EBoolean ent = (EBoolean) elements.get(index).get(0);
            ent.setValue(b);
            ent.setModified(true);
            elements.get(index).set(j, ent);
            System.out.println("Updated booleans, here's what we have now: ");
            for (int i = 1; i < elements.size(); i++) {
                System.out.println("TAB " + i + " Title: " + elements.get(i).get(0).getTitle() + "Boolean value: " + ((EBoolean) elements.get(i).get(0)).getValue());

            }
            return;
        }
    }

}

Output:

04-02 16:01:05.441 15442-15442/? I/System.out: Statistics: Index: 4 Array #         13 Elements in array #: 4
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 1 Title: BooleanBoolean    value: true
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 2 Title: BooleanBoolean value: false
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 3 Title: BooleanBoolean value: false
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 4 Title: BooleanBoolean value: false
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 5 Title: BooleanBoolean value: false
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 6 Title: BooleanBoolean value: false
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 7 Title: BooleanBoolean value: false
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 8 Title: BooleanBoolean value: false
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 9 Title: BooleanBoolean value: false
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 10 Title: BooleanBoolean value: false
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 11 Title: BooleanBoolean value: false
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 12 Title: BooleanBoolean value: false
04-02 16:01:05.441 15442-15442/? I/System.out: Updated booleans, here's what we have now:
04-02 16:01:05.441 15442-15442/? I/System.out: TAB 1 Title: BooleanBoolean value: true
 04-02 16:01:05.441 15442-15442/? I/System.out: TAB 2 Title: BooleanBoolean value: true
 04-02 16:01:05.441 15442-15442/? I/System.out: TAB 3 Title: BooleanBoolean value: true
 04-02 16:01:05.441 15442-15442/? I/System.out: TAB 4 Title: BooleanBoolean value: true
 04-02 16:01:05.441 15442-15442/? I/System.out: TAB 5 Title: BooleanBoolean value: true
 04-02 16:01:05.441 15442-15442/? I/System.out: TAB 6 Title: BooleanBoolean value: true
 04-02 16:01:05.441 15442-15442/? I/System.out: TAB 7 Title: BooleanBoolean value: true
 04-02 16:01:05.441 15442-15442/? I/System.out: TAB 8 Title: BooleanBoolean value: true
 04-02 16:01:05.441 15442-15442/? I/System.out: TAB 9 Title: BooleanBoolean value: true
 04-02 16:01:05.441 15442-15442/? I/System.out: TAB 10 Title: BooleanBoolean value: true
 04-02 16:01:05.441 15442-15442/? I/System.out: TAB 11 Title: BooleanBoolean value: true
 04-02 16:01:05.441 15442-15442/? I/System.out: TAB 12 Title: BooleanBoolean value: true


问:
What matcher format to use with Capybara/Minitest?
I'm trying out Capybara with Minitest as it's included in Rails 5.1. But being a newbie I'm a bit confused with how I should write the matchers/assertions.

I've found all of the following that seem to do the same thing (and all do work):

```<code>assert page.has_content?
has_content?
assert_content
</code>```

Is there any difference between these or any "correct" way?

答:
has_content?  is just a boolean method that returns true or false, it is not an assertion so that one's out.

assert page.has_content? is an assertion on a boolean method, so it will assert an error, but the error message will just be that it expected true and got false

assert_content will assert an error if the content is missing and give you detailed error messages about what failed, so that should be the one to use.

Basically prefer the asssertions defined in https://github.com/teamcapybara/capybara/blob/master/lib/capybara/minitest.rb when using with Minitest

Body:
I'm trying out Capybara with Minitest as it's included in Rails 5.1. But being a newbie I'm a bit confused with how I should write the matchers/assertions.

I've found all of the following that seem to do the same thing (and all do work):

assert page.has_content?
has_content?
assert_content

Is there any difference between these or any "correct" way?


问:
How to define structured data types in Grammar-Kit?
I want to define a Domain Specific Language (DSL) that is structures / cascaded like this

```<code>ROOT
  NAME "my dsl"
  TODO
    DESC "foo"
  END
  TODO
    DESC "bar"
  END
END
</code>```

For my understanding it needs the following rules:

ROOT and TODO objects has to start with their keyword and end with an END.

ROOT must have a NAME attribute.

TODO must have a DESC attribute

TODO is 0..n times in ROOT

How can I express such ruleset in a BNF?

答:
Based on the Custom Language Support Tutorial (Simple Language), the following BNF snippet works for me.</p>

```<code>{
  tokens=[
    space='regexp:[\s\n]+'
    string="regexp:'.*'"
  ]
}

simpleFile ::= 'ROOT' space nameAttr space (todoObj space)+ 'END'
nameAttr ::= 'NAME' space string

todoObj ::= 'TODO' space descAttr space 'END'
descAttr ::= 'DESC' space string
</code>```

Body:
I want to define a Domain Specific Language (DSL) that is structures / cascaded like this

ROOT
  NAME "my dsl"
  TODO
    DESC "foo"
  END
  TODO
    DESC "bar"
  END
END

For my understanding it needs the following rules:

ROOT and TODO objects has to start with their keyword and end with an END.

ROOT must have a NAME attribute.

TODO must have a DESC attribute

TODO is 0..n times in ROOT

How can I express such ruleset in a BNF?

Body:
Based on the Custom Language Support Tutorial (Simple Language), the following BNF snippet works for me.

{
  tokens=[
    space='regexp:[\s\n]+'
    string="regexp:'.*'"
  ]
}

simpleFile ::= 'ROOT' space nameAttr space (todoObj space)+ 'END'
nameAttr ::= 'NAME' space string

todoObj ::= 'TODO' space descAttr space 'END'
descAttr ::= 'DESC' space string