问:
physics contact delegate not working swift 3 xCode 8
I can't seem to get my didBegin contact function to work no matter what I do, my spriteNodes are set to dynamic and I'm pretty sure my categoryBitMasks and contactTestBitMasks are correct... Here's the physics part of my code. None of my print commands are getting printed from my didBeginContact function.

```<code>class GameScene: SKScene, SKPhysicsContactDelegate {

var theLine = SKSpriteNode()
var fallers = SKSpriteNode()

enum colliderType: UInt32 {

    case theLine = 1
    case fallers = 2
}

override func sceneDidLoad() {

self.physicsWorld.contactDelegate = self

    theLine = SKSpriteNode()
    theLine.zPosition = 0
    theLine.size = CGSize(width: 0, height: screenWidth / 128
    theLine.position = CGPoint(x: midX, y: midY)
    theLine.physicsBody = SKPhysicsBody(rectangleOf: theLine.size)
    theLine.physicsBody?.isDynamic = true
    theLine.physicsBody?.affectedByGravity = false
    theLine.physicsBody?.allowsRotation = false
    theLine.physicsBody?.categoryBitMask = colliderType.theLine.rawValue
    theLine.physicsBody?.contactTestBitMask = colliderType.fallers.rawValue
    theLine.physicsBody?.collisionBitMask = 0
    addChild(theLine)

fallers[i].size = CGSize(width: 75, height: 75)
fallers[i].color = UIColor.white
fallers[i].alpha = 1
fallers[i].setScale(ds * 4)
fallers[i].zPosition = 9
let fallerTexture = fallers[i].texture
fallers[i].physicsBody = SKPhysicsBody(texture: fallerTexture!, size:    fallers[i].size)
fallers[i].physicsBody!.isDynamic = true
fallers[i].physicsBody!.categoryBitMask = colliderType.fallers.rawValue
fallers[i].physicsBody!.contactTestBitMask = colliderType.theLine.rawValue
fallers[i].physicsBody!.collisionBitMask = 0
fallers[i].physicsBody!.affectedByGravity = false

addChild(fallers[i])

}

func didBegin(_ contact: SKPhysicsContact) {

//Detects collisions and what nodes the collisions are between.

if contact.bodyA.categoryBitMask == colliderType.theLine.rawValue && contact.bodyB.categoryBitMask == colliderType.fallers.rawValue {

    print("CONTACT")

} else if contact.bodyA.categoryBitMask == colliderType.fallers.rawValue && contact.bodyB.categoryBitMask == colliderType.theLine.rawValue {

    print("CONTACT")

    }

}
</code>```

Update

I just put an else statement in my didBeginContactDelegate and the code was triggered when the bodies made contact, but the problem is now, is that I can't sort what bodies these contacts are between.

答:
If you are using simple categories, with each physics body belonging to only one category, then this alternative form of didBeginContact may be more readable:

```<code>func didBeginContact(contact: SKPhysicsContact) {
    let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask

    switch contactMask {

    case colliderTytpe.fallers.rawValue | colliderType.theLine.rawValue:
        print("Collision between fallers and theLine")
        let fallersNode = contact.bodyA.categoryBitMask == colliderTytpe.fallers.rawValue ? contact.bodyA.node! : contact.bodyB.node!

        // Do something with fallersNode
        fallersNode.removeFromParent() // For example
        score += 10 // For example

    default :
        //Some other contact has occurred
        print("Some other contact")
    }
}
</code>```

(If you need to handle other collisions, just add more case blocks to the switch).

It avoids messing about with bodyA and bodyB, and sorting them into order. You only need to deal with them when you have to do something specific with one of the nodes, which is where this line of code comes into play:

```<code>let fallersNode = contact.bodyA.categoryBitMask == colliderTytpe.fallers.rawValue ? contact.bodyA.node! : contact.bodyB.node!
</code>```

Which is using Swift's ternary operator to say "if bodyA has faller's category bitMask, then set fallersNode to bodyA, else set fallersNode to bodyB.

Body:
I can't seem to get my didBegin contact function to work no matter what I do, my spriteNodes are set to dynamic and I'm pretty sure my categoryBitMasks and contactTestBitMasks are correct... Here's the physics part of my code. None of my print commands are getting printed from my didBeginContact function.

class GameScene: SKScene, SKPhysicsContactDelegate {

var theLine = SKSpriteNode()
var fallers = SKSpriteNode()

enum colliderType: UInt32 {

    case theLine = 1
    case fallers = 2
}

override func sceneDidLoad() {

self.physicsWorld.contactDelegate = self

    theLine = SKSpriteNode()
    theLine.zPosition = 0
    theLine.size = CGSize(width: 0, height: screenWidth / 128
    theLine.position = CGPoint(x: midX, y: midY)
    theLine.physicsBody = SKPhysicsBody(rectangleOf: theLine.size)
    theLine.physicsBody?.isDynamic = true
    theLine.physicsBody?.affectedByGravity = false
    theLine.physicsBody?.allowsRotation = false
    theLine.physicsBody?.categoryBitMask = colliderType.theLine.rawValue
    theLine.physicsBody?.contactTestBitMask = colliderType.fallers.rawValue
    theLine.physicsBody?.collisionBitMask = 0
    addChild(theLine)

fallers[i].size = CGSize(width: 75, height: 75)
fallers[i].color = UIColor.white
fallers[i].alpha = 1
fallers[i].setScale(ds * 4)
fallers[i].zPosition = 9
let fallerTexture = fallers[i].texture
fallers[i].physicsBody = SKPhysicsBody(texture: fallerTexture!, size:    fallers[i].size)
fallers[i].physicsBody!.isDynamic = true
fallers[i].physicsBody!.categoryBitMask = colliderType.fallers.rawValue
fallers[i].physicsBody!.contactTestBitMask = colliderType.theLine.rawValue
fallers[i].physicsBody!.collisionBitMask = 0
fallers[i].physicsBody!.affectedByGravity = false

addChild(fallers[i])

}

func didBegin(_ contact: SKPhysicsContact) {

//Detects collisions and what nodes the collisions are between.

if contact.bodyA.categoryBitMask == colliderType.theLine.rawValue && contact.bodyB.categoryBitMask == colliderType.fallers.rawValue {

    print("CONTACT")

} else if contact.bodyA.categoryBitMask == colliderType.fallers.rawValue && contact.bodyB.categoryBitMask == colliderType.theLine.rawValue {

    print("CONTACT")

    }

}

Update

I just put an else statement in my didBeginContactDelegate and the code was triggered when the bodies made contact, but the problem is now, is that I can't sort what bodies these contacts are between.

Body:
If you are using simple categories, with each physics body belonging to only one category, then this alternative form of didBeginContact may be more readable:

func didBeginContact(contact: SKPhysicsContact) {
    let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask

    switch contactMask {

    case colliderTytpe.fallers.rawValue | colliderType.theLine.rawValue:
        print("Collision between fallers and theLine")
        let fallersNode = contact.bodyA.categoryBitMask == colliderTytpe.fallers.rawValue ? contact.bodyA.node! : contact.bodyB.node!

        // Do something with fallersNode
        fallersNode.removeFromParent() // For example
        score += 10 // For example

    default :
        //Some other contact has occurred
        print("Some other contact")
    }
}

(If you need to handle other collisions, just add more case blocks to the switch).

It avoids messing about with bodyA and bodyB, and sorting them into order. You only need to deal with them when you have to do something specific with one of the nodes, which is where this line of code comes into play:

let fallersNode = contact.bodyA.categoryBitMask == colliderTytpe.fallers.rawValue ? contact.bodyA.node! : contact.bodyB.node!

Which is using Swift's ternary operator to say "if bodyA has faller's category bitMask, then set fallersNode to bodyA, else set fallersNode to bodyB.


来源: stackexchange

问:
Change font size by Facebook likes
Im trying to create a HTML that is live updating while input from the Facebook data. Is there a way to connect your font sizes (H1 etc.) to the Facebook likes. The more likes they have, the bigger the names. Also trying that is updating when there are changes in the amount of likes. </p>

<p>Big Thanks </p>

答:
You can use setInterval function, check for the number of likes on your object every n seconds and accordingly update the style of the HTML element:

```<code>// Will check and update the font size every 5 seconds

setInterval(function {
  FB.api(
    "/{object-id}/likes",
    function (response) {
      if (response && !response.error) {
        $("#element").css("font-size", response.total_count + "px");
      }
    }
  );
}, 5000);
</code>```

Of course you need some sort of conversion from total_count to actual font-size, you don't wanna have your font size something like 3667px.

ContentLicense: CC BY-SA 3.0

Title: Change font size by Facebook likes

Body:
Im trying to create a HTML that is live updating while input from the Facebook data. Is there a way to connect your font sizes (H1 etc.) to the Facebook likes. The more likes they have, the bigger the names. Also trying that is updating when there are changes in the amount of likes.

Big Thanks

Body:
You can use setInterval function, check for the number of likes on your object every n seconds and accordingly update the style of the HTML element:

// Will check and update the font size every 5 seconds

setInterval(function {
  FB.api(
    "/{object-id}/likes",
    function (response) {
      if (response && !response.error) {
        $("#element").css("font-size", response.total_count + "px");
      }
    }
  );
}, 5000);

Of course you need some sort of conversion from total_count to actual font-size, you don't wanna have your font size something like 3667px.


问:
How to access a child's child of a parent Node
I have a challenge accessing a child's child of a parentNode. Below is the xml i am working with:

```<code>String response = "<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<closure>
    <amount>1055296.0000</amount>
    <currency>USD</currency>
    <unit>2</unit>
    <year>2012</year>
    <taxes>
        <tax>
            <descript>FEE LEVY</descript>
            <taxAmt>
                <amt>30304.0000</amt>
                <currency>USD</currency>
            </taxAmt>
            <taxCode>SUR</taxCode>
        </tax>
        <tax>
            <descript>MED LEVY</descript>
            <taxAmt>
                <amt>25125.0000</amt>
                <currency>USD</currency>
            </taxAmt>
            <taxCode>CIS</taxCode>
        </tax>
    </taxes>
</closure>";
</code>```

Below is the code i have tried:

```<code>     DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
     InputSource src = new InputSource();`
     src.setCharacterStream(new StringReader(response));
     Document doc = builder.parse(src);
     String amount =doc.getElementsByTagName("amount").item(0).getTextContent();
     NodeList nodeList = doc.getElementsByTagName("tax");
     for (int i = 0; i < nodeList.getLength(); i++)
     {
     Node childNode = nodeList.item(i);
     }
</code>```

Please how do i get descript, taxAmt and taxCode inside the element tax?

答:
This is how I was able to solve the isssue i had:
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource src = new InputSource();
    src.setCharacterStream(new StringReader(response));
    Document doc = builder.parse(src);  </p>

```<code>NodeList nodeList = doc.getElementsByTagName("tax");
Node node;

    for (int i = 0; i < nodeList.getLength(); i++)
    {
        Node childNode = nodeList.item(i);
        NodeList nodelist  = childNode.getChildNodes();

         for(int ii = 0; ii < nodelist.getLength(); ii++)
         {
               node  = nodelist.item(ii);
                if(node.getNodeName().equalsIgnoreCase("description"))
                {
                    node.getTextContent();
                }
                else if(node.getNodeName().equalsIgnoreCase("taxAmount"))
                {
                    NodeList taxAmountNodelist = node.getChildNodes();
                   for(int iii = 0; iii < taxAmountNodelist.getLength(); iii++)
                   {
                       Node taxAmountNode  = taxAmountNodelist.item(iii);
                         if(taxAmountNode.getNodeName().equalsIgnoreCase("amount"))
                         {
                            taxAmountNode.getTextContent();
                         }
                   }
                }
            else if(node.getNodeName().equalsIgnoreCase("taxcode"))
            {
                node.getTextContent();
            }
         }

    }
</code>```

Body:
I have a challenge accessing a child's child of a parentNode. Below is the xml i am working with:

String response = "<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<closure>
    <amount>1055296.0000</amount>
    <currency>USD</currency>
    <unit>2</unit>
    <year>2012</year>
    <taxes>
        <tax>
            <descript>FEE LEVY</descript>
            <taxAmt>
                <amt>30304.0000</amt>
                <currency>USD</currency>
            </taxAmt>
            <taxCode>SUR</taxCode>
        </tax>
        <tax>
            <descript>MED LEVY</descript>
            <taxAmt>
                <amt>25125.0000</amt>
                <currency>USD</currency>
            </taxAmt>
            <taxCode>CIS</taxCode>
        </tax>
    </taxes>
</closure>";

Below is the code i have tried:

     DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
     InputSource src = new InputSource();`
     src.setCharacterStream(new StringReader(response));
     Document doc = builder.parse(src);
     String amount =doc.getElementsByTagName("amount").item(0).getTextContent();
     NodeList nodeList = doc.getElementsByTagName("tax");
     for (int i = 0; i < nodeList.getLength(); i++)
     {
     Node childNode = nodeList.item(i);
     }

Please how do i get descript, taxAmt and taxCode inside the element tax?

Body:
This is how I was able to solve the isssue i had:
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource src = new InputSource();
    src.setCharacterStream(new StringReader(response));
    Document doc = builder.parse(src);

NodeList nodeList = doc.getElementsByTagName("tax");
Node node;

    for (int i = 0; i < nodeList.getLength(); i++)
    {
        Node childNode = nodeList.item(i);
        NodeList nodelist  = childNode.getChildNodes();

         for(int ii = 0; ii < nodelist.getLength(); ii++)
         {
               node  = nodelist.item(ii);
                if(node.getNodeName().equalsIgnoreCase("description"))
                {
                    node.getTextContent();
                }
                else if(node.getNodeName().equalsIgnoreCase("taxAmount"))
                {
                    NodeList taxAmountNodelist = node.getChildNodes();
                   for(int iii = 0; iii < taxAmountNodelist.getLength(); iii++)
                   {
                       Node taxAmountNode  = taxAmountNodelist.item(iii);
                         if(taxAmountNode.getNodeName().equalsIgnoreCase("amount"))
                         {
                            taxAmountNode.getTextContent();
                         }
                   }
                }
            else if(node.getNodeName().equalsIgnoreCase("taxcode"))
            {
                node.getTextContent();
            }
         }

    }


问:
JPA: find result by interring foreign value
Here is my database

```<code>   CREATE TABLE Orders (
        OrderID int NOT NULL,
        OrderNumber int NOT NULL,
        products_id int,
        PRIMARY KEY (OrderID),
        FOREIGN KEY (products_id) REFERENCES product(products_id)
    );
</code>```

****I generated NetBeans entity class and it gives the following code;****

```<code>package Entity;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;

@Entity
@Table(name = "orders")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Orders.findAll", query = "SELECT o FROM Orders o")
    , @NamedQuery(name = "Orders.findByOrderID", query = "SELECT o FROM Orders o WHERE o.orderID = :orderID")
    , @NamedQuery(name = "Orders.findByOrderNumber", query = "SELECT o FROM Orders o WHERE o.orderNumber = :orderNumber")})
public class Orders implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @Column(name = "OrderID")
    private Integer orderID;
    @Basic(optional = false)
    @Column(name = "OrderNumber")
    private int orderNumber;

    public Orders() {
    }

    public Orders(Integer orderID) {
        this.orderID = orderID;
    }

    public Orders(Integer orderID, int orderNumber) {
        this.orderID = orderID;
        this.orderNumber = orderNumber;
    }

    public Integer getOrderID() {
        return orderID;
    }

    public void setOrderID(Integer orderID) {
        this.orderID = orderID;
    }

    public int getOrderNumber() {
        return orderNumber;
    }

    public void setOrderNumber(int orderNumber) {
        this.orderNumber = orderNumber;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (orderID != null ? orderID.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {

        if (!(object instanceof Orders)) {
            return false;
        }
        Orders other = (Orders) object;
        if ((this.orderID == null && other.orderID != null) || (this.orderID != null && !this.orderID.equals(other.orderID))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "Entity.Orders[ orderID=" + orderID + " ]";
    }

}
</code>```

****I am new of JPA, and I just want to get the "OrderNumber" by entering the "products_id" is it possible?**
I want something like this**

```<code>public Orders findOrderNumber(int productsId) {
        EntityManager em = getEntityManager();
        Orders order= null;
        try {
         order= (Orders) em.createQuery("SELECT o FROM Orders o WHERE o.productsId=" + productsId).getSingleResult();

        } catch (NoResultException e) {
            order= null;
        }

        return order;
    }
</code>```

答:
You should use a prepared statement.

How to use prepared statement in JPA

Right now your query is vulnerable to SQL-injection : https://www.owasp.org/index.php/SQL_Injection

What exactly isn't working right now?

Body:
Here is my database

   CREATE TABLE Orders (
        OrderID int NOT NULL,
        OrderNumber int NOT NULL,
        products_id int,
        PRIMARY KEY (OrderID),
        FOREIGN KEY (products_id) REFERENCES product(products_id)
    );

****I generated NetBeans entity class and it gives the following code;****

package Entity;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;

@Entity
@Table(name = "orders")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Orders.findAll", query = "SELECT o FROM Orders o")
    , @NamedQuery(name = "Orders.findByOrderID", query = "SELECT o FROM Orders o WHERE o.orderID = :orderID")
    , @NamedQuery(name = "Orders.findByOrderNumber", query = "SELECT o FROM Orders o WHERE o.orderNumber = :orderNumber")})
public class Orders implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @Column(name = "OrderID")
    private Integer orderID;
    @Basic(optional = false)
    @Column(name = "OrderNumber")
    private int orderNumber;

    public Orders() {
    }

    public Orders(Integer orderID) {
        this.orderID = orderID;
    }

    public Orders(Integer orderID, int orderNumber) {
        this.orderID = orderID;
        this.orderNumber = orderNumber;
    }

    public Integer getOrderID() {
        return orderID;
    }

    public void setOrderID(Integer orderID) {
        this.orderID = orderID;
    }

    public int getOrderNumber() {
        return orderNumber;
    }

    public void setOrderNumber(int orderNumber) {
        this.orderNumber = orderNumber;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (orderID != null ? orderID.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {

        if (!(object instanceof Orders)) {
            return false;
        }
        Orders other = (Orders) object;
        if ((this.orderID == null && other.orderID != null) || (this.orderID != null && !this.orderID.equals(other.orderID))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "Entity.Orders[ orderID=" + orderID + " ]";
    }

}

****I am new of JPA, and I just want to get the "OrderNumber" by entering the "products_id" is it possible?**
I want something like this**

public Orders findOrderNumber(int productsId) {
        EntityManager em = getEntityManager();
        Orders order= null;
        try {
         order= (Orders) em.createQuery("SELECT o FROM Orders o WHERE o.productsId=" + productsId).getSingleResult();

        } catch (NoResultException e) {
            order= null;
        }

        return order;
    }


问:
access images from resource folder on iphone
I have folder inside reource folder lets say

resource->folder A->61.png

so how to access this path I did this

```<code>NSString *myFilePath=   [[NSBundle mainBundle] pathForResource:@"61" ofType:@"png" inDirectory:@"A" ];

NSLog(@"file is at %@",myFilePath);// its null
</code>```

why my path is null?

答:
You do not need to use inDirectory. Even if you create directory under resource folder, all resources go to a flat directory under app bundle. </p>

```NSString *myFilePath=   [[NSBundle mainBundle] pathForResource:@"61" ofType:@"png"];```

ContentLicense: CC BY-SA 4.0

Body:
I have folder inside reource folder lets say

resource->folder A->61.png

so how to access this path I did this

NSString *myFilePath=   [[NSBundle mainBundle] pathForResource:@"61" ofType:@"png" inDirectory:@"A" ];

NSLog(@"file is at %@",myFilePath);// its null

why my path is null?

Body:
You do not need to use inDirectory. Even if you create directory under resource folder, all resources go to a flat directory under app bundle.

NSString *myFilePath=   [[NSBundle mainBundle] pathForResource:@"61" ofType:@"png"];

ContentLicense: CC BY-SA 2.5


问:
Java equivalent for C#'s ConfigurationManager.AppSettings[x]
New to Java and I'm trying to find the equivalent for web.config application settings in .NET.

So far I have found examples of something like this:

Properties props = new Properties();
FileInputStream fis = new FileInputStream("c:/appSettings.properties");
props.load(fis);
```

<p>However, I know that .NET caches the web.config file and inserting a call to <code>Configuration.AppSettings[x]</code> is not expensive. I'm looking for an equivalent solution. So that I can call for Application settings multiple times through out a page load. </p>

<p><strong>For Example:</strong></p>

<pre class="lang-xml prettyprint-override"><code><link  href="<%= ResolveUrl("~/css/main.css?ver=" + Configuration.AppSettings["version"]) %>" rel="Stylesheet" type="text/css" media="screen" />
</code>```

I can create a class that can do the equivalent, but i'd hate to reinvent the wheel if there is already something there.

答:
https://commons.apache.org/proper/commons-configuration/
apache commons configuration is the best choice.

Automatic Reloading
A common issue with properties file is to handle the reloading of the file when it changes.  The sample code is found beneath：

```<code>PropertiesConfiguration config = new
PropertiesConfiguration("usergui.properties");
config.setReloadingStrategy(new FileChangedReloadingStrategy());
</code>```

Body:
New to Java and I'm trying to find the equivalent for web.config application settings in .NET.

So far I have found examples of something like this:

Properties props = new Properties();
FileInputStream fis = new FileInputStream("c:/appSettings.properties");
props.load(fis);

However, I know that .NET caches the web.config file and inserting a call to Configuration.AppSettings[x] is not expensive. I'm looking for an equivalent solution. So that I can call for Application settings multiple times through out a page load.

For Example:

<link  href="<%= ResolveUrl("~/css/main.css?ver=" + Configuration.AppSettings["version"]) %>" rel="Stylesheet" type="text/css" media="screen" />

I can create a class that can do the equivalent, but i'd hate to reinvent the wheel if there is already something there.

Body:
https://commons.apache.org/proper/commons-configuration/
apache commons configuration is the best choice.

Automatic Reloading
A common issue with properties file is to handle the reloading of the file when it changes.  The sample code is found beneath：

PropertiesConfiguration config = new
PropertiesConfiguration("usergui.properties");
config.setReloadingStrategy(new FileChangedReloadingStrategy());


问:
React Syntax error on adding a second class on Toggle
How can i add second class to my
 "button" if i append 'toggle-button' the class doesn't work.

```<code><CSSTransitionGroup
    transitionName="buttonAninmated"
    transitionEnterTimeout={300}
    transitionLeaveTimeout={300}
>
    <div className={['toggle-button', this.state.active ? 'active-button': null]} onClick={this.toggleMenu}>
        <span></span>
        <span></span>
        <span></span>
    </div>
</CSSTransitionGroup>
</code>```

答:
Write it by using template literals:

```<code>className = {`toggle-button ${this.state.active ? `active-button` : ``}`}
</code>```

Or write it by using +:

```<code>className = {"toggle-button " + this.state.active ? "active-button" : ""}
</code>```

To apply multiple classes, write all the class names space separated.

Body:
How can i add second class to my
 "button" if i append 'toggle-button' the class doesn't work.

<CSSTransitionGroup
    transitionName="buttonAninmated"
    transitionEnterTimeout={300}
    transitionLeaveTimeout={300}
>

</CSSTransitionGroup>

Body:
Write it by using template literals:

className = {`toggle-button ${this.state.active ? `active-button` : ``}`}

Or write it by using +:

className = {"toggle-button " + this.state.active ? "active-button" : ""}

To apply multiple classes, write all the class names space separated.


问:
How to change background color in single ZK Grid Cells?
Anyone got any idea how to change the background color of a cell in a ZK grid? Been searching the web for several hours and can't find much. A static cell wouldn't be a problem, but this is a dynamically rendered grid.

Plan is to colour certain cells red or yellow because I want to highlight that specific value.

My Zul:

```<code><?page title="Ergebnis des Clusterings" contentType="text/html;charset=UTF-8"?>
<zk xmlns:n="native" xmlns:c="client">
    <style>body { background-color: #fcfcfc; }</style>
    <image id="image" src="http://i.imgur.com/dL3ahNV.gif"
        style="display: block; width: 300px; margin: 1% auto 0 auto;">
    </image>
    <window id="win" apply="org.zkoss.bind.BindComposer"
        style="margin: 0 auto; background: #ddf4ea; position: relative;"
        viewModel="@id('vm') @init('frontend.ClusteringOutputVM')"
        border="normal" width="1000px" position="center,top"
        mode="embedded">
        <caption label="KaufDort Cluster - Clustering Output"
            style="font-family: Segoe UI; font-style: normal; font-size: 18px; color: #000000; padding: 5px;" />
        <include style="margin-top: 20px; margin-bottom: 20px;"
            src="marketing.zul" />
        <hbox>
            <grid id="grid" model="@load(vm.mapModel)" hflex="max">
                <columns children="@load(vm.columnsModel)">
                    <template name="children">
                        <column hflex="min" label="@load(each)"
                            sort="none"
                            style="background: #ddf4ea; font-family: Segoe UI; font-style: normal; font-size: 18px; color: #000000; font-weight: normal;" />
                    </template>
                </columns>
                <template name="model" var="cur_row">
                    <row
                        children="@load(vm.columnsModel) @template(forEachStatus.index lt (vm.columnsModel.size()- cur_row.value.size()) ? 'fixed' : 'variable')">
                        <template name="fixed">
                            <cell>
                                <button label="@load(cur_row.key)"
                                    style="border: none; border-radius: 0px; background: #7f8c8d; color: white; text-shadow: none; font-size: 18px;"
                                    onClick="@command('showDiagram')" width="100%" />
                            </cell>
                        </template>

                        <template name="variable">
                            <cell>
                                <label
                                    style="text-align: left; font-family: Segoe UI; font-style: normal; font-size: 14px; color: #000000;"
                                    value="@load(cur_row.value[forEachStatus.index- vm.columnsModel.size()+ cur_row.value.size()])" />
                            </cell>
                        </template>
                    </row>
                </template>
            </grid>

            <image id="questionmark" src="Files/QuestionmarkButton.png"
                tooltip="centroid" style="cursor: help" />

        </hbox>
    </window>
    <popup id="centroid" width="300px">
        <html>
            <![CDATA[ Text]]>
        </html>
    </popup>
</zk>
</code>```

My VM:

```<code>public class ClusteringOutputVM {

    private ArrayList<KMeansCluster> clusterList;
    private ArrayList<Feature> featureList;
    private int numOfClusters;
    private ListModelMap data;
    private ListModel columns_model;
    private boolean[][] paintMe;
    @Wire
    private Grid grid;

    public ClusteringOutputVM() {

        data = new ListModelMap();
        columns_model = new ListModelList();

        getSessionGlobalVariables();
        transferDataToListModelMap();
        fillColumnsModel(numOfClusters);
    }

    @AfterCompose
    public void paintCells() {
        for (int i = 0; i < paintMe.length; i++) {
            for (int j = 0; j < paintMe[i].length; j++) {
                if(paintMe[i][j]){
                    grid.getCell(i, j); ?????
                }
            }
        }
    }

    private void transferDataToListModelMap() {
        List<String> valueList = new java.util.ArrayList<String>();
        int featureType = 0;

        for (int i = 0; i < featureList.size(); i++) {
            featureType = featureList.get(i).getFeatureType();
            if (featureType == 0) {
                NumericFeature nf = (NumericFeature) featureList.get(i);
                double mean = nf.getMean();
                double stDev = nf.getStdDev();

                for (int j = 0; j < clusterList.size(); j++) {
                    Instance in = clusterList.get(j).getCentroid();
                    String centroidVal = in.toString(i);
                    double value = Double.valueOf(centroidVal);
                    if (value > (mean + stDev) || value < (mean - stDev)) {
                        paintMe[i+1][j+1] = true;
                    }
                    valueList.add(centroidVal);

                }
            } else {
                for (int j = 0; j < clusterList.size(); j++) {
                    Instance in = clusterList.get(j).getCentroid();
                    paintMe[i+1][j+1] = false;
                    valueList.add(in.toString(i));
                }

                data.put((featureList.get(i).getFeatureName()), valueList);
                valueList = new ArrayList<String>();
            }
        }

    }

    private void getSessionGlobalVariables() {
        clusterList = (ArrayList<KMeansCluster>) Sessions.getCurrent()
                .getAttribute("finalClusterList");
        featureList = (ArrayList<Feature>) Sessions.getCurrent().getAttribute(
                "finalFeatureList");
        numOfClusters = (int) Sessions.getCurrent().getAttribute(
                "chosenNumOfClusters");
        paintMe = new boolean[featureList.size() + 1][clusterList.size() + 1];
    }

    private void fillColumnsModel(int endValue) {
        ((List) columns_model).add(new String("Feature"));
        for (int i = 1; i <= endValue; ++i)
            ((List) columns_model).add(new String("Cluster " + i));

    }

    public ListModel getColumnsModel() {
        return columns_model;
    }

    public ListModel getMapModel() {
        return data;
    }

    @Command
    public void showDiagram(
            @ContextParam(ContextType.COMPONENT) Component component) {

        Button b = (Button) component;
        String featureChosen = b.getLabel();
        Feature feat = null;
        for (int i = 0; i < featureList.size(); i++) {
            if (featureList.get(i).getFeatureName().equals(featureChosen)) {
                feat = featureList.get(i);
            }
        }
        Sessions.getCurrent().setAttribute("chosenFeature", feat);

        if (feat.getFeatureType() != 0)
            // koennte problematisch werden bei anderen Browsern
            Executions.getCurrent().sendRedirect("stackedColumns.zul");
        else
            Executions.getCurrent().sendRedirect("boxplot.zul");

    }

}
</code>```

答:
As chillworld said, @Wire does not work by default when using ViewModel. Read here how to do it, but note that it is discouraged.

The better solution in this context to put some ParamObject in your valueList for each row instead of just strings:

```<code>class ParamObject {
    private String label;
    private String sClass; // or style
    // getters and setters
}
</code>```

Create it in your ViewModel.transferDataToListModelMap():

```<code>Instance in = clusterList.get(j).getCentroid();
String centroidVal = in.toString(i);
double value = Double.valueOf(centroidVal);

ParamObject params = new ParamObject();
params.setLabel(centroidVal);
params.setSclass(value > (mean + stDev) || value < (mean - stDev) ? "colored" : "notColored")
valueList.add(params);
</code>```

You can then use data binding in your zul:

```<code><label sclass="cur_row.value[weird index calculation].sClass"
       style="your inline style for font"
       value="@load(cur_row.value[weird index calculation].label)" />
</code>```

You might want to store the index in a temporary field to keep it readable.

You can then write some sClasses for your style. If you prefer to do it with inline style instead, just concat it with the font styling you have already and bind the sClass/style attribute of your ParamObject against style instead of sclass.

Body:
Anyone got any idea how to change the background color of a cell in a ZK grid? Been searching the web for several hours and can't find much. A static cell wouldn't be a problem, but this is a dynamically rendered grid.

Plan is to colour certain cells red or yellow because I want to highlight that specific value.

My Zul:

<?page title="Ergebnis des Clusterings" contentType="text/html;charset=UTF-8"?>
<zk xmlns:n="native" xmlns:c="client">

    <image id="image" src="http://i.imgur.com/dL3ahNV.gif"
        style="display: block; width: 300px; margin: 1% auto 0 auto;">
    </image>
    <window id="win" apply="org.zkoss.bind.BindComposer"
        style="margin: 0 auto; background: #ddf4ea; position: relative;"
        viewModel="@id('vm') @init('frontend.ClusteringOutputVM')"
        border="normal" width="1000px" position="center,top"
        mode="embedded">

        <include style="margin-top: 20px; margin-bottom: 20px;"
            src="marketing.zul" />
        <hbox>
            <grid id="grid" model="@load(vm.mapModel)" hflex="max">
                <columns children="@load(vm.columnsModel)">
                    <template name="children">
                        <column hflex="min" label="@load(each)"
                            sort="none"
                            style="background: #ddf4ea; font-family: Segoe UI; font-style: normal; font-size: 18px; color: #000000; font-weight: normal;" />
                    </template>
                </columns>
                <template name="model" var="cur_row">
                    <row
                        children="@load(vm.columnsModel) @template(forEachStatus.index lt (vm.columnsModel.size()- cur_row.value.size()) ? 'fixed' : 'variable')">
                        <template name="fixed">
                            <cell>
                                <button label="@load(cur_row.key)"
                                    style="border: none; border-radius: 0px; background: #7f8c8d; color: white; text-shadow: none; font-size: 18px;"
                                    onClick="@command('showDiagram')" width="100%" />
                            </cell>
                        </template>

                        <template name="variable">
                            <cell>

                            </cell>
                        </template>
                    </row>
                </template>
            </grid>

            <image id="questionmark" src="Files/QuestionmarkButton.png"
                tooltip="centroid" style="cursor: help" />

        </hbox>
    </window>
    <popup id="centroid" width="300px">

            <![CDATA[ Text]]>

    </popup>
</zk>

My VM:

public class ClusteringOutputVM {

    private ArrayList<KMeansCluster> clusterList;
    private ArrayList<Feature> featureList;
    private int numOfClusters;
    private ListModelMap data;
    private ListModel columns_model;
    private boolean[][] paintMe;
    @Wire
    private Grid grid;

    public ClusteringOutputVM() {

        data = new ListModelMap();
        columns_model = new ListModelList();

        getSessionGlobalVariables();
        transferDataToListModelMap();
        fillColumnsModel(numOfClusters);
    }

    @AfterCompose
    public void paintCells() {
        for (int i = 0; i < paintMe.length; i++) {
            for (int j = 0; j < paintMe[i].length; j++) {
                if(paintMe[i][j]){
                    grid.getCell(i, j); ?????
                }
            }
        }
    }

    private void transferDataToListModelMap() {
        List<String> valueList = new java.util.ArrayList<String>();
        int featureType = 0;

        for (int i = 0; i < featureList.size(); i++) {
            featureType = featureList.get(i).getFeatureType();
            if (featureType == 0) {
                NumericFeature nf = (NumericFeature) featureList.get(i);
                double mean = nf.getMean();
                double stDev = nf.getStdDev();

                for (int j = 0; j < clusterList.size(); j++) {
                    Instance in = clusterList.get(j).getCentroid();
                    String centroidVal = in.toString(i);
                    double value = Double.valueOf(centroidVal);
                    if (value > (mean + stDev) || value < (mean - stDev)) {
                        paintMe[i+1][j+1] = true;
                    }
                    valueList.add(centroidVal);

                }
            } else {
                for (int j = 0; j < clusterList.size(); j++) {
                    Instance in = clusterList.get(j).getCentroid();
                    paintMe[i+1][j+1] = false;
                    valueList.add(in.toString(i));
                }

                data.put((featureList.get(i).getFeatureName()), valueList);
                valueList = new ArrayList<String>();
            }
        }

    }

    private void getSessionGlobalVariables() {
        clusterList = (ArrayList<KMeansCluster>) Sessions.getCurrent()
                .getAttribute("finalClusterList");
        featureList = (ArrayList<Feature>) Sessions.getCurrent().getAttribute(
                "finalFeatureList");
        numOfClusters = (int) Sessions.getCurrent().getAttribute(
                "chosenNumOfClusters");
        paintMe = new boolean[featureList.size() + 1][clusterList.size() + 1];
    }

    private void fillColumnsModel(int endValue) {
        ((List) columns_model).add(new String("Feature"));
        for (int i = 1; i <= endValue; ++i)
            ((List) columns_model).add(new String("Cluster " + i));

    }

    public ListModel getColumnsModel() {
        return columns_model;
    }

    public ListModel getMapModel() {
        return data;
    }

    @Command
    public void showDiagram(
            @ContextParam(ContextType.COMPONENT) Component component) {

        Button b = (Button) component;
        String featureChosen = b.getLabel();
        Feature feat = null;
        for (int i = 0; i < featureList.size(); i++) {
            if (featureList.get(i).getFeatureName().equals(featureChosen)) {
                feat = featureList.get(i);
            }
        }
        Sessions.getCurrent().setAttribute("chosenFeature", feat);

        if (feat.getFeatureType() != 0)
            // koennte problematisch werden bei anderen Browsern
            Executions.getCurrent().sendRedirect("stackedColumns.zul");
        else
            Executions.getCurrent().sendRedirect("boxplot.zul");

    }

}

Body:
As chillworld said, @Wire does not work by default when using ViewModel. Read here how to do it, but note that it is discouraged.

The better solution in this context to put some ParamObject in your valueList for each row instead of just strings:

class ParamObject {
    private String label;
    private String sClass; // or style
    // getters and setters
}

Create it in your ViewModel.transferDataToListModelMap():

Instance in = clusterList.get(j).getCentroid();
String centroidVal = in.toString(i);
double value = Double.valueOf(centroidVal);

ParamObject params = new ParamObject();
params.setLabel(centroidVal);
params.setSclass(value > (mean + stDev) || value < (mean - stDev) ? "colored" : "notColored")
valueList.add(params);

You can then use data binding in your zul:

<label sclass="cur_row.value[weird index calculation].sClass"
       style="your inline style for font"
       value="@load(cur_row.value[weird index calculation].label)" />

You might want to store the index in a temporary field to keep it readable.

You can then write some sClasses for your style. If you prefer to do it with inline style instead, just concat it with the font styling you have already and bind the sClass/style attribute of your ParamObject against style instead of sclass.


问:
Uncaught FirebaseError: Messaging: This method is available in a Window context
I'm using Firebase service worker for web push notification. Currently, I am facing this error:

```<code>Uncaught FirebaseError: Messaging: This method is available in a Window context. (messaging/only-available-in-window).
</code>```

I am using a website on my desktop to register the SW. How do I resolve this issue?

Error stack I'm getting in console.

```<code>browserErrorMessage: "Failed to register a ServiceWorker: ServiceWorker script evaluation failed"
code :"messaging/failed-serviceworker-registration"
message :"Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker: ServiceWorker script evaluation failed (messaging/failed-serviceworker-registration)."
stack: "FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker: ServiceWorker script evaluation failed (messaging/failed-serviceworker-registration).↵    at https://www.gstatic.com/firebasejs/3.7.0/firebase.js:555:225"
__proto__: Error
</code>```

Thank you

答:
This method should be there in the main javascript file, NOT in service worker. Service Worker works in the background.</p>

```<code>    messaging.onMessage(function(payload) {
      console.log("Message received. ", payload);
      // ...
    });
</code>```

Body:
I'm using Firebase service worker for web push notification. Currently, I am facing this error:

Uncaught FirebaseError: Messaging: This method is available in a Window context. (messaging/only-available-in-window).

I am using a website on my desktop to register the SW. How do I resolve this issue?

Error stack I'm getting in console.

browserErrorMessage: "Failed to register a ServiceWorker: ServiceWorker script evaluation failed"
code :"messaging/failed-serviceworker-registration"
message :"Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker: ServiceWorker script evaluation failed (messaging/failed-serviceworker-registration)."
stack: "FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker: ServiceWorker script evaluation failed (messaging/failed-serviceworker-registration).↵    at https://www.gstatic.com/firebasejs/3.7.0/firebase.js:555:225"
__proto__: Error

Thank you

Body:
This method should be there in the main javascript file, NOT in service worker. Service Worker works in the background.

    messaging.onMessage(function(payload) {
      console.log("Message received. ", payload);
      // ...
    });


问:
Prevent cross-site scripting attack from static site
I have hosted a static HTML page using GitHub Pages with a Contact Us form.

I found a solution so I can send the form to my email with https://formspree.io/ but i am not sure if this prevent an attacker to do XSS attack.

Maybe if i add HTML <input> pattern Attribute to my page prevent the attack?

Is there any way to prevent XSS attack without any server-side script?

I dont know how GitHub Pages handle xss attack and what are the vulnerabilities of html static forms.

答:
I dont know how GitHub Pages handle xss attack and what are the vulnerabilities of html static forms

GitHub pages does not offer any kind of backend scripting, which limits the security risk.

Formspree will help as it proposes a contact form which is secure (although xss vulnerability still exists, and are fixed).

You can see an example in 'Sending Contact Form Emails From Your GitHub Pages Site Using AJAX & Formspree'


问:
Missing values in lmer vs gls
I have a longitudinal dataset that I am performing an HLM analysis on using lmer in lme4. I would like to compare the results from this analysis to the results on the same data but using glsin the nlme package.

There are multiple measures for each participant in the dataset and several of the participants have values missing at one or more timepoints.

lmer does not seem to have a problem with this, but when I ran the same analysis using gls I got an error message

```<code>Error in na.fail.default(list(id = c(1001L, 1002L, 1003L, 1004L, 1005L,  :
  missing values in object
</code>```

So I have two questions

(1) how does lmer deal with the missing values?

(2) why does gls require 0 missing values when lmerseems to have no issue with NAs? I would rather not lose all that power by being forced to exclude all those participants who have missing data, so if there is some way to specify the same method of treating missing values in lmer except in gls that would be ideal. (otherwise multiple imputation I suppose?)

答:
The default na.action of lmer is na.omit, which means that any rows that have missing values on one or more variables in the model are removed from the dataset. The default action ins gls is na.fail which is why gls gives an error message when any variables in the model have missing values. Regardless of which function you use the power issue remains. You could specify the same method of handling missing data by typing gls(....,na.action = na.omit) but in both cases you're excluding rows with missing data.

Since you have longitudinal data excluding rows with missing data doesn't necessarily equate to excluding participants (but might mean that you're excluding some observations of some participants) and according to Snijder and Bosker (2012) does not lead to biased estimates assuming data are missing at random (MAR). I would start by examining any patterns in the missing data that could lead to bias e.g. because the variables that are related to the missing data mechanism are not included in the model. Multiple imputation can be an option but (depending on the circumstances) often does little to alleviate power issues.

Title: Missing values in lmer vs gls

Body:
I have a longitudinal dataset that I am performing an HLM analysis on using lmer in lme4. I would like to compare the results from this analysis to the results on the same data but using glsin the nlme package.

There are multiple measures for each participant in the dataset and several of the participants have values missing at one or more timepoints.

lmer does not seem to have a problem with this, but when I ran the same analysis using gls I got an error message

Error in na.fail.default(list(id = c(1001L, 1002L, 1003L, 1004L, 1005L,  :
  missing values in object

So I have two questions

(1) how does lmer deal with the missing values?

(2) why does gls require 0 missing values when lmerseems to have no issue with NAs? I would rather not lose all that power by being forced to exclude all those participants who have missing data, so if there is some way to specify the same method of treating missing values in lmer except in gls that would be ideal. (otherwise multiple imputation I suppose?)


问:
Jquery: Datepicker on an appended row in a table is not working
i have created a table that inside of it, contains a column in a row that lets the user picks the date. The datepicker works on the static text field, but on the one generated by the click of a button, it is not working.(The row is appended, but the datepicker will not appear on the newly generated row.)

This is the code for the table:

```<code><div class="table-responsive">
<table class = "table" id="dynamic_admin_add_event_time">
<thead>
<th>Event Date</th>
<th>Event Start</th>
<th>Event Ends</th>
<th></th>
</thead>

<tbody>
<tr>
<td><input type="text" id="dateEvent" name="admin_add_event_date[]"  class="form-control" required></td>
<td><input type="text" id="startTime" name="admin_add_start_event[]" class="form-control" required></td>
<td><input type="text" id="endTime" name="admin_add_end_event[]" class="form-control" required></td>
<td><button type="button" name=button_add_event_time id="add_event_time" class="btn btn-success">Add More Event</button></td>
</tr>
</tbody>
</table>
</div>
</code>```

This is the code for the datepicker:

```<code>  $("#dateEvent").datetimepicker({
  useCurrent: true,
  format: "dddd, MMM D YYYY"
  });
</code>```

And this is the one for the jquery for generating the rows:

```<code>$('#add_event_time').click(function(){

        i++;

        $('#dynamic_admin_add_event_time').append(
            '<tr id="row'+i+'">' +
            '<td><input type="text" id="dateEvent"name="admin_add_event_date[]" class="form-control" required></td>' +
            '<td><input type="text" id="startTime" name="admin_add_start_event[]" class="form-control" required></td>' +
            '<td><input type="text" id="endTime" name="admin_add_end_event[]" class="form-control" required></td>' +
            '<td><button type="button" name="button_remove_event_time" id="'+i+'" class="btn btn-danger btn_remove">Remove Event</button></td>' +
            '</tr>');
 });
</code>```

Can you guys help me by with this problem? Thank you.

答:
Button click inside redefine to reinitialize datetimepicker load like

datetimepicker assign

```<code>$(".dateEvent").datetimepicker({
   useCurrent: true,
   format: "dddd, MMM D YYYY"
});
</code>```

Script

```<code>$('#add_event_time').click(function(){
   i++;
    $('#dynamic_admin_add_event_time').append(
        '<tr id="row'+i+'">' +
        '<td><input type="text" id="dateEvent" class="form-control dateEvent" name="admin_add_event_date[]"  required></td>' +
        '<td><input type="text" id="startTime" name="admin_add_start_event[]" class="form-control" required></td>' +
        '<td><input type="text" id="endTime" name="admin_add_end_event[]" class="form-control" required></td>' +
        '<td><button type="button" name="button_remove_event_time" id="'+i+'" class="btn btn-danger btn_remove">Remove Event</button></td>' +
        '</tr>');
    $( ".dateEvent" ).datepicker();
});
</code>```

Body:
i have created a table that inside of it, contains a column in a row that lets the user picks the date. The datepicker works on the static text field, but on the one generated by the click of a button, it is not working.(The row is appended, but the datepicker will not appear on the newly generated row.)

This is the code for the table:

Event Date
Event Start
Event Ends

<input type="text" id="dateEvent" name="admin_add_event_date[]"  class="form-control" required>
<input type="text" id="startTime" name="admin_add_start_event[]" class="form-control" required>
<input type="text" id="endTime" name="admin_add_end_event[]" class="form-control" required>
<button type="button" name=button_add_event_time id="add_event_time" class="btn btn-success">Add More Event</button>

This is the code for the datepicker:

  $("#dateEvent").datetimepicker({
  useCurrent: true,
  format: "dddd, MMM D YYYY"
  });

And this is the one for the jquery for generating the rows:

$('#add_event_time').click(function(){

        i++;

        $('#dynamic_admin_add_event_time').append(
            '
' +
            '<input type="text" id="dateEvent"name="admin_add_event_date[]" class="form-control" required>	' +
            '<input type="text" id="startTime" name="admin_add_start_event[]" class="form-control" required>	' +
            '<input type="text" id="endTime" name="admin_add_end_event[]" class="form-control" required>	' +
            '<button type="button" name="button_remove_event_time" id="'+i+'" class="btn btn-danger btn_remove">Remove Event</button>	' +
            '
');
 });

Can you guys help me by with this problem? Thank you.

Body:
Button click inside redefine to reinitialize datetimepicker load like

datetimepicker assign

$(".dateEvent").datetimepicker({
   useCurrent: true,
   format: "dddd, MMM D YYYY"
});

Script

$('#add_event_time').click(function(){
   i++;
    $('#dynamic_admin_add_event_time').append(
        '<tr id="row'+i+'">' +
        '<td><input type="text" id="dateEvent" class="form-control dateEvent" name="admin_add_event_date[]"  required></td>' +
        '<td><input type="text" id="startTime" name="admin_add_start_event[]" class="form-control" required></td>' +
        '<td><input type="text" id="endTime" name="admin_add_end_event[]" class="form-control" required></td>' +
        '<td><button type="button" name="button_remove_event_time" id="'+i+'" class="btn btn-danger btn_remove">Remove Event</button></td>' +
        '</tr>');
    $( ".dateEvent" ).datepicker();
});


问:
python recursive functions - troubled with output
Having trouble with this python introductory course's last assignment.. first contact with programming, so..

Guidelines:

Implement the bother(n) function that returns a string containing "bother " (the word followed by a space) n times. If n is not a strictly positive integer, the function should return an empty string. This function must be implemented using recursion.

Using the above function, implement the elephants (n) function that returns a string containing the letter of "An elephant bothers a lot of people ..." from 1 to n elephants. If n is not greater than 1, the function should return an empty string. This function must also be implemented using recursion.

So, I tried:

```<code>def bother(n):
    if n <= 0:
        return ''
    elif n == 1:
        return 'bother '
    else:
        return 'bother ' + bother(n - 1)

def elephants(n):
    if n <= 0: return ''
    if n == 1: return 'An elephant bothers a lot of people...\r\n'
    return elephants(n - 1) \
           + str(n) + ' elephants ' + bother(n) + 'much more\r\n' \
           + str(n) + ' elephants ' + bother(n) + 'a lot of people\r\n'
</code>```

But calling elephants(2) should return:

```<code>An elephant bothers a lot of people...
2 elephants bother much more
</code>```

And calling elephants(4) should return:

```<code>An elephant bothers a lot of people...
2 elephants bother bother much more
2 elephants bother bother a lot of people
3 elephants bother bother bother much more
3 elephants bother bother bother a lot of people
4 elephants bother bother bother bother much more
</code>```

How can I do it?

答:
Try this:</p>

```<code>def bother(n):
    if n == 0:
        return 'bother '
    elif n <= 0:
        return ''
    else:
        return 'bother ' + bother(n - 1)

def elephants(n, first=True):  #first keeps track of which output per n
    if n <= 0:
        return ''
    elif n == 1:
        return "An elephant bothers a lot of people"
    elif first:
        return elephants(n, not first) \
        + str(n) + ' elephants ' + bother(n - 1) + 'a lot of people'
    else:
        return str(n) + ' elephants ' + bother(n - 1) + 'much more\n'

print(elephants(1))
print(elephants(2))
print(elephants(3))
print(elephants(4))

"""
This gives you the desired output. The main part of the elephants section if that it alternates between the two different returned strings:
-a lot of people         (first=True)
-much more               (first=False)

When called recursively it flips the Boolean with not operator and returns the second string, then flips back for the next value of n to the first returned string
"""
</code>```

Body:
Having trouble with this python introductory course's last assignment.. first contact with programming, so..

Guidelines:

Implement the bother(n) function that returns a string containing "bother " (the word followed by a space) n times. If n is not a strictly positive integer, the function should return an empty string. This function must be implemented using recursion.

Using the above function, implement the elephants (n) function that returns a string containing the letter of "An elephant bothers a lot of people ..." from 1 to n elephants. If n is not greater than 1, the function should return an empty string. This function must also be implemented using recursion.

So, I tried:

def bother(n):
    if n <= 0:
        return ''
    elif n == 1:
        return 'bother '
    else:
        return 'bother ' + bother(n - 1)

def elephants(n):
    if n <= 0: return ''
    if n == 1: return 'An elephant bothers a lot of people...\r\n'
    return elephants(n - 1) \
           + str(n) + ' elephants ' + bother(n) + 'much more\r\n' \
           + str(n) + ' elephants ' + bother(n) + 'a lot of people\r\n'

But calling elephants(2) should return:

An elephant bothers a lot of people...
2 elephants bother much more

And calling elephants(4) should return:

An elephant bothers a lot of people...
2 elephants bother bother much more
2 elephants bother bother a lot of people
3 elephants bother bother bother much more
3 elephants bother bother bother a lot of people
4 elephants bother bother bother bother much more

How can I do it?

Body:
Try this:

def bother(n):
    if n == 0:
        return 'bother '
    elif n <= 0:
        return ''
    else:
        return 'bother ' + bother(n - 1)

def elephants(n, first=True):  #first keeps track of which output per n
    if n <= 0:
        return ''
    elif n == 1:
        return "An elephant bothers a lot of people"
    elif first:
        return elephants(n, not first) \
        + str(n) + ' elephants ' + bother(n - 1) + 'a lot of people'
    else:
        return str(n) + ' elephants ' + bother(n - 1) + 'much more\n'

print(elephants(1))
print(elephants(2))
print(elephants(3))
print(elephants(4))

"""
This gives you the desired output. The main part of the elephants section if that it alternates between the two different returned strings:
-a lot of people         (first=True)
-much more               (first=False)

When called recursively it flips the Boolean with not operator and returns the second string, then flips back for the next value of n to the first returned string
"""


问:
How to add Image Source from WPF Application using c#?
I am a beginner in WPF Application. I have checked various tutorials but I am unable to find the option to add an image to my project. I am using Visual Studio 2015. In my .xaml page it is showing the image but once I run the program it is not showing the image. Can anyone please help me?

```<code><Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="438*"/>
            <ColumnDefinition Width="79*"/>
        </Grid.ColumnDefinitions>
        <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="266,114,0,0" VerticalAlignment="Top" Width="81" Height="20"/>
        <Image x:Name="image" HorizontalAlignment="Left" Height="96" Margin="52,71,0,0" VerticalAlignment="Top" Width="111" Source="/WpfApplication1;component/Images/Start.png"/>

    </Grid> </Window>
</code>```

答:
If the XAML Designer is showing it to you, then most probably, after building/compiling, the application cannot find the image. This is quite a common problem - the Designer and the actual application do their resource lookup a little bit different.

Right click on the project, pick "Clean", wait a little, then right click again and pick 'Build'. When it finishes, check the output bin\debug or bin\release directory and see if the image is there, sitting right next to the .exe file. If not, then go back to the project, rightclick on the image in the project and pick 'Properties' and there pick BuildAction=CopyToOutput (i.e. 'always' - probably the best option for images and similar read-only resources). Build the project again, and now it should be visible next to the .exe file, and your application should be able to find it (provided that the path-to-image in xaml is right).

If you don't see your image in the project, then you probably forgot to add it. Right click on the project, pick 'add existing' and add the image so it's in the project. Otherwise, VisualStudio build process has no idea about the image (even if XAML sees it) and will not copy it to the output directory.

What I described is just one option. There are many more available. For example, you may add the image as "Embedded Resource" so it is built-into the .exe and does not sit next to it. However, all of those options vary in details - specifically, they vary regarding:

how to add and configure image options in the project

how does the Path-To-Image should look like in XAML

so.. it's easy to mess up. For starters, focus on one option (like: Image-as-CopyToOutput, or Image-as-EmbeddedResource) and don't mix them up. Read articles carefully, because often it is not clearly stated which way they have chosen.

Edit:

I just noticed you provided the code. See, your path-to-image in XAML is now:

```<code>Source="/WpfApplication1;component/Images/Start.png"
</code>```

which suggests that this is an embedded resource. You can easily see that this is a special path: (name-of-dll-or-exe) ; (component) / path-to-file. If you use paths like that (they are formally called "pack-uri"), then you should make sure the image is added to the project, but that it is NOT set the image to "buildaction=CopyToOutput" like I advised, but to "BuildAction=EmbeddedResource". It should also be located not right away in the project root, but in "images/" subfolder, and also, that subfolder should be visible in the project in VS.

If you want to try the "CopyToOutput" way, then the path would be just:

```<code>Source="Images/Start.png"
</code>```

With 'CopyToOutput' mode, you actually don't need to care about adding the image to the project - all that's needed it to sure that there is an "Images" folder next to the .exe file right before running the .exe. However, you will have to remember about keeping that image there. If you add the folder and the image to the project, and set buildaction=content, then the VS will remember it for you and will place the folder and image next to the .exe as a part of the build.

So.. first of all, make sure that this image and folder are added to the Project. Then decide which type of BuildAction you want to try out, set it, write relevant path in the ImageSource, then .. keep fingers crossed. It can be hard when you do it for the first time, as there are many ways to do that (not only those 2 I mentioned) and VS/Xaml often don't report any errors..

Body:
I am a beginner in WPF Application. I have checked various tutorials but I am unable to find the option to add an image to my project. I am using Visual Studio 2015. In my .xaml page it is showing the image but once I run the program it is not showing the image. Can anyone please help me?

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="438*"/>
            <ColumnDefinition Width="79*"/>
        </Grid.ColumnDefinitions>
        <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="266,114,0,0" VerticalAlignment="Top" Width="81" Height="20"/>
        <Image x:Name="image" HorizontalAlignment="Left" Height="96" Margin="52,71,0,0" VerticalAlignment="Top" Width="111" Source="/WpfApplication1;component/Images/Start.png"/>

    </Grid> </Window>

Body:
If the XAML Designer is showing it to you, then most probably, after building/compiling, the application cannot find the image. This is quite a common problem - the Designer and the actual application do their resource lookup a little bit different.

Right click on the project, pick "Clean", wait a little, then right click again and pick 'Build'. When it finishes, check the output bin\debug or bin\release directory and see if the image is there, sitting right next to the .exe file. If not, then go back to the project, rightclick on the image in the project and pick 'Properties' and there pick BuildAction=CopyToOutput (i.e. 'always' - probably the best option for images and similar read-only resources). Build the project again, and now it should be visible next to the .exe file, and your application should be able to find it (provided that the path-to-image in xaml is right).

If you don't see your image in the project, then you probably forgot to add it. Right click on the project, pick 'add existing' and add the image so it's in the project. Otherwise, VisualStudio build process has no idea about the image (even if XAML sees it) and will not copy it to the output directory.

What I described is just one option. There are many more available. For example, you may add the image as "Embedded Resource" so it is built-into the .exe and does not sit next to it. However, all of those options vary in details - specifically, they vary regarding:

how to add and configure image options in the project

how does the Path-To-Image should look like in XAML

so.. it's easy to mess up. For starters, focus on one option (like: Image-as-CopyToOutput, or Image-as-EmbeddedResource) and don't mix them up. Read articles carefully, because often it is not clearly stated which way they have chosen.

Edit:

I just noticed you provided the code. See, your path-to-image in XAML is now:

Source="/WpfApplication1;component/Images/Start.png"

which suggests that this is an embedded resource. You can easily see that this is a special path: (name-of-dll-or-exe) ; (component) / path-to-file. If you use paths like that (they are formally called "pack-uri"), then you should make sure the image is added to the project, but that it is NOT set the image to "buildaction=CopyToOutput" like I advised, but to "BuildAction=EmbeddedResource". It should also be located not right away in the project root, but in "images/" subfolder, and also, that subfolder should be visible in the project in VS.

If you want to try the "CopyToOutput" way, then the path would be just:

Source="Images/Start.png"

With 'CopyToOutput' mode, you actually don't need to care about adding the image to the project - all that's needed it to sure that there is an "Images" folder next to the .exe file right before running the .exe. However, you will have to remember about keeping that image there. If you add the folder and the image to the project, and set buildaction=content, then the VS will remember it for you and will place the folder and image next to the .exe as a part of the build.

So.. first of all, make sure that this image and folder are added to the Project. Then decide which type of BuildAction you want to try out, set it, write relevant path in the ImageSource, then .. keep fingers crossed. It can be hard when you do it for the first time, as there are many ways to do that (not only those 2 I mentioned) and VS/Xaml often don't report any errors..


问:
Hide Django logo/name in header Django admin tool
I want to hide/change the name displayed in the header bar, the label that I want to change is "DJANGO" word as the next image shows"

答:
Another solution for customizing the admin header.

Just copy /django/contrib/admin/templates/admin/base_site.html from django source (Link Here) and paste it under your templates directory.

For example,

```<code>your_project/templates/admin/base_site.html
</code>```

Now you can change whatever you like in this template.

Hope this helps.

Body:
Another solution for customizing the admin header.

Just copy /django/contrib/admin/templates/admin/base_site.html from django source (Link Here) and paste it under your templates directory.

For example,

your_project/templates/admin/base_site.html

Now you can change whatever you like in this template.

Hope this helps.


问:
pandas groupby where you get the max of one column and the min of another column
I have a dataframe as follows:

```<code>user    num1    num2
a       1       1
a       2       2
a       3       3
b       4       4
b       5       5
</code>```

I want a dataframe which has the minimum from num1 for each user, and the maximum of num2 for each user.

The output should be like:

```<code>user    num1    num2
a       1       3
b       4       5
</code>```

I know that if I wanted the max of both columns I could just do:

```<code>a.groupby('user')['num1', 'num2'].max()
</code>```

Is there some equivalent without having to do something like:

```<code>series_1 = a.groupby('user')['num1'].min()
series_2 = a.groupby('user')['num2'].max()

# converting from series to df so I can do a join on user
df_1 = pd.DataFrame(np.array([series_1]).transpose(), index=series_1.index, columns=['num1'])
df_2 = pd.DataFrame(np.array([series_2]).transpose(), index=series_2.index, columns=['num2'])

df_1.join(df_2)
</code>```

答:
Use groupby + agg by dict, so then is necessary order columns by subset or reindex_axis. Last add reset_index for convert index to column if necessary.

```<code>df = a.groupby('user').agg({'num1':'min', 'num2':'max'})[['num1','num2']].reset_index()
print (df)
  user  num1  num2
0    a     1     3
1    b     4     5
</code>```

What is same as:

```<code>df = a.groupby('user').agg({'num1':'min', 'num2':'max'})
                      .reindex_axis(['num1','num2'], axis=1)
                      .reset_index()
print (df)
  user  num1  num2
0    a     1     3
1    b     4     5
</code>```

Body:
I have a dataframe as follows:

user    num1    num2
a       1       1
a       2       2
a       3       3
b       4       4
b       5       5

I want a dataframe which has the minimum from num1 for each user, and the maximum of num2 for each user.

The output should be like:

user    num1    num2
a       1       3
b       4       5

I know that if I wanted the max of both columns I could just do:

a.groupby('user')['num1', 'num2'].max()

Is there some equivalent without having to do something like:

series_1 = a.groupby('user')['num1'].min()
series_2 = a.groupby('user')['num2'].max()

# converting from series to df so I can do a join on user
df_1 = pd.DataFrame(np.array([series_1]).transpose(), index=series_1.index, columns=['num1'])
df_2 = pd.DataFrame(np.array([series_2]).transpose(), index=series_2.index, columns=['num2'])

df_1.join(df_2)

Body:
Use groupby + agg by dict, so then is necessary order columns by subset or reindex_axis. Last add reset_index for convert index to column if necessary.

df = a.groupby('user').agg({'num1':'min', 'num2':'max'})[['num1','num2']].reset_index()
print (df)
  user  num1  num2
0    a     1     3
1    b     4     5

What is same as:

df = a.groupby('user').agg({'num1':'min', 'num2':'max'})
                      .reindex_axis(['num1','num2'], axis=1)
                      .reset_index()
print (df)
  user  num1  num2
0    a     1     3
1    b     4     5


问:
Angular 2 value is not updating in html
I am working on an application where facebook login is required. Here is my ts file

```<code> ngOnInit() {
    setTimeout(() => {
      this.initialize();
    })
  }

  initialize() {
    (function (d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    setTimeout(() => {
      window.fbAsyncInit =  () =>{
        FB.init({
          appId: 'your-app-id', //I gave my app id here
          cookie: true,  // enable cookies to allow the server to access
          // the session
          xfbml: true,  // parse social plugins on this page
          version: 'v2.8' // use graph api version 2.8
        });
        this.checkFBLoginStatus();
      }
    })

  }

  checkFBLoginStatus() {
    FB.getLoginStatus((response) =>{
      this.verifyResponse(response);
    });
  }

 verifyResponse(response){
    this.response = response;

   console.log(this.response) // I am getting the console output
 }
</code>```

Here is my HTML

```<code><!--For Testing purpose-->
Response is->
<p *ngIf="response">{{response.status}}</p>
<!--For Testing purpose-->

<button *ngIf="response && response.status && response.status == 'unknown'" class="btn blue fb-login-button" (click)="loginUsingFacebook()"><span class="fa fa-facebook white-text"></span>Login Using Facebook</button>

<button *ngIf="response && response.status && response.status == 'not_authorized'" class="btn blue fb-login-button" (click)="continueUsingFacebook()"><span class="fa fa-facebook white-text"></span>Continue Using Facebook</button>

<button *ngIf="response && response.status && response.status == 'connected'" class="btn blue fb-login-button" (click)="logoutFacebook()"><span class="fa fa-facebook white-text"></span>Logout Facebook</button>
</code>```

The response.status is showing in console. But its not getting binded to html. And so i am not able to see the respective buttons.

I am trying to detect whether the user is logged in or if not, what is the best way i can capture the onlogin function of javascript (facebook attr) in typescript.

Thanks

答:
This is because the return event from the fbAsyncInit method is not recognized by the zone.js monkey patched event listeners. In other words, you are working outside the angular zone.

You should inject NgZone in your component, and reenter it using run:

```<code>constructor(private _ngZone: NgZone){}

ngOnInit() {
   this.initialize();
}

initialize() {
   window.fbAsyncInit =  () => {
     this._ngZone.run(() => {
       FB.init({
           ...
       });
       this.checkFBLoginStatus();
     });
   }
}
</code>```

Title: Angular 2 value is not updating in html

Body:
I am working on an application where facebook login is required. Here is my ts file

 ngOnInit() {
    setTimeout(() => {
      this.initialize();
    })
  }

  initialize() {
    (function (d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    setTimeout(() => {
      window.fbAsyncInit =  () =>{
        FB.init({
          appId: 'your-app-id', //I gave my app id here
          cookie: true,  // enable cookies to allow the server to access
          // the session
          xfbml: true,  // parse social plugins on this page
          version: 'v2.8' // use graph api version 2.8
        });
        this.checkFBLoginStatus();
      }
    })

  }

  checkFBLoginStatus() {
    FB.getLoginStatus((response) =>{
      this.verifyResponse(response);
    });
  }

 verifyResponse(response){
    this.response = response;

   console.log(this.response) // I am getting the console output
 }

Here is my HTML

Response is->

{{response.status}}

<button *ngIf="response && response.status && response.status == 'unknown'" class="btn blue fb-login-button" (click)="loginUsingFacebook()">Login Using Facebook</button>

<button *ngIf="response && response.status && response.status == 'not_authorized'" class="btn blue fb-login-button" (click)="continueUsingFacebook()">Continue Using Facebook</button>

<button *ngIf="response && response.status && response.status == 'connected'" class="btn blue fb-login-button" (click)="logoutFacebook()">Logout Facebook</button>

The response.status is showing in console. But its not getting binded to html. And so i am not able to see the respective buttons.

I am trying to detect whether the user is logged in or if not, what is the best way i can capture the onlogin function of javascript (facebook attr) in typescript.

Thanks

Body:
This is because the return event from the fbAsyncInit method is not recognized by the zone.js monkey patched event listeners. In other words, you are working outside the angular zone.

You should inject NgZone in your component, and reenter it using run:

constructor(private _ngZone: NgZone){}

ngOnInit() {
   this.initialize();
}

initialize() {
   window.fbAsyncInit =  () => {
     this._ngZone.run(() => {
       FB.init({
           ...
       });
       this.checkFBLoginStatus();
     });
   }
}


问:
How to remove trailing whitespaces with sed?
I have a simple shell script that removes trailing whitespace from a file. Is there any way to make this script more compact (without creating a temporary file)?</p>

```<code>sed 's/[ \t]*$//' $1 > $1__.tmp
cat $1__.tmp > $1
rm $1__.tmp
</code>```

答:
You can use the in place option -i of sed for Linux and Unix:

```<code>sed -i 's/[ \t]*$//' "$1"
</code>```

Be aware the expression will delete trailing t's on OSX (you can use gsed to avoid this problem). It may delete them on BSD too.

If you don't have gsed, here is the correct (but hard-to-read) sed syntax on OSX:

```<code>sed -i '' -E 's/[ '$'\t'']+$//' "$1"
</code>```

Three single-quoted strings ultimately become concatenated into a single argument/expression. There is no concatenation operator in bash, you just place strings one after the other with no space in between.

The $'\t' resolves as a literal tab-character in bash (using ANSI-C quoting), so the tab is correctly concatenated into the expression.

Body:
I have a simple shell script that removes trailing whitespace from a file. Is there any way to make this script more compact (without creating a temporary file)?

sed 's/[ \t]*$//' $1 > $1__.tmp
cat $1__.tmp > $1
rm $1__.tmp

Body:
You can use the in place option -i of sed for Linux and Unix:

sed -i 's/[ \t]*$//' "$1"

Be aware the expression will delete trailing t's on OSX (you can use gsed to avoid this problem). It may delete them on BSD too.

If you don't have gsed, here is the correct (but hard-to-read) sed syntax on OSX:

sed -i '' -E 's/[ '$'\t'']+$//' "$1"

Three single-quoted strings ultimately become concatenated into a single argument/expression. There is no concatenation operator in bash, you just place strings one after the other with no space in between.

The $'\t' resolves as a literal tab-character in bash (using ANSI-C quoting), so the tab is correctly concatenated into the expression.


答:
Try this code:</p>

```<code>// Retrieve operation using the JPA Entity Manager
order = em.find(Orders.class,productsId);

// get the orderNumber from an instance of Entity Orders
int orderNumber = order.getOrderNumber();
</code>```

Title: JPA: find result by interring foreign value

Body:
Here is my database

   CREATE TABLE Orders (
        OrderID int NOT NULL,
        OrderNumber int NOT NULL,
        products_id int,
        PRIMARY KEY (OrderID),
        FOREIGN KEY (products_id) REFERENCES product(products_id)
    );

****I generated NetBeans entity class and it gives the following code;****

package Entity;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;

@Entity
@Table(name = "orders")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Orders.findAll", query = "SELECT o FROM Orders o")
    , @NamedQuery(name = "Orders.findByOrderID", query = "SELECT o FROM Orders o WHERE o.orderID = :orderID")
    , @NamedQuery(name = "Orders.findByOrderNumber", query = "SELECT o FROM Orders o WHERE o.orderNumber = :orderNumber")})
public class Orders implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @Column(name = "OrderID")
    private Integer orderID;
    @Basic(optional = false)
    @Column(name = "OrderNumber")
    private int orderNumber;

    public Orders() {
    }

    public Orders(Integer orderID) {
        this.orderID = orderID;
    }

    public Orders(Integer orderID, int orderNumber) {
        this.orderID = orderID;
        this.orderNumber = orderNumber;
    }

    public Integer getOrderID() {
        return orderID;
    }

    public void setOrderID(Integer orderID) {
        this.orderID = orderID;
    }

    public int getOrderNumber() {
        return orderNumber;
    }

    public void setOrderNumber(int orderNumber) {
        this.orderNumber = orderNumber;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (orderID != null ? orderID.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {

        if (!(object instanceof Orders)) {
            return false;
        }
        Orders other = (Orders) object;
        if ((this.orderID == null && other.orderID != null) || (this.orderID != null && !this.orderID.equals(other.orderID))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "Entity.Orders[ orderID=" + orderID + " ]";
    }

}

****I am new of JPA, and I just want to get the "OrderNumber" by entering the "products_id" is it possible?**
I want something like this**

public Orders findOrderNumber(int productsId) {
        EntityManager em = getEntityManager();
        Orders order= null;
        try {
         order= (Orders) em.createQuery("SELECT o FROM Orders o WHERE o.productsId=" + productsId).getSingleResult();

        } catch (NoResultException e) {
            order= null;
        }

        return order;
    }

Body:
Try this code:

// Retrieve operation using the JPA Entity Manager
order = em.find(Orders.class,productsId);

// get the orderNumber from an instance of Entity Orders
int orderNumber = order.getOrderNumber();


问:
Comparing parsed XML with a string
I'm developing a web service that will receive a XML string and will compare with the internalName string. I'm using LINQ to parse the XML (and I think I'm doing it correctly) but I'm not sure how to compare the "value" withinternalName, per example.

```<code>    [WebMethod]
    public string WMCompare (string xml, string internalName)
    {
        XDocument xmlDoc = XDocument.Load(xml);

        var result = from ele in xmlDoc.Descendants("property")
                     select new
                     {
                         key = (string)ele.Element("key"),
                         value = (string)ele.Element("value")
                     };
        foreach (var i in result)
        {
        }
    }
}
</code>```

Thank you for your attention and I'm sorry about the newbie question. It's my first time working with XML.

答:
Considering that you are comparing string with value:

```<code>var newResult = result.Where(r => r.value.Equals(internalName))
</code>```

Alternatively, you may also compare while parsing your XML:

```<code>var result1 = from ele in doc.Descendants("property")
              where ele.HasElements && ele.Element("value") != null && ele.Element("value").Equals(internalName)
              select new
              {
                  key = (string)ele.Element("key"),
                  value = (string)ele.Element("value")
              };
</code>```

Title: Comparing parsed XML with a string

Body:
I'm developing a web service that will receive a XML string and will compare with the internalName string. I'm using LINQ to parse the XML (and I think I'm doing it correctly) but I'm not sure how to compare the "value" withinternalName, per example.

    [WebMethod]
    public string WMCompare (string xml, string internalName)
    {
        XDocument xmlDoc = XDocument.Load(xml);

        var result = from ele in xmlDoc.Descendants("property")
                     select new
                     {
                         key = (string)ele.Element("key"),
                         value = (string)ele.Element("value")
                     };
        foreach (var i in result)
        {
        }
    }
}

Thank you for your attention and I'm sorry about the newbie question. It's my first time working with XML.

Body:
Considering that you are comparing string with value:

var newResult = result.Where(r => r.value.Equals(internalName))

Alternatively, you may also compare while parsing your XML:

var result1 = from ele in doc.Descendants("property")
              where ele.HasElements && ele.Element("value") != null && ele.Element("value").Equals(internalName)
              select new
              {
                  key = (string)ele.Element("key"),
                  value = (string)ele.Element("value")
              };


答:
```<code><div className={"toggle-button " + (this.state.active ? 'active-button' : '')}>
</code>```

note the space after toggle-button

Title: React Syntax error on adding a second class on Toggle

Body:
How can i add second class to my
 "button" if i append 'toggle-button' the class doesn't work.

<CSSTransitionGroup
    transitionName="buttonAninmated"
    transitionEnterTimeout={300}
    transitionLeaveTimeout={300}
>

</CSSTransitionGroup>

Body:
<div className={"toggle-button " + (this.state.active ? 'active-button' : '')}>

note the space after toggle-button


问:
Calculate execution time of a SQL query?
I am providing search functionality in my website, when user searches a record then I want to display the time the query taken to get the results same as google does. When we search anything then google displays how much time it takes to get results?

For this I have declared a @start variable in my SP and finding the difference in the end, as below;

```<code>DECLARE @start_time DATETIME

SET @start_time = GETDATE()

-- my query
SELECT * FROM @search_temp_table

SELECT RTRIM(CAST(DATEDIFF(MS, @start_time, GETDATE()) AS CHAR(10))) AS 'TimeTaken'
</code>```

Is there any other easy and fast way, or a single line of query with which we can find out the time a query taken to execute?

I'm using SQL Server 2005.

答:
You can use

```<code>SET STATISTICS TIME { ON | OFF }
</code>```

Displays the number of milliseconds required to parse, compile, and execute each statement

When SET STATISTICS TIME is ON, the time statistics for a statement are displayed. When OFF, the time statistics are not displayed

```<code>USE AdventureWorks2012;
GO
SET STATISTICS TIME ON;
GO
SELECT ProductID, StartDate, EndDate, StandardCost
FROM Production.ProductCostHistory
WHERE StandardCost < 500.00;
GO
SET STATISTICS TIME OFF;
GO
</code>```

OwnerDisplayName: Prashant

Body:
I am providing search functionality in my website, when user searches a record then I want to display the time the query taken to get the results same as google does. When we search anything then google displays how much time it takes to get results?

For this I have declared a @start variable in my SP and finding the difference in the end, as below;

DECLARE @start_time DATETIME

SET @start_time = GETDATE()

-- my query
SELECT * FROM @search_temp_table

SELECT RTRIM(CAST(DATEDIFF(MS, @start_time, GETDATE()) AS CHAR(10))) AS 'TimeTaken'

Is there any other easy and fast way, or a single line of query with which we can find out the time a query taken to execute?

I'm using SQL Server 2005.

Body:
You can use

SET STATISTICS TIME { ON | OFF }

Displays the number of milliseconds required to parse, compile, and execute each statement

When SET STATISTICS TIME is ON, the time statistics for a statement are displayed. When OFF, the time statistics are not displayed

USE AdventureWorks2012;
GO
SET STATISTICS TIME ON;
GO
SELECT ProductID, StartDate, EndDate, StandardCost
FROM Production.ProductCostHistory
WHERE StandardCost < 500.00;
GO
SET STATISTICS TIME OFF;
GO


问:
IIS redirect only one domain on SSL
I have some website on IIS that was http, but now i have added the SSL, but only for one domain. But i have a lot of custom domain that poits to same website, this is what i need

Have ssl for www.example.com and example.com, but i also have www.examplenew.com, www.example34.com, example56.com that points to same website but i dont have ssl for them, i only need rewrite rule for www.example.com and example.com other i dont need.
I have made rewrite rule in web.config, for redirect to https but know its redirect all to ssl i dont need that, this is my web.config file

```<code> <rewrite>
      <rules>
        <rule name="HTTP to HTTPS redirect" stopProcessing="true">
          <match url="(*)" />
            <conditions>
              <add input="{HTTPS}" pattern="off" ignoreCase="true" />
            </conditions>
            <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" />
        </rule>
      </rules>
    </rewrite>
</code>```

答:
You need to add an additional condition to rewrite rule, which will check host:</p>

```<code><rules>
    <rule name="HTTP to HTTPS redirect" stopProcessing="true">
        <match url="(.*)" />
        <conditions>
            <add input="{HTTP_HOST}" pattern="^(www.)?example.com" />
            <add input="{HTTPS}" pattern="off" ignoreCase="true" />
        </conditions>
        <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" />
    </rule>
</rules>
</code>```

Title: IIS redirect only one domain on SSL

Body:
I have some website on IIS that was http, but now i have added the SSL, but only for one domain. But i have a lot of custom domain that poits to same website, this is what i need

Have ssl for www.example.com and example.com, but i also have www.examplenew.com, www.example34.com, example56.com that points to same website but i dont have ssl for them, i only need rewrite rule for www.example.com and example.com other i dont need.
I have made rewrite rule in web.config, for redirect to https but know its redirect all to ssl i dont need that, this is my web.config file

 <rewrite>
      <rules>
        <rule name="HTTP to HTTPS redirect" stopProcessing="true">
          <match url="(*)" />
            <conditions>
              <add input="{HTTPS}" pattern="off" ignoreCase="true" />
            </conditions>
            <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" />
        </rule>
      </rules>
    </rewrite>

Body:
You need to add an additional condition to rewrite rule, which will check host:

<rules>
    <rule name="HTTP to HTTPS redirect" stopProcessing="true">
        <match url="(.*)" />
        <conditions>
            <add input="{HTTP_HOST}" pattern="^(www.)?example.com" />
            <add input="{HTTPS}" pattern="off" ignoreCase="true" />
        </conditions>
        <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" />
    </rule>
</rules>