问:
Post two statements into database
I am trying to insert two statements into my sql database. But when I click on send I see that only the first statement is posted.

Does someone know whats wrong with my code and how I can solve it?

Here is my code:

```<code>$query1 = "INSERT INTO table1(firstname, lastname) VALUES (?, ?)";
$stmt1 = $db->prepare($query1);
$stmt1->execute(array($firstname, $lastname));

$query2 = "INSERT INTO table2(firstname, lastname) VALUES (?, ?)";
$stmt2 = $db->prepare($query2);
$stmt2->execute(array($firstname, $lastname));
</code>```

Title: Post two statements into database

Body:
I am trying to insert two statements into my sql database. But when I click on send I see that only the first statement is posted.

Does someone know whats wrong with my code and how I can solve it?

Here is my code:

$query1 = "INSERT INTO table1(firstname, lastname) VALUES (?, ?)";
$stmt1 = $db->prepare($query1);
$stmt1->execute(array($firstname, $lastname));

$query2 = "INSERT INTO table2(firstname, lastname) VALUES (?, ?)";
$stmt2 = $db->prepare($query2);
$stmt2->execute(array($firstname, $lastname));

Body:
When you prepare a sql statement you can check that everything is OK before attempting to execute the sql and then, by assigning a variable to the result of the execute method, check that there was a successful query and proceed to the next statement.

Two very basic tables - identical except in name.

mysql> describe table1;
+-----------+-------------+------+-----+---------+-------+
| Field     | Type        | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| firstname | varchar(50) | YES  |     | NULL    |       |
| lastname  | varchar(50) | YES  |     | NULL    |       |
+-----------+-------------+------+-----+---------+-------+

mysql> describe table2;
+-----------+-------------+------+-----+---------+-------+
| Field     | Type        | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| firstname | varchar(50) | YES  |     | NULL    |       |
| lastname  | varchar(50) | YES  |     | NULL    |       |
+-----------+-------------+------+-----+---------+-------+

mysql> select * from table1;select * from table2;
+------------------------+-----------------------+
| firstname              | lastname              |
+------------------------+-----------------------+
| firstname59365bf480611 | lastname59365bf480613 |
+------------------------+-----------------------+
1 row in set (0.00 sec)

+------------------------+-----------------------+
| firstname              | lastname              |
+------------------------+-----------------------+
| firstname59365bf480611 | lastname59365bf480613 |
+------------------------+-----------------------+
1 row in set (0.00 sec)

$firstname=uniqid('firstname');
$lastname=uniqid('lastname');

$dbhost =   'localhost';
$dbuser =   'root';
$dbpwd  =   '';
$dbname =   '';
$db     =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

$result = false;

$sql='insert into `table1` (`firstname`, `lastname`) values (?, ?)';
$stmt = $db->prepare( $sql );

if( $stmt ){

    $stmt->bind_param('ss',$firstname, $lastname );
    $result = $stmt->execute();
    $stmt->free_result();
    $stmt->close();

} else {
    exit( 'Error: Statement #1' );
}
if( $result ){

    $sql='insert into `table2` (`firstname`, `lastname`) values (?, ?)';
    $stmt = $db->prepare( $sql );

    if( $stmt ){

        $stmt->bind_param('ss',$firstname, $lastname );
        $result = $stmt->execute();
        $stmt->free_result();
        $stmt->close();

    } else {
        exit( 'Error: Statement #2' );
    }
}
$db->close();


来源: stackexchange

问:
How to solve circular reference in json serializer caused by hibernate bidirectional mapping?
I am writing a serializer to serialize POJO to JSON but stuck in circular reference problem. In  hibernate bidirectional one-to-many relation, parent references child and child references back to parent and here my serializer dies. (see example code below)

How to break this cycle? Can we get owner tree of an object to see whether object itself exists somewhere in its own owner hierarchy? Any other way to find if the reference is going to be circular? or any other idea to resolve this problem?

答:
If you are using Jackon to serialize, just apply @JsonBackReference to your bi-directinal mapping
It will solve the circular reference problem.

Note : @JsonBackReference is used to solve the Infinite recursion (StackOverflowError)

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Java: How can I read and store them in array by a new line in ArrayList?
Here is what my .txt file looks like (but more than 100 elements per line and more than 100 lines):

```<code>-0.89094    -0.86099    -0.82438    -0.78214    -0.73573    -0.68691    -0.63754
-0.42469    -0.3924     -0.36389    -0.33906    -0.31795    -0.30056    -0.28692
</code>```

What I want to do is read this .txt file and store them in Arryalist. The problem is when I read and store this data, they put all of this in the same array (I want them to store in 2 arrays split by a line).

Here is my code:

```<code>public class ReadStore {
    public static void main(String[] args) throws IOException {

    Scanner inFile = new Scanner(new File("Untitled.txt")).useDelimiter("\\s");
    ArrayList<Float> temps = new ArrayList<Float>();

    while (inFile.hasNextFloat()) {
      // find next line
      float token = inFile.nextFloat();
      temps.add(token);

    }

    inFile1.close();

    Float [] tempsArray = temps.toArray(new Float[0]);
    for (Float s : tempsArray) {
      System.out.println(s);
    }
  }
</code>```

Any suggestion for making this works?

答:
I might go about this by just reading in each line in its entirety, and then splitting on whitespace to access each floating point number.  This gets around the issue of having to distinguish spaces from line separators.

```<code>public class ReadStore {
    public static void main(String[] args) throws IOException {
        Scanner inFile = new Scanner(new File("Untitled.txt"));
        ArrayList<Float> temps = new ArrayList<Float>();

        while (inFile.hasNextLine()) {
            String line = inFile.nextLine();
            String[] nums = line.trim().split("\\s+");
            for (String num : nums) {
                float token = Float.parseFloat(num);
                temps.add(token);
            }
            Float [] tempsArray = temps.toArray(new Float[0]);
            for (Float s : tempsArray) {
                System.out.println(s);
            }
        }

        inFile.close();
    }
}
</code>```

Here is a demo showing that the logic works for a single line of your input file.  Note that I call String#trim() on each line before splitting it, just in case there is any leading or trailing whitespace which we don't want.

Rextester

Body:
Here is what my .txt file looks like (but more than 100 elements per line and more than 100 lines):

-0.89094    -0.86099    -0.82438    -0.78214    -0.73573    -0.68691    -0.63754
-0.42469    -0.3924     -0.36389    -0.33906    -0.31795    -0.30056    -0.28692

What I want to do is read this .txt file and store them in Arryalist. The problem is when I read and store this data, they put all of this in the same array (I want them to store in 2 arrays split by a line).

Here is my code:

public class ReadStore {
    public static void main(String[] args) throws IOException {

    Scanner inFile = new Scanner(new File("Untitled.txt")).useDelimiter("\\s");
    ArrayList<Float> temps = new ArrayList<Float>();

    while (inFile.hasNextFloat()) {
      // find next line
      float token = inFile.nextFloat();
      temps.add(token);

    }

    inFile1.close();

    Float [] tempsArray = temps.toArray(new Float[0]);
    for (Float s : tempsArray) {
      System.out.println(s);
    }
  }

Any suggestion for making this works?

Body:
I might go about this by just reading in each line in its entirety, and then splitting on whitespace to access each floating point number.  This gets around the issue of having to distinguish spaces from line separators.

public class ReadStore {
    public static void main(String[] args) throws IOException {
        Scanner inFile = new Scanner(new File("Untitled.txt"));
        ArrayList<Float> temps = new ArrayList<Float>();

        while (inFile.hasNextLine()) {
            String line = inFile.nextLine();
            String[] nums = line.trim().split("\\s+");
            for (String num : nums) {
                float token = Float.parseFloat(num);
                temps.add(token);
            }
            Float [] tempsArray = temps.toArray(new Float[0]);
            for (Float s : tempsArray) {
                System.out.println(s);
            }
        }

        inFile.close();
    }
}

Here is a demo showing that the logic works for a single line of your input file.  Note that I call String#trim() on each line before splitting it, just in case there is any leading or trailing whitespace which we don't want.

Rextester


问:
How to make one to one relationship EER diagram in MySql Workbench 6.3E
As the title said , how can i make the relationship in following image (connect to column)?

答: In the vertical toolbar you can see different connection (relation) tools. The last one with the picker symbol lets you select individual columns for a relationship. You can edit the cardinality and other properties at any time in the relationship editor (double click the relationship to open it). By editing the referencing table you can also edit the participating columns (via the created foreign key constraint.</p>


问:
avoid logging on jboss
I m using jboss as application server. When I deploy my application on server it prints logs on jboss. So, can anybody tell how and where to create logging.properties file to manage the logs on jboss. please reply me as soon as possible.

thank you.

答:
Here is the JBoss Documentation about logging.

And an article about JBoss logging configuration.

Good reading.

Edit :

You can set the JDK logging property :

```<code>java.util.logging.config.file = myLoggingFile.properties
</code>```

You can also launch the JBoss Server with the good JAVA_OPTS (example for JDK1.4) :

```<code>JAVA_OPTS="-Dorg.jboss.logging.Logger.pluginClass=logging.JDK14LoggerPlugin
           -Djava.util.logging.config.file=myLoggingFile.properties"
</code>```

Title: avoid logging on jboss

Body:
Here is the JBoss Documentation about logging.

And an article about JBoss logging configuration.

Good reading.

Edit :

You can set the JDK logging property :

java.util.logging.config.file = myLoggingFile.properties

You can also launch the JBoss Server with the good JAVA_OPTS (example for JDK1.4) :

JAVA_OPTS="-Dorg.jboss.logging.Logger.pluginClass=logging.JDK14LoggerPlugin
           -Djava.util.logging.config.file=myLoggingFile.properties"


问:
Auto layout constraints not behaving correctly?
So I have a pretty simple layout for a view that I have created, basically what i want it to look like after I'm done with adding constraints is as follows,

However, what I end up with is something else, and Im not sure why this behavior is happening.

So just a quick rundown of what I did in an attempt to achieve the layouts I wanted.

Center the X position of the "/" label

Set the the indexLabel that can be seen towards the left that says "1"

Constraint the "reps" label to the left of "/" label

Finally constraint the "reps field" to the right of indexLabel and left of "reps" label

```<code>private func setupDividerLabelLayout() {
    addSubview(dividerLabel)

    dividerLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    dividerLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
}

private func setupIndexLabelBackgroundLayout() {
    addSubview(indexLabelBackground)

    indexLabelBackground.leftAnchor.constraint(equalTo: leftAnchor, constant: 24).isActive = true
    indexLabelBackground.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    indexLabelBackground.heightAnchor.constraint(equalToConstant: 24).isActive = true
    indexLabelBackground.widthAnchor.constraint(equalToConstant: 24).isActive = true

}

private func setupRepsLabelLayout() {
    addSubview(repsLabel)

    repsLabel.rightAnchor.constraint(equalTo: dividerLabel.leftAnchor, constant: -16).isActive = true
    repsLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
}

private func setupRepsFieldLayout() {
    addSubview(repsField)

    repsField.rightAnchor.constraint(equalTo: repsLabel.leftAnchor, constant: -8).isActive = true
    repsField.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    repsField.leftAnchor.constraint(equalTo: indexLabelBackground.rightAnchor, constant: 8).isActive = true
}
</code>```

答:
In order let you anchors work you should add _ViewName_.translatesAutoresizingMaskIntoConstraints = false.
 so the code becomes as follows
Code to Use

```<code>private func setupDividerLabelLayout() {
    addSubview(dividerLabel)

    dividerLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    dividerLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
    dividerLabel.translatesAutoresizingMaskIntoConstraints = false
}

private func setupIndexLabelBackgroundLayout() {
    addSubview(indexLabelBackground)

    indexLabelBackground.leftAnchor.constraint(equalTo: leftAnchor, constant: 24).isActive = true
    indexLabelBackground.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    indexLabelBackground.heightAnchor.constraint(equalToConstant: 24).isActive = true
    indexLabelBackground.widthAnchor.constraint(equalToConstant: 24).isActive = true
    indexLabelBackground.translatesAutoresizingMaskIntoConstraints = false

}

private func setupRepsLabelLayout() {
    addSubview(repsLabel)

    repsLabel.rightAnchor.constraint(equalTo: dividerLabel.leftAnchor, constant: -16).isActive = true
    repsLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    repsLabel.translatesAutoresizingMaskIntoConstraints = false

}

private func setupRepsFieldLayout() {
    addSubview(repsField)

    repsField.rightAnchor.constraint(equalTo: repsLabel.leftAnchor, constant: -8).isActive = true
    repsField.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    repsField.leftAnchor.constraint(equalTo:
    indexLabelBackground.rightAnchor, constant: 8).isActive = true
    repsField.translatesAutoresizingMaskIntoConstraints = false
    indexLabelBackground.translatesAutoresizingMaskIntoConstraints = false

}
</code>```

Body:
So I have a pretty simple layout for a view that I have created, basically what i want it to look like after I'm done with adding constraints is as follows,

However, what I end up with is something else, and Im not sure why this behavior is happening.

So just a quick rundown of what I did in an attempt to achieve the layouts I wanted.

Center the X position of the "/" label

Set the the indexLabel that can be seen towards the left that says "1"

Constraint the "reps" label to the left of "/" label

Finally constraint the "reps field" to the right of indexLabel and left of "reps" label

private func setupDividerLabelLayout() {
    addSubview(dividerLabel)

    dividerLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    dividerLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
}

private func setupIndexLabelBackgroundLayout() {
    addSubview(indexLabelBackground)

    indexLabelBackground.leftAnchor.constraint(equalTo: leftAnchor, constant: 24).isActive = true
    indexLabelBackground.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    indexLabelBackground.heightAnchor.constraint(equalToConstant: 24).isActive = true
    indexLabelBackground.widthAnchor.constraint(equalToConstant: 24).isActive = true

}

private func setupRepsLabelLayout() {
    addSubview(repsLabel)

    repsLabel.rightAnchor.constraint(equalTo: dividerLabel.leftAnchor, constant: -16).isActive = true
    repsLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
}

private func setupRepsFieldLayout() {
    addSubview(repsField)

    repsField.rightAnchor.constraint(equalTo: repsLabel.leftAnchor, constant: -8).isActive = true
    repsField.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    repsField.leftAnchor.constraint(equalTo: indexLabelBackground.rightAnchor, constant: 8).isActive = true
}

Body:
In order let you anchors work you should add _ViewName_.translatesAutoresizingMaskIntoConstraints = false.
 so the code becomes as follows
Code to Use

private func setupDividerLabelLayout() {
    addSubview(dividerLabel)

    dividerLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    dividerLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
    dividerLabel.translatesAutoresizingMaskIntoConstraints = false
}

private func setupIndexLabelBackgroundLayout() {
    addSubview(indexLabelBackground)

    indexLabelBackground.leftAnchor.constraint(equalTo: leftAnchor, constant: 24).isActive = true
    indexLabelBackground.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    indexLabelBackground.heightAnchor.constraint(equalToConstant: 24).isActive = true
    indexLabelBackground.widthAnchor.constraint(equalToConstant: 24).isActive = true
    indexLabelBackground.translatesAutoresizingMaskIntoConstraints = false

}

private func setupRepsLabelLayout() {
    addSubview(repsLabel)

    repsLabel.rightAnchor.constraint(equalTo: dividerLabel.leftAnchor, constant: -16).isActive = true
    repsLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    repsLabel.translatesAutoresizingMaskIntoConstraints = false

}

private func setupRepsFieldLayout() {
    addSubview(repsField)

    repsField.rightAnchor.constraint(equalTo: repsLabel.leftAnchor, constant: -8).isActive = true
    repsField.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    repsField.leftAnchor.constraint(equalTo:
    indexLabelBackground.rightAnchor, constant: 8).isActive = true
    repsField.translatesAutoresizingMaskIntoConstraints = false
    indexLabelBackground.translatesAutoresizingMaskIntoConstraints = false

}


问:
Ansible playbook tags with repeated values not working
I am using Ansible playbook command as below:

```<code>ansible-playbook \
  -u xxxx \
  --extra-vars "user_pass=yyyy module1_version=09:02:01 module2_version=10:12:10" \
  --tags "module1,version-check,module2,version-check" \
  -i inventories/ \
  --limit "DEV" portal_version_test.yml
</code>```

Notice I'm keeping the repeated tag version-check in the command as I need to get the version from each module and do a version check after that. This way I can reuse the version-check task for all my modules.

But this command skips the first instance of version check, instead it executes in the order like module1 -> module2 -> version-check`

Does it mean can't we use the repeated tags in the ansible-playbook command?

My playbook is something like:

name: get version from module1
  ....
  tags: module1

name: get version from module2
  ...
  tags: module2

name: compare expected and actual version
  ....
  tags: version-check

答:
Does it mean can't we use the repeated tags in the ansible-playbook command?

No, you can not use "repeated" tags.

Tags are used as filters in Ansible, so you tell Ansible what tasks you want to execute.

Order of tags in --tags parameter doesn't matter, task are always executed in order of appearance in a playbook.

Body:
I am using Ansible playbook command as below:

ansible-playbook \
  -u xxxx \
  --extra-vars "user_pass=yyyy module1_version=09:02:01 module2_version=10:12:10" \
  --tags "module1,version-check,module2,version-check" \
  -i inventories/ \
  --limit "DEV" portal_version_test.yml

Notice I'm keeping the repeated tag version-check in the command as I need to get the version from each module and do a version check after that. This way I can reuse the version-check task for all my modules.

But this command skips the first instance of version check, instead it executes in the order like module1 -> module2 -> version-check`

Does it mean can't we use the repeated tags in the ansible-playbook command?

My playbook is something like:

name: get version from module1
  ....
  tags: module1

name: get version from module2
  ...
  tags: module2

name: compare expected and actual version
  ....
  tags: version-check


问:
How can I search a json file to return values satisfying a particular criteria?
Here is my json file:

```<code>{"items":[{"reputation":6623,"user_id":836,"location":"Durham, United Kingdom","link":"https://datascience.stackexchange.com/users/836/neil-slater","display_name":"Neil Slater"},{"reputation":6267,"user_id":381,"location":"Silicon Valley","link":"https://datascience.stackexchange.com/users/381/emre","display_name":"Emre"},{"reputation":5033,"user_id":2452,"location":"Atlanta, GA","link":"https://datascience.stackexchange.com/users/2452/aleksandr-blekh","display_name":"Aleksandr Blekh"},{"reputation":3537,"user_id":11097,"location":"Gurgaon, India","link":"https://datascience.stackexchange.com/users/11097/dawny33","display_name":"Dawny33"},{"reputation":3257,"user_id":21,"location":"London, United Kingdom","link":"https://datascience.stackexchange.com/users/21/sean-owen","display_name":"Sean Owen"}]
</code>```

How can I extract display names of users who are from a particular location, say Israel? I am trying to write nested query for the same but getting syntax errors.

答:
you could use a list comprehension like this:

```<code>import json
jsd = json.loads(<JSON STRING>) #  This return a dict object
displayNamesList = [dn['display_name'] for dn in jsd.values()[0] if 'Israel' in dn['display_name']]
</code>```

But the most important it's that you need to review a well formed json struct. I use http://codebeautify.org/jsonviewer in order to validate a json struct.

Hope this help you.

Body:
Here is my json file:

{"items":[{"reputation":6623,"user_id":836,"location":"Durham, United Kingdom","link":"https://datascience.stackexchange.com/users/836/neil-slater","display_name":"Neil Slater"},{"reputation":6267,"user_id":381,"location":"Silicon Valley","link":"https://datascience.stackexchange.com/users/381/emre","display_name":"Emre"},{"reputation":5033,"user_id":2452,"location":"Atlanta, GA","link":"https://datascience.stackexchange.com/users/2452/aleksandr-blekh","display_name":"Aleksandr Blekh"},{"reputation":3537,"user_id":11097,"location":"Gurgaon, India","link":"https://datascience.stackexchange.com/users/11097/dawny33","display_name":"Dawny33"},{"reputation":3257,"user_id":21,"location":"London, United Kingdom","link":"https://datascience.stackexchange.com/users/21/sean-owen","display_name":"Sean Owen"}]

How can I extract display names of users who are from a particular location, say Israel? I am trying to write nested query for the same but getting syntax errors.

Body:
you could use a list comprehension like this:

import json
jsd = json.loads(<JSON STRING>) #  This return a dict object
displayNamesList = [dn['display_name'] for dn in jsd.values()[0] if 'Israel' in dn['display_name']]

But the most important it's that you need to review a well formed json struct. I use http://codebeautify.org/jsonviewer in order to validate a json struct.

Hope this help you.


问:
Constant #1064 error on everything I do in mySQL through phpMyAdmin

1064 - You have an error in your SQL syntax

I've just done a fresh install of XAMPP and configured the usernames and passwords for phpMyAdmin and mySQL. So far so good, no errors and all working fine. But when I go to create a new database, create a new table, or even drop a table it always comes up with the #1064 Error message.

Error when dropping a database:

SELECT MAX( version ) FROM.WHERE db_name =  'new_database_test' AND
  table_name =  '' AND FIND_IN_SET(  'DROP DATABASE', tracking ) >0

MySQL said:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
  near 'WHERE db_name = 'new_database_test'  AND table_name = ''
  AND FIND_IN_SET('D' at line 1

Error when creating a database:

SQL query:  Edit

SELECT MAX( version ) FROM.WHERE db_name =  'new_test_db' AND
    table_name =  '' AND FIND_IN_SET(  'CREATE DATABASE', tracking ) >0

MySQL said:

#1064 - You have an error in your SQL syntax; check the manual that
    corresponds to your MySQL server version for the right syntax to use
    near 'WHERE db_name = 'new_test_db'  AND table_name = ''  AND
    FIND_IN_SET('CREATE ' at line 1

Error when adding a table:

SQL query:  Edit

SELECT MAX( version ) FROM.WHERE db_name =  'new_test_db' AND
  table_name =  'awesome_table' AND FIND_IN_SET(  'CREATE TABLE',
  tracking ) >0

MySQL said:

#1064 - You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'WHERE db_name = 'new_test_db'  AND table_name =
  'awesome_table'  AND FIND_IN' at line 1

Despite the errors it's showing the databases are getting created and dropped. But when I try to create a table it simply creates an empty table instead of including any of the columns I wanted.

Anybody have any idea how to fix this? I'm completely new to both mySQL and phpMyAdmin, so don't really know where to begin.

Thanks.

答:
What fixed it for me was:

```<code>1. go to table operations (where u clone or rename a table)
2. click on repair table (right side in table maintenance section)
</code>```

EDIT:

actually what the problem is for me is lowercase table name and I used a uppercase select query ..

Body:
What fixed it for me was:

1. go to table operations (where u clone or rename a table)
2. click on repair table (right side in table maintenance section)

EDIT:

actually what the problem is for me is lowercase table name and I used a uppercase select query ..


问:
WOW.js - how to avoid data-* attributes?
I'm using WOW.js to animate a few div containers and would like to avoid the data-* attributes.

Example HTML

```<code> <div class="wow slideInLeft" data-wow-duration="2s" data-wow-delay="5s">Content</div>
</code>```

Example JS

```<code>var wow = new WOW({
    boxClass:     'wow',
    animateClass: 'animated',
    offset:       0,
    mobile:       true,
    live:         true
});

wow.init();
</code>```

Is it possible to control the data attributes duration, delay, offset and iteration by a class or by JS, e.g. on init()?

My workaround would be to search for classes like class="wowDelay-5s" and add an attribute to it's element as data-wow-delay="5s", but I prefer the proper way, if there is any.

Thanks in advance!

答:
there are 2 different ways to get the data attributes with jquery.

fisrt, you look for the attr

```<code>var firstWay = $('.wow.slideInLeft').attr('data-wow-duration');
</code>```

second one is to use the data function from jquery

```<code>var secondWay = $('.wow.slideInLeft').data('wow-duration');
</code>```

to set the attribute with an init function it simple too

```<code>$('.wow.slideInLeft').attr('data-wow-duration') = '2s';
</code>```

and

```<code>$('.wow.slideInLeft').data('wow-duration', '2s');
</code>```

i hope this helps you

Body:
I'm using WOW.js to animate a few div containers and would like to avoid the data-* attributes.

Example HTML

Content

Example JS

var wow = new WOW({
    boxClass:     'wow',
    animateClass: 'animated',
    offset:       0,
    mobile:       true,
    live:         true
});

wow.init();

Is it possible to control the data attributes duration, delay, offset and iteration by a class or by JS, e.g. on init()?

My workaround would be to search for classes like class="wowDelay-5s" and add an attribute to it's element as data-wow-delay="5s", but I prefer the proper way, if there is any.

Thanks in advance!

Body:
there are 2 different ways to get the data attributes with jquery.

fisrt, you look for the attr

var firstWay = $('.wow.slideInLeft').attr('data-wow-duration');

second one is to use the data function from jquery

var secondWay = $('.wow.slideInLeft').data('wow-duration');

to set the attribute with an init function it simple too

$('.wow.slideInLeft').attr('data-wow-duration') = '2s';

and

$('.wow.slideInLeft').data('wow-duration', '2s');

i hope this helps you


问:
Managing Liquibase with GitFlow development model
We are using the git flow model for our development and trying to integrate liquibase for managing the database versioning efficiently. The problem comes when a developer is working on a feature branch and has made a DB script which is executed on his database and another developer's database, but it is not yet part of any release so it is not yet tagged. Now that feature is tested and becomes part of release and we tag the changeset and execute it on production.

The questions is how to rollback the changes made on the developer's machine because there was no tag defined at the moment when the script got executed and when we try to update it will the current tag it will show error "The table already exists".

How to manage these conditions through liquibase efficiently ?

答:
What we do is not linked to Git or GitFlow, but to the database itself:

Each time a db script is executed, it is done through a wrapper which will also record said script execution in a dedicated table of the database.

That way, next time that same script is applied, the wrapper will detect it was already executed, and won't apply it again.

This is an implementation of what a product like Flyway does already (as shown in this answer, you can use both: Liquidbase and Flyway, they seem to differ).

The point is: this is not manageable solely with a Version Control System: you need an additional tool to enforce/control the database upgrade process.


问:
What's the difference between L1 and L2 caches in web-applications with Hibernate as ORM mechanism?
I just want some general info about standard purpose of using L1 cache and L2 cache.

I'm curious because I'm investigating the system with terracotta as 2nd level cache and I've found that it also has 1st-level cache.

答: If Hibernate is anything similar to NHibernate (which it is, except the other way round), the Session is the first-level cache. Except that it is not cache in a general sense, but rather an identity map.


问:
How to initialize a two-dimensional array in Python?
I'm beginning python and I'm trying to use a two-dimensional list, that I initially fill up with the same variable in every place. I came up with this:

```<code>def initialize_twodlist(foo):
    twod_list = []
    new = []
    for i in range (0, 10):
        for j in range (0, 10):
            new.append(foo)
        twod_list.append(new)
        new = []
</code>```

It gives the desired result, but feels like a workaround. Is there an easier/shorter/more elegant way to do this?

Body:
I'm beginning python and I'm trying to use a two-dimensional list, that I initially fill up with the same variable in every place. I came up with this:

def initialize_twodlist(foo):
    twod_list = []
    new = []
    for i in range (0, 10):
        for j in range (0, 10):
            new.append(foo)
        twod_list.append(new)
        new = []

It gives the desired result, but feels like a workaround. Is there an easier/shorter/more elegant way to do this?

Body:
To initialize a two-dimensional list in Python, use

t = [ [0]*3 for i in range(3)]

But don't use [[v]*n]*n, it is a trap!

>>> a = [[0]*3]*3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0]=1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

ContentLicense: CC BY-SA 4.0


问:
Does value change when we clone an object, change certain values and add it to an arrayList?
Snippet:

List<Item> cartList= new ArrayList<Item>();

for(Item correctDataOfItem: correctDataList){

Item clonedItem=response.getItem().clone();

clonedItem = populateCartItem(correctDataOfItem, clonedItem);

/*In populateCartItem(), we set different values of item in clonedItem with the values from correctDataOfItem and return the clonedItem (with new values set)
*/

cartList.add(clonedItem);

}
```

Question:

While adding an element to the ArrayList, the data is correct. After each new element is added to the list, some data of the previous element is getting changed. Why is it so?

答: The default version of clone() method creates the shallow copy of an object. The shallow copy of an object will have exact copy of all the fields of original object. If original object has any references to other objects as fields, then only references of those objects are copied into clone object, copy of those objects are not created. That means any changes made to those objects through clone object will be reflected in original object or vice-versa.Can you please check your clone process</p>

Body:
Snippet:

List<Item> cartList= new ArrayList<Item>();

for(Item correctDataOfItem: correctDataList){

Item clonedItem=response.getItem().clone();

clonedItem = populateCartItem(correctDataOfItem, clonedItem);

/*In populateCartItem(), we set different values of item in clonedItem with the values from correctDataOfItem and return the clonedItem (with new values set)
*/

cartList.add(clonedItem);

}

Question:

While adding an element to the ArrayList, the data is correct. After each new element is added to the list, some data of the previous element is getting changed. Why is it so?


问:
spark startApplication never give me an AppId
I have a little problem with sparkSubmit, when I send my job, I would like to recover the appId to store it somewhere. But I can not retrieve my id.

All sparkLauncher parameters are valid and the job runs well.

```<code>    try{
        LOGGER.debug("Start submit SparkJob");

        try {
            sparkAppHandle = sparkLauncher.startApplication();

            boolean write = false;
            long limitTime = waitingTime /100;

            LOGGER.debug("waiting time : "+waitingTime+"ms");

            int i=0;
            //log
            while( i <= limitTime ){
                Thread.sleep(100);
                i++;
                String id = sparkAppHandle.getAppId();
                if(StringUtils.isNotBlank(id)){
                    LOGGER.debug("i="+(i*100)+"ms,  SPARK id :" + id + ",  SPARK state :" + sparkAppHandle.getState().name());
                    write = true;
                }
            }
            if(!write){
                LOGGER.debug("SPARK id is null");
            }

        } catch (Exception e) {
            LOGGER.debug("ERROR in startApplication " + e);

        }
        LOGGER.debug("End submit SparkJob");

    } catch (Exception e) {
        LOGGER.error("Error in Spark Launcher:", e);
    }
</code>```

Logs:

```<code>#09 Mar 2017 17:30:38,745  [DEBUG] (SparkServicesImpl.java:submitSparkJobsWithAppLaunch:143): Start submit SparkJob
#09 Mar 2017 17:30:38,774  [DEBUG] (SparkServicesImpl.java:submitSparkJobsWithAppLaunch:163): waiting time : 60000ms
#09 Mar 2017 17:31:38,942  [DEBUG] (SparkServicesImpl.java:submitSparkJobsWithAppLaunch:177): SPARK id null
#09 Mar 2017 17:31:38,942  [DEBUG] (SparkServicesImpl.java:submitSparkJobsWithAppLaunch:201): End submit SparkJob
</code>```

My job runs normally, everything works with "sparkLauncher.launch ();" but I do not think I can recover the appId with this method.

Can someone help me ?

答:
try SparkAppHandle.Listener
you can get application id in infoChanged</p>

Body:
I have a little problem with sparkSubmit, when I send my job, I would like to recover the appId to store it somewhere. But I can not retrieve my id.

All sparkLauncher parameters are valid and the job runs well.

    try{
        LOGGER.debug("Start submit SparkJob");

        try {
            sparkAppHandle = sparkLauncher.startApplication();

            boolean write = false;
            long limitTime = waitingTime /100;

            LOGGER.debug("waiting time : "+waitingTime+"ms");

            int i=0;
            //log
            while( i <= limitTime ){
                Thread.sleep(100);
                i++;
                String id = sparkAppHandle.getAppId();
                if(StringUtils.isNotBlank(id)){
                    LOGGER.debug("i="+(i*100)+"ms,  SPARK id :" + id + ",  SPARK state :" + sparkAppHandle.getState().name());
                    write = true;
                }
            }
            if(!write){
                LOGGER.debug("SPARK id is null");
            }

        } catch (Exception e) {
            LOGGER.debug("ERROR in startApplication " + e);

        }
        LOGGER.debug("End submit SparkJob");

    } catch (Exception e) {
        LOGGER.error("Error in Spark Launcher:", e);
    }

Logs:

#09 Mar 2017 17:30:38,745  [DEBUG] (SparkServicesImpl.java:submitSparkJobsWithAppLaunch:143): Start submit SparkJob
#09 Mar 2017 17:30:38,774  [DEBUG] (SparkServicesImpl.java:submitSparkJobsWithAppLaunch:163): waiting time : 60000ms
#09 Mar 2017 17:31:38,942  [DEBUG] (SparkServicesImpl.java:submitSparkJobsWithAppLaunch:177): SPARK id null
#09 Mar 2017 17:31:38,942  [DEBUG] (SparkServicesImpl.java:submitSparkJobsWithAppLaunch:201): End submit SparkJob

My job runs normally, everything works with "sparkLauncher.launch ();" but I do not think I can recover the appId with this method.

Can someone help me ?


问:
How to restrict navigation to some pages using Hardware back button in windows 10 universal app development?
I followed http://www.wintellect.com/devcenter/jprosise/handling-the-back-button-in-windows-10-uwp-apps

My navigation looks like :
Login->A->B->C.
When i press backbutton from C
It should navigate like this C->B->A and should not navigate to Login page form A.

```<code>    SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
    SystemNavigationManager.GetForCurrentView().BackRequested += Util.Navigation_BackRequested;

    public static void Navigation_BackRequested(object sender, BackRequestedEventArgs e)
    {
        Frame rootFrame = Window.Current.Content as Frame;
        if (rootFrame.Equals(typeof(MeetingsList)))
        {
            Util.debugLog("RESTRICT BACK ");
        }
        else
        {
            if (rootFrame.CanGoBack)
            {
                e.Handled = true;
                rootFrame.GoBack();
            }
        }
        SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;

    }
</code>```

答:
By default Back Button is Not Enable for UWP Development . Frist U need to Follow Up Following Link Which Describe  How to Enable Back Button to UWP App Development

http://www.wintellect.com/devcenter/jprosise/handling-the-back-button-in-windows-10-uwp-apps

Then You Can Restrict Navigation Using Following Code Tip

```<code>    private void App_BackRequested(object sender, Windows.UI.Core.BackRequestedEventArgs e)
    {
        Frame rootFrame = Window.Current.Content as Frame;
        bool status = false;
        if(rootFrame == null)
        {
            return;
        }
        if (rootFrame.SourcePageType.Name.Equals("POSummary") || rootFrame.SourcePageType.Name.Equals("AutoBinAllocation"))
        {
            e.Handled = true;
            status = true;

        }
        // Navigate back if possible, and if the event has not
        // already been handled .
        if (rootFrame.CanGoBack && e.Handled == false && status == false)
        {
            e.Handled = true;
            rootFrame.GoBack();
        }
    }
</code>```

Body:
I followed http://www.wintellect.com/devcenter/jprosise/handling-the-back-button-in-windows-10-uwp-apps

My navigation looks like :
Login->A->B->C.
When i press backbutton from C
It should navigate like this C->B->A and should not navigate to Login page form A.

    SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
    SystemNavigationManager.GetForCurrentView().BackRequested += Util.Navigation_BackRequested;

    public static void Navigation_BackRequested(object sender, BackRequestedEventArgs e)
    {
        Frame rootFrame = Window.Current.Content as Frame;
        if (rootFrame.Equals(typeof(MeetingsList)))
        {
            Util.debugLog("RESTRICT BACK ");
        }
        else
        {
            if (rootFrame.CanGoBack)
            {
                e.Handled = true;
                rootFrame.GoBack();
            }
        }
        SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;

    }

Body:
By default Back Button is Not Enable for UWP Development . Frist U need to Follow Up Following Link Which Describe  How to Enable Back Button to UWP App Development

http://www.wintellect.com/devcenter/jprosise/handling-the-back-button-in-windows-10-uwp-apps

Then You Can Restrict Navigation Using Following Code Tip

    private void App_BackRequested(object sender, Windows.UI.Core.BackRequestedEventArgs e)
    {
        Frame rootFrame = Window.Current.Content as Frame;
        bool status = false;
        if(rootFrame == null)
        {
            return;
        }
        if (rootFrame.SourcePageType.Name.Equals("POSummary") || rootFrame.SourcePageType.Name.Equals("AutoBinAllocation"))
        {
            e.Handled = true;
            status = true;

        }
        // Navigate back if possible, and if the event has not
        // already been handled .
        if (rootFrame.CanGoBack && e.Handled == false && status == false)
        {
            e.Handled = true;
            rootFrame.GoBack();
        }
    }


问:
Which and all libraries are OS/platform-independent?
Is there any library which doesn't use operating system calls for it's functionalities? If I'm writing an OS can cherry pick any of them?</p>

答:
Newlib is an implementation of the standard library for embedded systems. It tries to be as portable as possible. Even so, it still requires you to implement a number platform specific functions for each platform you'd like to run it on.

I would say that no, the standard libraries aren't platform independent. If you'd like to know which changes you should make for your port, look at: http://wiki.osdev.org/Porting_Newlib


问:
Spring Dependency Injection object pool
We have an Object which does some calculations in a spring boot container. Lets call it "Sheet". We need to instantiate - let's say 10 - sheets when the application is started. Every time we start a calculation we need one instance of that sheet to be accessed via DI to be run in an extra Thread.

Any idea if that is possible in Spring?

答:
You can achieve this in the following way.. lets say that you have a Sheet class as follow. I have used java8 to compile the code.

Sheet.java

```<code> @Component("sheet")
    @Scope(value = "prototype")
    public class Sheet {
        // Implementation goes here
    }
</code>```

Now you need a second class SheetPool which holds 10 instances of Sheet

SheetPool.java

```<code>public class SheetPool {

    private List<Sheet> sheets;

    public List<Sheet> getSheets() {
        return sheets;
    }

    public Sheet getObject() {
        int index = ThreadLocalRandom.current().nextInt(sheets.size());
        return sheets.get(index);
    }

}
</code>```

Note that SheetPool is not a Spring component. it is just a plain java class.

Now you need a third class which is a config class, which will take care of creating SpringPool object with 10 instance of Sheet

ApplicationConfig.java

```<code>@Configuration
public class ApplicationConfig {

@Autowired
ApplicationContext applicationContext;

@Bean
public SheetPool sheetPool() {
    SheetPool pool = new SheetPool();

    IntStream.range(0, 10).forEach(e -> {
        pool.getSheets().add((Sheet) applicationContext.getBean("sheet"));
    });

    return pool;
}
</code>```

}

Now when the application starts SheetPool  object will be create with 10 different instance of Sheet.. To access the Sheet object use the following code.

```<code>@Autowired
SheetPool  sheetPool;

Sheet sheetObj = sheetPool.getObject();
</code>```

Title: Spring Dependency Injection object pool

Body:
You can achieve this in the following way.. lets say that you have a Sheet class as follow. I have used java8 to compile the code.

Sheet.java

 @Component("sheet")
    @Scope(value = "prototype")
    public class Sheet {
        // Implementation goes here
    }

Now you need a second class SheetPool which holds 10 instances of Sheet

SheetPool.java

public class SheetPool {

    private List<Sheet> sheets;

    public List<Sheet> getSheets() {
        return sheets;
    }

    public Sheet getObject() {
        int index = ThreadLocalRandom.current().nextInt(sheets.size());
        return sheets.get(index);
    }

}

Note that SheetPool is not a Spring component. it is just a plain java class.

Now you need a third class which is a config class, which will take care of creating SpringPool object with 10 instance of Sheet

ApplicationConfig.java

@Configuration
public class ApplicationConfig {

@Autowired
ApplicationContext applicationContext;

@Bean
public SheetPool sheetPool() {
    SheetPool pool = new SheetPool();

    IntStream.range(0, 10).forEach(e -> {
        pool.getSheets().add((Sheet) applicationContext.getBean("sheet"));
    });

    return pool;
}

}

Now when the application starts SheetPool  object will be create with 10 different instance of Sheet.. To access the Sheet object use the following code.

@Autowired
SheetPool  sheetPool;

Sheet sheetObj = sheetPool.getObject();


问:
Cannot open source device in random_bytes() Laravel PHP 7.0
I visite many forum, but i can't find the best solution for my problems.
In laravel 5, i have this error :

```<code>Cannot open source device in random_bytes() :
Exception in Str.php line 243:
Cannot open source device
in Str.php line 243
at random_bytes('25') in Str.php line 243
at Str::randomBytes('25') in Str.php line 227
at Str::random('25') in Store.php line 197
at Store->generateSessionId() in Store.php line 173
</code>```

The str.php is in : httpdocs/vendor/laravel/framework/src/Illuminate/Support/Str.php
at :

```<code>/**
 * Generate a more truly "random" alpha-numeric string.
 *
 * @param  int  $length
 * @return string
 */
public static function random($length = 16)
{
    $string = '';

    while (($len = strlen($string)) < $length) {
        $size = $length - $len;

        $bytes = static::randomBytes($size);

        $string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
    }

    return $string;
}

/**
 * Generate a more truly "random" bytes.
 *
 * @param  int  $length
 * @return string
 */
public static function randomBytes($length = 16)
{
    return random_bytes($length);
}
</code>```

i use php 7. I also change random_bytes by openssl_random_pseudo_bytes(), it's work but i have another error that the framework can't generate hash for password. So i think openssl_random_bytes is not the best solution.

If someone can help.

Thanks

答:
From random_bytes documentation:

The sources of randomness used for this function are as follows:

On Windows, » CryptGenRandom() will always be used.

On Linux, the » getrandom(2) syscall will be used if available.

On other platforms, /dev/urandom will be used.

If none of the aforementioned sources are available, then an Exception will be thrown.

So, your case is last one. It's not your code problem, but server settings. What is the environment? Hosting, cloud, virtual server, local machine?

Body:
I visite many forum, but i can't find the best solution for my problems.
In laravel 5, i have this error :

Cannot open source device in random_bytes() :
Exception in Str.php line 243:
Cannot open source device
in Str.php line 243
at random_bytes('25') in Str.php line 243
at Str::randomBytes('25') in Str.php line 227
at Str::random('25') in Store.php line 197
at Store->generateSessionId() in Store.php line 173

The str.php is in : httpdocs/vendor/laravel/framework/src/Illuminate/Support/Str.php
at :

/**
 * Generate a more truly "random" alpha-numeric string.
 *
 * @param  int  $length
 * @return string
 */
public static function random($length = 16)
{
    $string = '';

    while (($len = strlen($string)) < $length) {
        $size = $length - $len;

        $bytes = static::randomBytes($size);

        $string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
    }

    return $string;
}

/**
 * Generate a more truly "random" bytes.
 *
 * @param  int  $length
 * @return string
 */
public static function randomBytes($length = 16)
{
    return random_bytes($length);
}

i use php 7. I also change random_bytes by openssl_random_pseudo_bytes(), it's work but i have another error that the framework can't generate hash for password. So i think openssl_random_bytes is not the best solution.

If someone can help.

Thanks


问:
How to redirect onclick while using iframe
I had to use an iframe to stop the page from reloading before the action was completed. However, I need it to refresh after the action is taking place. I tried two methods for this, refreshing the page and redirecting to the same page.

PHP:

```<code>if(isset($_POST['btn_name']) {
   //Action
   location.reload();
  //I also tried
    header("Location: index.php");
}
</code>```

HTML:

```<code><iframe width="0" height="0" border="0px solid white" style="display:none" name="iframe1" id="iframe1"></iframe>

        <form action="index.php" method="post" target="iframe1">
         <input type="submit" href="" style="margin-top:5px" name="btn_name" class="btn btn-success" value="Enter">
            </form>
</code>```

Thanks for your help. All input is appreciated.

答:
try to add this in your page where your iframe is(this is using jquery)

$('#iframe1').load(function() {
     if (this.contentWindow.location.href === 'http://location_redirected_in_php') {
        window.location.href = '/redirect_location';
     }
});

Body:
I had to use an iframe to stop the page from reloading before the action was completed. However, I need it to refresh after the action is taking place. I tried two methods for this, refreshing the page and redirecting to the same page.

PHP:

if(isset($_POST['btn_name']) {
   //Action
   location.reload();
  //I also tried
    header("Location: index.php");
}

HTML:

        <form action="index.php" method="post" target="iframe1">
         <input type="submit" href="" style="margin-top:5px" name="btn_name" class="btn btn-success" value="Enter">
            </form>

Thanks for your help. All input is appreciated.


问:
OpenGL and lwjgl Animation not working
i am currently learning to create small java games with OpenGl and lwjgl. I am currently working on an animation system for the entity but i ran into a problem.

```<code>Exception in thread "main" java.lang.RuntimeException: No OpenGL context found in the current thread.

at org.lwjgl.opengl.GLContext.getCapabilities(GLContext.java:124)
at org.lwjgl.opengl.GL30.glGenVertexArrays(GL30.java:1548)
at de.simagdo.simagdoRPG.openglObjects.Vao.create(Vao.java:21)
at de.simagdo.simagdoRPG.animation.models.AnimatedModelLoader.createVao(AnimatedModelLoader.java:73)
at de.simagdo.simagdoRPG.animation.models.AnimatedModelLoader.loadEntity(AnimatedModelLoader.java:28)
at de.simagdo.simagdoRPG.engineTester.SceneLoader.loadScene(SceneLoader.java:30)
at de.simagdo.simagdoRPG.engineTester.MainGameLoop.main(MainGameLoop.java:35)
</code>```

This is the error i am getting.

VAO Class:

```<code>private static final int BYTES_PER_FLOAT = 4;
private static final int BYTES_PER_INT = 4;
public final int id;
private List<Vbo> dataVbos = new ArrayList<>();
private Vbo indexVbo;
private int indexCount;

public static Vao create() {
    int id = GL30.glGenVertexArrays();
    return new Vao(id);
}

private Vao(int id) {
    this.id = id;
}

public int getIndexCount() {
    return indexCount;
}

public void bind(int... attributes) {
    bind();
    for (int i : attributes) {
        GL20.glEnableVertexAttribArray(i);
    }
}

public void unbind(int... attributes) {
    for (int i : attributes) {
        GL20.glDisableVertexAttribArray(i);
    }
    unbind();
}

public void createIndexBuffer(int[] indices) {
    this.indexVbo = Vbo.create(GL15.GL_ELEMENT_ARRAY_BUFFER);
    indexVbo.bind();
    indexVbo.storeData(indices);
    this.indexCount = indices.length;
}

public void createAttribute(int attribute, float[] data, int attrSize) {
    Vbo dataVbo = Vbo.create(GL15.GL_ARRAY_BUFFER);
    dataVbo.bind();
    dataVbo.storeData(data);
    GL20.glVertexAttribPointer(attribute, attrSize, GL11.GL_FLOAT, false, attrSize * BYTES_PER_FLOAT, 0);
    dataVbo.unbind();
    dataVbos.add(dataVbo);
}

public void createIntAttribute(int attribute, int[] data, int attrSize) {
    Vbo dataVbo = Vbo.create(GL15.GL_ARRAY_BUFFER);
    dataVbo.bind();
    dataVbo.storeData(data);
    GL30.glVertexAttribIPointer(attribute, attrSize, GL11.GL_INT, attrSize * BYTES_PER_INT, 0);
    dataVbo.unbind();
    dataVbos.add(dataVbo);
}

public void delete() {
    GL30.glDeleteVertexArrays(id);
    for (Vbo vbo : dataVbos) {
        vbo.delete();
    }
    indexVbo.delete();
}

private void bind() {
    GL30.glBindVertexArray(id);
}

private void unbind() {
    GL30.glBindVertexArray(0);
}
</code>```

The method, where i use it:

```<code>private static Vao createVao(MeshData data) {
    Vao vao = Vao.create();
    vao.bind();
    vao.createIndexBuffer(data.getIndices());
    vao.createAttribute(0, data.getVertices(), 3);
    vao.createAttribute(1, data.getTextureCoords(), 2);
    vao.createAttribute(2, data.getNormals(), 3);
    vao.createIntAttribute(3, data.getJointIds(), 3);
    vao.createAttribute(4, data.getVertexWeights(), 3);
    vao.unbind();
    return vao;
}
</code>```

答:
You have to initialize opengl before use any of its functionalities.

In LWJGL2:

```<code> Display.setDisplayMode(new DisplayMode(800, 600));
 Display.create();
</code>```

In LWJGL3(basically GLFW) you have to call:

```<code>  glfwInit();
</code>```

If you have initialized opengl you are trying to call opengl function from a different thread.

Also would be the same error if you are trying to use anything before your init calls.

If this does not help post your centext related code, even if glGenVertexArrays(); causing the problem "No OpenGL context found in the current thread." is a clear error.

Title: OpenGL and lwjgl Animation not working

Body:
i am currently learning to create small java games with OpenGl and lwjgl. I am currently working on an animation system for the entity but i ran into a problem.

Exception in thread "main" java.lang.RuntimeException: No OpenGL context found in the current thread.

at org.lwjgl.opengl.GLContext.getCapabilities(GLContext.java:124)
at org.lwjgl.opengl.GL30.glGenVertexArrays(GL30.java:1548)
at de.simagdo.simagdoRPG.openglObjects.Vao.create(Vao.java:21)
at de.simagdo.simagdoRPG.animation.models.AnimatedModelLoader.createVao(AnimatedModelLoader.java:73)
at de.simagdo.simagdoRPG.animation.models.AnimatedModelLoader.loadEntity(AnimatedModelLoader.java:28)
at de.simagdo.simagdoRPG.engineTester.SceneLoader.loadScene(SceneLoader.java:30)
at de.simagdo.simagdoRPG.engineTester.MainGameLoop.main(MainGameLoop.java:35)

This is the error i am getting.

VAO Class:

private static final int BYTES_PER_FLOAT = 4;
private static final int BYTES_PER_INT = 4;
public final int id;
private List<Vbo> dataVbos = new ArrayList<>();
private Vbo indexVbo;
private int indexCount;

public static Vao create() {
    int id = GL30.glGenVertexArrays();
    return new Vao(id);
}

private Vao(int id) {
    this.id = id;
}

public int getIndexCount() {
    return indexCount;
}

public void bind(int... attributes) {
    bind();
    for (int i : attributes) {
        GL20.glEnableVertexAttribArray(i);
    }
}

public void unbind(int... attributes) {
    for (int i : attributes) {
        GL20.glDisableVertexAttribArray(i);
    }
    unbind();
}

public void createIndexBuffer(int[] indices) {
    this.indexVbo = Vbo.create(GL15.GL_ELEMENT_ARRAY_BUFFER);
    indexVbo.bind();
    indexVbo.storeData(indices);
    this.indexCount = indices.length;
}

public void createAttribute(int attribute, float[] data, int attrSize) {
    Vbo dataVbo = Vbo.create(GL15.GL_ARRAY_BUFFER);
    dataVbo.bind();
    dataVbo.storeData(data);
    GL20.glVertexAttribPointer(attribute, attrSize, GL11.GL_FLOAT, false, attrSize * BYTES_PER_FLOAT, 0);
    dataVbo.unbind();
    dataVbos.add(dataVbo);
}

public void createIntAttribute(int attribute, int[] data, int attrSize) {
    Vbo dataVbo = Vbo.create(GL15.GL_ARRAY_BUFFER);
    dataVbo.bind();
    dataVbo.storeData(data);
    GL30.glVertexAttribIPointer(attribute, attrSize, GL11.GL_INT, attrSize * BYTES_PER_INT, 0);
    dataVbo.unbind();
    dataVbos.add(dataVbo);
}

public void delete() {
    GL30.glDeleteVertexArrays(id);
    for (Vbo vbo : dataVbos) {
        vbo.delete();
    }
    indexVbo.delete();
}

private void bind() {
    GL30.glBindVertexArray(id);
}

private void unbind() {
    GL30.glBindVertexArray(0);
}

The method, where i use it:

private static Vao createVao(MeshData data) {
    Vao vao = Vao.create();
    vao.bind();
    vao.createIndexBuffer(data.getIndices());
    vao.createAttribute(0, data.getVertices(), 3);
    vao.createAttribute(1, data.getTextureCoords(), 2);
    vao.createAttribute(2, data.getNormals(), 3);
    vao.createIntAttribute(3, data.getJointIds(), 3);
    vao.createAttribute(4, data.getVertexWeights(), 3);
    vao.unbind();
    return vao;
}

Body:
You have to initialize opengl before use any of its functionalities.

In LWJGL2:

 Display.setDisplayMode(new DisplayMode(800, 600));
 Display.create();

In LWJGL3(basically GLFW) you have to call:

  glfwInit();

If you have initialized opengl you are trying to call opengl function from a different thread.

Also would be the same error if you are trying to use anything before your init calls.

If this does not help post your centext related code, even if glGenVertexArrays(); causing the problem "No OpenGL context found in the current thread." is a clear error.


问:
Array Insertion Postgres
I have a table item with attributes no(integer) and price(integer), also another table cart with attributes no(integer) and items(array of item).

I have some records in items.

When i tried :

```<code>INSERT INTO myschema.cart VALUES(1,'{SELECT item from myschema.item}')
</code>```

I'am getting error malformed record literal.

I expected this to insert all items from myschema.item into the cart record.

答:
You can't write a subquery inside a string like that.

What you need to do is aggregate the items into a array with array_agg

```<code>INSERT INTO myschema.cart
VALUES (1, (SELECT array_agg(item) FROM myschema.item));
</code>```

Or

```<code>INSERT INTO myschema.cart
SELECT 1, array_agg(item) FROM myschema.item;
</code>```

Title: Array Insertion Postgres

Body:
I have a table item with attributes no(integer) and price(integer), also another table cart with attributes no(integer) and items(array of item).

I have some records in items.

When i tried :

INSERT INTO myschema.cart VALUES(1,'{SELECT item from myschema.item}')

I'am getting error malformed record literal.

I expected this to insert all items from myschema.item into the cart record.

Body:
You can't write a subquery inside a string like that.

What you need to do is aggregate the items into a array with array_agg

INSERT INTO myschema.cart
VALUES (1, (SELECT array_agg(item) FROM myschema.item));

Or

INSERT INTO myschema.cart
SELECT 1, array_agg(item) FROM myschema.item;


问:
How do I "git clone" a repo, including its submodules?
How do I clone a git repository so that it also clones its submodules?

Running git clone $REPO_URL merely creates empty submodule directories.

答:
With version 2.13 of Git and later, --recurse-submodules can be used instead of --recursive:

```<code>git clone --recurse-submodules -j8 git://github.com/foo/bar.git
cd bar
</code>```

Editor’s note: -j8 is an optional performance optimization that became available in version 2.8, and fetches up to 8 submodules at a time in parallel — see man git-clone.

With version 1.9 of Git up until version 2.12 (-j flag only available in version 2.8+):

```<code>git clone --recursive -j8 git://github.com/foo/bar.git
cd bar
</code>```

With version 1.6.5 of Git and later, you can use:

```<code>git clone --recursive git://github.com/foo/bar.git
cd bar
</code>```

For already cloned repos, or older Git versions, use:

```<code>git clone git://github.com/foo/bar.git
cd bar
git submodule update --init --recursive
</code>```

Body:
With version 2.13 of Git and later, --recurse-submodules can be used instead of --recursive:

git clone --recurse-submodules -j8 git://github.com/foo/bar.git
cd bar

Editor’s note: -j8 is an optional performance optimization that became available in version 2.8, and fetches up to 8 submodules at a time in parallel — see man git-clone.

With version 1.9 of Git up until version 2.12 (-j flag only available in version 2.8+):

git clone --recursive -j8 git://github.com/foo/bar.git
cd bar

With version 1.6.5 of Git and later, you can use:

git clone --recursive git://github.com/foo/bar.git
cd bar

For already cloned repos, or older Git versions, use:

git clone git://github.com/foo/bar.git
cd bar
git submodule update --init --recursive


问:
Wikitude Passing value from java to JavaScript to use it in AR.RelativeLocation
I passed an integer from java to javascript, and now I want to use the value to change the altitude of an object.

I added a to RelativeLoction var location = new AR.RelativeLocation(null, 8, 0, a);

The problem is it ignores the value that I passed which is 10 and take a as 0. I know that the value passed correctly from this var e = document.getElementById('loadingMessage').innerHTML = "Altitude: " + a; which shows Altitude: 10.

Javascript code:

```<code>var World = {
    loaded: false,
    rotating: false,

    init: function initFn() {
        this.createModelAtLocation();
    },

    createModelAtLocation: function createModelAtLocationFn() {

        /*
            First a location where the model should be displayed will be defined. This location will be relativ to the user.
        */
        var location = new AR.RelativeLocation(null, 8, 0, a);

        /*
            Next the model object is loaded.
        */
        var modelArrow = new AR.Model("assets/arrow.wt3", {
                    onLoaded: this.worldLoaded,
                    scale: {
                        x: 0.005,
                        y: 0.005,
                        z: 0.003
                    },
                    rotate: {
                                    x: 0.0,
                                    y: 90.0,
                                    z: 0.0
                                  },
                                  translate: {
                                      x: 0,
                                      y: 0,
                                      z: 0
                                    }

                });

        var indicatorImage = new AR.ImageResource("assets/indi.png");

        var indicatorDrawable = new AR.ImageDrawable(indicatorImage, 0.1, {
            verticalAnchor: AR.CONST.VERTICAL_ANCHOR.TOP
        });

        /*
            Putting it all together the location and 3D model is added to an AR.GeoObject.
        */
        var obj = new AR.GeoObject(location, {
            drawables: {
               cam: [modelArrow],
               indicator: [indicatorDrawable]
            }
        });
    },

    worldLoaded: function worldLoadedFn() {
        World.loaded = true;
        var e = document.getElementById('loadingMessage').innerHTML = "Altitude: " + a;
        e.parentElement.removeChild(e);
    }
};

    var a = 0;
    var altitude = 0;

       function setAltitude(altitude){
               a = altitude;
           }

World.init();
</code>```

Edit after Alex's answer:

Now the object and the altitude are not showing not sure if I'm missing something

```<code>var World = {
    location: null,
    loaded: false,
    rotating: false,

    init: function initFn() {
        this.createModelAtLocation();
    },

    createModelAtLocation: function createModelAtLocationFn() {

        /*

            First a location where the model should be displayed will be defined. This location will be relativ to the user.
        */
        //var location = new AR.RelativeLocation(null, 8, 0, a);
        World.location = new AR.RelativeLocation(null, 8, 0, a);

        /*
            Next the model object is loaded.
        */
        var modelArrow = new AR.Model("assets/arrow.wt3", {
                    onLoaded: this.worldLoaded,
                    scale: {
                        x: 0.005,
                        y: 0.005,
                        z: 0.003
                    },
                    rotate: {
                                    x: 0.0,
                                    y: 90.0,
                                    z: 0.0
                                  },
                                  translate: {
                                      x: 0,
                                      y: 0,
                                      z: 0
                                    }

                });

        var indicatorImage = new AR.ImageResource("assets/indi.png");

        var indicatorDrawable = new AR.ImageDrawable(indicatorImage, 0.1, {
            verticalAnchor: AR.CONST.VERTICAL_ANCHOR.TOP
        });

        /*
            Putting it all together the location and 3D model is added to an AR.GeoObject.
        */
        var obj = new AR.GeoObject(location, {
            drawables: {
               cam: [modelArrow],
               indicator: [indicatorDrawable]
            }
        });
    },

    worldLoaded: function worldLoadedFn() {
        World.loaded = true;
        var e = document.getElementById('loadingMessage').innerHTML = "Altitude: " + a;
        e.parentElement.removeChild(e);
    }
};
    var a = 0;
    var altitude = 0;

       function setAltitude(altitude){
               //a = altitude;
               //World.location.altitudeDelta  = altitude;
               World.location.a = altitude;
           }

World.init();
</code>```

答:
Keep in mind that Model.onLoaded is async. My assumption is that the order of which things are happening is: init() -> createModelAtLocation() -> java sets altitude -> worldLoaded().

What you could do to avoid this is:

```<code>var World = {
    location: null,
    ...
    World.location = new AR.RelativeLocation(null, 8, 0, a);
    ...
};

function setAltitude(altitude){
   World.location.altitudeDelta = altitude;
}
</code>```

Body:
I passed an integer from java to javascript, and now I want to use the value to change the altitude of an object.

I added a to RelativeLoction var location = new AR.RelativeLocation(null, 8, 0, a);

The problem is it ignores the value that I passed which is 10 and take a as 0. I know that the value passed correctly from this var e = document.getElementById('loadingMessage').innerHTML = "Altitude: " + a; which shows Altitude: 10.

Javascript code:

var World = {
    loaded: false,
    rotating: false,

    init: function initFn() {
        this.createModelAtLocation();
    },

    createModelAtLocation: function createModelAtLocationFn() {

        /*
            First a location where the model should be displayed will be defined. This location will be relativ to the user.
        */
        var location = new AR.RelativeLocation(null, 8, 0, a);

        /*
            Next the model object is loaded.
        */
        var modelArrow = new AR.Model("assets/arrow.wt3", {
                    onLoaded: this.worldLoaded,
                    scale: {
                        x: 0.005,
                        y: 0.005,
                        z: 0.003
                    },
                    rotate: {
                                    x: 0.0,
                                    y: 90.0,
                                    z: 0.0
                                  },
                                  translate: {
                                      x: 0,
                                      y: 0,
                                      z: 0
                                    }

                });

        var indicatorImage = new AR.ImageResource("assets/indi.png");

        var indicatorDrawable = new AR.ImageDrawable(indicatorImage, 0.1, {
            verticalAnchor: AR.CONST.VERTICAL_ANCHOR.TOP
        });

        /*
            Putting it all together the location and 3D model is added to an AR.GeoObject.
        */
        var obj = new AR.GeoObject(location, {
            drawables: {
               cam: [modelArrow],
               indicator: [indicatorDrawable]
            }
        });
    },

    worldLoaded: function worldLoadedFn() {
        World.loaded = true;
        var e = document.getElementById('loadingMessage').innerHTML = "Altitude: " + a;
        e.parentElement.removeChild(e);
    }
};

    var a = 0;
    var altitude = 0;

       function setAltitude(altitude){
               a = altitude;
           }

World.init();

Edit after Alex's answer:

Now the object and the altitude are not showing not sure if I'm missing something

var World = {
    location: null,
    loaded: false,
    rotating: false,

    init: function initFn() {
        this.createModelAtLocation();
    },

    createModelAtLocation: function createModelAtLocationFn() {

        /*

            First a location where the model should be displayed will be defined. This location will be relativ to the user.
        */
        //var location = new AR.RelativeLocation(null, 8, 0, a);
        World.location = new AR.RelativeLocation(null, 8, 0, a);

        /*
            Next the model object is loaded.
        */
        var modelArrow = new AR.Model("assets/arrow.wt3", {
                    onLoaded: this.worldLoaded,
                    scale: {
                        x: 0.005,
                        y: 0.005,
                        z: 0.003
                    },
                    rotate: {
                                    x: 0.0,
                                    y: 90.0,
                                    z: 0.0
                                  },
                                  translate: {
                                      x: 0,
                                      y: 0,
                                      z: 0
                                    }

                });

        var indicatorImage = new AR.ImageResource("assets/indi.png");

        var indicatorDrawable = new AR.ImageDrawable(indicatorImage, 0.1, {
            verticalAnchor: AR.CONST.VERTICAL_ANCHOR.TOP
        });

        /*
            Putting it all together the location and 3D model is added to an AR.GeoObject.
        */
        var obj = new AR.GeoObject(location, {
            drawables: {
               cam: [modelArrow],
               indicator: [indicatorDrawable]
            }
        });
    },

    worldLoaded: function worldLoadedFn() {
        World.loaded = true;
        var e = document.getElementById('loadingMessage').innerHTML = "Altitude: " + a;
        e.parentElement.removeChild(e);
    }
};
    var a = 0;
    var altitude = 0;

       function setAltitude(altitude){
               //a = altitude;
               //World.location.altitudeDelta  = altitude;
               World.location.a = altitude;
           }

World.init();

Body:
Keep in mind that Model.onLoaded is async. My assumption is that the order of which things are happening is: init() -> createModelAtLocation() -> java sets altitude -> worldLoaded().

What you could do to avoid this is:

var World = {
    location: null,
    ...
    World.location = new AR.RelativeLocation(null, 8, 0, a);
    ...
};

function setAltitude(altitude){
   World.location.altitudeDelta = altitude;
}


问:
AWS S3 bucket "404 Not Found"
At the moment I'm hosting a bundled Angular-2 App in an AWS S3 bucket, so it only contains .html and .js files.

The absolute path http://example.com/ does work but if I switch to any links, such as http://example.com/testsite it returns 404 error as below:

404 Not Found
Code: NoSuchKey
Message: The specified key does not exist.
Key: voucher
RequestId: 7A08F32C18D3C6D3
HostId: 6jTd5D5QDU+AP4vo+uRcHHVT5WeRAKjoPeqVb39xoKZZSvWWz/9TsNp41TbuKXmtpYbLZJiyqwE=
```

I already tried another bucket policy and I set every file to public, but it won't work for me.
Anyone has a solution? Please help.

答:
Your bucket policy Resource property needs to contain, note the /*:

```<code>"Resource":["arn:aws:s3:::bucketname/*"]
</code>```

You also need to set the error document to be your index.html

Title: AWS S3 bucket "404 Not Found"

Body:
At the moment I'm hosting a bundled Angular-2 App in an AWS S3 bucket, so it only contains .html and .js files.

The absolute path http://example.com/ does work but if I switch to any links, such as http://example.com/testsite it returns 404 error as below:

404 Not Found
Code: NoSuchKey
Message: The specified key does not exist.
Key: voucher
RequestId: 7A08F32C18D3C6D3
HostId: 6jTd5D5QDU+AP4vo+uRcHHVT5WeRAKjoPeqVb39xoKZZSvWWz/9TsNp41TbuKXmtpYbLZJiyqwE=

I already tried another bucket policy and I set every file to public, but it won't work for me.
Anyone has a solution? Please help.

Body:
Your bucket policy Resource property needs to contain, note the /*:

"Resource":["arn:aws:s3:::bucketname/*"]

You also need to set the error document to be your index.html


问:
Passing values to other components using props in reactjs
I'm binding some text values when a certain div is clicked in my react application. Now i'm facing a problem on passing these text values to another component using props.

My code looks like this

```<code>class PostOptionBar extends Component {

    constructor() {
        super();

        this.state = {

            postType: 'text',

        }

    }

    textType(postType) {

        this.setState({postType});

    }

    render() {

        return (

            <div className="post_type_selection_div">

                <div className="post_type_btn">

                    <div className="horiz_center" onClick={this.textType.bind(this,'text')}>
                        <img src={StarIcon} className="post_type_icon"/>
                        <a className="post_type_text">Text</a>
                    </div>

                </div>

                <div className="post_type_btn" onClick={this.textType.bind(this,'imageVote')}>

                    <div className="horiz_center">
                        <img src={StarIcon} className="post_type_icon"/>
                        <a className="post_type_text">Image poll</a>
                    </div>

                </div>

                <div className="post_type_btn" onClick={this.textType.bind(this,'poll')}>

                    <div className="horiz_center">
                        <img src={StarIcon} className="post_type_icon"/>
                        <a className="post_type_text">Text poll</a>
                    </div>

                </div>

            </div>

        );
    }
}

export default PostOptionBar;
</code>```

I can bind the values successfully within this class. If i log the postType i can clearly see that. But i want to pass postType to another component. I'm loading PostOptionBar in my other component like this.

```<code> <div className="polaroid">
   <PostOptionBar/>
 <div>
</code>```

I'm trying to do something like this in my 2nd component.But because i cannot pass postType from my 1st component to 2nd one i cannot do this.

```<code>    renderTab() {

        switch (this.state.postType) {
            case 'text':
                return <TextPost/>
            case 'imageVote':
                return <ImageVote/>
            case 'poll':
                return <TextVotePost/>

        }
    }
</code>```

答:
set state using

```<code><Component2 postType={this.state.postType}/>
</code>```

and fetch in component2 using

```<code>this.props.postType
</code>```

Body:
I'm binding some text values when a certain div is clicked in my react application. Now i'm facing a problem on passing these text values to another component using props.

My code looks like this

class PostOptionBar extends Component {

    constructor() {
        super();

        this.state = {

            postType: 'text',

        }

    }

    textType(postType) {

        this.setState({postType});

    }

    render() {

        return (

                        Text

                        Image poll

                        Text poll

        );
    }
}

export default PostOptionBar;

I can bind the values successfully within this class. If i log the postType i can clearly see that. But i want to pass postType to another component. I'm loading PostOptionBar in my other component like this.

   <PostOptionBar/>

I'm trying to do something like this in my 2nd component.But because i cannot pass postType from my 1st component to 2nd one i cannot do this.

    renderTab() {

        switch (this.state.postType) {
            case 'text':
                return <TextPost/>
            case 'imageVote':
                return <ImageVote/>
            case 'poll':
                return <TextVotePost/>

        }
    }

Body:
set state using

<Component2 postType={this.state.postType}/>

and fetch in component2 using

this.props.postType


问:
How can I add an assembly binding redirect to a .net core unit test project?
I'm trying to create a .net core unit test project against framework 4.6.1 which tests an project dependent on Microsoft.SqlServer.Types (10.0.0.0). Prior to .net core I'd add an app.config file with the binding redirect.  I've tried this but the binding redirect does not seem to be picked up when I run from visual studio. What can I do to fix the binding redirect?</p>

答:
Referencing the NuGet package Microsoft.NET.Test.Sdk >= 15.3.0 (I used Microsoft.NET.Test.Sdk 15.3.0-preview-20170601-03) solved this problem for me. That package automatically turns on the MSBuild properties mentioned in @Mardoxx's answer.

(I got this info from Martin Andreas Ullrich at https://github.com/NuGet/Home/issues/5335#issuecomment-306318810.)


问:
Understanding how Transcrypt autotests document the code
The autotests are an integral part of the documentation of Transcrypt. However I am struggling to understand how they reveal expected behavior.  For example in:
https://github.com/QQuick/Transcrypt/blob/master/transcrypt/development/automated_tests/transcrypt/proxies/init.py

I can't really tell what are the right/expected answers.  How does one interpret tests like the following?

```<code>autoTester.check (b.p, b.q, b.r, b.s)
b.p = 4
b.r = 5
autoTester.check (b.p, b.q, b.r, b.s)
</code>```

答:
The autotests are run both under CPython and Transcrypt. The outcomes are automatically verified to be identical when loading the result into your browser. This is known as "back to back testing" and it is what the calls to the checkfunction do. So correct behaviour for Transcrypt is simply ("operationally") defined as just CPython behavior. Python, like most scripting languages, lacks a formal semantics specification.

Transcrypt supports some 95% of CPython. The internals of Transcrypt, being a Python to JavaScript compiler, are quite different. This especially holds for the so called "magic methods" of CPython (the ones starting and ending with __), although, e.g. for operator overloading, many of them are supported by Transcrypt as well.  All features that are in autotests are supported with identical behavior, so together they lay down "what  you can do" in Transcrypt.

You can run the autotests yourself as follows, e.g. for the Transcrypt basic tests:

Go to folder .../development/automated_tests/transcrypt in your Transcrypt installation

At the command prompt type: transcrypt -r -c -da autotest.py

After that, at the command prompt type: transcrypt -c -da autotest.py

Open the generated file autotest.html in your browser

Click on the blue (or, not to be hoped, red) lines to see the outcome of the code to be compared. It should be unsurprising: All that the autotests do is indeed confirming Transcrypt behaviour on them is just CPython behaviour.

Autotest results for "Hello world" with deliberate error:

Transcrypt's basic features autotest results:

The value of the autotests is twofold:

Whenever a feature is added to Transcrypt, they make it easy to assure nothing has fallen over (regression test)

Reading throught the source of the autotests will give a good impression of which features are supported.

Of course a test like

```<code>autoTester.check (b.p, b.q, b.r, b.s)
b.p = 4
b.r = 5
autoTester.check (b.p, b.q, b.r, b.s)
</code>```

, although required for complete coverage, is quite trivial. However e.g. operator overloading code like

```<code>def __matmul__ (self, other):
    result = Matrix (self.nRows, other.nCols)
    for iTargetRow in range (result.nRows):
        for iTargetCol in range (result.nCols):
            for iTerm in range (self.nCols):
                result._ [iTargetRow][iTargetCol] += self._ [iTargetRow][iTerm] * other._ [iTerm][iTargetCol]
    return result
</code>```

isn't.

Code for library packages can also be autotested, and with complicated mathematical algorithms, e.g. the 2D FFT (transforming a image to a frequency array using complex numbers, part of Numscrypt) this is a necessity, to keep code like

```<code>__pragma__ ('opov')

orig2 = num.zeros ((128, 128), 'complex128')
orig2 [32 : 96, 32 : 96] = num.ones ((64, 64), 'complex128')

autoTester.check ('Original samples', num.round (orig2 + delta, 3) [64 : 68, 16 : 112] .tolist (), '<br>')

if transpiled:
    timeStartFft = getNow ()

freqs2 = fft.fft2 (orig2)
if transpiled:
    timeStopFft = getNow ()

autoTester.check ('Frequencies', num.round (freqs2 + delta, 3)  [64 : 68, 16 : 112] .tolist (), '<br>')

if transpiled:
    timeStartIfft = getNow ()
reconstr2 = fft.ifft2 (freqs2)
if transpiled:
    timeStopIfft = getNow ()

if transpiled:
    print ('FFT2 for {} samples took {} ms'.format (orig2.size, timeStopFft - timeStartFft))
    print ('IFFT2 for {} samples took {} ms'.format (orig2.size, timeStopIfft - timeStartIfft))

autoTester.check ('Reconstructed samples', num.round (reconstr2 + delta, 3)  [64 : 68, 16 : 112] .tolist (), '<br>')

__pragma__ ('noopov')
</code>```

from breaking. So whenever someone contributes to Transcrypt, he/she is encouraged to include an autotest. A good example of this is the regular expression module, which came with a fair amount of autotests.

Note that the autotests will hardly help you learn Python as such. There are many tutorials and books on that, e.g. "Python in a Nutshell" by Alex Martelli, Anna Ravenscroft and Steve Holden.

Some more info on the inner workings of Transcrypts autotest facility is found here:

http://www.transcrypt.org/docs/html/autotesting_transcrypt.html

Body:
The autotests are an integral part of the documentation of Transcrypt. However I am struggling to understand how they reveal expected behavior.  For example in:
https://github.com/QQuick/Transcrypt/blob/master/transcrypt/development/automated_tests/transcrypt/proxies/init.py

I can't really tell what are the right/expected answers.  How does one interpret tests like the following?

autoTester.check (b.p, b.q, b.r, b.s)
b.p = 4
b.r = 5
autoTester.check (b.p, b.q, b.r, b.s)

Body:
The autotests are run both under CPython and Transcrypt. The outcomes are automatically verified to be identical when loading the result into your browser. This is known as "back to back testing" and it is what the calls to the checkfunction do. So correct behaviour for Transcrypt is simply ("operationally") defined as just CPython behavior. Python, like most scripting languages, lacks a formal semantics specification.

Transcrypt supports some 95% of CPython. The internals of Transcrypt, being a Python to JavaScript compiler, are quite different. This especially holds for the so called "magic methods" of CPython (the ones starting and ending with __), although, e.g. for operator overloading, many of them are supported by Transcrypt as well.  All features that are in autotests are supported with identical behavior, so together they lay down "what  you can do" in Transcrypt.

You can run the autotests yourself as follows, e.g. for the Transcrypt basic tests:

Go to folder .../development/automated_tests/transcrypt in your Transcrypt installation

At the command prompt type: transcrypt -r -c -da autotest.py

After that, at the command prompt type: transcrypt -c -da autotest.py

Open the generated file autotest.html in your browser

Click on the blue (or, not to be hoped, red) lines to see the outcome of the code to be compared. It should be unsurprising: All that the autotests do is indeed confirming Transcrypt behaviour on them is just CPython behaviour.

Autotest results for "Hello world" with deliberate error:

Transcrypt's basic features autotest results:

The value of the autotests is twofold:

Whenever a feature is added to Transcrypt, they make it easy to assure nothing has fallen over (regression test)

Reading throught the source of the autotests will give a good impression of which features are supported.

Of course a test like

autoTester.check (b.p, b.q, b.r, b.s)
b.p = 4
b.r = 5
autoTester.check (b.p, b.q, b.r, b.s)

, although required for complete coverage, is quite trivial. However e.g. operator overloading code like

def __matmul__ (self, other):
    result = Matrix (self.nRows, other.nCols)
    for iTargetRow in range (result.nRows):
        for iTargetCol in range (result.nCols):
            for iTerm in range (self.nCols):
                result._ [iTargetRow][iTargetCol] += self._ [iTargetRow][iTerm] * other._ [iTerm][iTargetCol]
    return result

isn't.

Code for library packages can also be autotested, and with complicated mathematical algorithms, e.g. the 2D FFT (transforming a image to a frequency array using complex numbers, part of Numscrypt) this is a necessity, to keep code like

__pragma__ ('opov')

orig2 = num.zeros ((128, 128), 'complex128')
orig2 [32 : 96, 32 : 96] = num.ones ((64, 64), 'complex128')

autoTester.check ('Original samples', num.round (orig2 + delta, 3) [64 : 68, 16 : 112] .tolist (), '<br>')

if transpiled:
    timeStartFft = getNow ()

freqs2 = fft.fft2 (orig2)
if transpiled:
    timeStopFft = getNow ()

autoTester.check ('Frequencies', num.round (freqs2 + delta, 3)  [64 : 68, 16 : 112] .tolist (), '<br>')

if transpiled:
    timeStartIfft = getNow ()
reconstr2 = fft.ifft2 (freqs2)
if transpiled:
    timeStopIfft = getNow ()

if transpiled:
    print ('FFT2 for {} samples took {} ms'.format (orig2.size, timeStopFft - timeStartFft))
    print ('IFFT2 for {} samples took {} ms'.format (orig2.size, timeStopIfft - timeStartIfft))

autoTester.check ('Reconstructed samples', num.round (reconstr2 + delta, 3)  [64 : 68, 16 : 112] .tolist (), '<br>')

__pragma__ ('noopov')

from breaking. So whenever someone contributes to Transcrypt, he/she is encouraged to include an autotest. A good example of this is the regular expression module, which came with a fair amount of autotests.

Note that the autotests will hardly help you learn Python as such. There are many tutorials and books on that, e.g. "Python in a Nutshell" by Alex Martelli, Anna Ravenscroft and Steve Holden.

Some more info on the inner workings of Transcrypts autotest facility is found here:

http://www.transcrypt.org/docs/html/autotesting_transcrypt.html


问:
Can't open behance.net from phantomjs
I would like to open behance.net via phantomjs.

Unfortunately, Behance didn't open. It looks like error page from behance.

Here is my code:

```<code>page.settings.userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36';

page.open( "https://www.behance.net/gallery/51611361/Sound-Logo-Free-Download", function( status )
{
    if(status === "success")
    {

        page.injectJs('jquery.js');

        var result = page.evaluate(function()
        {
            console.log( $("body").html() );
            return 0
        });
        phantom.exit();
    }
});
</code>```

UPD

I rendered the page to jpeg, and it is just a black screen.

UPD 2. SOLUTION

Behance used 3 iframe inside the page, so onLoadFinished invokes 3 times. But when you call

```<code>open("url", function(){
    console.log('loaded'); // only one
})
</code>```

Solution:
write onLoadFinished function outside open function

```<code>page.onLoadFinished = function(status)
{
    console.log('loaded'); // three times. On three the page is loaded
}
</code>```

答:
We notice you are using an outdated version of
  Internet Explorer. This version is
  not supported by Behance.

This site doesn't like old IE versions (and I won't blame it).

Use a custom user userAgent: http://phantomjs.org/api/webpage/property/settings.html

This will prevent Phantom to request the page as Internet Explorer, and the site will accept to load.

Title: Can't open behance.net from phantomjs

Body:
I would like to open behance.net via phantomjs.

Unfortunately, Behance didn't open. It looks like error page from behance.

Here is my code:

page.settings.userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36';

page.open( "https://www.behance.net/gallery/51611361/Sound-Logo-Free-Download", function( status )
{
    if(status === "success")
    {

        page.injectJs('jquery.js');

        var result = page.evaluate(function()
        {
            console.log( $("body").html() );
            return 0
        });
        phantom.exit();
    }
});

UPD

I rendered the page to jpeg, and it is just a black screen.

UPD 2. SOLUTION

Behance used 3 iframe inside the page, so onLoadFinished invokes 3 times. But when you call

open("url", function(){
    console.log('loaded'); // only one
})

Solution:
write onLoadFinished function outside open function

page.onLoadFinished = function(status)
{
    console.log('loaded'); // three times. On three the page is loaded
}