问:
Symfony 4.0 doesn't work
To the point:

- I created new project on symfony 4.0: composer create-project symfony/skeleton sf4

- Welcome page is working

- I wanted to create my first page with https://symfony.com/doc/current/page_creation.html
and I did exactly what they say: create controller and route

- Welcome page changed status to: No route found for "GET /"  <-Solved

- new page path can't find file - Error 404

What am I doing wrong? That is silly

~src/Controller/SecurityController.php

```<code><?php
namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;

class SecurityController {
    public function logowanie() {
        return new Response(
            '<html><body>Logowanie</body></html>'
        );
    }
}
</code>```

~config/routes.yaml

```<code>index:
    path: /
    controller: App\Controller\MainController::index

logowanie:
    path: /logowanie
    controller: App\Controller\SecurityController::logowanie
</code>```

EDIT:

Home page works - thanks @Cerad

答:
There's no real route nor controller with welcome template on Symfony 4 apps, it's just a trick to improve the user's first experience.

The welcome response work only for root path / and upon added a route or installed a bundle that adds one (e.g. TwigBundle) this response disappears, as well as if debug mode has been deactivated.

Even, the status code of this response still is 404 (NOT FOUND).

Title: Symfony 4.0 doesn't work

Body:
To the point:

- I created new project on symfony 4.0: composer create-project symfony/skeleton sf4

- Welcome page is working

- I wanted to create my first page with https://symfony.com/doc/current/page_creation.html
and I did exactly what they say: create controller and route

- Welcome page changed status to: No route found for "GET /"  <-Solved

- new page path can't find file - Error 404

What am I doing wrong? That is silly

~src/Controller/SecurityController.php

<?php
namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;

class SecurityController {
    public function logowanie() {
        return new Response(
            'Logowanie'
        );
    }
}

~config/routes.yaml

index:
    path: /
    controller: App\Controller\MainController::index

logowanie:
    path: /logowanie
    controller: App\Controller\SecurityController::logowanie

EDIT:

Home page works - thanks @Cerad


来源: stackexchange

问:
BigQuery Data Location Setting
Is there a way to determine "BigQuery Data Location Setting", similar to "Cloud Storage Data Location Setting" or “Datastore Data Location Setting”?

Apparently there are some legal & tax issues for companies operating outside of the US when using services hosted in the US. Our legal guys have asked me to configure the BigQuery location to be in EU. But i couldn't find where to configure this.

Thanks

答:
Another issue arises when you want to copy datasets from one region to the other which is not currently possibly (at least directly). Here is how you can check the location of your dataset. Open up a Google Cloud Shell and enter this command:

bq show --format=prettyjson {PROJECT_ID}:{DATASET_NAME} | grep location

However, note that you cannot edit the location. You will need to backup/export all your tables, delete the dataset, and recreate the dataset with the desired location.

ContentLicense: CC BY-SA 3.0

Title: BigQuery Data Location Setting


问:
Apache Giraph on Cloudera VM - POM for org.apache.hadoop:hadoop-core:jar:2.6.0 missing, no dependency info
I am new to Hadoop/Giraph and Java. As part of a task, I downloaded Cloudera Quickstart VM and Giraph on top of it. I am using this book named "Practical Graph Analytics with Apache Giraph; Authors: Shaposhnik, Roman, Martella, Claudio, Logothetis, Dionysios" from which I tried to run the first example on Page 111 (Twitter Followership Graph).

Please find the below error while trying to run the changed pom.xml file with the hadoop version on the cluster 2.6.0-mr1-cdh5.12.0

```<code>`[cloudera@quickstart first]$ mvn clean install
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building book-examples 1.0.0
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.4.1:clean (default-clean) @ book-examples ---
[INFO] Deleting /home/cloudera/workspace/first/target
[INFO]
[INFO] --- maven-resources-plugin:2.5:resources (default-resources) @ book-examples ---
[debug] execute contextualize
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ book-examples ---
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 1 source file to /home/cloudera/workspace/first/target/classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[5,27] error: package org.apache.hadoop.io does not exist
[ERROR] /home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[6,27] error: package org.apache.hadoop.io does not exist
[ERROR] /home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[7,29] error: cannot find symbol
[ERROR]  package org.apache.hadoop.util
/home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[14,17] error: cannot find symbol
[ERROR]  class IntWritable
/home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[14,30] error: cannot find symbol
[ERROR]  class IntWritable
/home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[15,0] error: cannot find symbol
[ERROR]  class NullWritable
/home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[15,14] error: cannot find symbol
[ERROR]  class NullWritable
/home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[17,28] error: cannot find symbol
[ERROR]  class GiraphHelloWorld
/home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[18,3] error: cannot find symbol
[ERROR]  class GiraphHelloWorld
/home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[18,16] error: cannot find symbol
[ERROR]  class GiraphHelloWorld
/home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[19,12] error: cannot find symbol
[ERROR]  class GiraphHelloWorld
/home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[24,12] error: cannot find symbol
[ERROR]  class GiraphHelloWorld
/home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[24,25] error: cannot find symbol
[ERROR]  class GiraphHelloWorld
/home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[34,14] error: cannot find symbol
[INFO] 14 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.495s
[INFO] Finished at: Fri Dec 08 14:57:01 PST 2017
[INFO] Final Memory: 18M/57M
</code>```

`

I added the Cloudera Repository as per a fellow Stack overflow response. Please find the updated pom xml for which the above error applies:

```<code>`<?xml version="1.0" encoding="UTF-8"?>
<project>
<modelVersion>4.0.0</modelVersion>

<groupId>giraph</groupId>
<artifactId>book-examples</artifactId>
<version>1.0.0</version>

<dependencies>
<dependency>
<groupId>org.apache.giraph</groupId>
<artifactId>giraph-core</artifactId>
<version>1.1.0</version>
</dependency>

<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-core</artifactId>
<version>2.6.0-mr1-cdh5.12.0</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.4</version>
                <executions>
                    <execution>
                        <id>create-jar-bundle</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <descriptorRefs>
                                <descriptorRef>jar-with-dependencies</descriptorRef>
                            </descriptorRefs>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
</plugins>
</build>

<repositories>
        <repository>
            <id>cloudera</id>
            <url>https://repository.cloudera.com/artifactory/cloudera-repos</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>

</project>`
</code>```

The version in book for hadoop is 1.2.1. There is an issue with the book dependencies between two versions.

It would be great if anyone helps me understand how to handle this error.

Thanks in advance.

答:
The pom.xml in your book's copy is outdated. Use this one instead. Source: book examples repository on Github.

Edit:

You want to use a recent version of hadoop-core, but the most recent one Maven Central Repository (the default respository) offers is the 1.2.1. You will need to use the Cloudera Repository to get the most recent version of the library. To do that, simply add the repository to your pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>giraph</groupId>
    <artifactId>book-examples</artifactId>
    <version>1.0.0</version>

    <dependencies>
        <dependency>
            <groupId>org.apache.giraph</groupId>
            <artifactId>giraph-core</artifactId>
            <version>1.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-core</artifactId>
            <version>2.6.0-mr1-cdh5.12.0</version>
        </dependency>
    </dependencies>

    <build>
    </build>

    <repositories>
        <repository>
            <id>cloudera</id>
            <url>https://repository.cloudera.com/artifactory/cloudera-repos</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>
```

<p>You should now see that Maven tries to find the jars at Cloudera first, falling back to the Central:</p>

```$ mvn clean install
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building book-examples 1.0.0
[INFO] ------------------------------------------------------------------------
...
Downloading: https://repository.cloudera.com/artifactory/cloudera-repos/org/apache/hadoop/hadoop-core/2.6.0-mr1-cdh5.12.0/hadoop-core-2.6.0-mr1-cdh5.12.0.pom
Downloaded: https://repository.cloudera.com/artifactory/cloudera-repos/org/apache/hadoop/hadoop-core/2.6.0-mr1-cdh5.12.0/hadoop-core-2.6.0-mr1-cdh5.12.0.pom (6.4 kB at 2.9 kB/s)
...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.661 s
[INFO] Finished at: 2017-12-08T22:56:04+01:00
[INFO] Final Memory: 15M/224M
[INFO] ------------------------------------------------------------------------
```

<h3>Edit 2:</h3>

<p>Ok, I finally got it. Since version 2, Hadoop changed its packaging so instead of declaring a dependency on <code>hadoop-core</code>, you should use the <code>hadoop-client</code> which is a metapackage that aggregates all the necessary dependencies for you. Remove the <code>hadoop-core</code> dependency from your <code>pom.xml</code> and add instead:</p>

```<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-client</artifactId>
    <version>2.9.0</version>
</dependency>
```

Body:
I am new to Hadoop/Giraph and Java. As part of a task, I downloaded Cloudera Quickstart VM and Giraph on top of it. I am using this book named "Practical Graph Analytics with Apache Giraph; Authors: Shaposhnik, Roman, Martella, Claudio, Logothetis, Dionysios" from which I tried to run the first example on Page 111 (Twitter Followership Graph).

Please find the below error while trying to run the changed pom.xml file with the hadoop version on the cluster 2.6.0-mr1-cdh5.12.0

`[cloudera@quickstart first]$ mvn clean install
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building book-examples 1.0.0
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.4.1:clean (default-clean) @ book-examples ---
[INFO] Deleting /home/cloudera/workspace/first/target
[INFO]
[INFO] --- maven-resources-plugin:2.5:resources (default-resources) @ book-examples ---
[debug] execute contextualize
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ book-examples ---
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 1 source file to /home/cloudera/workspace/first/target/classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[5,27] error: package org.apache.hadoop.io does not exist
[ERROR] /home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[6,27] error: package org.apache.hadoop.io does not exist
[ERROR] /home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[7,29] error: cannot find symbol
[ERROR]  package org.apache.hadoop.util
/home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[14,17] error: cannot find symbol
[ERROR]  class IntWritable
/home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[14,30] error: cannot find symbol
[ERROR]  class IntWritable
/home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[15,0] error: cannot find symbol
[ERROR]  class NullWritable
/home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[15,14] error: cannot find symbol
[ERROR]  class NullWritable
/home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[17,28] error: cannot find symbol
[ERROR]  class GiraphHelloWorld
/home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[18,3] error: cannot find symbol
[ERROR]  class GiraphHelloWorld
/home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[18,16] error: cannot find symbol
[ERROR]  class GiraphHelloWorld
/home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[19,12] error: cannot find symbol
[ERROR]  class GiraphHelloWorld
/home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[24,12] error: cannot find symbol
[ERROR]  class GiraphHelloWorld
/home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[24,25] error: cannot find symbol
[ERROR]  class GiraphHelloWorld
/home/cloudera/workspace/first/src/main/java/GiraphHelloWorld.java:[34,14] error: cannot find symbol
[INFO] 14 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.495s
[INFO] Finished at: Fri Dec 08 14:57:01 PST 2017
[INFO] Final Memory: 18M/57M

`

I added the Cloudera Repository as per a fellow Stack overflow response. Please find the updated pom xml for which the above error applies:

`<?xml version="1.0" encoding="UTF-8"?>
<project>
<modelVersion>4.0.0</modelVersion>

<groupId>giraph</groupId>
<artifactId>book-examples</artifactId>
<version>1.0.0</version>

<dependencies>
<dependency>
<groupId>org.apache.giraph</groupId>
<artifactId>giraph-core</artifactId>
<version>1.1.0</version>
</dependency>

<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-core</artifactId>
<version>2.6.0-mr1-cdh5.12.0</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.4</version>
                <executions>
                    <execution>
                        <id>create-jar-bundle</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <descriptorRefs>
                                <descriptorRef>jar-with-dependencies</descriptorRef>
                            </descriptorRefs>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
</plugins>
</build>

<repositories>
        <repository>
            <id>cloudera</id>
            <url>https://repository.cloudera.com/artifactory/cloudera-repos</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>

</project>`

The version in book for hadoop is 1.2.1. There is an issue with the book dependencies between two versions.

It would be great if anyone helps me understand how to handle this error.

Thanks in advance.

Body:
The pom.xml in your book's copy is outdated. Use this one instead. Source: book examples repository on Github.

Edit:

You want to use a recent version of hadoop-core, but the most recent one Maven Central Repository (the default respository) offers is the 1.2.1. You will need to use the Cloudera Repository to get the most recent version of the library. To do that, simply add the repository to your pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>giraph</groupId>
    <artifactId>book-examples</artifactId>
    <version>1.0.0</version>

    <dependencies>
        <dependency>
            <groupId>org.apache.giraph</groupId>
            <artifactId>giraph-core</artifactId>
            <version>1.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-core</artifactId>
            <version>2.6.0-mr1-cdh5.12.0</version>
        </dependency>
    </dependencies>

    <build>
    </build>

    <repositories>
        <repository>
            <id>cloudera</id>
            <url>https://repository.cloudera.com/artifactory/cloudera-repos</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>

You should now see that Maven tries to find the jars at Cloudera first, falling back to the Central:

$ mvn clean install
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building book-examples 1.0.0
[INFO] ------------------------------------------------------------------------
...
Downloading: https://repository.cloudera.com/artifactory/cloudera-repos/org/apache/hadoop/hadoop-core/2.6.0-mr1-cdh5.12.0/hadoop-core-2.6.0-mr1-cdh5.12.0.pom
Downloaded: https://repository.cloudera.com/artifactory/cloudera-repos/org/apache/hadoop/hadoop-core/2.6.0-mr1-cdh5.12.0/hadoop-core-2.6.0-mr1-cdh5.12.0.pom (6.4 kB at 2.9 kB/s)
...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.661 s
[INFO] Finished at: 2017-12-08T22:56:04+01:00
[INFO] Final Memory: 15M/224M
[INFO] ------------------------------------------------------------------------

Edit 2:

Ok, I finally got it. Since version 2, Hadoop changed its packaging so instead of declaring a dependency on hadoop-core, you should use the hadoop-client which is a metapackage that aggregates all the necessary dependencies for you. Remove the hadoop-core dependency from your pom.xml and add instead:

<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-client</artifactId>
    <version>2.9.0</version>
</dependency>


问:
Using new <%: %> syntax/Razor with Mono & ASP.NET MVC`
Mono 2.8 claims to have C# 4.0/ASP.NET MVC 2 support.

However the new <%: %> syntax doesn't work.

Neither does Razor.

Is there  a way to make them work or should I just wait for Mono 3?

答:
Out of box support isn't there yet due to Razor itself not being part of the open source MVC assembly, but I have Razor working on Mono 2.8.1 by setting up precompilation and a custom view engine / base class that does not call BuildManager.

http://tqcblog.com/2011/01/23/precompiled-razor-for-shared-views-and-mono/

ContentLicense: CC BY-SA 2.5


问:
Weight random number towards range
Let's say I'm getting  random number in the range using:

```<code>random.randrange(100)
</code>```

Let's say that if it gives a number less than or equal to 25, you win and if it gives a number greater than 25, I win. I would then have a 75% chance to win.

How can I weight the chances of the number being greater than 25 by some percentage, say 1%.

So basically I'm trying to tilt the odds of me winning by another 1%, without changing just saying, "you win at 24 or less."

Let me know if this is unclear.

答:
It seems you want "unfair" dice, so to speak.

One way to get this, if you know the desired odds of winning, is to first decide whether you win or not. If you win, then choose a number among the winning numbers. If you lose, choose a number among the losing numbers.

For example:

```<code>import random

def die_roll():
    if random.random() < 0.26:
        return random.randrange(25)  # 0 to 24
    return random.randrange(25, 100)  # 25 to 99
</code>```

Title: Weight random number towards range

Body:
Let's say I'm getting  random number in the range using:

random.randrange(100)

Let's say that if it gives a number less than or equal to 25, you win and if it gives a number greater than 25, I win. I would then have a 75% chance to win.

How can I weight the chances of the number being greater than 25 by some percentage, say 1%.

So basically I'm trying to tilt the odds of me winning by another 1%, without changing just saying, "you win at 24 or less."

Let me know if this is unclear.

Body:
It seems you want "unfair" dice, so to speak.

One way to get this, if you know the desired odds of winning, is to first decide whether you win or not. If you win, then choose a number among the winning numbers. If you lose, choose a number among the losing numbers.

For example:

import random

def die_roll():
    if random.random() < 0.26:
        return random.randrange(25)  # 0 to 24
    return random.randrange(25, 100)  # 25 to 99


问:
hyperledger fabric chaincode dev mode connection error
I was following this tutorial of building a simple chaincode in dev mode here.
I'm stuck here
First I cleared everything with docker rm -f $(docker ps -aq).
When I enter docker-compose -f docker-compose-simple.yaml up it ends with this Error: Error getting broadcast client: Error connecting to orderer:7050 due to context deadline exceeded
cli          | Usage:
cli          |   peer channel create [flags]
cli          |
orderer      | 2017-12-05 20:44:53.681 UTC [orderer/common/deliver] Handle -> WARN 0d1 Error reading from stream: rpc error: code = Canceled desc = context canceled
orderer      | 2017-12-05 20:44:53.681 UTC [orderer/main] func1 -> DEBU 0d2 Closing Deliver stream
cli exited with code 1

What is causing problem? Is it dns problem that it can't find orderer?

答: Alright, I finally figured that out, the problem is in network, so I had in my virtual machine parameters set NAT for network, and nothing worked. I've set it to bridge mode and everything worked fine. </p>


问:
JavaScript Object properties do not get subtracted
I have been trying to create JavaScript objects which contain different attributes for characters in-game that are affected by an event happening in the game's current turn. When I access the current character in turn from an array of characters and apply the changes to his attributes according to the event's effect I just can't get the attributes to subtract. Even if the properties are negative they keep increasing instead of decreasing the character's attributes. If anyone can help me understand why this is happening I would be really grateful!

This is how the character object looks like:

```<code>let russian = {
    happiness: 7,
    vitality: 7,
    satiation: 7,
    log: [],
    portrait: 'russian'
};
</code>```

And this is the event object:

```<code>let playerInTurn = currentPlayer;
let event = {
    updateHappiness: -Math.abs(1),
    updateVitality: Math.abs(2),
    updateSatiation: -Math.abs(1),
    name: 'Cardio marathon',
    description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
    updateAttributes: function() {
        if (this.updateHappiness > 0) {
            charactersArray[currentPlayer].happiness += this.updateHappiness;
        } else {
            charactersArray[currentPlayer].happiness -= this.updateHappiness;
        }
        if (this.updateVitality > 0) {
            charactersArray[currentPlayer].vitality += this.updateVitality;
        } else {
            charactersArray[currentPlayer].vitality -= this.updateVitality;
        }
        if (this.updateSatiation > 0) {
            charactersArray[currentPlayer].satiation += this.updateSatiation;
        } else {
            charactersArray[currentPlayer].satiation -= this.updateSatiation;
        }
    }
}
</code>```

答: I did not notice I was subtracting negative numbers so I was instructed to get rid of the checks and just leave it at adding the attributes from the event to the character and now it works as intended. Thank you Nina Scholz, Mark_M and Slai</p>

Body:
I have been trying to create JavaScript objects which contain different attributes for characters in-game that are affected by an event happening in the game's current turn. When I access the current character in turn from an array of characters and apply the changes to his attributes according to the event's effect I just can't get the attributes to subtract. Even if the properties are negative they keep increasing instead of decreasing the character's attributes. If anyone can help me understand why this is happening I would be really grateful!

This is how the character object looks like:

let russian = {
    happiness: 7,
    vitality: 7,
    satiation: 7,
    log: [],
    portrait: 'russian'
};

And this is the event object:

let playerInTurn = currentPlayer;
let event = {
    updateHappiness: -Math.abs(1),
    updateVitality: Math.abs(2),
    updateSatiation: -Math.abs(1),
    name: 'Cardio marathon',
    description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
    updateAttributes: function() {
        if (this.updateHappiness > 0) {
            charactersArray[currentPlayer].happiness += this.updateHappiness;
        } else {
            charactersArray[currentPlayer].happiness -= this.updateHappiness;
        }
        if (this.updateVitality > 0) {
            charactersArray[currentPlayer].vitality += this.updateVitality;
        } else {
            charactersArray[currentPlayer].vitality -= this.updateVitality;
        }
        if (this.updateSatiation > 0) {
            charactersArray[currentPlayer].satiation += this.updateSatiation;
        } else {
            charactersArray[currentPlayer].satiation -= this.updateSatiation;
        }
    }
}


问:
NTP client in infinite loop (Not working )
I have designed a client from the reference given here.

I modified the code (see below) to fulfill these requirements

print timestamps in milliseonds

within infinite loop for getting NTP timestamps, RTT etc.

to define a cycle time (get time every x second)

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>

#define NTP_TIMESTAMP_DELTA 2208988800ull
#define ENDIAN_SWAP32(data)                                                    \
  ((data >> 24) |               /* right shift 3 bytes */                      \
   ((data & 0x00ff0000) >> 8) | /* right shift 1 byte */                       \
   ((data & 0x0000ff00) << 8) | /* left shift 1 byte */                        \
   ((data & 0x000000ff) << 24)) /* left shift 3 bytes */

void error(char *msg) {
  perror(msg); // Print the error message to stderr.
  exit(0);     // Quit the process.
}

int main(int argc, char *argv[]) {
  int sockfd, n;    // Socket file descriptor and the n return result from
                    // writing/reading from the socket.
  int portno = 123; // NTP UDP port number
  int i, z = 0;
  struct timeval tv1, tv2;

  typedef struct {
    unsigned li : 2; // Only two bits. Leap indicator.
    unsigned vn : 3; // Only three bits. Version number of the protocol.
    unsigned
        mode : 3; // Only three bits. Mode. Client will pick mode 3 for client.

    uint8_t stratum; // Eight bits. Stratum level of the local clock.
    uint8_t poll; // Eight bits. Maximum interval between successive messages.
    uint8_t precision; // Eight bits. Precision of the local clock.

    uint32_t rootDelay; // 32 bits. Total round trip delay time.
    uint32_t
        rootDispersion; // 32 bits. Max error aloud from primary clock source.
    uint32_t refId;     // 32 bits. Reference clock identifier.

    uint32_t refTm_s; // 32 bits. Reference time-stamp seconds.
    uint32_t refTm_f; // 32 bits. Reference time-stamp fraction of a second.

    uint32_t origTm_s; // 32 bits. Originate time-stamp seconds.
    uint32_t origTm_f; // 32 bits. Originate time-stamp fraction of a second.

    uint32_t rxTm_s; // 32 bits. Received time-stamp seconds.
    uint32_t rxTm_f; // 32 bits. Received time-stamp fraction of a second.

    uint32_t txTm_s; // 32 bits and the most important field the client cares
                     // about. Transmit time-stamp seconds.
    uint32_t txTm_f; // 32 bits. Transmit time-stamp fraction of a second.

  } ntp_packet; // Total: 384 bits or 48 bytes.

  // Create and zero out the packet. All 48 bytes worth.

  ntp_packet packet = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  memset(&packet, 0, sizeof(ntp_packet));
  *((char *)&packet + 0) =
      0x1b; // Represents 27 in base 10 or 00011011 in base 2.

  uint8_t *ptr = (uint8_t *)(&packet); /* to read raw bytes */
  struct sockaddr_in serv_addr;        // Server address data structure.
  struct hostent *server;              // Server data structure.

  sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // Create a UDP socket.

  if (sockfd < 0)
    error("ERROR opening socket");

  server = gethostbyname(argv[1]); // Convert URL to IP.

  if (server == NULL)
    error("ERROR, no such host");
  // Zero out the server address structure.
  bzero((char *)&serv_addr, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  // Copy the server's IP address to the server address structure.
  bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr,
        server->h_length);
  // Convert the port number integer to network big-endian style and save it to
  // the server address structure.
  serv_addr.sin_port = htons(portno);
  // Call up the server using its IP address and port number.
  if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
    error("ERROR connecting");
  printf("\nNTP client started \n\n");

  while (1) {

    z = z + 1;
    ntp_packet packet = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    memset(&packet, 0, sizeof(ntp_packet));
    *((char *)&packet + 0) =
        0x1b; // Represents 27 in base 10 or 00011011 in base 2.
    uint8_t *ptr = (uint8_t *)(&packet); /* to read raw bytes */
    gettimeofday(&tv1, NULL);
    unsigned long long millisecondsSinceEpochStart =
        (unsigned long long)(tv1.tv_sec) * 1000 +
        (unsigned long long)(tv1.tv_usec) / 1000;
    n = write(sockfd, (char *)&packet, sizeof(ntp_packet));

    if (n < 0)
      error("ERROR writing to socket");

    n = read(sockfd, (char *)&packet, sizeof(ntp_packet));
    if (n < 0)
      error("ERROR reading from socket");
    gettimeofday(&tv2, NULL);
    unsigned long long millisecondsSinceEpochEnd =
        (unsigned long long)(tv2.tv_sec) * 1000 +
        (unsigned long long)(tv2.tv_usec) / 1000;

    packet.precision = ntohl(packet.precision); // Precision

    packet.rootDelay = ntohl(packet.rootDelay);

    packet.rxTm_s = ntohl(packet.rxTm_s); // Time-stamp seconds.
    packet.rxTm_f = ntohl(packet.rxTm_f); // Time-stamp fraction of a second.

    packet.txTm_s = ntohl(packet.txTm_s); // Time-stamp seconds.
    packet.txTm_f = ntohl(packet.txTm_f); // Time-stamp fraction of a second.

    // packet.rootDelay = ntohl(packet.rootDelay); // RTT
    // time_t rootDelay = ( time_t ) ( packet.rootDelay - NTP_TIMESTAMP_DELTA );

    printf("\n................................................................."
           "...\n");
    printf("\nIteration Number : %d\n", z);
    printf("..................................................................."
           "..\n");
    printf("NTP Telegram Contains\n");
    for (i = 0; i < sizeof(ntp_packet); i++) {
      if (i != 0 && i % 8 == 0)
        printf("\n");
      printf("0x%2x ", ptr[i]);
    }
    printf("\n\n\n");

    printf("Client Send Timestamp T1(ms): %llu\n", millisecondsSinceEpochStart);

    printf("server Recieve Timestamp T2: %llu.", packet.rxTm_s);
    printf("%llu\n", packet.rxTm_f);

    printf("server Transmit Timestamp T3: %llu.", packet.txTm_s);
    printf("%llu\n", packet.txTm_f);

    printf("Client Recieve Timestamp T4(ms): %llu\n",
           millisecondsSinceEpochEnd);

    printf("RTT (calculated by NTP): %llu\n", packet.rootDelay);

    printf("Precision (calculated by NTP): %llu\n", packet.precision);

    sleep(atoi(argv[2]));
  }
  return 0;
  close(sockfd);
}
</code>```

Makefile:

```<code>.PHONY: all clean tags

CFLAGS := -Wall -O2

all: client

client: client.c
    $(CC) $(CFLAGS) $^ -o $@
    strip -s $@

tags:
    ctags -R .

clean:
    -rm *.o client
</code>```

make and run the code using

```<code>./client 0.pool.ntp.org 1
</code>```

The problem I am facing and need your suggestions possible code changes and improvements

The code doesn't work infinitely, it stops in between and doesn't print any output after some iteration (no error message is shown)

The timestamps are not of same size although 64 bits

RTT and precision print the same value and doesn't get updated in each iteration (Sometimes both shows 0)

How to build T2 from packet.rxTm_s and packet.rxTm_f as one timestamp of 64bit.

答:
I've read the C code and agree about the "quality" of this code in terms of things to do.

For the analysis, I disagree on this point:
- I don't think the problem is a real-time problem, this can be easily check by using wireshark and filter on the NTP protocol. Despite the fact, that the program fails, the wireshark should still capture data on the ethernet interface.
- For me, the problem seems to be caused by the Kiss-o'-Death Packet (see section 7.4 of the RFC 5905).
- A wireshark capture will help to know what really happens and investigate more deeply.

Body:
I have designed a client from the reference given here.

I modified the code (see below) to fulfill these requirements

print timestamps in milliseonds

within infinite loop for getting NTP timestamps, RTT etc.

to define a cycle time (get time every x second)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>

#define NTP_TIMESTAMP_DELTA 2208988800ull
#define ENDIAN_SWAP32(data)                                                    \
  ((data >> 24) |               /* right shift 3 bytes */                      \
   ((data & 0x00ff0000) >> 8) | /* right shift 1 byte */                       \
   ((data & 0x0000ff00) << 8) | /* left shift 1 byte */                        \
   ((data & 0x000000ff) << 24)) /* left shift 3 bytes */

void error(char *msg) {
  perror(msg); // Print the error message to stderr.
  exit(0);     // Quit the process.
}

int main(int argc, char *argv[]) {
  int sockfd, n;    // Socket file descriptor and the n return result from
                    // writing/reading from the socket.
  int portno = 123; // NTP UDP port number
  int i, z = 0;
  struct timeval tv1, tv2;

  typedef struct {
    unsigned li : 2; // Only two bits. Leap indicator.
    unsigned vn : 3; // Only three bits. Version number of the protocol.
    unsigned
        mode : 3; // Only three bits. Mode. Client will pick mode 3 for client.

    uint8_t stratum; // Eight bits. Stratum level of the local clock.
    uint8_t poll; // Eight bits. Maximum interval between successive messages.
    uint8_t precision; // Eight bits. Precision of the local clock.

    uint32_t rootDelay; // 32 bits. Total round trip delay time.
    uint32_t
        rootDispersion; // 32 bits. Max error aloud from primary clock source.
    uint32_t refId;     // 32 bits. Reference clock identifier.

    uint32_t refTm_s; // 32 bits. Reference time-stamp seconds.
    uint32_t refTm_f; // 32 bits. Reference time-stamp fraction of a second.

    uint32_t origTm_s; // 32 bits. Originate time-stamp seconds.
    uint32_t origTm_f; // 32 bits. Originate time-stamp fraction of a second.

    uint32_t rxTm_s; // 32 bits. Received time-stamp seconds.
    uint32_t rxTm_f; // 32 bits. Received time-stamp fraction of a second.

    uint32_t txTm_s; // 32 bits and the most important field the client cares
                     // about. Transmit time-stamp seconds.
    uint32_t txTm_f; // 32 bits. Transmit time-stamp fraction of a second.

  } ntp_packet; // Total: 384 bits or 48 bytes.

  // Create and zero out the packet. All 48 bytes worth.

  ntp_packet packet = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  memset(&packet, 0, sizeof(ntp_packet));
  *((char *)&packet + 0) =
      0x1b; // Represents 27 in base 10 or 00011011 in base 2.

  uint8_t *ptr = (uint8_t *)(&packet); /* to read raw bytes */
  struct sockaddr_in serv_addr;        // Server address data structure.
  struct hostent *server;              // Server data structure.

  sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // Create a UDP socket.

  if (sockfd < 0)
    error("ERROR opening socket");

  server = gethostbyname(argv[1]); // Convert URL to IP.

  if (server == NULL)
    error("ERROR, no such host");
  // Zero out the server address structure.
  bzero((char *)&serv_addr, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  // Copy the server's IP address to the server address structure.
  bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr,
        server->h_length);
  // Convert the port number integer to network big-endian style and save it to
  // the server address structure.
  serv_addr.sin_port = htons(portno);
  // Call up the server using its IP address and port number.
  if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
    error("ERROR connecting");
  printf("\nNTP client started \n\n");

  while (1) {

    z = z + 1;
    ntp_packet packet = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    memset(&packet, 0, sizeof(ntp_packet));
    *((char *)&packet + 0) =
        0x1b; // Represents 27 in base 10 or 00011011 in base 2.
    uint8_t *ptr = (uint8_t *)(&packet); /* to read raw bytes */
    gettimeofday(&tv1, NULL);
    unsigned long long millisecondsSinceEpochStart =
        (unsigned long long)(tv1.tv_sec) * 1000 +
        (unsigned long long)(tv1.tv_usec) / 1000;
    n = write(sockfd, (char *)&packet, sizeof(ntp_packet));

    if (n < 0)
      error("ERROR writing to socket");

    n = read(sockfd, (char *)&packet, sizeof(ntp_packet));
    if (n < 0)
      error("ERROR reading from socket");
    gettimeofday(&tv2, NULL);
    unsigned long long millisecondsSinceEpochEnd =
        (unsigned long long)(tv2.tv_sec) * 1000 +
        (unsigned long long)(tv2.tv_usec) / 1000;

    packet.precision = ntohl(packet.precision); // Precision

    packet.rootDelay = ntohl(packet.rootDelay);

    packet.rxTm_s = ntohl(packet.rxTm_s); // Time-stamp seconds.
    packet.rxTm_f = ntohl(packet.rxTm_f); // Time-stamp fraction of a second.

    packet.txTm_s = ntohl(packet.txTm_s); // Time-stamp seconds.
    packet.txTm_f = ntohl(packet.txTm_f); // Time-stamp fraction of a second.

    // packet.rootDelay = ntohl(packet.rootDelay); // RTT
    // time_t rootDelay = ( time_t ) ( packet.rootDelay - NTP_TIMESTAMP_DELTA );

    printf("\n................................................................."
           "...\n");
    printf("\nIteration Number : %d\n", z);
    printf("..................................................................."
           "..\n");
    printf("NTP Telegram Contains\n");
    for (i = 0; i < sizeof(ntp_packet); i++) {
      if (i != 0 && i % 8 == 0)
        printf("\n");
      printf("0x%2x ", ptr[i]);
    }
    printf("\n\n\n");

    printf("Client Send Timestamp T1(ms): %llu\n", millisecondsSinceEpochStart);

    printf("server Recieve Timestamp T2: %llu.", packet.rxTm_s);
    printf("%llu\n", packet.rxTm_f);

    printf("server Transmit Timestamp T3: %llu.", packet.txTm_s);
    printf("%llu\n", packet.txTm_f);

    printf("Client Recieve Timestamp T4(ms): %llu\n",
           millisecondsSinceEpochEnd);

    printf("RTT (calculated by NTP): %llu\n", packet.rootDelay);

    printf("Precision (calculated by NTP): %llu\n", packet.precision);

    sleep(atoi(argv[2]));
  }
  return 0;
  close(sockfd);
}

Makefile:

.PHONY: all clean tags

CFLAGS := -Wall -O2

all: client

client: client.c
    $(CC) $(CFLAGS) $^ -o $@
    strip -s $@

tags:
    ctags -R .

clean:
    -rm *.o client

make and run the code using

./client 0.pool.ntp.org 1

The problem I am facing and need your suggestions possible code changes and improvements

The code doesn't work infinitely, it stops in between and doesn't print any output after some iteration (no error message is shown)

The timestamps are not of same size although 64 bits

RTT and precision print the same value and doesn't get updated in each iteration (Sometimes both shows 0)

How to build T2 from packet.rxTm_s and packet.rxTm_f as one timestamp of 64bit.


问:
cc calls standard cc even though I said "export CC=/path/to/other/compiler. How can that be?
I’m on Ubuntu (Intel processor), trying to cross-compile for a server with a Realtek CPU. I installed the cross-compile development package. I can fire up the cross-compile gcc. Now, in order to have configure and make use the new compiler, I said:

```<code>export CC=/path/to/cross-compiler
</code>```

but when I say cc in bash, it still calls the system vanilla gcc. What could I be doing wrong?

答:
cc always calls system cc, this is expected behavior.

The CC variable is instead used by Makefiles, build scripts and configure scripts to suggest that they run a different executable. It is not used to allow anything to run the cc executable and in some way be redirected.

If you want to manually invoke the cross compiler, use /path/to/cross-compiler -o foo foo.c. If you have a script or command that hard codes cc, it's broken and must be fixed.

Body:
I’m on Ubuntu (Intel processor), trying to cross-compile for a server with a Realtek CPU. I installed the cross-compile development package. I can fire up the cross-compile gcc. Now, in order to have configure and make use the new compiler, I said:

export CC=/path/to/cross-compiler

but when I say cc in bash, it still calls the system vanilla gcc. What could I be doing wrong?


问:
Use a different matplotlibrc for savefig
I am using Jupyter Notebook, with a matplotlibrc style that's consistent with its theme set using jupyterthemes.  That plotting style however does not look good if I want to export it to PNG to use it within my other documents.

How do I specify a different matplotlibrc when I do a savefig?

答:
Most matplotlib style settings are applied at the moment the object they apply to is created.

You would hence need to create two different plots, one with the usual style of your notebook and another one with the style from the style file. The latter one would be the one to save.

A decent solution would be to create a plot in a function. You can then call this function within a context, with plt.style.context(<your style>): to give the figure a different style.

```<code>import matplotlib.pyplot as plt

def plot():
    fig, ax = plt.subplots()
    ax.plot([2,3,4], label="label")
    ax.legend()

# Plot with general style of the notebook
plot()

# Plot with your chosen style for saved figures
with plt.style.context('ggplot'):
    plot()
    plt.savefig("dark.png")
    #plt.close(plt.gcf()) # if you don't want to show this figure on screen

plt.show()
</code>```

Relevant here: The matplotlib customizing guide.

Body:
Most matplotlib style settings are applied at the moment the object they apply to is created.

You would hence need to create two different plots, one with the usual style of your notebook and another one with the style from the style file. The latter one would be the one to save.

A decent solution would be to create a plot in a function. You can then call this function within a context, with plt.style.context(<your style>): to give the figure a different style.

import matplotlib.pyplot as plt

def plot():
    fig, ax = plt.subplots()
    ax.plot([2,3,4], label="label")
    ax.legend()

# Plot with general style of the notebook
plot()

# Plot with your chosen style for saved figures
with plt.style.context('ggplot'):
    plot()
    plt.savefig("dark.png")
    #plt.close(plt.gcf()) # if you don't want to show this figure on screen

plt.show()

Relevant here: The matplotlib customizing guide.


问:
R RODBC sprintf not working
I am familiar with SAS but new to R. I am trying to pull data from a Netezza datamart and have no issue to get the data by typing in the date. But when I try to use sprintf with a dynamic date, the error message shows below. Thanks for reading my post and any help from you is appreciated, thank you!

my code works when typing the date:

```<code>test<- sqlQuery(db,"
SELECT DISTINCT
B.ACCOUNT_NB,
A.CUSTOMER_NBR,
C.DATA_AS_OF_DT as MONTH_END_ENTRY_DT_LR,
C.REGION
FROM  xxxxxxx
WHERE xxxx
AND C.DATA_AS_OF_DT= '2017-11-30'
)
</code>```

Same code DON'T work when using sprintf:

```<code>dt='2017-11-30'
test<- sqlQuery(db,sprintf("
SELECT DISTINCT
B.ACCOUNT_NB,
A.CUSTOMER_NBR,
C.DATA_AS_OF_DT as MONTH_END_ENTRY_DT_LR,
C.REGION
FROM  xxxxxxx
WHERE xxxx
AND C.DATA_AS_OF_DT= %s",dt)
)
</code>```

error msg is

test
  [1] "HY000 46 ERROR:  Inconsistent datatypes 'DATE' and 'INT4'"

  [2] "[RODBC] ERROR: Could not SQLExecDirect '\n                    SELECT DISTINCT\n  ............................      AND J.DATA_AS_OF_DT= 2017-11-30\n                         \n                         \n                         '"

答:
You should enclose the SQL string into quotation marks ('%s') within the string used in sprintf:

```<code>dt='2017-11-30'
test<- sqlQuery(db,sprintf("
SELECT DISTINCT
B.ACCOUNT_NB,
A.CUSTOMER_NBR,
C.DATA_AS_OF_DT as MONTH_END_ENTRY_DT_LR,
C.REGION
FROM  xxxxxxx
WHERE xxxx
AND C.DATA_AS_OF_DT='%s'",dt)
)
</code>```

Otherwise, string '2017-11-30' is interpreted as a mathematical expression 2017-11-30 which after subtractions yields 1976.

Title: R RODBC sprintf not working

Body:
I am familiar with SAS but new to R. I am trying to pull data from a Netezza datamart and have no issue to get the data by typing in the date. But when I try to use sprintf with a dynamic date, the error message shows below. Thanks for reading my post and any help from you is appreciated, thank you!

my code works when typing the date:

test<- sqlQuery(db,"
SELECT DISTINCT
B.ACCOUNT_NB,
A.CUSTOMER_NBR,
C.DATA_AS_OF_DT as MONTH_END_ENTRY_DT_LR,
C.REGION
FROM  xxxxxxx
WHERE xxxx
AND C.DATA_AS_OF_DT= '2017-11-30'
)

Same code DON'T work when using sprintf:

dt='2017-11-30'
test<- sqlQuery(db,sprintf("
SELECT DISTINCT
B.ACCOUNT_NB,
A.CUSTOMER_NBR,
C.DATA_AS_OF_DT as MONTH_END_ENTRY_DT_LR,
C.REGION
FROM  xxxxxxx
WHERE xxxx
AND C.DATA_AS_OF_DT= %s",dt)
)

error msg is

test
  [1] "HY000 46 ERROR:  Inconsistent datatypes 'DATE' and 'INT4'"

  [2] "[RODBC] ERROR: Could not SQLExecDirect '\n                    SELECT DISTINCT\n  ............................      AND J.DATA_AS_OF_DT= 2017-11-30\n                         \n                         \n                         '"

Body:
You should enclose the SQL string into quotation marks ('%s') within the string used in sprintf:

dt='2017-11-30'
test<- sqlQuery(db,sprintf("
SELECT DISTINCT
B.ACCOUNT_NB,
A.CUSTOMER_NBR,
C.DATA_AS_OF_DT as MONTH_END_ENTRY_DT_LR,
C.REGION
FROM  xxxxxxx
WHERE xxxx
AND C.DATA_AS_OF_DT='%s'",dt)
)

Otherwise, string '2017-11-30' is interpreted as a mathematical expression 2017-11-30 which after subtractions yields 1976.


问:
Error converting json response to custom class
I'm using GlassFish Server Open Source Edition 4.1.2. And I have the following code:

Usuario.java (a custom class where i want to store json response):

```<code>package masterticket.models;

import java.io.Serializable;

public class Usuario implements Serializable{
    private static final long serialVersionUID = 1L;
    int id;
    String nombre;
    String apellidos;
    String tipo;
    String email;
    String password;
    java.sql.Timestamp created;

    public Usuario(){
    }

    public Usuario(String nombre, String apellidos, String tipo, String email, String password){
        this.nombre   = nombre;
        this.apellidos = apellidos;
        this.tipo = tipo;
        this.email = email;
        this.password = password;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public String getApellidos() {
        return apellidos;
    }

    public void setApellidos(String apellidos) {
        this.apellidos = apellidos;
    }

    public String getTipo() {
        return tipo;
    }

    public void setTipo(String tipo) {
        this.tipo = tipo;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public java.sql.Timestamp getCreated() {
        return created;
    }

    public void setCreated(java.sql.Timestamp created) {
        this.created = created;
    }

}
</code>```

A spring controller:

```<code>package es.uc3m.tiw;

import es.uc3m.tiw.domains.*;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.http.*;
import org.json.JSONObject;

@Controller
public class Usuarios_Controller {

    @Autowired
    UsuarioDAO daousu;

    @RequestMapping("/todosusuarios")
    public @ResponseBody List<Usuario> getEventos(){
        return daousu.findAll();
    }

    @RequestMapping("/usuarios/{email}")
    public @ResponseBody Usuario getEventosByIdUsuario(@PathVariable String email){
        return daousu.findByEmail(email);
    }

    @RequestMapping(value="/usuarios", method = RequestMethod.POST)
    public @ResponseBody Usuario saveuser(@RequestBody Usuario puser){
        return daousu.save(puser);
    }

}
</code>```

And a servlet where i execute the call to the spring app:

```<code>...
client = ClientBuilder.newClient();
            webResource = client.target("http://localhost:10507/usuarios/"+email+"/");
            System.out.println("http://localhost:10506/usuarios/"+email+"/ poniendo usuario");
            Usuario usu=    webResource.request().accept("application/json").get(Usuario.class);
            System.out.println(usu.getApellidos());
...
</code>```

For some reason im not able to understand im getting this error on the glassfish log and this code wont work:

```<code>java.lang.NoClassDefFoundError: Could not initialize class org.eclipse.persistence.jaxb.BeanValidationHelper
    at org.eclipse.persistence.jaxb.JAXBBeanValidator.isConstrainedObject(JAXBBeanValidator.java:257)
    at org.eclipse.persistence.jaxb.JAXBBeanValidator.shouldValidate(JAXBBeanValidator.java:208)
    at org.eclipse.persistence.jaxb.JAXBUnmarshaller.validateAndBuildJAXBElement(JAXBUnmarshaller.java:235)
    at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:339)
    at org.eclipse.persistence.jaxb.rs.MOXyJsonProvider.readFrom(MOXyJsonProvider.java:660)
    at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:256)
    at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:235)
    at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:155)
    at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1085)
    at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:852)
    at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:786)
    at org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:326)
    at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:803)
    at org.glassfish.jersey.client.JerseyInvocation.access$700(JerseyInvocation.java:92)
    at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:700)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:696)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:420)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:316)
    at masterticket.controllers.login.doPost(login.java:115)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:748)
</code>```

API is working good because i tested it using postman and all calls work as expected. In fact im able to retrieve the response into a String but when I try to do the same with the Usuario class provided above, code breaks..

This is an example of the json im trying to parse:

```<code>[{"id":1,"nombre":"admin1","apellidos":"admin1","tipo":"admin","email":"admin1@correo.es","password":"81dc9bdb52d04dc20036dbd8313ed055","created":1510500279000}]
</code>```

答: This might be a bug in Glassfish at least there seems to have been one like this in 4.1.1 and I'm not sure if it was patched by 4.1.2

Body:
I'm using GlassFish Server Open Source Edition 4.1.2. And I have the following code:

Usuario.java (a custom class where i want to store json response):

package masterticket.models;

import java.io.Serializable;

public class Usuario implements Serializable{
    private static final long serialVersionUID = 1L;
    int id;
    String nombre;
    String apellidos;
    String tipo;
    String email;
    String password;
    java.sql.Timestamp created;

    public Usuario(){
    }

    public Usuario(String nombre, String apellidos, String tipo, String email, String password){
        this.nombre   = nombre;
        this.apellidos = apellidos;
        this.tipo = tipo;
        this.email = email;
        this.password = password;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public String getApellidos() {
        return apellidos;
    }

    public void setApellidos(String apellidos) {
        this.apellidos = apellidos;
    }

    public String getTipo() {
        return tipo;
    }

    public void setTipo(String tipo) {
        this.tipo = tipo;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public java.sql.Timestamp getCreated() {
        return created;
    }

    public void setCreated(java.sql.Timestamp created) {
        this.created = created;
    }

}

A spring controller:

package es.uc3m.tiw;

import es.uc3m.tiw.domains.*;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.http.*;
import org.json.JSONObject;

@Controller
public class Usuarios_Controller {

    @Autowired
    UsuarioDAO daousu;

    @RequestMapping("/todosusuarios")
    public @ResponseBody List<Usuario> getEventos(){
        return daousu.findAll();
    }

    @RequestMapping("/usuarios/{email}")
    public @ResponseBody Usuario getEventosByIdUsuario(@PathVariable String email){
        return daousu.findByEmail(email);
    }

    @RequestMapping(value="/usuarios", method = RequestMethod.POST)
    public @ResponseBody Usuario saveuser(@RequestBody Usuario puser){
        return daousu.save(puser);
    }

}

And a servlet where i execute the call to the spring app:

...
client = ClientBuilder.newClient();
            webResource = client.target("http://localhost:10507/usuarios/"+email+"/");
            System.out.println("http://localhost:10506/usuarios/"+email+"/ poniendo usuario");
            Usuario usu=    webResource.request().accept("application/json").get(Usuario.class);
            System.out.println(usu.getApellidos());
...

For some reason im not able to understand im getting this error on the glassfish log and this code wont work:

java.lang.NoClassDefFoundError: Could not initialize class org.eclipse.persistence.jaxb.BeanValidationHelper
    at org.eclipse.persistence.jaxb.JAXBBeanValidator.isConstrainedObject(JAXBBeanValidator.java:257)
    at org.eclipse.persistence.jaxb.JAXBBeanValidator.shouldValidate(JAXBBeanValidator.java:208)
    at org.eclipse.persistence.jaxb.JAXBUnmarshaller.validateAndBuildJAXBElement(JAXBUnmarshaller.java:235)
    at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:339)
    at org.eclipse.persistence.jaxb.rs.MOXyJsonProvider.readFrom(MOXyJsonProvider.java:660)
    at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:256)
    at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:235)
    at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:155)
    at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1085)
    at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:852)
    at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:786)
    at org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:326)
    at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:803)
    at org.glassfish.jersey.client.JerseyInvocation.access$700(JerseyInvocation.java:92)
    at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:700)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:696)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:420)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:316)
    at masterticket.controllers.login.doPost(login.java:115)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:748)

API is working good because i tested it using postman and all calls work as expected. In fact im able to retrieve the response into a String but when I try to do the same with the Usuario class provided above, code breaks..

This is an example of the json im trying to parse:

[{"id":1,"nombre":"admin1","apellidos":"admin1","tipo":"admin","email":"admin1@correo.es","password":"81dc9bdb52d04dc20036dbd8313ed055","created":1510500279000}]


问:
Creating arrays dynamically using PHP
Hey folks, please lend a hand to a PHP beginner. I'm trying to put a load of dynamically created variabled into an array to re-read later, reason is a SOAP message sent is a mess and im trying to create a less complicated array:

```<code>$placea = "place a";
$placeb = "place b";

$myarray = array();

echo "```";
print_r($myarray);
echo "```";
</code>```

what i want to be able to do:

```<code>Array
(
    [0] => [Place A] => Array
        (
            [0] => [Accommodation] => Array
                (
                    [RoomId] => 001
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )
            [1] => [Accommodation] => Array
                (
                    [RoomId] => 002
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )

        )    Array
(
    [1] => [Place B] => Array
        (
            [0] => [Accommodation] => Array
                (
                    [RoomId] => 101
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )
            [1] => [Accommodation] => Array
                (
                    [RoomId] => 102
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )

        )

)
</code>```

how would i write that out in php? sorry if its bleek and/or the array structure is incorrect

答:
So you just need to use the array initializer repetitively.

If you want to initialize an array in PHP with some values, say 1 through 4, you make a call like:

```<code>$foo = array(1, 2, 3, 4);
</code>```

And if you want to make an associative array, where you store some key/value pairs, you make a call like:

```<code>$foo = array('key' => 'value', 'other key' => 'other value');
</code>```

But you can of course nest calls, and mix and match layers of associative and non associative arrays to achieve something like your example, e.g.:

```<code>$foo = array(
    'Place A' => array(
        // note use of first array on the next line is
        // to generate structure like [0] => 'Accomodation' => ...
        array('Accomodation' => array(
            'RoomId' => '001',
            'RoomAvail' => true,
            'Date' => '12.04.2011')
        )),
        array('Accomodation' => array(
            'RoomId' => '002',
            'RoomAvail' => true,
            'Date' => '12.04.2011')
        ))
    ),
    'Place B' => array(
        array('Accomodation' => array(
            'RoomId' => '101',
            'RoomAvail' => true,
            'Date' => '12.04.2011')
        )),
        array('Accomodation' => array(
            'RoomId' => '102',
            'RoomAvail' => true,
            'Date' => '12.04.2011')
        ))
    )
);
</code>```

This will very nearly produce what you're looking for, to make it replicate exactly what you have you would wrap each 'Place A' with an array and each "place" would get its own assignment to some variable $foo (I assumed this wasn't actually what you wanted and wrote something maybe slightly more intuitive).

Title: Creating arrays dynamically using PHP

Body:
Hey folks, please lend a hand to a PHP beginner. I'm trying to put a load of dynamically created variabled into an array to re-read later, reason is a SOAP message sent is a mess and im trying to create a less complicated array:

$placea = "place a";
$placeb = "place b";

$myarray = array();

echo "
";
print_r($myarray);
echo "
";

what i want to be able to do:

Array
(
    [0] => [Place A] => Array
        (
            [0] => [Accommodation] => Array
                (
                    [RoomId] => 001
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )
            [1] => [Accommodation] => Array
                (
                    [RoomId] => 002
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )

        )    Array
(
    [1] => [Place B] => Array
        (
            [0] => [Accommodation] => Array
                (
                    [RoomId] => 101
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )
            [1] => [Accommodation] => Array
                (
                    [RoomId] => 102
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )

        )

)

how would i write that out in php? sorry if its bleek and/or the array structure is incorrect

Body:
So you just need to use the array initializer repetitively.

If you want to initialize an array in PHP with some values, say 1 through 4, you make a call like:

$foo = array(1, 2, 3, 4);

And if you want to make an associative array, where you store some key/value pairs, you make a call like:

$foo = array('key' => 'value', 'other key' => 'other value');

But you can of course nest calls, and mix and match layers of associative and non associative arrays to achieve something like your example, e.g.:

$foo = array(
    'Place A' => array(
        // note use of first array on the next line is
        // to generate structure like [0] => 'Accomodation' => ...
        array('Accomodation' => array(
            'RoomId' => '001',
            'RoomAvail' => true,
            'Date' => '12.04.2011')
        )),
        array('Accomodation' => array(
            'RoomId' => '002',
            'RoomAvail' => true,
            'Date' => '12.04.2011')
        ))
    ),
    'Place B' => array(
        array('Accomodation' => array(
            'RoomId' => '101',
            'RoomAvail' => true,
            'Date' => '12.04.2011')
        )),
        array('Accomodation' => array(
            'RoomId' => '102',
            'RoomAvail' => true,
            'Date' => '12.04.2011')
        ))
    )
);

This will very nearly produce what you're looking for, to make it replicate exactly what you have you would wrap each 'Place A' with an array and each "place" would get its own assignment to some variable $foo (I assumed this wasn't actually what you wanted and wrote something maybe slightly more intuitive).


问:
Pass class's variable as argument
I am working on Android Studio, and I want to accomplish the following:

I have this class with some variables:

```<code>class test {
   private String prop1;
   private int prop2;
   private boolean prop3;
}
</code>```

I want to create a 'generic' method which can change some variable to a new value, like:

```<code>public changeVar(Variable var, Value val) {
    this.var = val;
}
</code>```

I was wondering if there is any clever way of doing that without the need to make tens of set methods for each variable.

Thank you.

答:
If you are just tired to write (or generate) getters/setter for your code and/or do not like to have that getter/setter stuff boilerplating your code then I would recommend to check some external tool like Lombok, see especially annotations @Getter&@Setter. For Android Studio.

See also Is it safe to use Project Lombok?

If you really want to make it as you suggest then the answer might be reflection. There are some posts about it in SO, like:

Java, set field value with reflection

java reflection nested object set private field

But: I am not too so sure if it is clever to do it using reflection. It could obfuscate things a lot.

Title: Pass class's variable as argument

Body:
I am working on Android Studio, and I want to accomplish the following:

I have this class with some variables:

class test {
   private String prop1;
   private int prop2;
   private boolean prop3;
}

I want to create a 'generic' method which can change some variable to a new value, like:

public changeVar(Variable var, Value val) {
    this.var = val;
}

I was wondering if there is any clever way of doing that without the need to make tens of set methods for each variable.

Thank you.


问:
Nested if statement?
I'm trying to make a button that puts text that I need in TextView on specific EditText conditions, when EditText is empty, TextView is showing right text, but when I write numbers into the EditText field and press the button - program crashes.

```<code>    public void Guess(View view) {
    EditText Spejimas = (EditText) findViewById(R.id.guess);
    Tekstas = (TextView) findViewById(R.id.textView3);

    if (Spejimas.getText().length() == 0) {
        Tekstas.setText("Oops, you forgot to type your guess!");
    } else if (Spejimas.getText().length() != 0) {
        int Guessas = Integer.parseInt(Spejimas.toString());
        if (Guessas == number) {
            Tekstas.setText("Congratulations! You got it right!");
        } else if (Guessas > number) {
            Tekstas.setText("Your number is too high, try again!");
        } else if (Guessas < number) {
            Tekstas.setText("Your number is too low, try again!");
        }
    }
}
</code>```

I want TextView to say: "Congratulations! You got it right!", when Guessas is equal to number, "Your number is too high, try again!", when Guessas is higher than number and "Your number is too low, try again!", when Guessas is lower than number.

When I'm pressing the button that triggers this block of code when EditText has number(s) in it, program crashes.

答:
That's because you don't cast the value that getText method returns. The getText returns Editable. You should add toString() method to everywhere you call getText, like this:

```<code>if (Spejimas.getText().toString().length() == 0) {
    Tekstas.setText("Oops, you forgot to type your guess!");
} else if (Spejimas.getText().toString().length() != 0) {
    int Guessas = Integer.parseInt(Spejimas.getText().toString());
    if (Guessas == number) {
        Tekstas.setText("Congratulations! You got it right!");
    } else if (Guessas > number) {
        Tekstas.setText("Your number is too high, try again!");
    } else if (Guessas < number) {
        Tekstas.setText("Your number is too low, try again!");
    }
}
</code>```

And also, you have an issue in this line:

```<code>int Guessas = Integer.parseInt(Spejimas.toString());
</code>```

You should change it to this:

```<code>int Guessas = Integer.parseInt(Spejimas.getText().toString());
</code>```

Title: Nested if statement?

Body:
I'm trying to make a button that puts text that I need in TextView on specific EditText conditions, when EditText is empty, TextView is showing right text, but when I write numbers into the EditText field and press the button - program crashes.

    public void Guess(View view) {
    EditText Spejimas = (EditText) findViewById(R.id.guess);
    Tekstas = (TextView) findViewById(R.id.textView3);

    if (Spejimas.getText().length() == 0) {
        Tekstas.setText("Oops, you forgot to type your guess!");
    } else if (Spejimas.getText().length() != 0) {
        int Guessas = Integer.parseInt(Spejimas.toString());
        if (Guessas == number) {
            Tekstas.setText("Congratulations! You got it right!");
        } else if (Guessas > number) {
            Tekstas.setText("Your number is too high, try again!");
        } else if (Guessas < number) {
            Tekstas.setText("Your number is too low, try again!");
        }
    }
}

I want TextView to say: "Congratulations! You got it right!", when Guessas is equal to number, "Your number is too high, try again!", when Guessas is higher than number and "Your number is too low, try again!", when Guessas is lower than number.

When I'm pressing the button that triggers this block of code when EditText has number(s) in it, program crashes.

Body:
That's because you don't cast the value that getText method returns. The getText returns Editable. You should add toString() method to everywhere you call getText, like this:

if (Spejimas.getText().toString().length() == 0) {
    Tekstas.setText("Oops, you forgot to type your guess!");
} else if (Spejimas.getText().toString().length() != 0) {
    int Guessas = Integer.parseInt(Spejimas.getText().toString());
    if (Guessas == number) {
        Tekstas.setText("Congratulations! You got it right!");
    } else if (Guessas > number) {
        Tekstas.setText("Your number is too high, try again!");
    } else if (Guessas < number) {
        Tekstas.setText("Your number is too low, try again!");
    }
}

And also, you have an issue in this line:

int Guessas = Integer.parseInt(Spejimas.toString());

You should change it to this:

int Guessas = Integer.parseInt(Spejimas.getText().toString());


问:
Gatsby-js client side javascript inline in blog post
I am trying to setup a Blog using Gatsby-JS. I have some posts in markdown that contain inline javascript.

As an example:

```<code><script>window.alert("hello");</script>
</code>```

I test the site using the command "Gatsby serve"

When I browse to my post via the index of the blog. The script is not executed. In the web console there are no errors.

When on the post page itself. If I do F5 or ctrl-f5 then the "hello" alert is displayed.

After uploading the site to github pages this behavior changes. I cannot get the script to execute by F5 or by navigating via the index. Only when I press ctrl+F5 the script is executed.

live test-blog can be found here (it show multiple alerts and tries to load plotly). https://dwjbosman.github.io/lstm-neural-network-for-sequence-learning/

答:
The previous answer pointed me in the right direction.

I gave all the inline scripts an attribute data-my-script. Next I added the following to layouts/index.jsx (not html.jsx as this is rendered only server side).

```<code>componentDidMount() {
    let scripts = window.jQuery.find('[data-my-script]')
    console.log(scripts);
        scripts.forEach(function forEachScript(element) {
            const script = window.jQuery(element).text();
            window.eval(script);
        });

  }

  render() {
    const { children } = this.props;
    return (
      <Navigation config={config} LocalTitle={this.getLocalTitle()}>
        <div ref={contentElement => (this.contentElement = contentElement)}>
          <Helmet>
            <meta name="description" content={config.siteDescription} />
            // for plotly inside notebooks
            //  <script src="https://cdn.plot.ly/plotly-latest.min.js" />
            <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.5/require.min.js"/>
            <script src="https://code.jquery.com/jquery-3.2.1.min.js"/>
          </Helmet>
          {children()}
        </div>
      </Navigation>
    );
  }
}
</code>```

Body:
I am trying to setup a Blog using Gatsby-JS. I have some posts in markdown that contain inline javascript.

As an example:

I test the site using the command "Gatsby serve"

When I browse to my post via the index of the blog. The script is not executed. In the web console there are no errors.

When on the post page itself. If I do F5 or ctrl-f5 then the "hello" alert is displayed.

After uploading the site to github pages this behavior changes. I cannot get the script to execute by F5 or by navigating via the index. Only when I press ctrl+F5 the script is executed.

live test-blog can be found here (it show multiple alerts and tries to load plotly). https://dwjbosman.github.io/lstm-neural-network-for-sequence-learning/

Body:
The previous answer pointed me in the right direction.

I gave all the inline scripts an attribute data-my-script. Next I added the following to layouts/index.jsx (not html.jsx as this is rendered only server side).

componentDidMount() {
    let scripts = window.jQuery.find('[data-my-script]')
    console.log(scripts);
        scripts.forEach(function forEachScript(element) {
            const script = window.jQuery(element).text();
            window.eval(script);
        });

  }

  render() {
    const { children } = this.props;
    return (
      <Navigation config={config} LocalTitle={this.getLocalTitle()}>
        <div ref={contentElement => (this.contentElement = contentElement)}>
          <Helmet>
            <meta name="description" content={config.siteDescription} />
            // for plotly inside notebooks
            //  <script src="https://cdn.plot.ly/plotly-latest.min.js" />
            <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.5/require.min.js"/>
            <script src="https://code.jquery.com/jquery-3.2.1.min.js"/>
          </Helmet>
          {children()}
        </div>
      </Navigation>
    );
  }
}


问:
How to place an element on top of other
I want to place an element on top of other without modifying the position of the second. I mean:

.container {
 display: flex;
 align-content: baseline;
 padding: 50px;
 width: 50px;
 height: 50px;
 background-color: blue;
}

.base {
  color: black;
}

.top {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="base">
    base
    <div class="top">
      should be on top
    </div>
  </div>
</div></code>```

I want the should be on top div to be placed above the base div, and the base div to still be aligned the way it does. I have tried using relative positioning and giving negative bottom values but it isn't that responsive. This is how i want them to be, except for base should keep the previous position:

    .container {
     display: flex;
     align-content: baseline;
     padding: 50px;
     width: 50px;
     height: 50px;
     background-color: blue;
    }

    .base {
      color: black;
    }

    .top {
      color: red;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="top">
    should be on top
    <div class="base">
      base
    </div>
  </div>
</div></code>```

should be ontop div have to be on top of base, and base where it was before. How can I do this?

This is what I was trying:

    .container {
     display: flex;
     align-content: baseline;
     padding: 50px;
     width: 50px;
     height: 50px;
     background-color: blue;
    }

    .base {
      color: black;
    }

    .top {
      position: relative;
      color: red;
      bottom: 4.8em;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="container">
      <div class="base">
        base
        <div class="top">
          should be on top
        </div>
      </div>
    </div></code>```

That's how I want them to be placed. But if the # of lines of should be ontop div changes then it overflow above of the base div. I think it could be done using js, but I prefer it was only with css. Is there a way to do this?

答:
If I understood you correctly this is what you want:

.container {
     display: flex;
     align-content: baseline;
     padding: 50px;
     width: 50px;
     height: 50px;
     background-color: blue;
      position: relative;
      justify-content: center;
      position: rela
    }

    .base {
      color: black;
    }

    .top {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      margin: auto;
      color: red;
      bottom: 4.8em;
      text-align: center;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
      <div class="base">
        base
        <div class="top">
          should be on top
        </div>
      </div>
    </div></code>```

I added justify-content: center and align-items: center properties to .container element so the .base element is always centred.

I added absolute positioning to .top element so it's always positioned at the top. I also added relative positioning to .container so the absolute position og .top element is based on the position of .container. That's how absolute positioning works (it's relative to first element with positioning different than static).

I added text-align: center to .top so the text is centred.

You can try to add more lines to .top element to see if this is expected behaviour.

Title: How to place an element on top of other

Body:
I want to place an element on top of other without modifying the position of the second. I mean:

.container {
 display: flex;
 align-content: baseline;
 padding: 50px;
 width: 50px;
 height: 50px;
 background-color: blue;
}

.base {
  color: black;
}

.top {
  color: red;
}

    base

      should be on top

I want the should be on top div to be placed above the base div, and the base div to still be aligned the way it does. I have tried using relative positioning and giving negative bottom values but it isn't that responsive. This is how i want them to be, except for base should keep the previous position:

    .container {
     display: flex;
     align-content: baseline;
     padding: 50px;
     width: 50px;
     height: 50px;
     background-color: blue;
    }

    .base {
      color: black;
    }

    .top {
      color: red;
    }

    should be on top

      base

should be ontop div have to be on top of base, and base where it was before. How can I do this?

This is what I was trying:

    .container {
     display: flex;
     align-content: baseline;
     padding: 50px;
     width: 50px;
     height: 50px;
     background-color: blue;
    }

    .base {
      color: black;
    }

    .top {
      position: relative;
      color: red;
      bottom: 4.8em;
    }

        base

          should be on top

That's how I want them to be placed. But if the # of lines of should be ontop div changes then it overflow above of the base div. I think it could be done using js, but I prefer it was only with css. Is there a way to do this?

Body:
If I understood you correctly this is what you want:

.container {
     display: flex;
     align-content: baseline;
     padding: 50px;
     width: 50px;
     height: 50px;
     background-color: blue;
      position: relative;
      justify-content: center;
      position: rela
    }

    .base {
      color: black;
    }

    .top {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      margin: auto;
      color: red;
      bottom: 4.8em;
      text-align: center;
    }

<div class="container">
      <div class="base">
        base
        <div class="top">
          should be on top
        </div>
      </div>
    </div>

I added justify-content: center and align-items: center properties to .container element so the .base element is always centred.

I added absolute positioning to .top element so it's always positioned at the top. I also added relative positioning to .container so the absolute position og .top element is based on the position of .container. That's how absolute positioning works (it's relative to first element with positioning different than static).

I added text-align: center to .top so the text is centred.

You can try to add more lines to .top element to see if this is expected behaviour.


问:
Does HTML5 remove the distinction between strict and transitional?
From what I have read, it appears that HTML5 removes the distinction between strict and transitional (always strict now). I have not been able to find it specifically mentioned anywhere, only implied. Is this the case?</p>

答:
From what I have gathered so far html5 has some sloppy allowances, for instance, you can tag upper or lower case. It will not necessarily flag certain fudging as xhtml 1.1 will. I suspect this can lead into problems down the line for the casual/sloppy coder.

I code in xhtml strict.  I would advise anyone learning html to learn strict coding practices - it will teach you how to code consistently and accurately, and how to problem solve succinctly, and to be better prepared as xml standards open up for more and more practical use.

I cannot stress how glad I am I started coding strict.
If you search on "is html5 strict" (the truth is out there) you will find tones of what I am saying reflected/shared in the more educated circles (imho), so I think my remarks are fairly sound.  You will also find good advice on maintaining your tried and true xhtml coding while stretching your legs with (x)html5.  (If you don't know why I added the (x) there, then you are not done searching ;^)  Try searching html5 + xml  ;^)
HTH, Cheers.


问:
Are C compilers like gcc smart enough to bit shifts in place?
Unlike assembly code, in C there is no way to bit shift a value in place. To shift the bits in variable an assignment must always be performed:

```<code>x = x << 3;
</code>```

Are compilers like gcc smart enough to realize that this is an in-place bit shift and compile it like this:

```<code>shl x, 3
</code>```

or will the compiler put the result first in a register, then move it back into x (which would require two extra unnecessary instructions).

答:
what did you see when you tried it? why not just try it?

unsigned int fun ( unsigned int x )
    {
        return (x<<3);
    }
    Disassembly of section .text:

```<code>00000000 <fun>:
   0:   e1a00180    lsl r0, r0, #3
   4:   e12fff1e    bx  lr

Disassembly of section .text:

00000000 <_fun>:
   0:   1166            mov r5, -(sp)
   2:   1185            mov sp, r5
   4:   1d40 0004       mov 4(r5), r0
   8:   0cc0            asl r0
   a:   0cc0            asl r0
   c:   0cc0            asl r0
   e:   1585            mov (sp)+, r5
  10:   0087            rts pc

Disassembly of section .text:

0000000000000000 <fun>:
   0:   531d7000    lsl w0, w0, #3
   4:   d65f03c0    ret

Disassembly of section .text:

0000000000000000 <fun>:
   0:   8d 04 fd 00 00 00 00    lea    0x0(,%rdi,8),%eax
   7:   c3                      retq

00000000 <fun>:
   0:   42 18 0c 5c     rpt #3 { rlax.w r12     ;
   4:   30 41           ret

Disassembly of section .text:

00000000 <fun>:
   0:   050e                    slli    x10,x10,0x3
   2:   8082                    ret

unsigned int x;

void fun ( void )
{
    x=x<<3;
}
Disassembly of section .text:

00000000 <fun>:
   0:   e59f200c    ldr r2, [pc, #12]   ; 14 <fun+0x14>
   4:   e5923000    ldr r3, [r2]
   8:   e1a03183    lsl r3, r3, #3
   c:   e5823000    str r3, [r2]
  10:   e12fff1e    bx  lr
  14:   00000000    andeq   r0, r0, r0
</code>```

and so on

Body:
Unlike assembly code, in C there is no way to bit shift a value in place. To shift the bits in variable an assignment must always be performed:

x = x << 3;

Are compilers like gcc smart enough to realize that this is an in-place bit shift and compile it like this:

shl x, 3

or will the compiler put the result first in a register, then move it back into x (which would require two extra unnecessary instructions).

Body:
what did you see when you tried it? why not just try it?

unsigned int fun ( unsigned int x )
    {
        return (x<<3);
    }
    Disassembly of section .text:

00000000 <fun>:
   0:   e1a00180    lsl r0, r0, #3
   4:   e12fff1e    bx  lr

Disassembly of section .text:

00000000 <_fun>:
   0:   1166            mov r5, -(sp)
   2:   1185            mov sp, r5
   4:   1d40 0004       mov 4(r5), r0
   8:   0cc0            asl r0
   a:   0cc0            asl r0
   c:   0cc0            asl r0
   e:   1585            mov (sp)+, r5
  10:   0087            rts pc

Disassembly of section .text:

0000000000000000 <fun>:
   0:   531d7000    lsl w0, w0, #3
   4:   d65f03c0    ret

Disassembly of section .text:

0000000000000000 <fun>:
   0:   8d 04 fd 00 00 00 00    lea    0x0(,%rdi,8),%eax
   7:   c3                      retq

00000000 <fun>:
   0:   42 18 0c 5c     rpt #3 { rlax.w r12     ;
   4:   30 41           ret

Disassembly of section .text:

00000000 <fun>:
   0:   050e                    slli    x10,x10,0x3
   2:   8082                    ret

unsigned int x;

void fun ( void )
{
    x=x<<3;
}
Disassembly of section .text:

00000000 <fun>:
   0:   e59f200c    ldr r2, [pc, #12]   ; 14 <fun+0x14>
   4:   e5923000    ldr r3, [r2]
   8:   e1a03183    lsl r3, r3, #3
   c:   e5823000    str r3, [r2]
  10:   e12fff1e    bx  lr
  14:   00000000    andeq   r0, r0, r0

and so on