问:
Including file inside a class php
I am doing something using classes in php for very first time.
I am trying to fetch an return object array items in class.

This is my class

```<code>class User {

    $dbconn = include("config.php");
    private $dbHost     = $dbconn->host;
    private $dbUsername = $dbconn->username;
    private $dbPassword = $dbconn->pass;
    private $dbName     = $dbconn->database;
    private $userTbl    = 'users';

    function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " . $conn->connect_error);
            }else{
                $this->db = $conn;
            }
        }
    }
}
</code>```

This is my config.php file

```<code>return (object) array(
    'host' => 'localhost',
    'username' => 'my_user',
    'pass' => 'my_pass',
    'database' => 'my_db'
);
</code>```

How do i do it?

```<code>PHP Parse error:  syntax error, unexpected '$dbconn' (T_VARIABLE)
</code>```

答:
Maybe you should change in your code to </p>

```<code>function __construct()
    {
        //included db file
        include 'config.php';
        if (!isset($this->db))
        {
//code here
}
</code>```

Title: Including file inside a class php

Body:
I am doing something using classes in php for very first time.
I am trying to fetch an return object array items in class.

This is my class

class User {

    $dbconn = include("config.php");
    private $dbHost     = $dbconn->host;
    private $dbUsername = $dbconn->username;
    private $dbPassword = $dbconn->pass;
    private $dbName     = $dbconn->database;
    private $userTbl    = 'users';

    function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " . $conn->connect_error);
            }else{
                $this->db = $conn;
            }
        }
    }
}

This is my config.php file

return (object) array(
    'host' => 'localhost',
    'username' => 'my_user',
    'pass' => 'my_pass',
    'database' => 'my_db'
);

How do i do it?

PHP Parse error:  syntax error, unexpected '$dbconn' (T_VARIABLE)

Body:
Maybe you should change in your code to

function __construct()
    {
        //included db file
        include 'config.php';
        if (!isset($this->db))
        {
//code here
}


来源: stackexchange

问:
Player-turn based Dice game (having trouble with loops)
Background; I'm trying to create a dice game for multi-players where you can choose how many players, sides on the die and dice's themselves you want in the game. And players each take a turn rolling n amount of dices and per each roll the score gets appended to the player classes playerScore property. Once a player reaches X amount of points, player is declared a winner.

Problem; The below code is part of the "Game" class. When I compile the code, the game does what I expect for the most part; it rolls 5 dices each turn per player and appends the points to said player, but once the player reaches 100 points, the player is declared a winner, but the die's are rolled again for another player, despite the fact that the while loop is invalidated. The way i see it, the problem is with the for loop, but I have no idea how to fix this, i tried "break" but it only breaks from the if statement.

My program has 3 classes; Die, Player, Game. If you need more information or screen shots. I can provide them.

P.S. If you think this code could be improved, please comment, I'd be glad to hear it out.

答:
I think your flow was just a little off, this may work better. To me the real issue was you should have rolled the dice first, then checked if it was a win. This would make your WHILE work properly.</p>

```<code>public void StartGame(int maxPoints)
{
    while (!gameEnded)
    {
        for (int i = 0; i < playerArray.Length; i++)
        {
           playerArray[i].PlayerScore += rollAllDice();
           Console.WriteLine("'{0}': {1}", playerArray[i].PlayerName, playerArray[i].PlayerScore);

            if(playerArray[i].PlayerScore >= maxPoints){
                Console.WriteLine("Congratulations, Player '{0}' has won by reaching {1} points.",playerArray[i].PlayerName, playerArray[i].PlayerScore);
                gameEnded = true;
                break;
            }
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I think your flow was just a little off, this may work better. To me the real issue was you should have rolled the dice first, then checked if it was a win. This would make your WHILE work properly.

public void StartGame(int maxPoints)
{
    while (!gameEnded)
    {
        for (int i = 0; i < playerArray.Length; i++)
        {
           playerArray[i].PlayerScore += rollAllDice();
           Console.WriteLine("'{0}': {1}", playerArray[i].PlayerName, playerArray[i].PlayerScore);

            if(playerArray[i].PlayerScore >= maxPoints){
                Console.WriteLine("Congratulations, Player '{0}' has won by reaching {1} points.",playerArray[i].PlayerName, playerArray[i].PlayerScore);
                gameEnded = true;
                break;
            }
        }
    }
}


问:
Django Form Not Validating
I want to implement forgot password functionality. In my verification code function, form is not validating.
Here is my Views File:

```<code>def getVerCode(request):
    if (request.method == 'POST'):
        form = VerCodeForm(request.POST)
        print(form.errors)
        if (form.is_valid()):
            print('VALID')
            code = request.POST.get('verCode', '')
            print('GETVERCODE : ', verCode)
            if (code == verCode):
                pass
            return HttpResponseRedirect('/custom/GetPassword', {'form': form})
    else:
        form = VerCodeForm()
    return render_to_response('EmailVerification.html', {'form': form})
</code>```

Template:

```<code>{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'FormStyle.css' %}" />

{% block body %}
    <div class = "formArea"> {% csrf_token %}
        <label> Enter the verification code sent to your email account: </label>
        {{ hidden_email }}
        <div class="formFields">
            <form method="POST">
                <input type="text" name = "email" size="50"> </input>
                {{ form.verCode.errors }}
                <input type="submit" value="Submit">
            </form>
        </div>
    </div>
{% endblock %}
</code>```

Form:

```<code>class VerCodeForm(forms.Form):
    verCode = forms.CharField(max_length = 10)
</code>```

I tried to print the form.errors:

It says
This Field is Required!

答:
A better way would have been, if you had used loop to produce the fields in the template.

Check this out:

```<code>{% for field in form %}
<div>
<label>{{field.label_tag}}</label>
<div> {{field}} </div>
</div>
{% endfor %}
</code>```

This will help you in preventing these errors in future and writing lot less code in template.

Title: Django Form Not Validating

Body:
I want to implement forgot password functionality. In my verification code function, form is not validating.
Here is my Views File:

def getVerCode(request):
    if (request.method == 'POST'):
        form = VerCodeForm(request.POST)
        print(form.errors)
        if (form.is_valid()):
            print('VALID')
            code = request.POST.get('verCode', '')
            print('GETVERCODE : ', verCode)
            if (code == verCode):
                pass
            return HttpResponseRedirect('/custom/GetPassword', {'form': form})
    else:
        form = VerCodeForm()
    return render_to_response('EmailVerification.html', {'form': form})

Template:

{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'FormStyle.css' %}" />

{% block body %}

 {% csrf_token %}
         Enter the verification code sent to your email account:
        {{ hidden_email }}

            <form method="POST">
                <input type="text" name = "email" size="50"> </input>
                {{ form.verCode.errors }}
                <input type="submit" value="Submit">
            </form>

{% endblock %}

Form:

class VerCodeForm(forms.Form):
    verCode = forms.CharField(max_length = 10)

I tried to print the form.errors:

It says
This Field is Required!

Body:
A better way would have been, if you had used loop to produce the fields in the template.

Check this out:

{% for field in form %}
<div>
<label>{{field.label_tag}}</label>
<div> {{field}} </div>
</div>
{% endfor %}

This will help you in preventing these errors in future and writing lot less code in template.


问:
Symfony 3.2 parameter defined into parameters.php is not defined in PDO session configuration
I'm using symfony 3.2, i want to have a dynamic database connection, so i 'm importing a file parameters.php in my config.yml file :

```<code>imports:
    - { resource: parameters.php }
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: services.yml }
</code>```

In the parameters.php i am defining database_name :

```<code>$container->setParameter('database_name', $dbName);
</code>```

This work fine with native file session, but when i'm using pdo session following the symfony example :

```<code>services:
    session.handler.pdo:
        class:     Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler
        public:    false
        arguments:
           - 'mysql:host=%database_host%;port=%database_port%;dbname=%database_name%'
           - { db_username: '%database_user%', db_password: '%database_password%' }
</code>```

I'have an error on compilation :

```<code> [Symfony\Component\DependencyInjection\Exception\RuntimeException]
  A string value must be composed of strings and/or numbers, but found parameter "database_name" of type boolean inside string value "mysql:host=%database_host%;port=%database_port%;dbname=%database_name%".
</code>```

It's like symfony don't know the parameter "database_name".

Can anyone help me ?

答:
OK, it's seems not to be the way to do it ...
Finally i've create a Custom ConnectionFactory

```<code>use Doctrine\Bundle\DoctrineBundle\ConnectionFactory;

class MyConnectionFactory extends ConnectionFactory {

    public function createConnection(array $params, \Doctrine\DBAL\Configuration $config = null, \Doctrine\Common\EventManager $eventManager = null, array $mappingTypes = array()) {

      // Determine here params ....

        $params['dbname'] = $dbName;
        $params['host'] = $dbHost
        $params['user'] = $dbUser
        $params['password'] = $dbCode;

        return parent::createConnection($params, $config, $eventManager, $mappingTypes);
    }
</code>```

It's work !

Body:
I'm using symfony 3.2, i want to have a dynamic database connection, so i 'm importing a file parameters.php in my config.yml file :

imports:
    - { resource: parameters.php }
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: services.yml }

In the parameters.php i am defining database_name :

$container->setParameter('database_name', $dbName);

This work fine with native file session, but when i'm using pdo session following the symfony example :

services:
    session.handler.pdo:
        class:     Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler
        public:    false
        arguments:
           - 'mysql:host=%database_host%;port=%database_port%;dbname=%database_name%'
           - { db_username: '%database_user%', db_password: '%database_password%' }

I'have an error on compilation :

 [Symfony\Component\DependencyInjection\Exception\RuntimeException]
  A string value must be composed of strings and/or numbers, but found parameter "database_name" of type boolean inside string value "mysql:host=%database_host%;port=%database_port%;dbname=%database_name%".

It's like symfony don't know the parameter "database_name".

Can anyone help me ?

Body:
OK, it's seems not to be the way to do it ...
Finally i've create a Custom ConnectionFactory

use Doctrine\Bundle\DoctrineBundle\ConnectionFactory;

class MyConnectionFactory extends ConnectionFactory {

    public function createConnection(array $params, \Doctrine\DBAL\Configuration $config = null, \Doctrine\Common\EventManager $eventManager = null, array $mappingTypes = array()) {

      // Determine here params ....

        $params['dbname'] = $dbName;
        $params['host'] = $dbHost
        $params['user'] = $dbUser
        $params['password'] = $dbCode;

        return parent::createConnection($params, $config, $eventManager, $mappingTypes);
    }

It's work !


问:
Liferay 7 ignores AssetEntryQuery parameters
AssetEntryQuery is ignoring all the parameters I set, thus executing a wildcard query and retrieving all my asset entries.

Snippet of what I'm doing right now:

```<code>long[] classTypeIds = new long[] { 30837 };

AssetEntryQuery assetQuery = new AssetEntryQuery();
assetQuery.setClassTypeIds(classTypeIds);

List<AssetEntry> entries = AssetEntryLocalServiceUtil.getEntries(assetQuery);

foreach (AssetEntry entry : entries) {
    System.out.printf("Entry with classTypeId %d expected %d", entry.getClassTypeId(), 30837);
}
</code>```

When I execute this code, it returns a List of ALL the entries from liferay without their classTypeId being filtered.

Output:

```<code>[...]
Entry with classTypeId 0 expected 30837
Entry with classTypeId 0 expected 30837
Entry with classTypeId 28920 expected 30837
Entry with classTypeId 30331 expected 30837
Entry with classTypeId 30837 expected 30837
Entry with classTypeId 30837 expected 30837
Entry with classTypeId 30837 expected 30837
Entry with classTypeId 30921 expected 30837
[...]
</code>```

Am I missing something so Liferay is ignoring my AssetEntryQuery params or is it a bug within Liferay itself?

答:
I don't know if it's intentional or not (probably not), but in the assetentry table of my DB (I'm only looking at it for dev purposes, as it's never recommended to do anything directly to the DB), the classtypeid field is 0 for all entries in my build of the latest liferay-portal master branch. This is just a shot in the dark, but you could try calling

AssetEntryQuery.setClassNameIds

instead of setClassTypeIds, and see if that does the trick.

Body:
AssetEntryQuery is ignoring all the parameters I set, thus executing a wildcard query and retrieving all my asset entries.

Snippet of what I'm doing right now:

long[] classTypeIds = new long[] { 30837 };

AssetEntryQuery assetQuery = new AssetEntryQuery();
assetQuery.setClassTypeIds(classTypeIds);

List<AssetEntry> entries = AssetEntryLocalServiceUtil.getEntries(assetQuery);

foreach (AssetEntry entry : entries) {
    System.out.printf("Entry with classTypeId %d expected %d", entry.getClassTypeId(), 30837);
}

When I execute this code, it returns a List of ALL the entries from liferay without their classTypeId being filtered.

Output:

[...]
Entry with classTypeId 0 expected 30837
Entry with classTypeId 0 expected 30837
Entry with classTypeId 28920 expected 30837
Entry with classTypeId 30331 expected 30837
Entry with classTypeId 30837 expected 30837
Entry with classTypeId 30837 expected 30837
Entry with classTypeId 30837 expected 30837
Entry with classTypeId 30921 expected 30837
[...]

Am I missing something so Liferay is ignoring my AssetEntryQuery params or is it a bug within Liferay itself?


问:
none latin names of variables in c#
I have named my button object (WinForms) with all hebrew letters and then added click event... and it worked.

Is this some new lang feature I've missed?

```<code>this.כפתור = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// כפתור
//
this.כפתור.Location = new System.Drawing.Point(58, 48);
this.כפתור.Name = "כפתור";
this.כפתור.Size = new System.Drawing.Size(75, 23);
this.כפתור.TabIndex = 0;
this.כפתור.Text = "button1";
this.כפתור.UseVisualStyleBackColor = true;
this.כפתור.Click += new System.EventHandler(this.button1_Click);

private void button1_Click(object sender, EventArgs e)
{
כפתור.Text = "BLAH BLAH";
}
</code>```

答:
The C# language specification shows what you can and cannot use for identifiers.

http://msdn.microsoft.com/en-us/library/aa664670%28v=VS.71%29.aspx

It basically says that unicode characters are permitted for certain sets of characters, and I'm assuming the set that includes Hebrew is in that list. (I don't know the set name for Hebrew characters sets)

ContentLicense: CC BY-SA 2.5

Title: none latin names of variables in c#

Body:
I have named my button object (WinForms) with all hebrew letters and then added click event... and it worked.

Is this some new lang feature I've missed?

this.כפתור = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// כפתור
//
this.כפתור.Location = new System.Drawing.Point(58, 48);
this.כפתור.Name = "כפתור";
this.כפתור.Size = new System.Drawing.Size(75, 23);
this.כפתור.TabIndex = 0;
this.כפתור.Text = "button1";
this.כפתור.UseVisualStyleBackColor = true;
this.כפתור.Click += new System.EventHandler(this.button1_Click);

private void button1_Click(object sender, EventArgs e)
{
כפתור.Text = "BLAH BLAH";
}


问:
Handling string search and substitution in R
I am a beginner in R, used Matlab before and I have been searching around for a solution to my problem but I do not appear to find one.
I have a very large vector with text entries. Something like

CAT06
6CAT
CAT 6
DOG3
3DOG

I would like to be able to find a function such that: If an entry is found and it contains "CAT" & "6" (no matter position), substitute cat6. If an entry is found and it contains "DOG" & "3" (no matter position) substitute dog3. So the outcome should be:

cat6 cat6 cat6 dog3 dog3

Can anybody help on this? Thank you very much, find myself a bit lost!

答:
The input shown in the question is ambiguous as per my comment under the question. We show how to calculate it depending on which of three assumptions was intended.

1) vector input with embedded spaces  Remove the digits and spaces ("[0-9 ]") in the first gsub and remove the non-digits ("\\D") in the second gsub converting to numeric to avoid leading zeros and then paste together:

```<code>x1 <- c("CAT06", "6CAT", "CAT 6", "DOG3", "3DOG") # test input

paste0(gsub("[0-9 ]", "", x1), as.numeric(gsub("\\D", "", x1)))
## [1] "CAT6" "CAT6" "CAT6" "DOG3" "DOG3"
</code>```

2) single string Form chars by removing all digits and scanning the result in.  Then form nums by removing everything except digits and spaces and scanning the result.  Finally paste these together.

```<code>x2 <- "CAT06 6CAT CAT 6 DOG3 3DOG" # test input

chars <- scan(textConnection(gsub("\\d", "", x2)), what = "", quiet = TRUE)
nums <- scan(textConnection(gsub("[^ 0-9]", "", x2)), , quiet = TRUE)
y <- paste0(chars, nums)
y
## [1] "CAT6" "CAT6" "CAT6" "DOG3" "DOG3"
</code>```

or if a single output stirng is wanted add this:

```<code>paste(y, collapse = " ")
</code>```

3) vector input without embedded spaces  Reduce this to case (2) and then apply (2).

```<code>x3 <- c("CAT06", "6CAT", "CAT", "6", "DOG3", "3DOG") # test input

xx <- paste(x3, collapse = " ")
chars <- scan(textConnection(gsub("\\d", "", xx)), what = "", quiet = TRUE)
nums <- scan(textConnection(gsub("[^ 0-9]", "", xx)), , quiet = TRUE)
y <- paste0(chars, nums)
y
## [1] "CAT6" "CAT6" "CAT6" "DOG3" "DOG3"
</code>```

Note that this actually works for all three inputs.  That is if we replace x3 with x1 or x2 it still works and as with (2) then if a single output string is wanted then add paste(y, collapse = " ")

Body:
The input shown in the question is ambiguous as per my comment under the question. We show how to calculate it depending on which of three assumptions was intended.

1) vector input with embedded spaces  Remove the digits and spaces ("[0-9 ]") in the first gsub and remove the non-digits ("\\D") in the second gsub converting to numeric to avoid leading zeros and then paste together:

x1 <- c("CAT06", "6CAT", "CAT 6", "DOG3", "3DOG") # test input

paste0(gsub("[0-9 ]", "", x1), as.numeric(gsub("\\D", "", x1)))
## [1] "CAT6" "CAT6" "CAT6" "DOG3" "DOG3"

2) single string Form chars by removing all digits and scanning the result in.  Then form nums by removing everything except digits and spaces and scanning the result.  Finally paste these together.

x2 <- "CAT06 6CAT CAT 6 DOG3 3DOG" # test input

chars <- scan(textConnection(gsub("\\d", "", x2)), what = "", quiet = TRUE)
nums <- scan(textConnection(gsub("[^ 0-9]", "", x2)), , quiet = TRUE)
y <- paste0(chars, nums)
y
## [1] "CAT6" "CAT6" "CAT6" "DOG3" "DOG3"

or if a single output stirng is wanted add this:

paste(y, collapse = " ")

3) vector input without embedded spaces  Reduce this to case (2) and then apply (2).

x3 <- c("CAT06", "6CAT", "CAT", "6", "DOG3", "3DOG") # test input

xx <- paste(x3, collapse = " ")
chars <- scan(textConnection(gsub("\\d", "", xx)), what = "", quiet = TRUE)
nums <- scan(textConnection(gsub("[^ 0-9]", "", xx)), , quiet = TRUE)
y <- paste0(chars, nums)
y
## [1] "CAT6" "CAT6" "CAT6" "DOG3" "DOG3"

Note that this actually works for all three inputs.  That is if we replace x3 with x1 or x2 it still works and as with (2) then if a single output string is wanted then add paste(y, collapse = " ")


问:
How can I pass code into a method without it running first?
Please help as how can I achieve below in java.

```<code>public class TestUserFunctions {

    public static boolean equals(int val1, int val2){
        if(val1==val2){
            return true;
        } else{
            return false;
        }
    }
    public static Object iterateValue(String ittr, int iterations){
        for(int i=1; i <= iterations; i++){
            System.out.println("Printing iteration #"+i);
        }
        return ittr;
    }

    private static void ifElse(boolean condition, Object returnstr, Object elsestr){
        if(condition){
            System.out.println("TRUE");
            //Need a code here which will iterate string value only once.
        } else{
            System.out.println("FALSE");
            //Need a code here which will iterate string value thrice as specified.
        }
    }

    public static void main(String[] args){
        ifElse(equals(1, 1), iterateValue("Value", 1), iterateValue("Value", 3));
    }
}
</code>```

I may be wrong in many aspect here with my above code. I am sorry for that.
The expected output here is

```<code>TRUE
Printing iteration #1
</code>```

In case of ifElse(equals(1, 1), iterateValue("Value", 1), iterateValue("Value", 3)); the expected output is

```<code>FALSE
Printing iteration #1
Printing iteration #2
Printing iteration #3
</code>```

答:
Your problem can be expressed more succinctly like this:

```<code>public class Demo() {

   static int x = 0;

   static int incrementAndReturnX() {
       x++;
       return x;
   }

   static void ifElse(boolean predicate, int t, int f) {
       if(predicate) {
          return t;
       } else {
          return f;
       }
   }

   static void main(String... args) {
       System.out.println(ifElse(false, incrementAndReturnX(), incrementAndReturnX());
   }
}
</code>```

This prints 2.. Why is this, and how can we make it return 1?

The answer is the order in which Java calls methods. When it deals with ifElse(true, incrementAndReturnX(), incrementAndReturnX()), it runs the methods passed as parameters, so as to get an object or a primitive. Then it invokes ifElse().

So:

Java notes that true is a primitive. Nothing to do. Move on.

Java calls incrementAndReturnX(). x is incremented. 1 is returned.

Java calls incrementAndReturnX() again. x is incremented. 2 is returned.

Java uses the values it has collected to call ifElse(false, 1, 2)

You can see that the result of this is 2.

What we need is some way of passing a method to the ifElse() routine, as if it was an object, so that it can choose whether to run it or not. In Java 7, the only way we could do that was by creating classes containing our methods, so we could pass them around.

```<code> interface IntegerSupplier() {
      int get();
 }

 ...

 final int[] x = new int[1];

 IntegerSupplier incrementAndReturnX = new IntegerSupplier() {
      x[0] += 1;
      return x[0];
 };
</code>```

Note this is using anonymous class syntax. We are creating a new class here, and creating an instance of it, without giving it a name.

We are also wrapping x in an array, because the inner class can only refer to final variables, and we need to be able to modify the value.

```<code> public int ifOrElse(boolean predicate, IntegerSupplier t, IntegerSupplier f) {
   if(true) {
       return t.get();
   } else {
       return f.get();
   }
 }
</code>```

The key here is that the code that increments x is in a method that's not called until inside the if block.

As of Java 8, we have a much neater way of doing the same thing. We can very succinctly declare something very like our IntegerSupplier using what is called a lambda:

```<code>  Supplier<Integer> incrementAndReturnX = () {
      x[0]++;
      return x;
  }

 public int ifOrElse(boolean predicate, Supplier<Integer> t, Supplier<Integer> f) {
   if(true) {
       return t.get();
   } else {
       return f.get();
   }
 }
</code>```

(java.util.function.Supplier is provided by the JRE: we don't need to declare our own)

This whole way of thinking is called functional programming, and is very powerful and expressive.

Body:
Please help as how can I achieve below in java.

public class TestUserFunctions {

    public static boolean equals(int val1, int val2){
        if(val1==val2){
            return true;
        } else{
            return false;
        }
    }
    public static Object iterateValue(String ittr, int iterations){
        for(int i=1; i <= iterations; i++){
            System.out.println("Printing iteration #"+i);
        }
        return ittr;
    }

    private static void ifElse(boolean condition, Object returnstr, Object elsestr){
        if(condition){
            System.out.println("TRUE");
            //Need a code here which will iterate string value only once.
        } else{
            System.out.println("FALSE");
            //Need a code here which will iterate string value thrice as specified.
        }
    }

    public static void main(String[] args){
        ifElse(equals(1, 1), iterateValue("Value", 1), iterateValue("Value", 3));
    }
}

I may be wrong in many aspect here with my above code. I am sorry for that.
The expected output here is

TRUE
Printing iteration #1

In case of ifElse(equals(1, 1), iterateValue("Value", 1), iterateValue("Value", 3)); the expected output is

FALSE
Printing iteration #1
Printing iteration #2
Printing iteration #3

Body:
Your problem can be expressed more succinctly like this:

public class Demo() {

   static int x = 0;

   static int incrementAndReturnX() {
       x++;
       return x;
   }

   static void ifElse(boolean predicate, int t, int f) {
       if(predicate) {
          return t;
       } else {
          return f;
       }
   }

   static void main(String... args) {
       System.out.println(ifElse(false, incrementAndReturnX(), incrementAndReturnX());
   }
}

This prints 2.. Why is this, and how can we make it return 1?

The answer is the order in which Java calls methods. When it deals with ifElse(true, incrementAndReturnX(), incrementAndReturnX()), it runs the methods passed as parameters, so as to get an object or a primitive. Then it invokes ifElse().

So:

Java notes that true is a primitive. Nothing to do. Move on.

Java calls incrementAndReturnX(). x is incremented. 1 is returned.

Java calls incrementAndReturnX() again. x is incremented. 2 is returned.

Java uses the values it has collected to call ifElse(false, 1, 2)

You can see that the result of this is 2.

What we need is some way of passing a method to the ifElse() routine, as if it was an object, so that it can choose whether to run it or not. In Java 7, the only way we could do that was by creating classes containing our methods, so we could pass them around.

 interface IntegerSupplier() {
      int get();
 }

 ...

 final int[] x = new int[1];

 IntegerSupplier incrementAndReturnX = new IntegerSupplier() {
      x[0] += 1;
      return x[0];
 };

Note this is using anonymous class syntax. We are creating a new class here, and creating an instance of it, without giving it a name.

We are also wrapping x in an array, because the inner class can only refer to final variables, and we need to be able to modify the value.

 public int ifOrElse(boolean predicate, IntegerSupplier t, IntegerSupplier f) {
   if(true) {
       return t.get();
   } else {
       return f.get();
   }
 }

The key here is that the code that increments x is in a method that's not called until inside the if block.

As of Java 8, we have a much neater way of doing the same thing. We can very succinctly declare something very like our IntegerSupplier using what is called a lambda:

  Supplier<Integer> incrementAndReturnX = () {
      x[0]++;
      return x;
  }

 public int ifOrElse(boolean predicate, Supplier<Integer> t, Supplier<Integer> f) {
   if(true) {
       return t.get();
   } else {
       return f.get();
   }
 }

(java.util.function.Supplier is provided by the JRE: we don't need to declare our own)

This whole way of thinking is called functional programming, and is very powerful and expressive.


问:
XML to JSON getJSONArray() issues
I read XML from a URL as Follows:

```<code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import java.util.Base64;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.json.JSONObject;
import org.json.XML;

public class WebGet {

public static void disableCertificateValidation() throws MalformedURLException, IOException, NoSuchAlgorithmException, KeyManagementException {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    }
    };

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    // Install the all-trusting trust manager
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    String credentials = "user" + ":" + "psw";
    String encoding = Base64.getEncoder().encodeToString(credentials.getBytes("UTF-8"));
    URL url = new URL("someURL");
    URLConnection con = url.openConnection();
    con.setRequestProperty("Authorization", String.format("Basic %s", encoding));
    BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String apiResponse = "";
    while ((apiResponse = br.readLine()) != null) {
        sb.append(apiResponse);
    }

    System.out.println(sb);
    JSONObject jsonObj = XML.toJSONObject(sb.toString());
    System.out.println("---------------------------");
    System.out.println(jsonObj);
    jsonObj.getJSONArray("devices");

}

public static void main(String[] args){
    disableCertificateValidation();
}
}
</code>```

Everything prints and works fine except the "jsonObj.getJSONArray("devices");" which throws the following exception:

Exception in thread "main" org.json.JSONException: JSONObject["devices"] is not a JSONArray.
      at org.json.JSONObject.getJSONArray(JSONObject.java:622)

My Output is show here:

{"devices": {
    "total": 71,
    "count": 71,
    "device": [
        {
            "domain_id": 1,
            "offline": false,
            "domain_name": "Default",
            "vendor": "Cisco",
            "topology": true,
            "ip": "22.201.120.101",
            "name": "eagnmn-red-rdmvpn",
            "model": "asa",
            "id": 55
        },
        {
            "domain_id": 1,
            "offline": false,
            "domain_name": "Default",
            "vendor": "Cisco",
            "topology": true,
            "ip": "22.201.120.51",
            "name": "eagnmn-red-ras",
            "model": "asa",
            "id": 54
        },

Where am I going wrong?

答:
you need to use

```<code>JSONArray deviceArray = jsonObj.getJSONObject("devices").getJSONArray("device")
</code>```

because your object contains devices JSONObject which further contains your device JSONArray

Title: XML to JSON getJSONArray() issues

Body:
I read XML from a URL as Follows:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import java.util.Base64;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.json.JSONObject;
import org.json.XML;

public class WebGet {

public static void disableCertificateValidation() throws MalformedURLException, IOException, NoSuchAlgorithmException, KeyManagementException {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    }
    };

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    // Install the all-trusting trust manager
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    String credentials = "user" + ":" + "psw";
    String encoding = Base64.getEncoder().encodeToString(credentials.getBytes("UTF-8"));
    URL url = new URL("someURL");
    URLConnection con = url.openConnection();
    con.setRequestProperty("Authorization", String.format("Basic %s", encoding));
    BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String apiResponse = "";
    while ((apiResponse = br.readLine()) != null) {
        sb.append(apiResponse);
    }

    System.out.println(sb);
    JSONObject jsonObj = XML.toJSONObject(sb.toString());
    System.out.println("---------------------------");
    System.out.println(jsonObj);
    jsonObj.getJSONArray("devices");

}

public static void main(String[] args){
    disableCertificateValidation();
}
}

Everything prints and works fine except the "jsonObj.getJSONArray("devices");" which throws the following exception:

Exception in thread "main" org.json.JSONException: JSONObject["devices"] is not a JSONArray.
      at org.json.JSONObject.getJSONArray(JSONObject.java:622)

My Output is show here:

{"devices": {
    "total": 71,
    "count": 71,
    "device": [
        {
            "domain_id": 1,
            "offline": false,
            "domain_name": "Default",
            "vendor": "Cisco",
            "topology": true,
            "ip": "22.201.120.101",
            "name": "eagnmn-red-rdmvpn",
            "model": "asa",
            "id": 55
        },
        {
            "domain_id": 1,
            "offline": false,
            "domain_name": "Default",
            "vendor": "Cisco",
            "topology": true,
            "ip": "22.201.120.51",
            "name": "eagnmn-red-ras",
            "model": "asa",
            "id": 54
        },

Where am I going wrong?

Body:
you need to use

JSONArray deviceArray = jsonObj.getJSONObject("devices").getJSONArray("device")

because your object contains devices JSONObject which further contains your device JSONArray


问:
SQL - execute query from table cells
I have a database with one table, Queries. This table has two columns, name and Query. In column named Query I'm recording some SQL statements.

I'm trying to execute these statements after selecting them from the table.

This is my code, but output is incorrect, only the statements listed, without execution:

```<code>DECLARE @STR_QUERY NVARCHAR(max);
SET @STR_QUERY = 'SELECT Query FROM [AccHelper].[dbo].[Queries]'

EXECUTE SP_EXECUTESQL @STR_QUERY
</code>```

答:
Try below:</p>

```<code>DECLARE @STR_QUERY NVARCHAR(max);
SET @STR_QUERY = (SELECT Query FROM [AccHelper].[dbo].[Queries])

EXECUTE SP_EXECUTESQL @STR_QUERY
</code>```

ContentLicense: CC BY-SA 4.0

Title: SQL - execute query from table cells

Body:
I have a database with one table, Queries. This table has two columns, name and Query. In column named Query I'm recording some SQL statements.

I'm trying to execute these statements after selecting them from the table.

This is my code, but output is incorrect, only the statements listed, without execution:

DECLARE @STR_QUERY NVARCHAR(max);
SET @STR_QUERY = 'SELECT Query FROM [AccHelper].[dbo].[Queries]'

EXECUTE SP_EXECUTESQL @STR_QUERY

Body:
Try below:

DECLARE @STR_QUERY NVARCHAR(max);
SET @STR_QUERY = (SELECT Query FROM [AccHelper].[dbo].[Queries])

EXECUTE SP_EXECUTESQL @STR_QUERY


问:
Getting real world coordinates from Forge model
Is it possible to get the real world coordinates form the original model in the Forge viewer? It looks like when a model is loaded into the Viewer it is placed with the center of the model in the origin of the Viewer. </p>

答:
viewer.model.getData().globalOffset is what you are looking for:
Aligning Coordinate Systems in Autodesk Forge Viewer


问:
Outlook REST API 403 error while trying to fetch user emails
I am trying to fetch emails from user's outlook mail using Outlook REST API. I have been able to successfully authenticate user and get user access token, however, when I try to make an AJAX call to  Outlook REST API, I get the following error:

```<code>GET https://outlook.office.com/api/v2.0/me/messages?callback=jQuery31008093694845457056_1490285639120 403 (Forbidden)
</code>```

Also, I get following error from error function callback of AJAX:

```<code>Object {readyState: 4, status: 404, statusText: "error"}
</code>```

Here is my code:

```<code>var ADAL = new AuthenticationContext({
    instance: 'https://login.microsoftonline.com/',
    tenant: 'common',
    clientId: '',        //Intentionally left blank here

    redirectUri: 'http://localhost:8383/',
    callback: userSignedIn,
    popUp: true
});

function signIn() {
    ADAL.login();
}

function userSignedIn(err, token) {
    console.log('userSignedIn called');
    if (!err) {
        console.log(token);            //This works!
        fetchUserSentMails(token);
    } else {
        console.error("error: " + err);
    }
}

function fetchUserSentMails(token) {
    var user = ADAL.getCachedUser();
    console.log(user.profile.name);        //This works!

    $.ajax({                  //This doesn't work
        type: 'GET',
        crossDomain: true,
        url: 'https://outlook.office.com/api/v2.0/me/messages',
        dataType: 'jsonp',
        headers: {'Authorization': 'Bearer ' + token},
        success: function (res) {
            console.log(res);
        },
        error: function (x, t, m) {
            console.log(x);
            console.log(t);
            console.log(m);
        }
    });
}
</code>```

What am I doing wrong??

答: I see that you are getting timeout error. I had the exact same issue with timeout and I could only fix this by manipulating adal.js library. In this library there is a timeout of 6 seconds and it seems like it is very tight for some applications being loaded locally. To give it a quick test, you can find LOADFRAME_TIMEOUT: '6000' in adal.js and replace it with LOADFRAME_TIMEOUT: '30000', which will give you 30 seconds to load your application. I hope it works for you!</p>

Body:
I am trying to fetch emails from user's outlook mail using Outlook REST API. I have been able to successfully authenticate user and get user access token, however, when I try to make an AJAX call to  Outlook REST API, I get the following error:

GET https://outlook.office.com/api/v2.0/me/messages?callback=jQuery31008093694845457056_1490285639120 403 (Forbidden)

Also, I get following error from error function callback of AJAX:

Object {readyState: 4, status: 404, statusText: "error"}

Here is my code:

var ADAL = new AuthenticationContext({
    instance: 'https://login.microsoftonline.com/',
    tenant: 'common',
    clientId: '',        //Intentionally left blank here

    redirectUri: 'http://localhost:8383/',
    callback: userSignedIn,
    popUp: true
});

function signIn() {
    ADAL.login();
}

function userSignedIn(err, token) {
    console.log('userSignedIn called');
    if (!err) {
        console.log(token);            //This works!
        fetchUserSentMails(token);
    } else {
        console.error("error: " + err);
    }
}

function fetchUserSentMails(token) {
    var user = ADAL.getCachedUser();
    console.log(user.profile.name);        //This works!

    $.ajax({                  //This doesn't work
        type: 'GET',
        crossDomain: true,
        url: 'https://outlook.office.com/api/v2.0/me/messages',
        dataType: 'jsonp',
        headers: {'Authorization': 'Bearer ' + token},
        success: function (res) {
            console.log(res);
        },
        error: function (x, t, m) {
            console.log(x);
            console.log(t);
            console.log(m);
        }
    });
}

What am I doing wrong??


问:
Java book for experienced programmers (PHP)
I searched on few questions earlier asked here but my context is not matching exactly to them.
I am working on LAMP from past few years. I recently learnt Java SL-314 Syllabus thinking my knowledge in PHP and other PLUS some knowledge in core Java from Oracle website can be helpful.
I saw Java document is very poor compared to PHP. In PHP, one can get everything basic from the php.net site itself. For a simple thing like showing the resultset data to servlet or JSP from plain java code, I need to search a lot and still I cannot get past ArrayList etc. I was looking for a code in Java like this in PHP:

```<code>while ($row = mysql_fetch_assoc($result)) {
    echo $row["userid"];
    echo $row["fullname"];
    echo $row["userstatus"];
}
</code>```

I mean I want to use all fields the way I want.

I have a book, Java in Nutshell but that seems too theoretical. I need small book so that I can read it soon. I want to develop web app using Java. For getting help from core java, I want simple example codes to do all normal work I used to do in PHP.

Please help me find simple Java book with example code which can help me do all normal stuff one do in PHP.

答: Having recently moved to Java from other programming languages, I found little books like "Java phrasebook" by Timothy R. Fisher particularly valuable, as they contain many examples about pratical topics (strings, data structures, file management, db connection, xml parsing, threads,..): they will not make you a guru, but at least you can get immediately in touch with the language.</p>

Body:
I searched on few questions earlier asked here but my context is not matching exactly to them.
I am working on LAMP from past few years. I recently learnt Java SL-314 Syllabus thinking my knowledge in PHP and other PLUS some knowledge in core Java from Oracle website can be helpful.
I saw Java document is very poor compared to PHP. In PHP, one can get everything basic from the php.net site itself. For a simple thing like showing the resultset data to servlet or JSP from plain java code, I need to search a lot and still I cannot get past ArrayList etc. I was looking for a code in Java like this in PHP:

while ($row = mysql_fetch_assoc($result)) {
    echo $row["userid"];
    echo $row["fullname"];
    echo $row["userstatus"];
}

I mean I want to use all fields the way I want.

I have a book, Java in Nutshell but that seems too theoretical. I need small book so that I can read it soon. I want to develop web app using Java. For getting help from core java, I want simple example codes to do all normal work I used to do in PHP.

Please help me find simple Java book with example code which can help me do all normal stuff one do in PHP.


问:
Which file is this line of code looking for
I am new to working with node packages. I am trying to add canvas to my project. However I am seeing this error:

```<code>ERROR in ./~/canvas/lib/bindings.js
Module not found: Error: Can't resolve '../build/Release/canvas' in      'C:\Users\me\myapp\node_modules\canvas\lib'
@ ./~/canvas/lib/bindings.js 3:17-51
@ ./~/canvas/lib/canvas.js
@ ./app/app.js
@ ./app/components/base/base.spec.js
</code>```

I look in the bindings.js file and the only code is:

```<code>module.exports = require('../build/Release/canvas');
</code>```

I navigate to the ../build/Release/canvas folder and find 5 files named canvas with different extensions:

```<code>canvas.exp
canvas.lib
canvas.map
canvas.node
canvas.pdb
</code>```

Is the require code looking for any of these files? What is causing the 'Can't resolve' error?

答:
```<code>module.exports = require('../build/Release/canvas');
</code>```

this require will look for (depend of node configuration):
- canvas.js
- canvas.ts
- index.js
- index.ts

required file should have js moduloe structure

Body:
I am new to working with node packages. I am trying to add canvas to my project. However I am seeing this error:

ERROR in ./~/canvas/lib/bindings.js
Module not found: Error: Can't resolve '../build/Release/canvas' in      'C:\Users\me\myapp\node_modules\canvas\lib'
@ ./~/canvas/lib/bindings.js 3:17-51
@ ./~/canvas/lib/canvas.js
@ ./app/app.js
@ ./app/components/base/base.spec.js

I look in the bindings.js file and the only code is:

module.exports = require('../build/Release/canvas');

I navigate to the ../build/Release/canvas folder and find 5 files named canvas with different extensions:

canvas.exp
canvas.lib
canvas.map
canvas.node
canvas.pdb

Is the require code looking for any of these files? What is causing the 'Can't resolve' error?

Body:
module.exports = require('../build/Release/canvas');

this require will look for (depend of node configuration):
- canvas.js
- canvas.ts
- index.js
- index.ts

required file should have js moduloe structure


问:
skipLocationChange not working perfectly
I'm using skipLocationChange to navigate between 3 map components: Cesium, Leaflet and Openlayers 3. my Application is preserving location among the components as you can see in mapmip.webiks.com (old version).
in order to set the bounds when moving from component to other I'm subscribe to the following function:

```<code>setQueryBoundsOnNavigationEnd(event:NavigationEnd):void {
let urlTree:UrlTree = this.leaflet.router.parseUrl(event.url);
urlTree.queryParams['bounds'] = this.getBounds().toString();
extras.skipLocationChange = this.skipLocationChange;
return this.router.navigateByUrl(url, extras);
 }
</code>```

by this way

```<code>leaflet.router.events.filter(event => event instanceof NavigationEnd && event.url.includes("/cesium")).take(1).subscribe(this.setQueryBoundsOnNavigationEnd.bind(this));
</code>```

but when I'm get back form cesium - the url is not hidden anymore.

Thanks in advance !

答: I was missing unsubsribe(), hence there were NavigationError and the state didn't load properly</p>

Body:
I'm using skipLocationChange to navigate between 3 map components: Cesium, Leaflet and Openlayers 3. my Application is preserving location among the components as you can see in mapmip.webiks.com (old version).
in order to set the bounds when moving from component to other I'm subscribe to the following function:

setQueryBoundsOnNavigationEnd(event:NavigationEnd):void {
let urlTree:UrlTree = this.leaflet.router.parseUrl(event.url);
urlTree.queryParams['bounds'] = this.getBounds().toString();
extras.skipLocationChange = this.skipLocationChange;
return this.router.navigateByUrl(url, extras);
 }

by this way

leaflet.router.events.filter(event => event instanceof NavigationEnd && event.url.includes("/cesium")).take(1).subscribe(this.setQueryBoundsOnNavigationEnd.bind(this));

but when I'm get back form cesium - the url is not hidden anymore.

Thanks in advance !


问:
Cell styles in OpenXML spreadsheet (SpreadsheetML)
I've generated a .xlsx spreadsheet in C# using the OpenXML SDK, but can't figure out how to get cell styles working. I've been studying files produced by Excel, and can't quite figure out how it's done.

Right now, I'm creating a fill, creating a CellStyleFormat that points at the fill, creating a CellFormat that points at the index of the CellStyleFormat, then creating a CellStyle that points to the CellFormat.

Here's the code I'm using to generate the document:

```<code>Console.WriteLine("Creating document");
using (var spreadsheet = SpreadsheetDocument.Create("output.xlsx", SpreadsheetDocumentType.Workbook))
{
    Console.WriteLine("Creating workbook");
    spreadsheet.AddWorkbookPart();
    spreadsheet.WorkbookPart.Workbook = new Workbook();
    Console.WriteLine("Creating worksheet");
    var wsPart = spreadsheet.WorkbookPart.AddNewPart<WorksheetPart>();
    wsPart.Worksheet = new Worksheet();

    var stylesPart = spreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>();
    stylesPart.Stylesheet = new Stylesheet();
    stylesPart.Stylesheet.Fills = new Fills();

    // create a solid red fill
    var solidRed = new PatternFill() { PatternType = PatternValues.Solid };
    solidRed.AppendChild(new BackgroundColor { Rgb = HexBinaryValue.FromString("FF00FF00") });

    stylesPart.Stylesheet.Fills.AppendChild(new Fill { PatternFill = new PatternFill() { PatternType = PatternValues.None } });
    stylesPart.Stylesheet.Fills.AppendChild(new Fill { PatternFill = solidRed });
    stylesPart.Stylesheet.CellStyleFormats = new CellStyleFormats();
    stylesPart.Stylesheet.CellStyleFormats.AppendChild(new CellFormat { FillId = 0, ApplyFill = false });
    stylesPart.Stylesheet.CellStyleFormats.AppendChild(new CellFormat { FillId = 1, ApplyFill = true });
    stylesPart.Stylesheet.CellFormats = new CellFormats();
    stylesPart.Stylesheet.CellFormats.AppendChild(new CellFormat { FormatId = 0 });
    stylesPart.Stylesheet.CellFormats.AppendChild(new CellFormat { FormatId = 1 });
    stylesPart.Stylesheet.CellStyles = new CellStyles();
    stylesPart.Stylesheet.CellStyles.AppendChild(new CellStyle { Name = "None", FormatId = 0 });
    stylesPart.Stylesheet.CellStyles.AppendChild(new CellStyle { Name = "Solid Red", FormatId = 1 });

    stylesPart.Stylesheet.Save();

    Console.WriteLine("Creating sheet data");
    var sheetData = wsPart.Worksheet.AppendChild(new SheetData());

    Console.WriteLine("Adding rows / cells...");

    var row = sheetData.AppendChild(new Row());
    row.AppendChild(new Cell() { CellValue = new CellValue("This"),  DataType = CellValues.String });
    row.AppendChild(new Cell() { CellValue = new CellValue("is"),    DataType = CellValues.String });
    row.AppendChild(new Cell() { CellValue = new CellValue("a"),     DataType = CellValues.String });
    row.AppendChild(new Cell() { CellValue = new CellValue("test."), DataType = CellValues.String });

    sheetData.AppendChild(new Row());

    row = sheetData.AppendChild(new Row());
    row.AppendChild(new Cell() { CellValue = new CellValue("Value:"),   DataType = CellValues.String });
    row.AppendChild(new Cell() { CellValue = new CellValue("123"),      DataType = CellValues.Number });
    row.AppendChild(new Cell() { CellValue = new CellValue("Formula:"), DataType = CellValues.String });
    row.AppendChild(new Cell() { CellFormula = new CellFormula("B3"),   StyleIndex = 1 }); //

    Console.WriteLine("Saving worksheet");
    wsPart.Worksheet.Save();

    Console.WriteLine("Creating sheet list");
    var sheets = spreadsheet.WorkbookPart.Workbook.AppendChild(new Sheets());
    sheets.AppendChild(new Sheet() { Id = spreadsheet.WorkbookPart.GetIdOfPart(wsPart), SheetId = 1, Name = "Test" });

    Console.WriteLine("Saving workbook");
    spreadsheet.WorkbookPart.Workbook.Save();

    Console.WriteLine("Done.");
}
</code>```

Here's the generated XML:

workbook.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<x:workbook xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
  <x:sheets>
    <x:sheet name="Test" sheetId="1" r:id="Rbad86b8c80844a16" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" />
  </x:sheets>
</x:workbook>
</code>```

styles.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<x:styleSheet xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
  <x:fills>
    <x:fill>
      <x:patternFill patternType="none" />
    </x:fill>
    <x:fill>
      <x:patternFill patternType="solid">
        <x:bgColor rgb="FF00FF00" />
      </x:patternFill>
    </x:fill>
  </x:fills>
  <x:cellStyleXfs>
    <x:xf fillId="0" applyFill="0" />
    <x:xf fillId="1" applyFill="1" />
  </x:cellStyleXfs>
  <x:cellXfs>
    <x:xf xfId="0" />
    <x:xf xfId="1" />
  </x:cellXfs>
  <x:cellStyles>
    <x:cellStyle name="None" xfId="0" />
    <x:cellStyle name="Solid Red" xfId="1" />
  </x:cellStyles>
</x:styleSheet>
</code>```

worksheets/sheet.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<x:worksheet xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
  <x:sheetData>
    <x:row>
      <x:c t="str"><x:v>This</x:v></x:c>
      <x:c t="str"><x:v>is</x:v></x:c>
      <x:c t="str"><x:v>a</x:v></x:c>
      <x:c t="str"><x:v>test.</x:v></x:c>
    </x:row>
    <x:row />
    <x:row>
      <x:c t="str"><x:v>Value:</x:v></x:c>
      <x:c t="n"><x:v>123</x:v></x:c>
      <x:c t="str"><x:v>Formula:</x:v></x:c>
      <x:c s="1"><x:f>B3</x:f></x:c>
    </x:row>
  </x:sheetData>
</x:worksheet>
</code>```

The last cell of the last row is where I'm trying to add the style.

This all validates properly when I run it through the OpenXML SDK Productivity Tool, but, when I attempt to open the file in Excel, I get the following error:

Repaired Records: Format from /xl/styles.xml part (Styles)

The spreadsheet then shows, but the fill isn't applied.

Any idea how to go about fixing this?

答:
A more generic answer, all this I found after testing, so no documentation to point to.

Once you set a CellFormats collection in the stylesheet Excel runs a deeper validation on it.

CellFormats cannot be empty, it must have at least one CellFormat there.

Once you add a CellFormat, Excel will complain if Fills, Fonts or Borders collections are empty.

First Font is used as default for whole workbook and also Column/Row headers in Excel.

Excel will ignore first CellFormat, so just add an empty one.

If you need a Border or Fill in your format, Excel will also ignore first Border and Fill, so also add empty ones as first child in Borders and Fills.

Finally, starting in the second CellFormat (s = "1") you're good to go.

Tested in Excel 2010.

Body:
I've generated a .xlsx spreadsheet in C# using the OpenXML SDK, but can't figure out how to get cell styles working. I've been studying files produced by Excel, and can't quite figure out how it's done.

Right now, I'm creating a fill, creating a CellStyleFormat that points at the fill, creating a CellFormat that points at the index of the CellStyleFormat, then creating a CellStyle that points to the CellFormat.

Here's the code I'm using to generate the document:

Console.WriteLine("Creating document");
using (var spreadsheet = SpreadsheetDocument.Create("output.xlsx", SpreadsheetDocumentType.Workbook))
{
    Console.WriteLine("Creating workbook");
    spreadsheet.AddWorkbookPart();
    spreadsheet.WorkbookPart.Workbook = new Workbook();
    Console.WriteLine("Creating worksheet");
    var wsPart = spreadsheet.WorkbookPart.AddNewPart<WorksheetPart>();
    wsPart.Worksheet = new Worksheet();

    var stylesPart = spreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>();
    stylesPart.Stylesheet = new Stylesheet();
    stylesPart.Stylesheet.Fills = new Fills();

    // create a solid red fill
    var solidRed = new PatternFill() { PatternType = PatternValues.Solid };
    solidRed.AppendChild(new BackgroundColor { Rgb = HexBinaryValue.FromString("FF00FF00") });

    stylesPart.Stylesheet.Fills.AppendChild(new Fill { PatternFill = new PatternFill() { PatternType = PatternValues.None } });
    stylesPart.Stylesheet.Fills.AppendChild(new Fill { PatternFill = solidRed });
    stylesPart.Stylesheet.CellStyleFormats = new CellStyleFormats();
    stylesPart.Stylesheet.CellStyleFormats.AppendChild(new CellFormat { FillId = 0, ApplyFill = false });
    stylesPart.Stylesheet.CellStyleFormats.AppendChild(new CellFormat { FillId = 1, ApplyFill = true });
    stylesPart.Stylesheet.CellFormats = new CellFormats();
    stylesPart.Stylesheet.CellFormats.AppendChild(new CellFormat { FormatId = 0 });
    stylesPart.Stylesheet.CellFormats.AppendChild(new CellFormat { FormatId = 1 });
    stylesPart.Stylesheet.CellStyles = new CellStyles();
    stylesPart.Stylesheet.CellStyles.AppendChild(new CellStyle { Name = "None", FormatId = 0 });
    stylesPart.Stylesheet.CellStyles.AppendChild(new CellStyle { Name = "Solid Red", FormatId = 1 });

    stylesPart.Stylesheet.Save();

    Console.WriteLine("Creating sheet data");
    var sheetData = wsPart.Worksheet.AppendChild(new SheetData());

    Console.WriteLine("Adding rows / cells...");

    var row = sheetData.AppendChild(new Row());
    row.AppendChild(new Cell() { CellValue = new CellValue("This"),  DataType = CellValues.String });
    row.AppendChild(new Cell() { CellValue = new CellValue("is"),    DataType = CellValues.String });
    row.AppendChild(new Cell() { CellValue = new CellValue("a"),     DataType = CellValues.String });
    row.AppendChild(new Cell() { CellValue = new CellValue("test."), DataType = CellValues.String });

    sheetData.AppendChild(new Row());

    row = sheetData.AppendChild(new Row());
    row.AppendChild(new Cell() { CellValue = new CellValue("Value:"),   DataType = CellValues.String });
    row.AppendChild(new Cell() { CellValue = new CellValue("123"),      DataType = CellValues.Number });
    row.AppendChild(new Cell() { CellValue = new CellValue("Formula:"), DataType = CellValues.String });
    row.AppendChild(new Cell() { CellFormula = new CellFormula("B3"),   StyleIndex = 1 }); //

    Console.WriteLine("Saving worksheet");
    wsPart.Worksheet.Save();

    Console.WriteLine("Creating sheet list");
    var sheets = spreadsheet.WorkbookPart.Workbook.AppendChild(new Sheets());
    sheets.AppendChild(new Sheet() { Id = spreadsheet.WorkbookPart.GetIdOfPart(wsPart), SheetId = 1, Name = "Test" });

    Console.WriteLine("Saving workbook");
    spreadsheet.WorkbookPart.Workbook.Save();

    Console.WriteLine("Done.");
}

Here's the generated XML:

workbook.xml

<?xml version="1.0" encoding="utf-8"?>
<x:workbook xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
  <x:sheets>
    <x:sheet name="Test" sheetId="1" r:id="Rbad86b8c80844a16" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" />
  </x:sheets>
</x:workbook>

styles.xml

<?xml version="1.0" encoding="utf-8"?>
<x:styleSheet xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
  <x:fills>
    <x:fill>
      <x:patternFill patternType="none" />
    </x:fill>
    <x:fill>
      <x:patternFill patternType="solid">
        <x:bgColor rgb="FF00FF00" />
      </x:patternFill>
    </x:fill>
  </x:fills>
  <x:cellStyleXfs>
    <x:xf fillId="0" applyFill="0" />
    <x:xf fillId="1" applyFill="1" />
  </x:cellStyleXfs>
  <x:cellXfs>
    <x:xf xfId="0" />
    <x:xf xfId="1" />
  </x:cellXfs>
  <x:cellStyles>
    <x:cellStyle name="None" xfId="0" />
    <x:cellStyle name="Solid Red" xfId="1" />
  </x:cellStyles>
</x:styleSheet>

worksheets/sheet.xml

<?xml version="1.0" encoding="utf-8"?>
<x:worksheet xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
  <x:sheetData>
    <x:row>
      <x:c t="str"><x:v>This</x:v></x:c>
      <x:c t="str"><x:v>is</x:v></x:c>
      <x:c t="str"><x:v>a</x:v></x:c>
      <x:c t="str"><x:v>test.</x:v></x:c>
    </x:row>
    <x:row />
    <x:row>
      <x:c t="str"><x:v>Value:</x:v></x:c>
      <x:c t="n"><x:v>123</x:v></x:c>
      <x:c t="str"><x:v>Formula:</x:v></x:c>
      <x:c s="1"><x:f>B3</x:f></x:c>
    </x:row>
  </x:sheetData>
</x:worksheet>

The last cell of the last row is where I'm trying to add the style.

This all validates properly when I run it through the OpenXML SDK Productivity Tool, but, when I attempt to open the file in Excel, I get the following error:

Repaired Records: Format from /xl/styles.xml part (Styles)

The spreadsheet then shows, but the fill isn't applied.

Any idea how to go about fixing this?


问:
After update Mac OSX Sierra, iPhone can not connect to Mac's localhost
Last night I updated my Mac to the already-vilified OSX Sierra 10.12.4.

Tonight, I went to test my localhost webapp on iPhone. Prior to tonight, this worked by browsing in iPhone Safari to address 192.168.1.64:1337. My IP has not changed.

Tonight, iPhone Safari returns, "Safari cannot open the page because it could not connect to the server."

How to re-connect iPhone???

答: I was experiencing the same issue. I was using MAMP PRO and in the end i switched to use the "via Xip.io (LAN only)" option under Hosts/General/Name resolution. I also had to update my database to reflect the url it provided and clear the site cache. All works perfectly again using this different method. </p>


问:
Exploded deployment fails on JBoss 5
I have a web application which deploys fine as an ear file. But when I try to deploy it in exploded form it fails like this:

```<code>17:13:17,305 ERROR [AbstractKernelController] Error installing to Start: name=persistence.unit:unitName=app.ear/#app-persistence state=Create
java.lang.RuntimeException: could not find relative path: lib/persistence-jpa.jar
    at org.jboss.jpa.deployment.PersistenceUnitDeployment.getRelativeURL(PersistenceUnitDeployment.java:208)
    at org.jboss.jpa.deployment.PersistenceUnitDeployment.start(PersistenceUnitDeployment.java:267)
.
.
.
Caused by: java.lang.RuntimeException: could not find child 'lib/persistence-jpa.jar' on 'FileHandler@4348388[path= context=file:/home/petteri/bin/jboss-5.1.0.GA/server/standard/deploy/ real=file:/home/petteri/bin/jboss-5.1.0.GA/server/standard/deploy/]'
    at org.jboss.jpa.deployment.PersistenceUnitDeployment.getRelativeURL(PersistenceUnitDeployment.java:203)
</code>```

The persistence.xml looks like this:

```<code><persistence
    xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">

    <persistence-unit name="app-persistence">
        <jta-data-source>java:/app</jta-data-source>
        <jar-file>lib/persistence-jpa.jar</jar-file>
        <properties>

 ... some hibernate stuff ...

        </properties>
    </persistence-unit>
</persistence>
</code>```

Any ideas? Thanks!

答:
Directory structure should be:

EAR

    - warfile.WAR

    - lib

           -  persistence-jpa.jar

            -  The other jar file which contain persistence.xml

    - enterpricejavabean.ejb

persistace.xml file jar element should be  <jar-file>../lib/persistence-jpa.jar</jar-file>

Title: Exploded deployment fails on JBoss 5

Body:
I have a web application which deploys fine as an ear file. But when I try to deploy it in exploded form it fails like this:

17:13:17,305 ERROR [AbstractKernelController] Error installing to Start: name=persistence.unit:unitName=app.ear/#app-persistence state=Create
java.lang.RuntimeException: could not find relative path: lib/persistence-jpa.jar
    at org.jboss.jpa.deployment.PersistenceUnitDeployment.getRelativeURL(PersistenceUnitDeployment.java:208)
    at org.jboss.jpa.deployment.PersistenceUnitDeployment.start(PersistenceUnitDeployment.java:267)
.
.
.
Caused by: java.lang.RuntimeException: could not find child 'lib/persistence-jpa.jar' on 'FileHandler@4348388[path= context=file:/home/petteri/bin/jboss-5.1.0.GA/server/standard/deploy/ real=file:/home/petteri/bin/jboss-5.1.0.GA/server/standard/deploy/]'
    at org.jboss.jpa.deployment.PersistenceUnitDeployment.getRelativeURL(PersistenceUnitDeployment.java:203)

The persistence.xml looks like this:

<persistence
    xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">

    <persistence-unit name="app-persistence">
        <jta-data-source>java:/app</jta-data-source>
        <jar-file>lib/persistence-jpa.jar</jar-file>
        <properties>

 ... some hibernate stuff ...

        </properties>
    </persistence-unit>
</persistence>

Any ideas? Thanks!


问:
SQL or returning less results
I'm using mysql with a linked Access 2013 front.
So firstly I can get results using a query like:

```<code>SELECT * FROM [tablename] WHERE [name] LIKE '%test%';
</code>```

However as soon as I throw in an or operator:

```<code>SELECT * FROM [tablename] WHERE [name] LIKE '%test%' OR [id] LIKE '%test%';
</code>```

As far as I know each side of the OR operator should be evaluated to boolean values, left to right, then return a result as soon as one of them is true. But I'm getting less results than just querying the name on its own.

Any ideas? (Or questions)

答:
It's not a perfect answer, but you might be able to try:

```<code>SELECT * FROM [tablename] WHERE [name] LIKE '%test%'
UNION
SELECT * FROM [tablename] WHERE [id] LIKE '%test%';
</code>```

Not very elegant, but it should get the job done.

Title: SQL or returning less results

Body:
I'm using mysql with a linked Access 2013 front.
So firstly I can get results using a query like:

SELECT * FROM [tablename] WHERE [name] LIKE '%test%';

However as soon as I throw in an or operator:

SELECT * FROM [tablename] WHERE [name] LIKE '%test%' OR [id] LIKE '%test%';

As far as I know each side of the OR operator should be evaluated to boolean values, left to right, then return a result as soon as one of them is true. But I'm getting less results than just querying the name on its own.

Any ideas? (Or questions)

Body:
It's not a perfect answer, but you might be able to try:

SELECT * FROM [tablename] WHERE [name] LIKE '%test%'
UNION
SELECT * FROM [tablename] WHERE [id] LIKE '%test%';

Not very elegant, but it should get the job done.


问:
How to create PDF file in Python and put LaTeX data?
I need to create pdf file with some LaTeX data.
What I have:

```<code>min_latex = (r"\documentclass{article}"
         r"\begin{document}"
         r"Hello, world!"
         r"\end{document}")

from latex import build_pdf

# this builds a pdf-file inside a temporary directory
pdf = build_pdf(min_latex)

# look at the first few bytes of the header
print bytes(pdf)[:10]

with open('temp.pdf', 'wb+') as f:
    f.write(pdf)
</code>```

But I have the following error message:

```<code>File "temp.py", line 18, in <module> f.write(pdf) TypeError: argument 1 must be convertible to a buffer, not Data
</code>```

答:
pdf is not a string - you have to invoke one of its methods to save it:

```<code>pdf.save_to("/tmp/foo.pdf")
</code>```

In general, it's a good idea to go into the interactive interpreter and paste in your program up to including the pdf = ... line. Then you can say help(pdf) to find out what you can do with that object.

Body:
I need to create pdf file with some LaTeX data.
What I have:

min_latex = (r"\documentclass{article}"
         r"\begin{document}"
         r"Hello, world!"
         r"\end{document}")

from latex import build_pdf

# this builds a pdf-file inside a temporary directory
pdf = build_pdf(min_latex)

# look at the first few bytes of the header
print bytes(pdf)[:10]

with open('temp.pdf', 'wb+') as f:
    f.write(pdf)

But I have the following error message:

File "temp.py", line 18, in <module> f.write(pdf) TypeError: argument 1 must be convertible to a buffer, not Data

Body:
pdf is not a string - you have to invoke one of its methods to save it:

pdf.save_to("/tmp/foo.pdf")

In general, it's a good idea to go into the interactive interpreter and paste in your program up to including the pdf = ... line. Then you can say help(pdf) to find out what you can do with that object.


问:
Import code from file using awk in bash
We'd like to import code between two strings and put them in an variable.

We have:

```<code>job=1

listen="$(awk -v a="BEGIN-$job" -v e="END-$job" '/BEGIN {print a}/{p=1;next} /BEGIN {print e}/{p=0;exit} p' whatsthat.file)"
</code>```

whatsthat.file (edited):

```<code>BEGIN-1

echo "some code"

END-1

BEGIN-2

echo "next job"

END-2
</code>```

Final result for variable $listen should be:

```<code>echo "some code"
</code>```

But the command above leaves $listen empty.

答:
Your awk command has several problems, what you're looking for is this:

```<code>job=1

listen="$(
awk -v a="BEGIN-$job" -v e="END-$job" '$0==a {p=1;next} $0==e {exit} p && NF' whatsthat.file
)"
</code>```

Patterns $0==a and $0==e check the input line at hand ($0) against the variables a and b for equality. If so, the associated action ({...}) is executed.

{p=1;next}, which is executed for the start of the range of interest, sets (conceptually) Boolean flag p and moves to the next input line; its purpose is to indicate that subsequent lines - due to being inside the range of interest - should (potentially) be printed.

{exit}, which is executed for the end of the range, unconditionally ends processing (the range-ending line, just like the range-starting one, shouldn't be printed).

p && NF is a pattern that tests flag p and whether the input line is nonempty (NF contains the number of whitespace-separated fields on the line, and that number is 0 for empty or blank lines); if both conditions are met, the input line at hand is implicitly printed (which is Awk's default action in the absence of an action associated with a pattern).

Title: Import code from file using awk in bash

Body:
We'd like to import code between two strings and put them in an variable.

We have:

job=1

listen="$(awk -v a="BEGIN-$job" -v e="END-$job" '/BEGIN {print a}/{p=1;next} /BEGIN {print e}/{p=0;exit} p' whatsthat.file)"

whatsthat.file (edited):

BEGIN-1

echo "some code"

END-1

BEGIN-2

echo "next job"

END-2

Final result for variable $listen should be:

echo "some code"

But the command above leaves $listen empty.

Body:
Your awk command has several problems, what you're looking for is this:

job=1

listen="$(
awk -v a="BEGIN-$job" -v e="END-$job" '$0==a {p=1;next} $0==e {exit} p && NF' whatsthat.file
)"

Patterns $0==a and $0==e check the input line at hand ($0) against the variables a and b for equality. If so, the associated action ({...}) is executed.

{p=1;next}, which is executed for the start of the range of interest, sets (conceptually) Boolean flag p and moves to the next input line; its purpose is to indicate that subsequent lines - due to being inside the range of interest - should (potentially) be printed.

{exit}, which is executed for the end of the range, unconditionally ends processing (the range-ending line, just like the range-starting one, shouldn't be printed).

p && NF is a pattern that tests flag p and whether the input line is nonempty (NF contains the number of whitespace-separated fields on the line, and that number is 0 for empty or blank lines); if both conditions are met, the input line at hand is implicitly printed (which is Awk's default action in the absence of an action associated with a pattern).


问:
Font-Awesome Icons are not centering on page
I have a div that is a page on my site, and I am trying to center these font-awesome icons on it. But for some reason they wont center. I have searched for a solution but none have worked so far.

Click the "about" button to see what I am talking about.

$(function() {

  $('#fadeContent').click(function(){
    var bodyContent = $('#bodyContent')
    bodyContent.fadeIn(400);
    bodyContent.click(function() {
      $(this).fadeOut(400);
    })
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: black;
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color:black;
}

#bodyContent{
  display:none;
  position:absolute;
  color: white;
  width:100%;
  height:100%;
  background:#454545;
  z-index: 100;
}

.fa-times{
    position: absolute;
    top: 0px;
    right: 0px;
    font-size: 3em;
    margin-right: 2%;
    margin-top: 1.5%;
}

.fa-twitter,
.fa-github,
.fa-steam {
    display: inline-block;
    position: relative;
    text-align: center;
    font-size: 2.5em;
    padding: .5em;
    border: 3px solid white;
    margin-top: 20%;
    margin-left: 1.5%;
    margin-right: 1.5%;
}

.fa-times:hover{
    color: #e84d4d;
    cursor: pointer;
}

#home {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 20%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.about {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 37%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

#projects {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 54%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

#contact {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 71%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

#home:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

.about:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

#projects:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

#contact:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}
@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Home</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play" rel="stylesheet">

    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>
    <link rel='stylesheet prefetch' href='http://rawgit.com/fralec/elegantShareJS/master/css/elegant.css'>

    <link rel="stylesheet" type="text/css" href="css/style.css">

    <button id="home">Home</button>
    <button id="fadeContent" class="about">About</button>
    <button id="projects">Projects</button>
    <button id="contact">Contact</button>

```

答: Add text-align: center to #bodyContent in CSS.

Body:
I have a div that is a page on my site, and I am trying to center these font-awesome icons on it. But for some reason they wont center. I have searched for a solution but none have worked so far.

Click the "about" button to see what I am talking about.

$(function() {

  $('#fadeContent').click(function(){
    var bodyContent = $('#bodyContent')
    bodyContent.fadeIn(400);
    bodyContent.click(function() {
      $(this).fadeOut(400);
    })
  });

});

body {
  background-color: black;
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color:black;
}

#bodyContent{
  display:none;
  position:absolute;
  color: white;
  width:100%;
  height:100%;
  background:#454545;
  z-index: 100;
}

.fa-times{
    position: absolute;
    top: 0px;
    right: 0px;
    font-size: 3em;
    margin-right: 2%;
    margin-top: 1.5%;
}

.fa-twitter,
.fa-github,
.fa-steam {
    display: inline-block;
    position: relative;
    text-align: center;
    font-size: 2.5em;
    padding: .5em;
    border: 3px solid white;
    margin-top: 20%;
    margin-left: 1.5%;
    margin-right: 1.5%;
}

.fa-times:hover{
    color: #e84d4d;
    cursor: pointer;
}

#home {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 20%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

.about {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 37%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

#projects {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 54%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

#contact {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 71%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

#home:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

.about:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

#projects:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

#contact:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}
@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Home</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play" rel="stylesheet">

    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>
    <link rel='stylesheet prefetch' href='http://rawgit.com/fralec/elegantShareJS/master/css/elegant.css'>

    <link rel="stylesheet" type="text/css" href="css/style.css">

    <button id="home">Home</button>
    <button id="fadeContent" class="about">About</button>
    <button id="projects">Projects</button>
    <button id="contact">Contact</button>


问:
Check box value is coming as false if it is disabled in primefaces
I have a requirement like this.

there is a file uploader alopng with checkbox and save, cancel buttons.

I have to disable the check box if the file is invalid and the selection should stay.

After disabling if I click the save button the checkbox value is coming as false in backing bean eventhough it's showing as checked in the dialog.

While debugging I seen that the primeface framework is not getting the id of the disabled checkbox,

Here is my xhtml file:

```<code>    <h:form id="fileupload_form" enctype="multipart/form-data">
    <h:panelGroup id="fileupload_Panel">
    <p:message for="fileupload_Panel"></p:message>

    <p:panelGrid styleClass="noBorderGrid global_docs" columns="4">

        <h:outputText style="min-width:100px!important; margin-left: 42px;"></h:outputText>
        <p:selectBooleanCheckbox id="tt" value="#{bean.selectedDocs}"/>
        <h:outputText value="xx}"/>

        <h:outputText style="min-width:100px!important; margin-left: 42px;" rendered="#{cc.attrs.bean != null and cc.attrs.bean.currentDocument != null}"></h:outputText>
        <p:selectBooleanCheckbox id="checkBox" value="#{fileBean.tqpReport}"  disabled="${not fileBean.isActive}"/>
        <h:outputText value="xxxx"/>
        <p:tooltip for="t" value="xxxx"/>

    </p:panelGrid>

    <p:fileUpload id="documentFileUploader" fileUploadListener="#{bean.uploadDocumentsListener}"
                    mode="advanced" dragDropSupport="true" multiple="true" auto="true"  update="@form" process="@form"
                    onstart="PF('ajax').show();"  onerror="PF('ajax').hide();"
                    style="width: 98%; max-width: 480px; max-height: 150px; overflow: auto;" styleClass="file-uploader-drag-drop" label="#{msgs.choose}" />
    </h:panelGroup>

     <p:panelGrid styleClass="noBorderGrid buttonTable" columns="3" style="float:right;">
         <p:commandButton id="save" icon="ui-icon-disk" styleClass="blue_button" value="${msgs.save}" style="float:right;"
        process="@form" update="@form" action="#{bean.save()}"/>
         <p:commandButton id="cancel" icon="ui-icon-close" styleClass="blue_button" value="${msgs.cancel}"
        action="#{bean.cancel()}"  style="float:right;"
        process="@this"/>
</p:panelGrid>

 </h:form>
</code>```

While debugging I found that in the

```<code>   public void decode(FacesContext context, UIComponent component)
</code>```

method of

```<code>   SelectBooleanCheckboxRenderer.java class
</code>```

the id of the disabled check box is null from that statement. I don't understand why? If the check box is not disabled I am getting the correct value.

```<code>  String submittedValue = (String) context.getExternalContext().getRequestParameterMap().get(clientId + "_input");
</code>```

答: Disabled elements are not posted as part form submission; you can see this answer for some more details. Assuming that you're using a ViewScoped bean you can use AJAX to post the value back to the bean when the value changes. </p>

Body:
I have a requirement like this.

there is a file uploader alopng with checkbox and save, cancel buttons.

I have to disable the check box if the file is invalid and the selection should stay.

After disabling if I click the save button the checkbox value is coming as false in backing bean eventhough it's showing as checked in the dialog.

While debugging I seen that the primeface framework is not getting the id of the disabled checkbox,

Here is my xhtml file:

    <h:form id="fileupload_form" enctype="multipart/form-data">
    <h:panelGroup id="fileupload_Panel">

        <h:outputText style="min-width:100px!important; margin-left: 42px;"></h:outputText>

        <h:outputText value="xx}"/>

        <h:outputText style="min-width:100px!important; margin-left: 42px;" rendered="#{cc.attrs.bean != null and cc.attrs.bean.currentDocument != null}"></h:outputText>

        <h:outputText value="xxxx"/>

    </h:panelGroup>

 </h:form>

While debugging I found that in the

   public void decode(FacesContext context, UIComponent component)

method of

   SelectBooleanCheckboxRenderer.java class

the id of the disabled check box is null from that statement. I don't understand why? If the check box is not disabled I am getting the correct value.

  String submittedValue = (String) context.getExternalContext().getRequestParameterMap().get(clientId + "_input");


问:
ServiceStack Funq ReuseScope.Request injects same object instead of a new instance
I'm having a problem with ReuseScope.Request. I'm getting the same instance injected on every request even though I specify ReuseScope.Request. I configured the container using these two calls to get a MasterConfig:

```<code>this.container.RegisterAutoWiredAs<ApiConfigFactory, IConfigFactory>().ReusedWithin(ReuseScope.Container);
this.container.Register(c => c.Resolve<IConfigFactory>().GetMasterConfig(true)).ReusedWithin(ReuseScope.Request);
</code>```

The GetMasterConfig(true) method returns a new concrete MasterConfig. However, when I try to use the MasterConfig in the service, I get the same instance on every request.

```<code>public class MyService
{
    private readonly MasterConfig masterConfig;

    public SaleService(MasterConfig masterConfig)
    {
        this.masterConfig = masterConfig;
    }

    public object Post(MyRequest request)
    {
        // **masterConfig is the same instance here on every request**
    }
}
</code>```

If I change the scope on the MasterConfig Register to ReuseScope.None, I get a new MasterConfig loaded as expected. What am I missing? Is there a problem with the way I am registering MasterConfig? Why does ReuseScope.None fix the issue? Why does ReuseScope.Request give me the same instance?

Note:

答:
I also had exactly the same issue, using ServiceStack version 4.5.6

Here is my code for registration

```<code>container.RegisterAutoWiredAs<EventConditionalLoadingRepository, IEventConditionalLoadingRepository>()
    .ReusedWithin(ReuseScope.Request);

container.RegisterAutoWiredAs<MetaRiskRepository, IMetaRiskRepository>()
    .ReusedWithin(ReuseScope.Request);

container.RegisterAutoWiredAs<RiskStoreConnectivityService, IRiskStoreConnectivityService>()
    .ReusedWithin(ReuseScope.Request);

container.Register<IUnitOfWork>(c =>
{
    return new UnitOfWork();
}).ReusedWithin(ReuseScope.Request);

container.Register(c => (IUnitOfWorkEnlistable)c.Resolve<IUnitOfWork>())
    .ReusedWithin(ReuseScope.Request);
</code>```

And here is my service that takes these dependencies

```<code>public AnalysisServiceStackService(
    IEventConditionalLoadingRepository eventConditionalLoadingRepository,
    IMetaRiskRepository metaRiskRepository,
    IUnitOfWork unitOfWork)
{

    _eventConditionalLoadingRepository = eventConditionalLoadingRepository;
    _metaRiskRepository = metaRiskRepository;
    _unitOfWork = unitOfWork;
    _log.Information("AnalysisServiceStackService constructed");
}
</code>```

You can see that I have a log statement there, which when I hit this service up via postman for sequential requests, I get this sort of thing logged

```<code>2017-03-30 15:34:10 [Information] AnalysisServiceStackService constructed
2017-03-30 15:34:11 [Information] AnalysisServiceStackService constructed
2017-03-30 15:34:12 [Information] AnalysisServiceStackService constructed
2017-03-30 15:34:13 [Information] AnalysisServiceStackService constructed
2017-03-30 15:34:14 [Information] AnalysisServiceStackService constructed
2017-03-30 15:34:15 [Information] AnalysisServiceStackService constructed
2017-03-30 15:34:16 [Information] AnalysisServiceStackService constructed
2017-03-30 15:34:17 [Information] AnalysisServiceStackService constructed
</code>```

So I know the service itself should be attempting to resolve a new PerRequest instance of the IOC components it needs.

If I then use Visual studio and use the Debug "Make Object ID" feature to check what the IOC container is giving me they are the same instance.

Call 1 : 1st Request

see the #1 Object ID created by Visual Studio

Call 2 : 2nd Request

See the #1 Object ID which means its the same instance it should NOT be. It should be a new instance for a new request

And just to prove that these are different calls, here is the logs for the Constructor being run twice, once for each request

Only thing that fixed this for me was the suggested fix of Reuse.None

But if I have to do that I might as well just use the AutoFac adapter (which I would prefer to use anyway) and use the standard AutoFac INstancePerLifeTimeScope : http://docs.autofac.org/en/latest/lifetime/instance-scope.html#instance-per-lifetime-scope

Any ideas?

Body:
I'm having a problem with ReuseScope.Request. I'm getting the same instance injected on every request even though I specify ReuseScope.Request. I configured the container using these two calls to get a MasterConfig:

this.container.RegisterAutoWiredAs<ApiConfigFactory, IConfigFactory>().ReusedWithin(ReuseScope.Container);
this.container.Register(c => c.Resolve<IConfigFactory>().GetMasterConfig(true)).ReusedWithin(ReuseScope.Request);

The GetMasterConfig(true) method returns a new concrete MasterConfig. However, when I try to use the MasterConfig in the service, I get the same instance on every request.

public class MyService
{
    private readonly MasterConfig masterConfig;

    public SaleService(MasterConfig masterConfig)
    {
        this.masterConfig = masterConfig;
    }

    public object Post(MyRequest request)
    {
        // **masterConfig is the same instance here on every request**
    }
}

If I change the scope on the MasterConfig Register to ReuseScope.None, I get a new MasterConfig loaded as expected. What am I missing? Is there a problem with the way I am registering MasterConfig? Why does ReuseScope.None fix the issue? Why does ReuseScope.Request give me the same instance?

Note:

Body:
I also had exactly the same issue, using ServiceStack version 4.5.6

Here is my code for registration

container.RegisterAutoWiredAs<EventConditionalLoadingRepository, IEventConditionalLoadingRepository>()
    .ReusedWithin(ReuseScope.Request);

container.RegisterAutoWiredAs<MetaRiskRepository, IMetaRiskRepository>()
    .ReusedWithin(ReuseScope.Request);

container.RegisterAutoWiredAs<RiskStoreConnectivityService, IRiskStoreConnectivityService>()
    .ReusedWithin(ReuseScope.Request);

container.Register<IUnitOfWork>(c =>
{
    return new UnitOfWork();
}).ReusedWithin(ReuseScope.Request);

container.Register(c => (IUnitOfWorkEnlistable)c.Resolve<IUnitOfWork>())
    .ReusedWithin(ReuseScope.Request);

And here is my service that takes these dependencies

public AnalysisServiceStackService(
    IEventConditionalLoadingRepository eventConditionalLoadingRepository,
    IMetaRiskRepository metaRiskRepository,
    IUnitOfWork unitOfWork)
{

    _eventConditionalLoadingRepository = eventConditionalLoadingRepository;
    _metaRiskRepository = metaRiskRepository;
    _unitOfWork = unitOfWork;
    _log.Information("AnalysisServiceStackService constructed");
}

You can see that I have a log statement there, which when I hit this service up via postman for sequential requests, I get this sort of thing logged

2017-03-30 15:34:10 [Information] AnalysisServiceStackService constructed
2017-03-30 15:34:11 [Information] AnalysisServiceStackService constructed
2017-03-30 15:34:12 [Information] AnalysisServiceStackService constructed
2017-03-30 15:34:13 [Information] AnalysisServiceStackService constructed
2017-03-30 15:34:14 [Information] AnalysisServiceStackService constructed
2017-03-30 15:34:15 [Information] AnalysisServiceStackService constructed
2017-03-30 15:34:16 [Information] AnalysisServiceStackService constructed
2017-03-30 15:34:17 [Information] AnalysisServiceStackService constructed

So I know the service itself should be attempting to resolve a new PerRequest instance of the IOC components it needs.

If I then use Visual studio and use the Debug "Make Object ID" feature to check what the IOC container is giving me they are the same instance.

Call 1 : 1st Request

see the #1 Object ID created by Visual Studio

Call 2 : 2nd Request

See the #1 Object ID which means its the same instance it should NOT be. It should be a new instance for a new request

And just to prove that these are different calls, here is the logs for the Constructor being run twice, once for each request

Only thing that fixed this for me was the suggested fix of Reuse.None

But if I have to do that I might as well just use the AutoFac adapter (which I would prefer to use anyway) and use the standard AutoFac INstancePerLifeTimeScope : http://docs.autofac.org/en/latest/lifetime/instance-scope.html#instance-per-lifetime-scope

Any ideas?


问:
Including file inside a class php
I am doing something using classes in php for very first time.
I am trying to fetch an return object array items in class.

This is my class

```<code>class User {

    $dbconn = include("config.php");
    private $dbHost     = $dbconn->host;
    private $dbUsername = $dbconn->username;
    private $dbPassword = $dbconn->pass;
    private $dbName     = $dbconn->database;
    private $userTbl    = 'users';

    function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " . $conn->connect_error);
            }else{
                $this->db = $conn;
            }
        }
    }
}
</code>```

This is my config.php file

```<code>return (object) array(
    'host' => 'localhost',
    'username' => 'my_user',
    'pass' => 'my_pass',
    'database' => 'my_db'
);
</code>```

How do i do it?

```<code>PHP Parse error:  syntax error, unexpected '$dbconn' (T_VARIABLE)
</code>```

答:
The other way is to define constants in config file and use them in class.

in config.php file

```<code>define('HOST', 'localhost');
define('USERNAME', 'my_user');
define('PASS', 'my_pass');
define('DATABASE', 'my_db');
</code>```

In class file

```<code>include("config.php")
class User {
    private $dbHost     = HOST;
    private $dbUsername = USERNAME;
    private $dbPassword = PASS;
    private $dbName     = DATABASE;
    private $userTbl    = 'users';

    function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " . $conn->connect_error);
            }else{
                $this->db = $conn;
            }
        }
    }
}
</code>```

Title: Including file inside a class php

Body:
I am doing something using classes in php for very first time.
I am trying to fetch an return object array items in class.

This is my class

class User {

    $dbconn = include("config.php");
    private $dbHost     = $dbconn->host;
    private $dbUsername = $dbconn->username;
    private $dbPassword = $dbconn->pass;
    private $dbName     = $dbconn->database;
    private $userTbl    = 'users';

    function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " . $conn->connect_error);
            }else{
                $this->db = $conn;
            }
        }
    }
}

This is my config.php file

return (object) array(
    'host' => 'localhost',
    'username' => 'my_user',
    'pass' => 'my_pass',
    'database' => 'my_db'
);

How do i do it?

PHP Parse error:  syntax error, unexpected '$dbconn' (T_VARIABLE)

Body:
The other way is to define constants in config file and use them in class.

in config.php file

define('HOST', 'localhost');
define('USERNAME', 'my_user');
define('PASS', 'my_pass');
define('DATABASE', 'my_db');

In class file

include("config.php")
class User {
    private $dbHost     = HOST;
    private $dbUsername = USERNAME;
    private $dbPassword = PASS;
    private $dbName     = DATABASE;
    private $userTbl    = 'users';

    function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " . $conn->connect_error);
            }else{
                $this->db = $conn;
            }
        }
    }
}


问:
What is the advantage of a symbol that binds to a value and function at the same time?
In lisp, a symbol can be bound to both a value and a function at the same time.
For example,

Symbol f bound to a function

```<code>(defun f(x)
    (* 2 x))
</code>```

Symbol f bound to a value

```<code>(setq f 10)
</code>```

So i write something like this:

```<code>(f f)
</code>```

=> 20

What is the benefit of such a feature?

答: It's useful for everyday tasks, but the main reason is because of macros, you'll understand why once you study it.</p>

Body:
In lisp, a symbol can be bound to both a value and a function at the same time.
For example,

Symbol f bound to a function

(defun f(x)
    (* 2 x))

Symbol f bound to a value

(setq f 10)

So i write something like this:

(f f)

=> 20

What is the benefit of such a feature?