问:
PHP PDO login code - repeats error, not able to login [ correct username and password is entered]
I am struggling to get the login code to run successfully.  It keeps on echoing the "Username or Password incorrect.." section, though the correct username and password in entered.  Am I missing something somewhere, please help.</p>

```<code>    <?php
//Check login details
    session_start();
    //get user input from the form
    if (isset($_POST['Submit'])) {
        $username = checkData($_POST['username']);
        $password = checkData($_POST['password']);

        require ('config.php'); //database connection
        global $dbselect;

        $qry = 'SELECT username, password
                FROM users
                WHERE username = :username AND password = :password
                LIMIT 1';
        $statement = $dbselect->prepare($qry);
        $statement->bindValue(':username', $username);
        $statement->bindValue(':password', $password);
        $statement->execute();
        $login = $statement->fetch(PDO::FETCH_ASSOC);
        if (count($login) > 0 && password_verify($password, $login['password'])) {
            $_SESSION['username'] = $login['username'];
            header('location:home.html');
        } else {
            echo "Username or Password incorrect. Please try again.";
        }
        $statement->closeCursor();
    }

    //validate data
    function checkData($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }
?>
</code>```

答:
The following worked in test ( up to the password_verify where I used a different test as I have PHP 5.3.2 and hence no password_verify ) ~ hopefully it might prove of benefit.

```<code><?php
    session_start();

    /* error messages used to display to user */
    $ex=array(
        0   =>  'One or more required POST variables are not set',
        1   =>  'Both username & password are required',
        2   =>  'Failed to prepare SQL query',
        3   =>  'Query failed',
        4   =>  'No results',
        5   =>  'Invalid login details'
    );

    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        try{
            if( isset( $_POST['Submit'], $_POST['username'], $_POST['password'] ) ) {

                $username = !empty( $_POST['username'] ) ? filter_input( INPUT_POST, 'username', FILTER_SANITIZE_STRING ) : false;
                $password = !empty( $_POST['password'] ) ? filter_input( INPUT_POST, 'password', FILTER_SANITIZE_STRING ) : false;

                if( $username && $password ){

                    require('config.php');
                    global $dbselect;/* ??? */

                    /* use the username in the sql not password & username */
                    $sql='select `username`, `password`
                            from `users`
                            where `username` = :username';
                    $stmt=$dbselect->prepare( $sql );

                    /* only proceed if prepared statement succeeded */
                    if( $stmt ){
                        $stmt->bindParam( ':username', $username );
                        $status=$stmt->execute();

                        if( !$status )throw new Exception('',3);

                        $rows=$stmt->rowCount();
                        if( !$rows > 0 )throw new Exception('',4);

                        $result = $stmt->fetchObject();
                        $stmt->closeCursor();

                        /* password_verify is available from PHP 5.5 onwards ~ I have 5.3.2 :( */
                        if( $result && function_exists('password_verify') && password_verify( $password, $result->password ) ){
                            /* valid */
                             $_SESSION['username']=$username;
                             exit( header('Location: home.html') );
                        } else {
                            /* bogus - invalid credentials */
                            throw new Exception('',5);
                        }
                    } else {
                        /* sql prepared statement failed */
                        throw new Exception('',2);
                    }
                } else {
                    /* either username or password was empty */
                    throw new Exception('',1);
                }
            } else {
                /* one or more POST variables are not set */
                throw new Exception('',0);
            }
        }catch( Exception $e ){

            /* set a session variable to ensure error message is displayed only once */
            $_SESSION['error']=$ex[ $e->getCode() ];

            /* reload the login page with error code */
            exit( header( 'Location: ?error=' . $e->getCode() ) );
        }
    }
?>

    <!doctype html>
    <html>
        <head>
            <title>Login</title>
        </head>
        <body>
        <!-- the php/html login page -->

        <form method='post'>
            <input type='text' name='username' />
            <input type='password' name='password' />
            <input type='submit' name='Submit' value='Login' />

            <?php
                if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['error'], $_SESSION['error'] ) ){

                    unset( $_SESSION['error'] );

                    /* display the error message */
                    echo "<h2 style='color:red'>{$ex[ $_GET['error'] ]}</h2>";
                }
            ?>
        </form>
        </body>
    </html>
</code>```

Body:
I am struggling to get the login code to run successfully.  It keeps on echoing the "Username or Password incorrect.." section, though the correct username and password in entered.  Am I missing something somewhere, please help.

    <?php
//Check login details
    session_start();
    //get user input from the form
    if (isset($_POST['Submit'])) {
        $username = checkData($_POST['username']);
        $password = checkData($_POST['password']);

        require ('config.php'); //database connection
        global $dbselect;

        $qry = 'SELECT username, password
                FROM users
                WHERE username = :username AND password = :password
                LIMIT 1';
        $statement = $dbselect->prepare($qry);
        $statement->bindValue(':username', $username);
        $statement->bindValue(':password', $password);
        $statement->execute();
        $login = $statement->fetch(PDO::FETCH_ASSOC);
        if (count($login) > 0 && password_verify($password, $login['password'])) {
            $_SESSION['username'] = $login['username'];
            header('location:home.html');
        } else {
            echo "Username or Password incorrect. Please try again.";
        }
        $statement->closeCursor();
    }

    //validate data
    function checkData($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }
?>

Body:
The following worked in test ( up to the password_verify where I used a different test as I have PHP 5.3.2 and hence no password_verify ) ~ hopefully it might prove of benefit.

<?php
    session_start();

    /* error messages used to display to user */
    $ex=array(
        0   =>  'One or more required POST variables are not set',
        1   =>  'Both username & password are required',
        2   =>  'Failed to prepare SQL query',
        3   =>  'Query failed',
        4   =>  'No results',
        5   =>  'Invalid login details'
    );

    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        try{
            if( isset( $_POST['Submit'], $_POST['username'], $_POST['password'] ) ) {

                $username = !empty( $_POST['username'] ) ? filter_input( INPUT_POST, 'username', FILTER_SANITIZE_STRING ) : false;
                $password = !empty( $_POST['password'] ) ? filter_input( INPUT_POST, 'password', FILTER_SANITIZE_STRING ) : false;

                if( $username && $password ){

                    require('config.php');
                    global $dbselect;/* ??? */

                    /* use the username in the sql not password & username */
                    $sql='select `username`, `password`
                            from `users`
                            where `username` = :username';
                    $stmt=$dbselect->prepare( $sql );

                    /* only proceed if prepared statement succeeded */
                    if( $stmt ){
                        $stmt->bindParam( ':username', $username );
                        $status=$stmt->execute();

                        if( !$status )throw new Exception('',3);

                        $rows=$stmt->rowCount();
                        if( !$rows > 0 )throw new Exception('',4);

                        $result = $stmt->fetchObject();
                        $stmt->closeCursor();

                        /* password_verify is available from PHP 5.5 onwards ~ I have 5.3.2 :( */
                        if( $result && function_exists('password_verify') && password_verify( $password, $result->password ) ){
                            /* valid */
                             $_SESSION['username']=$username;
                             exit( header('Location: home.html') );
                        } else {
                            /* bogus - invalid credentials */
                            throw new Exception('',5);
                        }
                    } else {
                        /* sql prepared statement failed */
                        throw new Exception('',2);
                    }
                } else {
                    /* either username or password was empty */
                    throw new Exception('',1);
                }
            } else {
                /* one or more POST variables are not set */
                throw new Exception('',0);
            }
        }catch( Exception $e ){

            /* set a session variable to ensure error message is displayed only once */
            $_SESSION['error']=$ex[ $e->getCode() ];

            /* reload the login page with error code */
            exit( header( 'Location: ?error=' . $e->getCode() ) );
        }
    }
?>

    <!doctype html>
    <html>
        <head>
            <title>Login</title>
        </head>
        <body>
        <!-- the php/html login page -->

        <form method='post'>
            <input type='text' name='username' />
            <input type='password' name='password' />
            <input type='submit' name='Submit' value='Login' />

            <?php
                if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['error'], $_SESSION['error'] ) ){

                    unset( $_SESSION['error'] );

                    /* display the error message */
                    echo "<h2 style='color:red'>{$ex[ $_GET['error'] ]}</h2>";
                }
            ?>
        </form>
        </body>
    </html>


来源: stackexchange

问:
Query Excel where Rows and Columns are reversed
How can I query an Excel file where the rows and columns are reversed / rotated 90 degrees?

Can it be done with a SELECT query, or do I need to recurse the cells programmatically?

It's for a .NET app, so linq or other suggestions are welcome.

答:
.NET does not include a method to transpose data tables. You have to make your own. This website Link has a tutorial on an example transpose method. I will copy and paste the code snippet below:</p>

```<code>private DataTable Transpose(DataTable dt)
{
DataTable dtNew = new DataTable();

//adding columns
for(int i=0; i<=dt.Rows.Count; i++)
{
   dtNew.Columns.Add(i.ToString());
}

//Changing Column Captions:
dtNew.Columns[0].ColumnName = " ";

 for(int i=0; i<dt.Rows.Count; i++)
 {
  //For dateTime columns use like below
   dtNew.Columns[i+1].ColumnName =Convert.ToDateTime(dt.Rows[i].ItemArray[0].ToString()).ToString("MM/dd/yyyy");
  //Else just assign the ItermArry[0] to the columnName prooperty
 }

//Adding Row Data
for(int k=1; k<dt.Columns.Count; k++)
{
    DataRow r = dtNew.NewRow();
    r[0] = dt.Columns[k].ToString();
    for(int j=1; j<=dt.Rows.Count; j++)
    r[j] = dt.Rows[j-1][k];
    dtNew.Rows.Add(r);
}

return dtNew;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
.NET does not include a method to transpose data tables. You have to make your own. This website Link has a tutorial on an example transpose method. I will copy and paste the code snippet below:

private DataTable Transpose(DataTable dt)
{
DataTable dtNew = new DataTable();

//adding columns
for(int i=0; i<=dt.Rows.Count; i++)
{
   dtNew.Columns.Add(i.ToString());
}

//Changing Column Captions:
dtNew.Columns[0].ColumnName = " ";

 for(int i=0; i<dt.Rows.Count; i++)
 {
  //For dateTime columns use like below
   dtNew.Columns[i+1].ColumnName =Convert.ToDateTime(dt.Rows[i].ItemArray[0].ToString()).ToString("MM/dd/yyyy");
  //Else just assign the ItermArry[0] to the columnName prooperty
 }

//Adding Row Data
for(int k=1; k<dt.Columns.Count; k++)
{
    DataRow r = dtNew.NewRow();
    r[0] = dt.Columns[k].ToString();
    for(int j=1; j<=dt.Rows.Count; j++)
    r[j] = dt.Rows[j-1][k];
    dtNew.Rows.Add(r);
}

return dtNew;
}


问:
using enum inside a switch
Can we use enum inside a switch?

```<code>public enum Color {
  RED,BLUE,YELLOW

}

 public class Use {
  Color c = Color.BLUE;

  public void test(){
      switch(c){
      case Color.BLUE:

      }
  }
}
</code>```

I am getting some error in this.

```<code>The enum constant Color.BLUE reference cannot be qualified in a case label  Use.java        line 7  Java Problem
</code>```

答:
```<code>enum MyEnum{
    A,B,C

    MyEnum(){
        switch(this){
            case A:
                 //....
                 break;
            case B:
                 //....
                 break;
            case C:
                 //....
                 break;
        }
    }
}
</code>```

Title: using enum inside a switch

Body:
Can we use enum inside a switch?

public enum Color {
  RED,BLUE,YELLOW

}

 public class Use {
  Color c = Color.BLUE;

  public void test(){
      switch(c){
      case Color.BLUE:

      }
  }
}

I am getting some error in this.

The enum constant Color.BLUE reference cannot be qualified in a case label  Use.java        line 7  Java Problem


问:
Swift 4 attributedString get typing attributes
I am trying to create AttributedString and add the attributes from

typingAttributes(from textView)

The problem is that

.typingAttributes

return

[String, Any]

and

NSAttributedString(string:.. , attributes:[])

needs

[NSAttributedStringKey: Any]

My code:

```<code>NSAttributedString(string: "test123", attributes: self.textView.typingAttributes)
</code>```

I don't want to create for in cycle to go through all keys and change them to

```<code>NSAttributedStringKey
</code>```

答:
Here is my helper class, which I use custom fonts</p>

```<code>import UIKit

struct AttributedStringHelper {

enum FontType: String {
    case bold = "GothamRounded-Bold"
    case medium = "GothamRounded-Medium"
    case book = "GothamRounded-Book"
}

static func getString(text: String, fontType: FontType, size: CGFloat, color: UIColor, isUnderlined: Bool? = nil) -> NSAttributedString {

    var attributes : [NSAttributedStringKey : Any] = [
        NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue) : UIFont(name: fontType.rawValue, size: size)!,
        NSAttributedStringKey.foregroundColor : color]

    if let isUnderlined = isUnderlined, isUnderlined {
        attributes[NSAttributedStringKey.underlineStyle] = 1
    }

    let attributedString = NSAttributedString(string: text, attributes: attributes)
    return attributedString
}
}
</code>```

Body:
I am trying to create AttributedString and add the attributes from

typingAttributes(from textView)

The problem is that

.typingAttributes

return

[String, Any]

and

NSAttributedString(string:.. , attributes:[])

needs

[NSAttributedStringKey: Any]

My code:

NSAttributedString(string: "test123", attributes: self.textView.typingAttributes)

I don't want to create for in cycle to go through all keys and change them to

NSAttributedStringKey

Body:
Here is my helper class, which I use custom fonts

import UIKit

struct AttributedStringHelper {

enum FontType: String {
    case bold = "GothamRounded-Bold"
    case medium = "GothamRounded-Medium"
    case book = "GothamRounded-Book"
}

static func getString(text: String, fontType: FontType, size: CGFloat, color: UIColor, isUnderlined: Bool? = nil) -> NSAttributedString {

    var attributes : [NSAttributedStringKey : Any] = [
        NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue) : UIFont(name: fontType.rawValue, size: size)!,
        NSAttributedStringKey.foregroundColor : color]

    if let isUnderlined = isUnderlined, isUnderlined {
        attributes[NSAttributedStringKey.underlineStyle] = 1
    }

    let attributedString = NSAttributedString(string: text, attributes: attributes)
    return attributedString
}
}


问:
Sorting XML file with XSLT or Python based on attribute of child element
I have a number of XML-files with a structure like this:

```<code><titles>
  <title mode="example" name="name_example">
    <titleselect>
      <attribute_a>attrib_a</attribute_a>
      <attribute_b>attrib_b</attribute_b>
      <attribute_c>attrib_c</attribute_c>
      <sort_attribute>New York</sort_attribute>
    </titleselect>
  </title>
  <title mode="another_example" name="another_name">
    <titleselect>
      <attribute_a>attrib_a</attribute_a>
      <attribute_b>attrib_b</attribute_b>
      <attribute_c>attrib_c</attribute_c>
      <sort_attribute>Boston</sort_attribute>
    </titleselect>
  </title>
  <title mode="final_example" name="final_name">
    <titleselect>
      <attribute_a>attrib_a</attribute_a>
      <attribute_b>attrib_b</attribute_b>
      <attribute_c>attrib_c</attribute_c>
      <sort_attribute>Chicago</sort_attribute>
    </titleselect>
  </title>
</titles>
</code>```

I am trying to sort the "titles" alphabetically by the "sort_attribute". My desired output is like this:

```<code><titles>
      <title mode="another_example" name="another_name">
        <titleselect>
          <attribute_a>attrib_a</attribute_a>
          <attribute_b>attrib_b</attribute_b>
          <attribute_c>attrib_c</attribute_c>
          <sort_attribute>Boston</sort_attribute>
        </titleselect>
      </title>
      <title mode="final_example" name="final_name">
        <titleselect>
          <attribute_a>attrib_a</attribute_a>
          <attribute_b>attrib_b</attribute_b>
          <attribute_c>attrib_c</attribute_c>
          <sort_attribute>Chicago</sort_attribute>
        </titleselect>
      </title>
      <title mode="example" name="name_example">
        <titleselect>
          <attribute_a>attrib_a</attribute_a>
          <attribute_b>attrib_b</attribute_b>
          <attribute_c>attrib_c</attribute_c>
          <sort_attribute>New York</sort_attribute>
        </titleselect>
      </title>
    </titles>
</code>```

Is there anyway to achieve this, preferably using XSLT or Python?
I am completely new to the world of XSLT, but I have tried applying a number of solutions from other relevant questions e.g. XSLT sort parent element based on child element attribute
to no avail.

答:
If you are still interested in a Python solution, it can be achieved by using ElementTree.

How it works:

Getting all the title nodes

Removing each one from the root node

Sorting the title nodes in memory based on the sort_attribute tag

Adding each title node back to the root element in the correct order

```<code>import xml.etree.ElementTree as ET

def get_sort_attribute_tag_value(node):
    return node.find('titleselect').find('sort_attribute').text

with open('test.xml') as f:
    xml_node = ET.fromstring(f.read())

title_nodes = xml_node.findall('title')

for title_node in title_nodes:
    xml_node.remove(title_node)

title_nodes.sort(key=get_sort_attribute_tag_value)

for title_node in title_nodes:
    xml_node.append(title_node)

print(ET.tostring(xml_node).decode())

# in order to save as a new file
with open('new_file.xml', 'w') as f:
    f.write(ET.tostring(xml_node).decode())
</code>```

Outputs:

```<code><titles>
    <title mode="another_example" name="another_name">
        <titleselect>
            <attribute_a>attrib_a</attribute_a>
            <attribute_b>attrib_b</attribute_b>
            <attribute_c>attrib_c</attribute_c>
            <sort_attribute>Boston</sort_attribute>
        </titleselect>
    </title>
    <title mode="final_example" name="final_name">
        <titleselect>
            <attribute_a>attrib_a</attribute_a>
            <attribute_b>attrib_b</attribute_b>
            <attribute_c>attrib_c</attribute_c>
            <sort_attribute>Chicago</sort_attribute>
        </titleselect>
    </title>
    <title mode="example" name="name_example">
        <titleselect>
            <attribute_a>attrib_a</attribute_a>
            <attribute_b>attrib_b</attribute_b>
            <attribute_c>attrib_c</attribute_c>
            <sort_attribute>New York</sort_attribute>
        </titleselect>
    </title>
</titles>
</code>```

Body:
I have a number of XML-files with a structure like this:

<titles>
  <title mode="example" name="name_example">
    <titleselect>
      <attribute_a>attrib_a</attribute_a>
      <attribute_b>attrib_b</attribute_b>
      <attribute_c>attrib_c</attribute_c>
      <sort_attribute>New York</sort_attribute>
    </titleselect>
  </title>
  <title mode="another_example" name="another_name">
    <titleselect>
      <attribute_a>attrib_a</attribute_a>
      <attribute_b>attrib_b</attribute_b>
      <attribute_c>attrib_c</attribute_c>
      <sort_attribute>Boston</sort_attribute>
    </titleselect>
  </title>
  <title mode="final_example" name="final_name">
    <titleselect>
      <attribute_a>attrib_a</attribute_a>
      <attribute_b>attrib_b</attribute_b>
      <attribute_c>attrib_c</attribute_c>
      <sort_attribute>Chicago</sort_attribute>
    </titleselect>
  </title>
</titles>

I am trying to sort the "titles" alphabetically by the "sort_attribute". My desired output is like this:

<titles>
      <title mode="another_example" name="another_name">
        <titleselect>
          <attribute_a>attrib_a</attribute_a>
          <attribute_b>attrib_b</attribute_b>
          <attribute_c>attrib_c</attribute_c>
          <sort_attribute>Boston</sort_attribute>
        </titleselect>
      </title>
      <title mode="final_example" name="final_name">
        <titleselect>
          <attribute_a>attrib_a</attribute_a>
          <attribute_b>attrib_b</attribute_b>
          <attribute_c>attrib_c</attribute_c>
          <sort_attribute>Chicago</sort_attribute>
        </titleselect>
      </title>
      <title mode="example" name="name_example">
        <titleselect>
          <attribute_a>attrib_a</attribute_a>
          <attribute_b>attrib_b</attribute_b>
          <attribute_c>attrib_c</attribute_c>
          <sort_attribute>New York</sort_attribute>
        </titleselect>
      </title>
    </titles>

Is there anyway to achieve this, preferably using XSLT or Python?
I am completely new to the world of XSLT, but I have tried applying a number of solutions from other relevant questions e.g. XSLT sort parent element based on child element attribute
to no avail.

Body:
If you are still interested in a Python solution, it can be achieved by using ElementTree.

How it works:

Getting all the title nodes

Removing each one from the root node

Sorting the title nodes in memory based on the sort_attribute tag

Adding each title node back to the root element in the correct order

import xml.etree.ElementTree as ET

def get_sort_attribute_tag_value(node):
    return node.find('titleselect').find('sort_attribute').text

with open('test.xml') as f:
    xml_node = ET.fromstring(f.read())

title_nodes = xml_node.findall('title')

for title_node in title_nodes:
    xml_node.remove(title_node)

title_nodes.sort(key=get_sort_attribute_tag_value)

for title_node in title_nodes:
    xml_node.append(title_node)

print(ET.tostring(xml_node).decode())

# in order to save as a new file
with open('new_file.xml', 'w') as f:
    f.write(ET.tostring(xml_node).decode())

Outputs:

<titles>
    <title mode="another_example" name="another_name">
        <titleselect>
            <attribute_a>attrib_a</attribute_a>
            <attribute_b>attrib_b</attribute_b>
            <attribute_c>attrib_c</attribute_c>
            <sort_attribute>Boston</sort_attribute>
        </titleselect>
    </title>
    <title mode="final_example" name="final_name">
        <titleselect>
            <attribute_a>attrib_a</attribute_a>
            <attribute_b>attrib_b</attribute_b>
            <attribute_c>attrib_c</attribute_c>
            <sort_attribute>Chicago</sort_attribute>
        </titleselect>
    </title>
    <title mode="example" name="name_example">
        <titleselect>
            <attribute_a>attrib_a</attribute_a>
            <attribute_b>attrib_b</attribute_b>
            <attribute_c>attrib_c</attribute_c>
            <sort_attribute>New York</sort_attribute>
        </titleselect>
    </title>
</titles>


问:
playing with java Operators (XOR and AND/OR)
In a program I am trying to check two boolean values (returned from a function); the condition that needs to be checked is:

- only if any one of the returned value is true and the other is false then I have a problem;

- else if both are true or false I am good to go to next step.

Which of the following two examples would be the efficient way to check the condition, or is there a better solution?

a and b are integer values on which I am checking a condition for correctness in isCorrect function and it return true or false.

1.

```<code> // checking for the correctness of both a and b
 if ((isCorrect(a) && !isCorrect(b)) ||
     (!isCorrect(a) && isCorrect(b)))
 {
   // a OR b is incorrect
 }
 else
 {
   // a AND b are both correct or incorrect
 }
</code>```

2.

```<code>  // checking for the correctness of both a and b
  if (! (isCorrect(a) ^ isCorrect(b)))
  {
    // a OR b is incorrect
  }
  else
  {
    // a AND b are correct or incorrect
  }
</code>```

Thanks,

Ivar

P.S: code readability is not an issue.
EDIT: I meant to have an XOR in the second option.
Also, I agree with the == and != options, but what if I had to use boolean operators?

答:
```<code>if (isCorrect(a) != isCorrect(b)) {
  // a OR b is incorrect
} else {
  // a AND b are correct or incorrect
}
</code>```

Body:
In a program I am trying to check two boolean values (returned from a function); the condition that needs to be checked is:

- only if any one of the returned value is true and the other is false then I have a problem;

- else if both are true or false I am good to go to next step.

Which of the following two examples would be the efficient way to check the condition, or is there a better solution?

a and b are integer values on which I am checking a condition for correctness in isCorrect function and it return true or false.

1.

 // checking for the correctness of both a and b
 if ((isCorrect(a) && !isCorrect(b)) ||
     (!isCorrect(a) && isCorrect(b)))
 {
   // a OR b is incorrect
 }
 else
 {
   // a AND b are both correct or incorrect
 }

2.

  // checking for the correctness of both a and b
  if (! (isCorrect(a) ^ isCorrect(b)))
  {
    // a OR b is incorrect
  }
  else
  {
    // a AND b are correct or incorrect
  }

Thanks,

Ivar

P.S: code readability is not an issue.
EDIT: I meant to have an XOR in the second option.
Also, I agree with the == and != options, but what if I had to use boolean operators?

ContentLicense: CC BY-SA 2.5


问:
Adding stored procedures complex types in Entity Framework
I am trying to use a stored procedure in Entity Framework that returns nothing.

I did the following:

Added a function (right click on stored procedure -> add -> function import-> Complex Type -> Get column information -> create New Complex-Type)

My function name: summarySP_Result. After building the project the entity class is not generated in Generated_code (BusinessAccount.web.g.cs)

But entity classes for tables and views are all created but nor for stored procedure.

Can anybody give the idea why it is not generated entity class in BusinessAccount.web.g.cs?

Update :

Let me confirm ReturnDataFromTemTable_result entity class created in your XXXXXX.web.g.cs class.

Like :

```<code>[DataContract(Namespace="http://schemas.datacontract.org/2004/07/BizFramework.Web.Model")]
public sealed partial class ReturnDataFromTemTable_Result : Entity
{
   -------------------
 }
</code>```

答: To add complex type correctly, go Model browser, right click on function, then display edit, click edit an fill the dialog box. The name of the function should be same as name of the stored procedure. Click OK button. Now function is created. Then right click on the created function and go edit again.There is a update button aside of complex type button.Update it using that update button. Now complex type is created completely.</p>

Body:
I am trying to use a stored procedure in Entity Framework that returns nothing.

I did the following:

Added a function (right click on stored procedure -> add -> function import-> Complex Type -> Get column information -> create New Complex-Type)

My function name: summarySP_Result. After building the project the entity class is not generated in Generated_code (BusinessAccount.web.g.cs)

But entity classes for tables and views are all created but nor for stored procedure.

Can anybody give the idea why it is not generated entity class in BusinessAccount.web.g.cs?

Update :

Let me confirm ReturnDataFromTemTable_result entity class created in your XXXXXX.web.g.cs class.

Like :

[DataContract(Namespace="http://schemas.datacontract.org/2004/07/BizFramework.Web.Model")]
public sealed partial class ReturnDataFromTemTable_Result : Entity
{
   -------------------
 }


问:
Two array combine or flipped
I have this two arrays:

```<code>array:4 [▼
  0 => 518
  1 => 519
  2 => 520
  3 => 521
]
</code>```

and this one:

```<code>array:4 [▼
  0 => "1"
  1 => "2"
  2 => "3"
  3 => "3"
]
</code>```

Can someone please help me how to achieve like this..

```<code>array:4 [▼
 518=>1
  519=> 2
 520 => 3
  521 => 3
]
</code>```

I do not know if it is possible or not like

答:
You can loop through and use the key to associate between your arrays.  You have a little type juggling to do.

```<code><?php
$one =
[
  0 => 518,
  1 => 519,
  2 => 520,
  3 => 521
];

$two =
[
  0 => "1",
  1 => "2",
  2 => "3",
  3 => "3"
];

$desired =
[
  518 => 1,
  519 => 2,
  520 => 3,
  521 => 3
];

foreach($one as $k=>$v)
{
    $out[$v] = (int) $two[$k];
}

if($desired === $out) {
    echo 'All good.';
}
</code>```

Output:

```<code>All good.
</code>```

Title: Two array combine or flipped

Body:
I have this two arrays:

array:4 [▼
  0 => 518
  1 => 519
  2 => 520
  3 => 521
]

and this one:

array:4 [▼
  0 => "1"
  1 => "2"
  2 => "3"
  3 => "3"
]

Can someone please help me how to achieve like this..

array:4 [▼
 518=>1
  519=> 2
 520 => 3
  521 => 3
]

I do not know if it is possible or not like

Body:
You can loop through and use the key to associate between your arrays.  You have a little type juggling to do.

<?php
$one =
[
  0 => 518,
  1 => 519,
  2 => 520,
  3 => 521
];

$two =
[
  0 => "1",
  1 => "2",
  2 => "3",
  3 => "3"
];

$desired =
[
  518 => 1,
  519 => 2,
  520 => 3,
  521 => 3
];

foreach($one as $k=>$v)
{
    $out[$v] = (int) $two[$k];
}

if($desired === $out) {
    echo 'All good.';
}

Output:

All good.


问:
Delegates in C#
I`m having some trouble in understanding how delegates in C# work. I have many code examples, but i still could not grasp it properly.

Can someone explain it to me in "plain english"? Of course! examples of code will help, but i think i need more of a description of how/why it works.

EDIT:

Well, the question is: why does delegates work? What is a "flow chart" of the entire process?

What are the pre-requisites of using delegates?

I hope this makes the question clearer.

答:
1) First you have to understand why/when you need a delegate, what is the problem that it solve.

In my experience I mainly use them to allow a user to customize an object's behavior.

Immagine a Grid component that allows the developer to customize how each column will be rendered.
For example you want to write a of red color value when it's a number under zero.

The developer that create the Grid does not know how the user want to customize the output so it need a mechanism that let the user of the component to inject some logic into the component.

2) Then you have to understand how the delegate works

What is confusing is the strange code you have to write to do so, and the many ways you have to do the same thing.

This is the grid class:

```<code>// the grid let the programmer that will use it to customize the output
public class Grid{

    // 1) First I declare only the interface of the delegate
    public delegate String ValueFormatterDelegate(String v);

    // 2) I declare a handler of the implementation of the delegate
    public ValueFormatterDelegate ValueFormatterHandler;

    // 3) I call the handler inside the Print method
    public void Print(String x){
        Console.WriteLine( ValueFormatterHandler.Invoke(x) );
    }

}
</code>```

// 1) First I declare only the interface of the delegate
  public delegate String ValueFormatterDelegate(String v);

Note that is like a normal method but:

it has a delegate keyword

it don't has a implementation

In this way I say: "the method that will format the output has this interface: it will take a string as input and it will output a string"

It remember to me a definition of a method of an interface.

// 2) I declare a handler of the implementation of the delegate
  public ValueFormatterDelegate ValueFormatterHandler;

Now I have to create a property of the type of the delegate that will handle te implementation of this method.

// 3) I call the handler inside the Print method
  public void Print(String x){
    Console.WriteLine( ValueFormatterHandler.Invoke(x) );
  }

Inside the Print method I can use the handler that will link the real implementation.

ValueFormatterHandler is of type ValueFormatterDelegate
and ValueFormatterDelegate is ad delegate
and .Invoke is a method of delegate type

This is a program that use my Grid class and is able to personalize it on the fly.
The problem here is the many ways you have to do the same thing.

```<code>using System;

public class Program{
    public static void Main(){

        var printer = new Printer();

        // METHOD 1 : link to a named method
        // here i link the handler of the delegate to a real method
        // the FormatXXX is a static method defined at the ed of this code
        printer.ValueFormatter = FormatXXX;

        // when i call Print("hello")
        printer.Print("hello"); // XXhelloXX

        // METHOD 2 : anonimous method
        // think at this like a method but without a name
        // FormatYY (String x ){ return "YY"+x+"YY"; };
        //  become
        // delegate (String x ){ return "YY"+x+"YY"; };
        printer.ValueFormatter = delegate (String x ){ return "YY"+x+"YY"; };
        printer.Print("hello"); // YYhelloYY

        // METHOD 3 : anonimous method using lambda
        // as you can note the type of parameter x is inferred from the delegate declaration
        // public delegate String ValueFormatterDelegate(String v);
        printer.ValueFormatter = (x)=>"KK" + x + "KK";

    }

    public static String FormatXXX(String y){
        return "XX"+ y +"XX";
    }

}
</code>```

Title: Delegates in C#

Body:
1) First you have to understand why/when you need a delegate, what is the problem that it solve.

In my experience I mainly use them to allow a user to customize an object's behavior.

Immagine a Grid component that allows the developer to customize how each column will be rendered.
For example you want to write a of red color value when it's a number under zero.

The developer that create the Grid does not know how the user want to customize the output so it need a mechanism that let the user of the component to inject some logic into the component.

2) Then you have to understand how the delegate works

What is confusing is the strange code you have to write to do so, and the many ways you have to do the same thing.

This is the grid class:

// the grid let the programmer that will use it to customize the output
public class Grid{

    // 1) First I declare only the interface of the delegate
    public delegate String ValueFormatterDelegate(String v);

    // 2) I declare a handler of the implementation of the delegate
    public ValueFormatterDelegate ValueFormatterHandler;

    // 3) I call the handler inside the Print method
    public void Print(String x){
        Console.WriteLine( ValueFormatterHandler.Invoke(x) );
    }

}

// 1) First I declare only the interface of the delegate
  public delegate String ValueFormatterDelegate(String v);

Note that is like a normal method but:

it has a delegate keyword

it don't has a implementation

In this way I say: "the method that will format the output has this interface: it will take a string as input and it will output a string"

It remember to me a definition of a method of an interface.

// 2) I declare a handler of the implementation of the delegate
  public ValueFormatterDelegate ValueFormatterHandler;

Now I have to create a property of the type of the delegate that will handle te implementation of this method.

// 3) I call the handler inside the Print method
  public void Print(String x){
    Console.WriteLine( ValueFormatterHandler.Invoke(x) );
  }

Inside the Print method I can use the handler that will link the real implementation.

ValueFormatterHandler is of type ValueFormatterDelegate
and ValueFormatterDelegate is ad delegate
and .Invoke is a method of delegate type

This is a program that use my Grid class and is able to personalize it on the fly.
The problem here is the many ways you have to do the same thing.

using System;

public class Program{
    public static void Main(){

        var printer = new Printer();

        // METHOD 1 : link to a named method
        // here i link the handler of the delegate to a real method
        // the FormatXXX is a static method defined at the ed of this code
        printer.ValueFormatter = FormatXXX;

        // when i call Print("hello")
        printer.Print("hello"); // XXhelloXX

        // METHOD 2 : anonimous method
        // think at this like a method but without a name
        // FormatYY (String x ){ return "YY"+x+"YY"; };
        //  become
        // delegate (String x ){ return "YY"+x+"YY"; };
        printer.ValueFormatter = delegate (String x ){ return "YY"+x+"YY"; };
        printer.Print("hello"); // YYhelloYY

        // METHOD 3 : anonimous method using lambda
        // as you can note the type of parameter x is inferred from the delegate declaration
        // public delegate String ValueFormatterDelegate(String v);
        printer.ValueFormatter = (x)=>"KK" + x + "KK";

    }

    public static String FormatXXX(String y){
        return "XX"+ y +"XX";
    }

}


问:
Sorted Dictionary - C#
I'm trying to figure out how to create a sorted dictionary where the key is sorted in a non-alphabetical manner.  Is there a way I can define the way I want it to sort?

For example, the keys might be in order like the following:

```<code>AAA1X
AAB1Y
AAC1Y
AAA2X
AAB2Y
AAC2X
</code>```

Although the first three letters are alphabetical, if I sort as is it will lump them in the wrong order (due to the number). Also note, that there is either a X or Y at the end.  In the code, there will only ever be an X or a Y.

Even if I can write an enumeration for the ordering of all possible combinations I'd be willing to do that as well, but I'm not sure how I can use the sorted dictionary and an enumeration...

I know this is a bit vague, but any help would be much appreciated!

Cheers!

答:
One of the constructors for SortedDictionary<TKey, TValue> takes an IComparer<TKey>, where you can specify a custom comparer class that the dictionary will use for sorting.

```<code>public class CustomComparer : IComparer<string>
{
    public int Compare(string x, string y)
    {
        // do your own comparison however you like; return a negative value
        // to indicate that x < y, a positive value to indicate that x > y,
        // or 0 to indicate that they are equal.
    }
}

...

SortedDictionary<string, object> dict =
              new SortedDictionary<string, object>(new CustomComparer());
</code>```

Title: Sorted Dictionary - C#

Body:
I'm trying to figure out how to create a sorted dictionary where the key is sorted in a non-alphabetical manner.  Is there a way I can define the way I want it to sort?

For example, the keys might be in order like the following:

AAA1X
AAB1Y
AAC1Y
AAA2X
AAB2Y
AAC2X

Although the first three letters are alphabetical, if I sort as is it will lump them in the wrong order (due to the number). Also note, that there is either a X or Y at the end.  In the code, there will only ever be an X or a Y.

Even if I can write an enumeration for the ordering of all possible combinations I'd be willing to do that as well, but I'm not sure how I can use the sorted dictionary and an enumeration...

I know this is a bit vague, but any help would be much appreciated!

Cheers!

Body:
One of the constructors for SortedDictionary<TKey, TValue> takes an IComparer<TKey>, where you can specify a custom comparer class that the dictionary will use for sorting.

public class CustomComparer : IComparer<string>
{
    public int Compare(string x, string y)
    {
        // do your own comparison however you like; return a negative value
        // to indicate that x < y, a positive value to indicate that x > y,
        // or 0 to indicate that they are equal.
    }
}

...

SortedDictionary<string, object> dict =
              new SortedDictionary<string, object>(new CustomComparer());


问:
Carthage Xcode 9 Error
I try to install Carthage in my project but it always crash on launch.

Nothing works from what I've tried..

Error:

```<code>dyld: Library not loaded: @rpath/StarscreamSocketIO.framework/StarscreamSocketIO
Referenced from: /private/var/containers/Bundle/Application/69ADA4FD-59A0-4840-9A64-XXXXX/XXXX.app/Frameworks/SocketIO.framework/SocketIO
Reason: image not found
</code>```

Carthage folder:

Linked Frameworks and Libraries:

Run Script:

Copy Files:

I also tried to set the framework in Embedded Binaries.

Thank you.

Edit: Cartfile file:

答:
Swift 3

If you can't port your code to Swift 4, the following is a possible workaround:

1.inside your main project, drag and drop the file Starscream.xcodeproj which is inside:

```<code>Carthage/Checkouts/socket.io-client-swift/Source/Starscream
</code>```

2.add the framework StarscreamSocketIO.framework inside the section "Linked Frameworks and Libraries"

3.compile and run

Swift 4

socket.io v11 had a bug with Carthage:
github.com/socketio/socket.io-client-swift/issues/787
although it's possible to fix it with some manual workarounds, I recommend you to upgrade to the latest socket.io v13

Title: Carthage Xcode 9 Error

Body:
I try to install Carthage in my project but it always crash on launch.

Nothing works from what I've tried..

Error:

dyld: Library not loaded: @rpath/StarscreamSocketIO.framework/StarscreamSocketIO
Referenced from: /private/var/containers/Bundle/Application/69ADA4FD-59A0-4840-9A64-XXXXX/XXXX.app/Frameworks/SocketIO.framework/SocketIO
Reason: image not found

Carthage folder:

Linked Frameworks and Libraries:

Run Script:

Copy Files:

I also tried to set the framework in Embedded Binaries.

Thank you.

Edit: Cartfile file:

Body:
Swift 3

If you can't port your code to Swift 4, the following is a possible workaround:

1.inside your main project, drag and drop the file Starscream.xcodeproj which is inside:

Carthage/Checkouts/socket.io-client-swift/Source/Starscream

2.add the framework StarscreamSocketIO.framework inside the section "Linked Frameworks and Libraries"

3.compile and run

Swift 4

socket.io v11 had a bug with Carthage:
github.com/socketio/socket.io-client-swift/issues/787
although it's possible to fix it with some manual workarounds, I recommend you to upgrade to the latest socket.io v13


问:
Convert Json string to Json object in Swift 4
I try to convert JSON string to a JSON object but after JSONSerialization the output is nil in JSON.

Response String:

```<code>[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]
</code>```

I try to convert this string with my code below:

```<code>let jsonString = response.result.value
let data: Data? = jsonString?.data(using: .utf8)
let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String:AnyObject]
 print(json ?? "Empty Data")
</code>```

答:
The problem is that you thought your jsonString is a dictionary. It's not.

It's an array of dictionaries.
In raw json strings, arrays begin with [ and dictionaries begin with {.

I used your json string with below code :

```<code>let string = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]"
let data = string.data(using: .utf8)!
do {
    if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>]
    {
       print(jsonArray) // use the json here
    } else {
        print("bad json")
    }
} catch let error as NSError {
    print(error)
}
</code>```

and I am getting the output :

```<code>[["form_desc": <null>, "form_name": Activity 4 with Images, "canonical_name": df_SAWERQ, "form_id": 3465]]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I try to convert JSON string to a JSON object but after JSONSerialization the output is nil in JSON.

Response String:

[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]

I try to convert this string with my code below:

let jsonString = response.result.value
let data: Data? = jsonString?.data(using: .utf8)
let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String:AnyObject]
 print(json ?? "Empty Data")

Body:
The problem is that you thought your jsonString is a dictionary. It's not.

It's an array of dictionaries.
In raw json strings, arrays begin with [ and dictionaries begin with {.

I used your json string with below code :

let string = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]"
let data = string.data(using: .utf8)!
do {
    if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>]
    {
       print(jsonArray) // use the json here
    } else {
        print("bad json")
    }
} catch let error as NSError {
    print(error)
}

and I am getting the output :

[["form_desc": <null>, "form_name": Activity 4 with Images, "canonical_name": df_SAWERQ, "form_id": 3465]]


问:
How to filter an array in MS Access
I am writing an array which can compare with my database(query). May I know how can I make it so it can include a "Or" logic within my array? Because I would like to get the output like Filter = myArray(0) Or myArray(1) Or myArray(2) ... Since I don't have the number of my array because it is depends on how many inputs did the user type, so I just have a myArray(x).
Thank you.

```<code>Private Sub TestButton_Click()
Dim myArray As Variant
Dim Status_Input As Variant
Dim x As Variant
Dim i As Variant
Dim Status_Filter As Variant

Status_Input = Forms![try2].StatusInput

myArray = Split(Status_Input, ";")

For x = LBound(myArray) To UBound(myArray)
MsgBox " " & myArray(x) & " "             'MsgBox = 03 20 27 (3 MsgBoxes)

Status_Filter = _
"[Status] Like " & myArray(x)

Debug.Print Status_Filter
Me.Filter = Status_Filter
Me.FilterOn = True

Next x
</code>```

End Sub

答:
Reading your code, you could eventually try another path.

```<code>status_filter = "status IN ( " & replace(status_input,";",",") & ")"
</code>```

this should evaluate to something like:

```<code>status_filter = "status IN (2, 4, 6)"
</code>```

Since status_input is already a list, if the values are numeric, the above should work, and be efficient.

Title: How to filter an array in MS Access

Body:
I am writing an array which can compare with my database(query). May I know how can I make it so it can include a "Or" logic within my array? Because I would like to get the output like Filter = myArray(0) Or myArray(1) Or myArray(2) ... Since I don't have the number of my array because it is depends on how many inputs did the user type, so I just have a myArray(x).
Thank you.

Private Sub TestButton_Click()
Dim myArray As Variant
Dim Status_Input As Variant
Dim x As Variant
Dim i As Variant
Dim Status_Filter As Variant

Status_Input = Forms![try2].StatusInput

myArray = Split(Status_Input, ";")

For x = LBound(myArray) To UBound(myArray)
MsgBox " " & myArray(x) & " "             'MsgBox = 03 20 27 (3 MsgBoxes)

Status_Filter = _
"[Status] Like " & myArray(x)

Debug.Print Status_Filter
Me.Filter = Status_Filter
Me.FilterOn = True

Next x

End Sub

Body:
Reading your code, you could eventually try another path.

status_filter = "status IN ( " & replace(status_input,";",",") & ")"

this should evaluate to something like:

status_filter = "status IN (2, 4, 6)"

Since status_input is already a list, if the values are numeric, the above should work, and be efficient.


问:
Parsing XML using Python ElementTree
I have an XML document in the following format

```<code><root>
<H D="14/11/2017">
<FC>
    <F LV="0">The quick</F>
    <F LV="1">brown</F>
    <F LV="2">fox</F>
</FC>
</H>
<H D="14/11/2017">
<FC>
    <F LV="0">The lazy</F>
    <F LV="1">fox</F>
</FC>
</H>
</root>
</code>```

How can I extract the text from 'D' inside H tag and also all the text inside the F tags.

答:
This should help you </p>

```<code>import xml.etree.ElementTree as ET
data='''
<root>
<H D="14/11/2017">
<FC>
    <F LV="0">The quick</F>
    <F LV="1">brown</F>
    <F LV="2">fox</F>
</FC>
</H>
<H D="14/11/2017">
<FC>
    <F LV="0">The lazy</F>
    <F LV="1">fox</F>
</FC>
</H>
</root>
'''
#list created to store data
D_data=[]
F_data=[]

#data parsed
root= ET.XML(data)

#This will get the value of D
for sub in root:
    b=(sub.attrib.get('D'))
    D_data.append(b)

#This will get all the text for F tag in xml
for f in root.iter("F"):
    b=f.text
    #print f.tag,f.attrib,f.text
    F_data.append(b)

print D_data
print F_data
</code>```

Title: Parsing XML using Python ElementTree

Body:
I have an XML document in the following format

<root>
<H D="14/11/2017">
<FC>
    <F LV="0">The quick</F>
    <F LV="1">brown</F>
    <F LV="2">fox</F>
</FC>
</H>
<H D="14/11/2017">
<FC>
    <F LV="0">The lazy</F>
    <F LV="1">fox</F>
</FC>
</H>
</root>

How can I extract the text from 'D' inside H tag and also all the text inside the F tags.

Body:
This should help you

import xml.etree.ElementTree as ET
data='''
<root>
<H D="14/11/2017">
<FC>
    <F LV="0">The quick</F>
    <F LV="1">brown</F>
    <F LV="2">fox</F>
</FC>
</H>
<H D="14/11/2017">
<FC>
    <F LV="0">The lazy</F>
    <F LV="1">fox</F>
</FC>
</H>
</root>
'''
#list created to store data
D_data=[]
F_data=[]

#data parsed
root= ET.XML(data)

#This will get the value of D
for sub in root:
    b=(sub.attrib.get('D'))
    D_data.append(b)

#This will get all the text for F tag in xml
for f in root.iter("F"):
    b=f.text
    #print f.tag,f.attrib,f.text
    F_data.append(b)

print D_data
print F_data


问:
OpenWrap vs NuGet
What is the difference between OpenWrap and NuGet. And what you prefer ?</p>

答:
One of the key tenets of NuGet (and an important difference with OpenWrap) is that it doesn't try to change the way you work.  Instead, it makes it much easier to do the things that you already do today.

Say for instance that you're trying to use a Foo library, which depends on a Bar library.  Today, you'd have to manually find those libraries, copy them to your machine and add references to them.  Then later newer versions will come out and you'll go through similar motions to get them updated.

In such scenario, both NuGet and OW will make it easy to bring in those references, but the key difference is that NuGet does it in a way that is completely non-invasive.  i.e. it will get the binaries onto your machine and references them in the same way as if you had done it manually.  After it has done that, your project file is completely 'normal', without any ties to NuGet at build or runtime.

What this means is that if you get some libraries via NuGet and put your project in source control, another developer is then able to use your project without needing NuGet at all.

The OpenWrap approach has merits as well, but to go that route, you have to be willing to be using OpenWrap all the way, and not easily be able to move away from it.

There are many other differences (like rich VS support in NuGet), but this is what I view as the most fundamental difference between the two.

Title: OpenWrap vs NuGet


问:
How to disable last page button in primeNG datatable?
I want to disable last page button in the primeNG datatable div.
The paginator is in the p-datatable tag.

code :

```<code>  <div class="ui-g-12">
      <p-dataTable [value]="bossDataTable" resizableColumns="true" columnResizeMode="expand" [lazy]="true" [rows]="15" [paginator]="true"
      [totalRecords]="totalRecords" [rowsPerPageOptions]="[15,20,25,30,40,50]" (onLazyLoad)="getBossDataTable($event)" >

         <!--some columns here -->
          <p-footer><span><label i18n>Total:</label> {{totalRecords}}</span></p-footer>
      </p-dataTable>
</code>```

According to doc:
https://www.primefaces.org/primeng/#/paginator

I got last page style here:
ui-paginator-last

How can I disable the last page button?Hide it or disable it is OK.

Now the paginator looks like :
|< < 1 2 3 4 5 > >|

答:
You can use CSS to hide the last page button like this:

```<code>.ui-paginator > .ui-paginator-last {
  display: none!important;
}
</code>```

Since .ui-paginator-last is an anchor tag you can simulate it being disabled by doing this:

```<code>.ui-paginator > .ui-paginator-last {
  pointer-events: none;
  color: gray;
}
</code>```

If you want the pagination to be unique you can add it to the footer of the DataTable and give it a unique styleClass:

```<code><p-dataTable [value]="cars" (change)="onDataTableChange($event)"
    styleClass="hidden-last"
    resizableColumns="true" [reorderableColumns]="true">
  <p-column *ngFor="let col of cols" [field]="col.field"
    [header]="col.header"></p-column>
  <p-footer><p-paginator styleClass="paginator1"></p-paginator></p-footer>
</p-dataTable>
</code>```

Then you'll have to do the same thing, but use the class name you gave the paginator:

```<code>.paginator1 > .ui-paginator-last {
  pointer-events: none;
  color: gray;
}
</code>```

or:

```<code>.paginator1 > .ui-paginator-last {
  display: none!important;
}
</code>```

Here's a plnkr demonstrating this approach (two tables, one last button disabled):
Click here

Body:
I want to disable last page button in the primeNG datatable div.
The paginator is in the p-datatable tag.

code :

Total: {{totalRecords}}

According to doc:
https://www.primefaces.org/primeng/#/paginator

I got last page style here:
ui-paginator-last

How can I disable the last page button?Hide it or disable it is OK.

Now the paginator looks like :
|< < 1 2 3 4 5 > >|

Body:
You can use CSS to hide the last page button like this:

.ui-paginator > .ui-paginator-last {
  display: none!important;
}

Since .ui-paginator-last is an anchor tag you can simulate it being disabled by doing this:

.ui-paginator > .ui-paginator-last {
  pointer-events: none;
  color: gray;
}

If you want the pagination to be unique you can add it to the footer of the DataTable and give it a unique styleClass:

<p-dataTable [value]="cars" (change)="onDataTableChange($event)"
    styleClass="hidden-last"
    resizableColumns="true" [reorderableColumns]="true">
  <p-column *ngFor="let col of cols" [field]="col.field"
    [header]="col.header"></p-column>
  <p-footer><p-paginator styleClass="paginator1"></p-paginator></p-footer>
</p-dataTable>

Then you'll have to do the same thing, but use the class name you gave the paginator:

.paginator1 > .ui-paginator-last {
  pointer-events: none;
  color: gray;
}

or:

.paginator1 > .ui-paginator-last {
  display: none!important;
}

Here's a plnkr demonstrating this approach (two tables, one last button disabled):
Click here


问:
How to target domain root in a Firebase hosting header rule
I have a web app using custom domain. This domain has A record mapped to 151.101.1.195 and 151.101.65.195.

Everything works correctly, but when I have firebase.json like this:

```<code>{
  "hosting": {
    "public": "dist",
    "headers": [{
      "source": "**/*.html",
      "headers": [{
        "key": "Cache-Control",
        "value": "private, max-age=0, no-cache"
      }]
    }]
  }
}
</code>```

I still see the response headers like this when I visit https://mycustomdomain.com:

```<code>accept-ranges:bytes
cache-control:max-age=3600
content-encoding:gzip
content-length:839
content-type:text/html; charset=utf-8
date:Wed, 27 Sep 2017 06:54:58 GMT
etag:"f0b36e6c2a348eb46d07907fea856e9a"
last-modified:Wed, 27 Sep 2017 06:53:07 GMT
server:nginx
status:200
strict-transport-security:max-age=31556926
vary:Accept-Encoding
via:1.1 varnish
x-cache:HIT
x-cache-hits:2
x-powered-by:Express
x-served-by:cache-bma7024-BMA
x-timer:S1506495298.256593,VS0,VE0
</code>```

I expect the cache control header to be modified, but it doesn't change.

How can I change the response headers for domain root?

答:
For anyone looking, I ended up doing it like this, and it seems to work:

{
  "hosting": {
    "public": "dist",
    "headers": [
      {
        "source": "/",
        "headers": [{
          "key": "Cache-Control",
          "value": "private, max-age=0, no-cache"
        }]
      },
      {
        "source": "**/*",
        "headers": [{
          "key": "Cache-Control",
          "value": "private, max-age=0, no-cache"
        }]
      },
      {
        "source": "**/*.js",
        "headers": [{
          "key": "Cache-Control",
          "value": "max-age=31536000"
        }]
      },
      {
        "source": "**/*.css",
        "headers": [{
          "key": "Cache-Control",
          "value": "max-age=31536000"
        }]
      },
      {
        "source": "**/*.jpg",
        "headers": [{
          "key": "Cache-Control",
          "value": "max-age=31536000"
        }]
      },
      {
        "source": "**/*.png",
        "headers": [{
          "key": "Cache-Control",
          "value": "max-age=31536000"
        }]
      }
    ],
    "rewrites": [
        { "source": "/api/1/mina", "function": "mydata" },
        { "source": "**", "destination": "/index.html" }
      ]
  }
}
```

This also works with functions. Note that .js files are also agressively cached, as we use cache busting urls.

Body:
I have a web app using custom domain. This domain has A record mapped to 151.101.1.195 and 151.101.65.195.

Everything works correctly, but when I have firebase.json like this:

{
  "hosting": {
    "public": "dist",
    "headers": [{
      "source": "**/*.html",
      "headers": [{
        "key": "Cache-Control",
        "value": "private, max-age=0, no-cache"
      }]
    }]
  }
}

I still see the response headers like this when I visit https://mycustomdomain.com:

accept-ranges:bytes
cache-control:max-age=3600
content-encoding:gzip
content-length:839
content-type:text/html; charset=utf-8
date:Wed, 27 Sep 2017 06:54:58 GMT
etag:"f0b36e6c2a348eb46d07907fea856e9a"
last-modified:Wed, 27 Sep 2017 06:53:07 GMT
server:nginx
status:200
strict-transport-security:max-age=31556926
vary:Accept-Encoding
via:1.1 varnish
x-cache:HIT
x-cache-hits:2
x-powered-by:Express
x-served-by:cache-bma7024-BMA
x-timer:S1506495298.256593,VS0,VE0

I expect the cache control header to be modified, but it doesn't change.

How can I change the response headers for domain root?

Body:
For anyone looking, I ended up doing it like this, and it seems to work:

{
  "hosting": {
    "public": "dist",
    "headers": [
      {
        "source": "/",
        "headers": [{
          "key": "Cache-Control",
          "value": "private, max-age=0, no-cache"
        }]
      },
      {
        "source": "**/*",
        "headers": [{
          "key": "Cache-Control",
          "value": "private, max-age=0, no-cache"
        }]
      },
      {
        "source": "**/*.js",
        "headers": [{
          "key": "Cache-Control",
          "value": "max-age=31536000"
        }]
      },
      {
        "source": "**/*.css",
        "headers": [{
          "key": "Cache-Control",
          "value": "max-age=31536000"
        }]
      },
      {
        "source": "**/*.jpg",
        "headers": [{
          "key": "Cache-Control",
          "value": "max-age=31536000"
        }]
      },
      {
        "source": "**/*.png",
        "headers": [{
          "key": "Cache-Control",
          "value": "max-age=31536000"
        }]
      }
    ],
    "rewrites": [
        { "source": "/api/1/mina", "function": "mydata" },
        { "source": "**", "destination": "/index.html" }
      ]
  }
}

This also works with functions. Note that .js files are also agressively cached, as we use cache busting urls.


问:
display a paperclip image using Foreign key association
I have two Models. I would like to use the foreign key(resource_id) in my resources_game model to display an image.

This is my Resource Model

```<code>class Resource < ActiveRecord::Base

has_many :resource_books
has_many :resource_games, :dependent => :destroy
belongs_to :resouce_type
has_attached_file :image, :styles => { :small => "100x120>"},
                  :url  => "/assets/games/images/:basename/:style/:basename.:extension",
                  :path =>":rails_root/public/assets/games/images/:basename/:style/:basename.:extension"
accepts_nested_attributes_for :resource_books, :resource_games
</code>```

This is my ResourceGame Model

```<code>class ResourceGame < ActiveRecord::Base

belongs_to :resource, :class_name => ResourceGame, :foreign_key => :resource_id
attr_accessor :add_resources

has_attached_file :image, :styles => { :small => "100x120>"},
                  :url  => "/assets/games/images/:basename/:style/:basename.:extension",
                  :path =>":rails_root/public/assets/games/images/:basename/:style/:basename.:extension"

accepts_nested_attributes_for :add_resource
</code>```

If the image was stored in the resources table I would retrieve and populate the table like this:

in my Resources Controller:

```<code>@latest_resources = Resource.paginate(:page => params[:page],:order => "id DESC", :per_page => 10)
</code>```

then in my view:

```<code><% @latest_resources.each do |project| %>

   <tr>
     <td><%= image_tag project.image.url(:small)  %></td>
     <td><%= project.resouce_type_name %></td>
     <td><%= project.name %></td>
     <td><%= project.url %></td>
   </tr>
<% end %>
</code>```

The image is being stored in the resources_game table, so what should I do to write in the image_tag in my view to retrieve it?

答:
you need to use form_for and build a nested form. Here are the instructions, go over it and then ping me.

@resource.resourcegames  is an array because you have an has_many relationship, so when you use form_for you can either have 1 nested form or many nested forms.

Also I quote the paperclip github page

Usage

The basics of Paperclip are quite simple: Declare that your model has an attachment with the has_attached_file method, and give it a name.

Paperclip will wrap up to four attributes (all prefixed with that attachment's name, so you can have multiple attachments per model if you wish) and give them a friendly front end. These attributes are:

```<code><attachment>_file_name
<attachment>_file_size
<attachment>_content_type
<attachment>_updated_at
</code>```

By default, only _file_name is required for Paperclip to operate. You'll need to add _content_type in case you want to use content type validation.

More information about the options passed to has_attached_file is available in the documentation of Paperclip::ClassMethods.

There are several guides at the following links

http://www.railscook.com/recipes/multiple-files-upload-with-nested-resource-using-paperclip-in-rails/

Rails + Paperclip - Update/Edit multiple images

https://github.com/thoughtbot/paperclip/issues/1734

https://groups.google.com/forum/#!topic/rubyonrails-talk/Waxw8D6seRc

https://sleekd.com/general/adding-multiple-images-to-a-rails-model-with-paperclip/

Body:
I have two Models. I would like to use the foreign key(resource_id) in my resources_game model to display an image.

This is my Resource Model

class Resource < ActiveRecord::Base

has_many :resource_books
has_many :resource_games, :dependent => :destroy
belongs_to :resouce_type
has_attached_file :image, :styles => { :small => "100x120>"},
                  :url  => "/assets/games/images/:basename/:style/:basename.:extension",
                  :path =>":rails_root/public/assets/games/images/:basename/:style/:basename.:extension"
accepts_nested_attributes_for :resource_books, :resource_games

This is my ResourceGame Model

class ResourceGame < ActiveRecord::Base

belongs_to :resource, :class_name => ResourceGame, :foreign_key => :resource_id
attr_accessor :add_resources

has_attached_file :image, :styles => { :small => "100x120>"},
                  :url  => "/assets/games/images/:basename/:style/:basename.:extension",
                  :path =>":rails_root/public/assets/games/images/:basename/:style/:basename.:extension"

accepts_nested_attributes_for :add_resource

If the image was stored in the resources table I would retrieve and populate the table like this:

in my Resources Controller:

@latest_resources = Resource.paginate(:page => params[:page],:order => "id DESC", :per_page => 10)

then in my view:

<% @latest_resources.each do |project| %>

     <%= image_tag project.image.url(:small)  %>
     <%= project.resouce_type_name %>
     <%= project.name %>
     <%= project.url %>

<% end %>

The image is being stored in the resources_game table, so what should I do to write in the image_tag in my view to retrieve it?

Body:
you need to use form_for and build a nested form. Here are the instructions, go over it and then ping me.

@resource.resourcegames  is an array because you have an has_many relationship, so when you use form_for you can either have 1 nested form or many nested forms.

Also I quote the paperclip github page

Usage

The basics of Paperclip are quite simple: Declare that your model has an attachment with the has_attached_file method, and give it a name.

Paperclip will wrap up to four attributes (all prefixed with that attachment's name, so you can have multiple attachments per model if you wish) and give them a friendly front end. These attributes are:

<attachment>_file_name
<attachment>_file_size
<attachment>_content_type
<attachment>_updated_at

By default, only _file_name is required for Paperclip to operate. You'll need to add _content_type in case you want to use content type validation.

More information about the options passed to has_attached_file is available in the documentation of Paperclip::ClassMethods.

There are several guides at the following links

http://www.railscook.com/recipes/multiple-files-upload-with-nested-resource-using-paperclip-in-rails/

Rails + Paperclip - Update/Edit multiple images

https://github.com/thoughtbot/paperclip/issues/1734

https://groups.google.com/forum/#!topic/rubyonrails-talk/Waxw8D6seRc

https://sleekd.com/general/adding-multiple-images-to-a-rails-model-with-paperclip/


问:
GD Library image generation does not work with mySQL query
Long story short, I have a project that requires creating a user's avatar based on their data from the database. The avatar is generated using the imagepng() and imagecopy() functions.

The user's avatar can either be male or female and that preference is saved in an SQL database as column "user_gender" where "0" = female and "1" = male:

Screenshot of table in phpmyadmin

So the idea is that we take the data from the database, assign the value (0 or 1) to a variable, then use that variable to generate the image. See code below:

```<code><?php

    //Database connection script not included, but works fine

    $id = 1;

        $sqlQuery = "SELECT * FROM table WHERE id = :id";
        $statement = $db->prepare($sqlQuery);
        $statement->execute(array(':id' => $id));

        while($rs = $statement->fetch())
        {
            $gender = $rs['user_gender'];

        }

    if($gender == "0")
    {
        //Allocation of images, file paths
        $bodytype ="images/female/f_body.png";
    }
    else
    {
        $bodytype ="images/male/f_body.png";
    }

    header('Content-Type: image/png');

    $destination = imagecreatefrompng($bodytype);

    imagealphablending($destination, true);
    imagesavealpha($destination, true);

    imagepng($destination);
?>
</code>```

This code however, does not work as it results in a blank black page on the browser.

HOWEVER, this code, without any pulling from the database, works perfectly fine:

```<code><?php

//taking out the sql query and just creating a $gender variable for testing

$gender = "0";

if($gender === 0)
{
    $bodytype ="images/female/f_body.png";
}
else
{
    $bodytype ="images/female/f_body.png";
}

header('Content-Type: image/png');

$destination = imagecreatefrompng($bodytype);

imagealphablending($destination, true);
imagesavealpha($destination, true);

imagepng($destination);
?>
</code>```

This is the output with the second code, showing that the image generation is indeed functional and the problem is most likely the passing from sql to php:

Working image generation in browser

I'd be extremely grateful to know what I am doing wrong or being hinted as to why the code stops working if the variable is pulled from the database.

Thank you!

答:
I tried your code and encountered the same problem so I did some digging it and found that nothing was returned from the database so what I did was prefix the database name along with the tablename and it worked. See code below

```<code>$gender = '';

$sqlQuery = "SELECT * FROM register.users WHERE id = :id";
$statement = $db->prepare($sqlQuery);
$statement->execute(array('id' => 1));

while($rs = $statement->fetch())
{
    $gender = $rs['gender'];
}

if($gender == 0)
{
    $bodytype ="images/female/f_body.png";
}
else if($gender == 1)
{
    $bodytype ="images/male/m_body.png";
}

$destination = imagecreatefrompng($bodytype);

imagealphablending($destination, true);
imagesavealpha($destination, true);

header('Content-Type: image/png');
imagepng($destination);
</code>```

Try it and let me know how it goes.

Body:
Long story short, I have a project that requires creating a user's avatar based on their data from the database. The avatar is generated using the imagepng() and imagecopy() functions.

The user's avatar can either be male or female and that preference is saved in an SQL database as column "user_gender" where "0" = female and "1" = male:

Screenshot of table in phpmyadmin

So the idea is that we take the data from the database, assign the value (0 or 1) to a variable, then use that variable to generate the image. See code below:

<?php

    //Database connection script not included, but works fine

    $id = 1;

        $sqlQuery = "SELECT * FROM table WHERE id = :id";
        $statement = $db->prepare($sqlQuery);
        $statement->execute(array(':id' => $id));

        while($rs = $statement->fetch())
        {
            $gender = $rs['user_gender'];

        }

    if($gender == "0")
    {
        //Allocation of images, file paths
        $bodytype ="images/female/f_body.png";
    }
    else
    {
        $bodytype ="images/male/f_body.png";
    }

    header('Content-Type: image/png');

    $destination = imagecreatefrompng($bodytype);

    imagealphablending($destination, true);
    imagesavealpha($destination, true);

    imagepng($destination);
?>

This code however, does not work as it results in a blank black page on the browser.

HOWEVER, this code, without any pulling from the database, works perfectly fine:

<?php

//taking out the sql query and just creating a $gender variable for testing

$gender = "0";

if($gender === 0)
{
    $bodytype ="images/female/f_body.png";
}
else
{
    $bodytype ="images/female/f_body.png";
}

header('Content-Type: image/png');

$destination = imagecreatefrompng($bodytype);

imagealphablending($destination, true);
imagesavealpha($destination, true);

imagepng($destination);
?>

This is the output with the second code, showing that the image generation is indeed functional and the problem is most likely the passing from sql to php:

Working image generation in browser

I'd be extremely grateful to know what I am doing wrong or being hinted as to why the code stops working if the variable is pulled from the database.

Thank you!

Body:
I tried your code and encountered the same problem so I did some digging it and found that nothing was returned from the database so what I did was prefix the database name along with the tablename and it worked. See code below

$gender = '';

$sqlQuery = "SELECT * FROM register.users WHERE id = :id";
$statement = $db->prepare($sqlQuery);
$statement->execute(array('id' => 1));

while($rs = $statement->fetch())
{
    $gender = $rs['gender'];
}

if($gender == 0)
{
    $bodytype ="images/female/f_body.png";
}
else if($gender == 1)
{
    $bodytype ="images/male/m_body.png";
}

$destination = imagecreatefrompng($bodytype);

imagealphablending($destination, true);
imagesavealpha($destination, true);

header('Content-Type: image/png');
imagepng($destination);

Try it and let me know how it goes.


问:
App has conflicting provisioning settings in Build Settings
I have generated a certificate and created a provisioning profile for my project so that I could make push notification in it, but when in Build Setting -> CodeSigning I write the name of provisioning profile and give my team name in General an error appears that AppName has conflicting provisioning settings.

How can I correct this?

The error looks like this

答:
Goto Build Settings -> Signing

Set

Code Signing Identity to IOS Developer (Automatic)

Provisioning Profile to Automatic

Provisioning Profile(Deprecated) to Automatic

Uncheck "Automatically manage signing", then check it again and reselect the Team.


问:
Django: How to update Photo model that uses Imagekit without re-uploading photo on save()
I have a Photo model that I want to update.  When I try to save I get errors from my s3 bucket as well as validation errors about certain fields cannot be null.  I think I understand why it is doing this, it assumes this is a totally new image upload, but all I want to do is edit the title. How can I accomplish this?  Any help would be greatly appreciated.</p>

答:
Your file storage shouldn't be called unless the file associated with your FileField has changed. In your case, I don't see a reason why s3 should ever even get hit by doing a simple photo.title = 'New title'; photo.save()

It could be lots of other issues, granted, I haven't tried Imagekit yet (very nice app!), but I'm guessing something, somewhere is inadvertently altering your ImageField file data. I suggest you write a simple test that edits an existing Photo model instance and debug the issue thoroughly.


问:
Excel vba: Create a macro to connect a slicer to multiple pivot tables
I am trying to create a macro that will change the data source for three pivot tables.  Then, a single slicer that is already on the sheet will be connected to all three pivot tables.  The pivot tables all will take their data from the same place.

When I try this, I get an error at the step to connect the slicer to pivot tables 2 and 3.  If I run the macro with only the steps to change the data source for each pivot table, I noticed that the slicer only has one option in the "report connections" box instead of 3.

Here is what I have:

```<code>Sheets("Sales").Select
ActiveSheet.PivotTables("PivotTable1").ChangePivotCache ActiveWorkbook. _
PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Table3", Version _
:=xlPivotTableVersion15)

ActiveSheet.PivotTables("PivotTable2").ChangePivotCache ActiveWorkbook. _
PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Table3", Version _
:=xlPivotTableVersion15)

ActiveSheet.PivotTables("PivotTable3").ChangePivotCache ActiveWorkbook. _
PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Table3", Version _
:=xlPivotTableVersion15)

ActiveWorkbook.SlicerCaches("Slicer_Year").PivotTables.AddPivotTable ( _
ActiveSheet.PivotTables("PivotTable1"))
ActiveWorkbook.SlicerCaches("Slicer_Year").PivotTables.AddPivotTable ( _
ActiveSheet.PivotTables("PivotTable2"))
ActiveWorkbook.SlicerCaches("Slicer_Year").PivotTables.AddPivotTable ( _
ActiveSheet.PivotTables("PivotTable3"))
</code>```

答:
I had the same problem and it was the last parenthesis which was causing the error.
So you should replace this:

```<code>ActiveWorkbook.SlicerCaches("Slicer_Year").PivotTables.AddPivotTable ( _
ActiveSheet.PivotTables("PivotTable2"))
</code>```

with this:

```<code> ActiveWorkbook.SlicerCaches("Slicer_Year").PivotTables.AddPivotTable _
 ActiveSheet.PivotTables("PivotTable2")
</code>```

Also you could write your code in this way:

```<code>Dim WB as Workbook
Dim WS as Worksheet

Set WB = ActiveWorkbook
Set WS = WB.Sheets("Sales")

WB.SlicerCaches("Slicer_Year").PivotTables.AddPivotTable _
WS.PivotTables("PivotTable2")
</code>```

Body:
I am trying to create a macro that will change the data source for three pivot tables.  Then, a single slicer that is already on the sheet will be connected to all three pivot tables.  The pivot tables all will take their data from the same place.

When I try this, I get an error at the step to connect the slicer to pivot tables 2 and 3.  If I run the macro with only the steps to change the data source for each pivot table, I noticed that the slicer only has one option in the "report connections" box instead of 3.

Here is what I have:

Sheets("Sales").Select
ActiveSheet.PivotTables("PivotTable1").ChangePivotCache ActiveWorkbook. _
PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Table3", Version _
:=xlPivotTableVersion15)

ActiveSheet.PivotTables("PivotTable2").ChangePivotCache ActiveWorkbook. _
PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Table3", Version _
:=xlPivotTableVersion15)

ActiveSheet.PivotTables("PivotTable3").ChangePivotCache ActiveWorkbook. _
PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Table3", Version _
:=xlPivotTableVersion15)

ActiveWorkbook.SlicerCaches("Slicer_Year").PivotTables.AddPivotTable ( _
ActiveSheet.PivotTables("PivotTable1"))
ActiveWorkbook.SlicerCaches("Slicer_Year").PivotTables.AddPivotTable ( _
ActiveSheet.PivotTables("PivotTable2"))
ActiveWorkbook.SlicerCaches("Slicer_Year").PivotTables.AddPivotTable ( _
ActiveSheet.PivotTables("PivotTable3"))

Body:
I had the same problem and it was the last parenthesis which was causing the error.
So you should replace this:

ActiveWorkbook.SlicerCaches("Slicer_Year").PivotTables.AddPivotTable ( _
ActiveSheet.PivotTables("PivotTable2"))

with this:

 ActiveWorkbook.SlicerCaches("Slicer_Year").PivotTables.AddPivotTable _
 ActiveSheet.PivotTables("PivotTable2")

Also you could write your code in this way:

Dim WB as Workbook
Dim WS as Worksheet

Set WB = ActiveWorkbook
Set WS = WB.Sheets("Sales")

WB.SlicerCaches("Slicer_Year").PivotTables.AddPivotTable _
WS.PivotTables("PivotTable2")


问:
How to instantiate model Angular 2
I'm creating a very basic Angular 2 Application with the purpose of CRUD products. I have a CreateProductComponent but I'm having trouble instantiating the model that I wan't to use on my view. I'm getting this error:

This is my code:

create-product.component.ts

```<code>import { Component, OnInit }  from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';

import { Product } from '../product'
import { ProductService } from '../product.service'

@Component({
    moduleId: module.id,
    selector: 'app-create-product',
    templateUrl: 'create-product.html',
    styleUrls: ['create-product.css'],
})
export class CreateProductComponent {

    model: new Product(1,'2',1); <- error on this line

    constructor(private productService: ProductService) { }

    addProduct() {

        //this.productService.addProduct(this.product);
    }
}
</code>```

product.ts

```<code>export class Product {

    constructor(
        public ID: number,
        public Name: string,
        public Price: number
    ) { }
}
</code>```

Ideally, I would like to create an empty product, or a product with defaul values so that when a form in the view is filled with the product data this data is passed down to the product. Does anyone know how to solve this?

答:
In typescript terminology ':' means you are declaring a type for a variable you have defined.

'=' means you are assigning a value to your variable.

But here what you did is instead of assigning a value you are trying to declare a value (which is not correct according to syntax)

so either you can directly assign a value like

```<code>model = new Product(1,'2',1);
</code>```

or else you can first declare a type for your variable and then assign a value in either of these two ways (I personally prefer this way)

```<code>model: Product = new Product(1,'2',1);
</code>```

or

```<code>model: Product;
model = new Product(1,'2',1);
</code>```

Title: How to instantiate model Angular 2

Body:
I'm creating a very basic Angular 2 Application with the purpose of CRUD products. I have a CreateProductComponent but I'm having trouble instantiating the model that I wan't to use on my view. I'm getting this error:

This is my code:

create-product.component.ts

import { Component, OnInit }  from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';

import { Product } from '../product'
import { ProductService } from '../product.service'

@Component({
    moduleId: module.id,
    selector: 'app-create-product',
    templateUrl: 'create-product.html',
    styleUrls: ['create-product.css'],
})
export class CreateProductComponent {

    model: new Product(1,'2',1); <- error on this line

    constructor(private productService: ProductService) { }

    addProduct() {

        //this.productService.addProduct(this.product);
    }
}

product.ts

export class Product {

    constructor(
        public ID: number,
        public Name: string,
        public Price: number
    ) { }
}

Ideally, I would like to create an empty product, or a product with defaul values so that when a form in the view is filled with the product data this data is passed down to the product. Does anyone know how to solve this?

Body:
In typescript terminology ':' means you are declaring a type for a variable you have defined.

'=' means you are assigning a value to your variable.

But here what you did is instead of assigning a value you are trying to declare a value (which is not correct according to syntax)

so either you can directly assign a value like

model = new Product(1,'2',1);

or else you can first declare a type for your variable and then assign a value in either of these two ways (I personally prefer this way)

model: Product = new Product(1,'2',1);

or

model: Product;
model = new Product(1,'2',1);


问:
ERROR: Syntax error at or near ","
Please resolve this query

```<code>select
    to_char(date_trunc('day',create_time),'DD Month YYYY') as date,
    to_char(min(create_time),'HH24:mi') as login_time where login_status = 1,
    to_char(max(create_time),'HH24:mi') as login_out where login_status = 0
from
    users.access_log
where
    user_id = 1010
group by
    user_id, actionlink_id, date_trunc('day', create_time)
</code>```

getting an error at or near ","

Don't know how to write where condition in to_char function.

答:
Use a join to bring the two login and logout rows together:

```<code>select
    to_char(date_trunc('day',create_time),'DD Month YYYY') as date,
    to_char(min(a.create_time),'HH24:mi') as login_time,
    to_char(max(b.create_time),'HH24:mi') as login_out
from users.access_log a
left join users.access_log b on b.user_id = a.user_id
   and b.login_status = 0
   and date_trunc('day', b.create_time) = date_trunc('day', a.create_time)
   and b.actionlink_id = a.actionlink_id
where a.user_id = 1010
and a.login_status = 1
group by a.user_id, a.actionlink_id, date_trunc('day', a.create_time)
</code>```

Title: ERROR: Syntax error at or near ","

Body:
Please resolve this query

select
    to_char(date_trunc('day',create_time),'DD Month YYYY') as date,
    to_char(min(create_time),'HH24:mi') as login_time where login_status = 1,
    to_char(max(create_time),'HH24:mi') as login_out where login_status = 0
from
    users.access_log
where
    user_id = 1010
group by
    user_id, actionlink_id, date_trunc('day', create_time)

getting an error at or near ","

Don't know how to write where condition in to_char function.

Body:
Use a join to bring the two login and logout rows together:

select
    to_char(date_trunc('day',create_time),'DD Month YYYY') as date,
    to_char(min(a.create_time),'HH24:mi') as login_time,
    to_char(max(b.create_time),'HH24:mi') as login_out
from users.access_log a
left join users.access_log b on b.user_id = a.user_id
   and b.login_status = 0
   and date_trunc('day', b.create_time) = date_trunc('day', a.create_time)
   and b.actionlink_id = a.actionlink_id
where a.user_id = 1010
and a.login_status = 1
group by a.user_id, a.actionlink_id, date_trunc('day', a.create_time)


问:
How do I to get the current cell position x and y in a DataGridView?
I have a Windows form with a calendar which is hidden. I want to show the form right under the current cell of a DataGridView. The position changes according to the position of current cell.

I don't want the current cell or current column, I want the position so that I can set the location of my date forms.

Here is what I am using but its not working:

```<code>int po_X = paygrid.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).Left+paygrid.Left;
int po_Y = paygrid.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).Bottom+paygrid.Top;
form_date.Location = new System.Drawing.Point(po_X, po_Y);
</code>```

答:
```<code>Rectangle cellRect = paygrid.GetCellDisplayRectangle(e.ColumnIndex,
e.RowIndex, true);
</code>```

So You can use:

```<code>cellRect.X - for X position, cellRect.Y - for Y position,
cellRect.Width - for column width and cellRect.Height - for column height
</code>```

Body:
I have a Windows form with a calendar which is hidden. I want to show the form right under the current cell of a DataGridView. The position changes according to the position of current cell.

I don't want the current cell or current column, I want the position so that I can set the location of my date forms.

Here is what I am using but its not working:

int po_X = paygrid.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).Left+paygrid.Left;
int po_Y = paygrid.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).Bottom+paygrid.Top;
form_date.Location = new System.Drawing.Point(po_X, po_Y);

Body:
Rectangle cellRect = paygrid.GetCellDisplayRectangle(e.ColumnIndex,
e.RowIndex, true);

So You can use:

cellRect.X - for X position, cellRect.Y - for Y position,
cellRect.Width - for column width and cellRect.Height - for column height


问:
playing with java Operators (XOR and AND/OR)
In a program I am trying to check two boolean values (returned from a function); the condition that needs to be checked is:

- only if any one of the returned value is true and the other is false then I have a problem;

- else if both are true or false I am good to go to next step.

Which of the following two examples would be the efficient way to check the condition, or is there a better solution?

a and b are integer values on which I am checking a condition for correctness in isCorrect function and it return true or false.

1.

```<code> // checking for the correctness of both a and b
 if ((isCorrect(a) && !isCorrect(b)) ||
     (!isCorrect(a) && isCorrect(b)))
 {
   // a OR b is incorrect
 }
 else
 {
   // a AND b are both correct or incorrect
 }
</code>```

2.

```<code>  // checking for the correctness of both a and b
  if (! (isCorrect(a) ^ isCorrect(b)))
  {
    // a OR b is incorrect
  }
  else
  {
    // a AND b are correct or incorrect
  }
</code>```

Thanks,

Ivar

P.S: code readability is not an issue.
EDIT: I meant to have an XOR in the second option.
Also, I agree with the == and != options, but what if I had to use boolean operators?

答:
Your test doesn't need boolean operators, just this:

```<code>if (isCorrect(a) == isCorrect(b)) {
    // they both have the same value
} else {
    // they don't ...
}
</code>```

EDIT - I deliberately didn't use the same comments to reflect that the primary purpose of the comment should be to describe the intent, and not the specific implementation.  In this case the simplest statement of intent is that both a and b obtained the same result.

Body:
In a program I am trying to check two boolean values (returned from a function); the condition that needs to be checked is:

- only if any one of the returned value is true and the other is false then I have a problem;

- else if both are true or false I am good to go to next step.

Which of the following two examples would be the efficient way to check the condition, or is there a better solution?

a and b are integer values on which I am checking a condition for correctness in isCorrect function and it return true or false.

1.

 // checking for the correctness of both a and b
 if ((isCorrect(a) && !isCorrect(b)) ||
     (!isCorrect(a) && isCorrect(b)))
 {
   // a OR b is incorrect
 }
 else
 {
   // a AND b are both correct or incorrect
 }

2.

  // checking for the correctness of both a and b
  if (! (isCorrect(a) ^ isCorrect(b)))
  {
    // a OR b is incorrect
  }
  else
  {
    // a AND b are correct or incorrect
  }

Thanks,

Ivar

P.S: code readability is not an issue.
EDIT: I meant to have an XOR in the second option.
Also, I agree with the == and != options, but what if I had to use boolean operators?

Body:
Your test doesn't need boolean operators, just this:

if (isCorrect(a) == isCorrect(b)) {
    // they both have the same value
} else {
    // they don't ...
}

EDIT - I deliberately didn't use the same comments to reflect that the primary purpose of the comment should be to describe the intent, and not the specific implementation.  In this case the simplest statement of intent is that both a and b obtained the same result.


问:
how to use optional and filter along to retrieve an object from chained/cascaded objects generated by wsdl2java
I understand flatMap is recommended when dealing with hierarchical objects in Java, particularly while extracting values from objects created out of XML files.

Whithout relying on Optional and since getCommercieleNaam() will bring me a list, I coded:

```<code>NaamOndernemingLijstCommercieelType naamOndernemingLijstCommercieel = onderneming.getNamen()
        .getCommercieleNamen();
NaamOndernemingType naamOndernemingType = naamOndernemingLijstCommercieel.getCommercieleNaam().stream()
        .filter(x -> x.getTaalcode().getValue() == "nl").findFirst().get();
</code>```

In few words, it will walk throw the cascade object and return the first name found for language Netherlands. I see this as very unsafe and, instead of checking all objects if they are null, I prefer to use Optional.

Then I try code what I understand it is the correct way but I don't know how to apply filter in order to retrieve only the object from the list matching a criteria (language == "nl" in my scenario):

```<code>    Optional<NamenOndernemingType> optionalNamenOnderneming = onderneming.getNamen();
    NaamOndernemingType naamOndernemingType = optionalNamenOnderneming.flatMap(NamenOndernemingType::getCommercieleNamen)
            .flatMap(NaamOndernemingLijstCommercieelType::getCommercieleNaam)
            .filter(x -> "nl".equals(x.toString()));
</code>```

PS.: in dutch, naam means name (singular) and Namen means names (plural)

Well, the closest I got was

```<code>    Optional<NamenOndernemingType> optionalNamenOnderneming = Optional.ofNullable(onderneming.getNamen());
    List<NaamOndernemingType> listNaamOndernemingType = optionalNamenOnderneming
            .flatMap(NamenOndernemingType::getCommercieleNamen)
            .map(NaamOndernemingLijstCommercieelType::getCommercieleNaam);
</code>```

But it is neither working and after I fix this, I need to filter also.

*edited

```<code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "NamenOndernemingType", propOrder = {
    "maatschappelijkeNamen",
    "afgekorteNamen",
    "commercieleNamen"
})
public class NamenOndernemingType {

...

    public NaamOndernemingLijstCommercieelType getCommercieleNamen() {
        return commercieleNamen;
    }

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "NaamOndernemingLijstCommercieelType", propOrder = {
    "commercieleNaam"
})
public class NaamOndernemingLijstCommercieelType {
...

    public List<NaamOndernemingType> getCommercieleNaam() {
</code>```

* Solution *

```<code>Optional.ofNullable(onderneming.getNamen()).map(NamenOndernemingType::getCommercieleNamen)
                .map(NaamOndernemingLijstCommercieelType::getCommercieleNaam).get().stream().filter(Objects::nonNull)
                .filter(x -> x.getTaalcode().getValue() == "nl").findFirst()
                .ifPresent(o -> myMethod("onderneming_commerciele_naam", o.getNaam().getValue()));
</code>```

PS.: future readers my find worth read my other question as weel:
how use Optional with cascaded objects not created with Optional

答:
Thanks to the Aominè recommendations and to the discussion based on how use Optional with cascaded objects not created with Optional

I reached this solution:

```<code>Optional.ofNullable(onderneming.getNamen()).map(NamenOndernemingType::getCommercieleNamen)
                .map(NaamOndernemingLijstCommercieelType::getCommercieleNaam).get().stream().filter(Objects::nonNull)
                .filter(x -> x.getTaalcode().getValue() == "nl").findFirst()
                .ifPresent(o -> myMethod("onderneming_commerciele_naam", o.getNaam().getValue()));
</code>```

Body:
I understand flatMap is recommended when dealing with hierarchical objects in Java, particularly while extracting values from objects created out of XML files.

Whithout relying on Optional and since getCommercieleNaam() will bring me a list, I coded:

NaamOndernemingLijstCommercieelType naamOndernemingLijstCommercieel = onderneming.getNamen()
        .getCommercieleNamen();
NaamOndernemingType naamOndernemingType = naamOndernemingLijstCommercieel.getCommercieleNaam().stream()
        .filter(x -> x.getTaalcode().getValue() == "nl").findFirst().get();

In few words, it will walk throw the cascade object and return the first name found for language Netherlands. I see this as very unsafe and, instead of checking all objects if they are null, I prefer to use Optional.

Then I try code what I understand it is the correct way but I don't know how to apply filter in order to retrieve only the object from the list matching a criteria (language == "nl" in my scenario):

    Optional<NamenOndernemingType> optionalNamenOnderneming = onderneming.getNamen();
    NaamOndernemingType naamOndernemingType = optionalNamenOnderneming.flatMap(NamenOndernemingType::getCommercieleNamen)
            .flatMap(NaamOndernemingLijstCommercieelType::getCommercieleNaam)
            .filter(x -> "nl".equals(x.toString()));

PS.: in dutch, naam means name (singular) and Namen means names (plural)

Well, the closest I got was

    Optional<NamenOndernemingType> optionalNamenOnderneming = Optional.ofNullable(onderneming.getNamen());
    List<NaamOndernemingType> listNaamOndernemingType = optionalNamenOnderneming
            .flatMap(NamenOndernemingType::getCommercieleNamen)
            .map(NaamOndernemingLijstCommercieelType::getCommercieleNaam);

But it is neither working and after I fix this, I need to filter also.

*edited

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "NamenOndernemingType", propOrder = {
    "maatschappelijkeNamen",
    "afgekorteNamen",
    "commercieleNamen"
})
public class NamenOndernemingType {

...

    public NaamOndernemingLijstCommercieelType getCommercieleNamen() {
        return commercieleNamen;
    }

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "NaamOndernemingLijstCommercieelType", propOrder = {
    "commercieleNaam"
})
public class NaamOndernemingLijstCommercieelType {
...

    public List<NaamOndernemingType> getCommercieleNaam() {

* Solution *

Optional.ofNullable(onderneming.getNamen()).map(NamenOndernemingType::getCommercieleNamen)
                .map(NaamOndernemingLijstCommercieelType::getCommercieleNaam).get().stream().filter(Objects::nonNull)
                .filter(x -> x.getTaalcode().getValue() == "nl").findFirst()
                .ifPresent(o -> myMethod("onderneming_commerciele_naam", o.getNaam().getValue()));

PS.: future readers my find worth read my other question as weel:
how use Optional with cascaded objects not created with Optional

Body:
Thanks to the Aominè recommendations and to the discussion based on how use Optional with cascaded objects not created with Optional

I reached this solution:

Optional.ofNullable(onderneming.getNamen()).map(NamenOndernemingType::getCommercieleNamen)
                .map(NaamOndernemingLijstCommercieelType::getCommercieleNaam).get().stream().filter(Objects::nonNull)
                .filter(x -> x.getTaalcode().getValue() == "nl").findFirst()
                .ifPresent(o -> myMethod("onderneming_commerciele_naam", o.getNaam().getValue()));