问:
Why is my firebase database not waiting to update values
So I am really new to threading and I've been reading up on it all day. For some reason though the data isn't loading before other code executes

Basically I need all the values that have a key ["whatever"] to be filled into an array, which works in other places because I don't need to load it first. So i have checked and double checked the keys that I am updating do exist and the keys I am extracting do exist maybe not the values yet but the keys do.

The problem is the code goes to fast to through the method. How would I make the main thread wait untill my firebase has loaded the data I have tried it below but it does not seem to be working

here is my code

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let alertController = UIAlertController(title: "Accept Bet", message: "Match the bet of " + amountBets[indexPath.row], preferredStyle: .alert)

    let okButton = UIAlertAction(title: "No", style: .default, handler: { (action) -> Void in
        print("Ok button tapped")
    })

    let yesButton = UIAlertAction(title: "Yes", style: .default, handler: { (action) -> Void in
        // let them know to wait a second or the bet won't go through
        var waitController = UIAlertController(title: "Please Wait", message: "You must wait for the bet to go through", preferredStyle: .alert)

        self.present(waitController, animated: true, completion: nil)
        //take away that bitches money
        self.takeAwayMoney(self.amountBets[indexPath.row], completion: { (result: Bool?) in

            guard let boolResult = result else {
                return
            }

            if boolResult == true {
                self.updateBet(indexPath.row, completion: {(result: String?) in

                    guard let resultRecieved = result else {
                        return
                    }
                    print(self.opposingUserNames)
                    //let delayInSeconds = 7.0 // 1
                    //DispatchQueue.main.asyncAfter(deadline: .now() + delayInSeconds) { // 2
                    self.dismiss(animated: true, completion: nil)
                    let successController = UIAlertController(title: "Success", message: "You have made a bet with " + self.opposingUserNames!, preferredStyle: .alert)
                    let okButt = UIAlertAction(title: "Ok", style: .default, handler: nil)
                    successController.addAction(okButt)
                    self.present(successController, animated: true, completion: nil)
                    //lastly delete the opposing UserName
                    print(self.opposingUserNames)
                    self.amountBets.remove(at: indexPath.row)
                    self.tableView.reloadData()
                    print("Second")
                    print(self.opposingUserNames)
                    //}

                })
            } else {
                return
            }

        })

        //then delete that cell and do another pop up that says successful
        // check if value is yes or no in the database

    })

    alertController.addAction(okButton)
    alertController.addAction(yesButton)
    present(alertController, animated: true, completion: nil)
}
</code>```

The below function updates the values OpposingUsername and show

```<code>func updateBet(_ index: Int, completion: @escaping (_ something: String?) -> Void) {
    let userID = FIRAuth.auth()?.currentUser?.uid
    datRef.child("User").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
        // Get user value
        let value = snapshot.value as? NSDictionary
        // ...

        self.datRef.child("Bets").observe(.childAdded, with: { snapshot in
            //
            // this is the unique identifier of the bet.  eg, -Kfx81GvUxoHpmmMwJ9P
            guard let dict = snapshot.value as? [String: AnyHashable] else {
                print("failed to get dictionary from Bets.\(self.userName)")
                return
            }
            let values = ["OpposingUsername": self.userName,"Show": "no"]

            self.datRef.child("Bets").child(self.tieBetToUser[index]).updateChildValues(values)
            // now get the opposing username which is just the Username registered to that specific bet
            self.datRef.child("Bets").child(self.tieBetToUser[index]).observe(.childAdded, with: { snapshot in
                guard let dict2 = snapshot.value as? [String: AnyHashable] else {
                    return
                }
                let userNameOfOtherPlayer = dict2["Username"] as? String
                self.opposingUserNames = userNameOfOtherPlayer!
                completion(self.opposingUserNames)
            })

        })

    }) { (error) in
        print(error.localizedDescription)
    }

}
</code>```

ok so with this updated code it cuts out the logic errors I had earlier, but now the app hangs on my waitAlertViewController. Not sure why. it does updated the bet in the firebase database so I know its working and running that code but its like never completing it all. sorry bibscy I see what you mean now

completion handlers are pretty powerful once you understand them better

答:
```<code> //Notice that I made `result: String?` optional, it may or may not have a value.
 func getOpoosingUserNames(_ username: String,_ index: Int, completion: @escaping (_ result: String?) -> Void ) {
    let userID = FIRAuth.auth()?.currentUser?.uid
    datRef.child("User").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
        // Get user value
        let value = snapshot.value as? NSDictionary
        let username = value?["username"] as? String ?? ""
        self.userName = username

        // ...

        self.datRef.child("Bets").observe(.childAdded, with: { snapshot in
            //
            // this is the unique identifier of the bet.  eg, -Kfx81GvUxoHpmmMwJ9P

            let betId = snapshot.key as String
            guard let dict = snapshot.value as? [String: AnyHashable] else {
                print("failed to get dictionary from Bets.\(self.userName)")
                return
            }
            if let show = dict["Show"] as? String {

                let opposingUser = dict["OpposingUsername"] as? String
                    self.opposingUserNames.append(opposingUser!)
            }

             completion(opposingUserNames)
        })
    }) { (error) in
        print(error.localizedDescription)
    }

}

    //update the be
   func updateBet(_ index: Int, completion: @escaping (_ something: [String]?) -> Void) {
  let userID = FIRAuth.auth()?.currentUser?.uid
datRef.child("User").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
    // Get user value
     let value = snapshot.value as? NSDictionary
    // ...

     self.datRef.child("Bets").observe(.childAdded, with: { snapshot in
        //
        // this is the unique identifier of the bet.  eg, -Kfx81GvUxoHpmmMwJ9P
        guard let dict = snapshot.value as? [String: AnyHashable] else {
            print("failed to get dictionary from Bets.\(self.userName)")
            return
        }
         let values = ["OpposingUsername": self.userName,"Show": "no"]

    //store the values received from Firebase in let valueOfUpdate and pass this
  // constant to your completion handler completion(valueOfUpdate) so that you can use this value in func
   //tableView(_ tableView:_, didSelectRowAt indexPath:_)
          let valueOfUpdate =  self.datRef.child("Bets").child(self.tieBetToUser[index]).updateChildValues(values)

     completion(valueOfUpdate)
  }) { (error) in
    print(error.localizedDescription)
  }

}

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let alertController = UIAlertController(title: "Accept Bet", message: "Match the bet of " + amountBets[indexPath.row], preferredStyle: .alert)

    let okButton = UIAlertAction(title: "No", style: .default, handler: { (action) -> Void in
        print("Ok button tapped")
    })

    let yesButton = UIAlertAction(title: "Yes", style: .default, handler: { (action) -> Void in
        //take away that bitches money
        self.takeAwayMoney(self.amountBets[indexPath.row])

        //then delete that cell and do another pop up that says successful
        // check if value is yes or no in the database
        self.updateBet(indexPath.row, completion: {(result: String) in

  guard let resultReceivedInupdateBet = result, else {
    print("result of updateBet() is \(result)")
}
         print("If you see this print, database was updated")

  //calling this method with the indexPath.row clicked by the user
     self.getOpoosingUserNames(self.userName, indexPath.row, completion: { (result: [String]) in

 guard let resultReceivedIngetOpoosingUserNames = result{
      print("result of getOpoosingUserNames is \(result)")
 }
     print("If you see this print, you received a value from db after calling getOpoosingUserNames and that value is in \(result) ")

  //result is not nil, resultReceivedIngetOpoosingUserNames has the same value as result.

 }//end of self.getOpoosingUserNames

        self.checkForNo(indexPath.row)
        self.amountBets.remove(at: indexPath.row)
        self.tableView.reloadData()
        print(self.opposingUserNames)

        let successController = UIAlertController(title: "Success", message: "You have made a bet with " + self.opposingUserNames[indexPath.row], preferredStyle: .alert)
        let okButt = UIAlertAction(title: "Ok", style: .default, handler: nil)
        successController.addAction(okButt)
        self.present(successController, animated: true, completion: nil)
        //lastly delete the opposing UserName
        self.opposingUserNames.remove(at: indexPath.row)

    })

    alertController.addAction(okButton)
    alertController.addAction(yesButton)
    present(alertController, animated: true, completion: nil)
 }
</code>```

Body:
So I am really new to threading and I've been reading up on it all day. For some reason though the data isn't loading before other code executes

Basically I need all the values that have a key ["whatever"] to be filled into an array, which works in other places because I don't need to load it first. So i have checked and double checked the keys that I am updating do exist and the keys I am extracting do exist maybe not the values yet but the keys do.

The problem is the code goes to fast to through the method. How would I make the main thread wait untill my firebase has loaded the data I have tried it below but it does not seem to be working

here is my code

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let alertController = UIAlertController(title: "Accept Bet", message: "Match the bet of " + amountBets[indexPath.row], preferredStyle: .alert)

    let okButton = UIAlertAction(title: "No", style: .default, handler: { (action) -> Void in
        print("Ok button tapped")
    })

    let yesButton = UIAlertAction(title: "Yes", style: .default, handler: { (action) -> Void in
        // let them know to wait a second or the bet won't go through
        var waitController = UIAlertController(title: "Please Wait", message: "You must wait for the bet to go through", preferredStyle: .alert)

        self.present(waitController, animated: true, completion: nil)
        //take away that bitches money
        self.takeAwayMoney(self.amountBets[indexPath.row], completion: { (result: Bool?) in

            guard let boolResult = result else {
                return
            }

            if boolResult == true {
                self.updateBet(indexPath.row, completion: {(result: String?) in

                    guard let resultRecieved = result else {
                        return
                    }
                    print(self.opposingUserNames)
                    //let delayInSeconds = 7.0 // 1
                    //DispatchQueue.main.asyncAfter(deadline: .now() + delayInSeconds) { // 2
                    self.dismiss(animated: true, completion: nil)
                    let successController = UIAlertController(title: "Success", message: "You have made a bet with " + self.opposingUserNames!, preferredStyle: .alert)
                    let okButt = UIAlertAction(title: "Ok", style: .default, handler: nil)
                    successController.addAction(okButt)
                    self.present(successController, animated: true, completion: nil)
                    //lastly delete the opposing UserName
                    print(self.opposingUserNames)
                    self.amountBets.remove(at: indexPath.row)
                    self.tableView.reloadData()
                    print("Second")
                    print(self.opposingUserNames)
                    //}

                })
            } else {
                return
            }

        })

        //then delete that cell and do another pop up that says successful
        // check if value is yes or no in the database

    })

    alertController.addAction(okButton)
    alertController.addAction(yesButton)
    present(alertController, animated: true, completion: nil)
}

The below function updates the values OpposingUsername and show

func updateBet(_ index: Int, completion: @escaping (_ something: String?) -> Void) {
    let userID = FIRAuth.auth()?.currentUser?.uid
    datRef.child("User").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
        // Get user value
        let value = snapshot.value as? NSDictionary
        // ...

        self.datRef.child("Bets").observe(.childAdded, with: { snapshot in
            //
            // this is the unique identifier of the bet.  eg, -Kfx81GvUxoHpmmMwJ9P
            guard let dict = snapshot.value as? [String: AnyHashable] else {
                print("failed to get dictionary from Bets.\(self.userName)")
                return
            }
            let values = ["OpposingUsername": self.userName,"Show": "no"]

            self.datRef.child("Bets").child(self.tieBetToUser[index]).updateChildValues(values)
            // now get the opposing username which is just the Username registered to that specific bet
            self.datRef.child("Bets").child(self.tieBetToUser[index]).observe(.childAdded, with: { snapshot in
                guard let dict2 = snapshot.value as? [String: AnyHashable] else {
                    return
                }
                let userNameOfOtherPlayer = dict2["Username"] as? String
                self.opposingUserNames = userNameOfOtherPlayer!
                completion(self.opposingUserNames)
            })

        })

    }) { (error) in
        print(error.localizedDescription)
    }

}

ok so with this updated code it cuts out the logic errors I had earlier, but now the app hangs on my waitAlertViewController. Not sure why. it does updated the bet in the firebase database so I know its working and running that code but its like never completing it all. sorry bibscy I see what you mean now

completion handlers are pretty powerful once you understand them better


来源: stackexchange

问:
Fabricjs custom class border and background
I've created a class that extend IText and i want to draw a border like selection.

The class code below : (fiddle exemple)

```<code>var LabeledBubble = fabric.util.createClass(fabric.IText,{
   type: 'labeledBubble',
   initialize: function(options) {
     options || (options = {});

     this.callSuper('initialize',options);
     this.set('bubbleType',options.bubbleType || 'Rect');
     this.set('backColor',options.backColor || '#FFF');
     this.set('borderColor',options.borderColor || '#000');
     this.set('borderWidth',options.borderWidth || 1);
     this.set('borderDash',options.borderDash || []);
     this.textAlign = "center";
  },
  toObject: function() {
    return fabric.util.object.extend(this.callSuper('toObject'),{
      bubbleType: this.get('bubbleType')
    });
  },
  _render: function(ctx,noTransform) {
    var w = this.width,
        h = this.height,
        x = noTransform ? this.left : -this.width / 2,
        y = noTransform ? this.top : -this.height / 2;
    ctx.save();
    ctx.fillStyle = "#FF0000";
    ctx.strokeStyle = "#000000";
    ctx.lineWidth = 2;
    ctx.fillRect(x, y, w, h);
    ctx.strokeRect(x, y, w, h);
    ctx.restore();
    this.callSuper('_render',ctx);
  }
});
</code>```

But the result is not what i want.

The result :

I want that :

Thanks in advance.

答:
I found a solution : </p>

```<code>var LabeledBubble = fabric.util.createClass(fabric.IText,{
    type: 'labeledBubble',
    initialize: function(options) {
        options || (options = {});

        this.callSuper('initialize',options);
        this.set('bubbleType',options.bubbleType || 'Rect');
        this.set('backColor',options.backColor || '#FFF');
        this.set('borderColor',options.borderColor || '#000');
        this.set('borderWidth',options.borderWidth || 1);
        this.set('borderDash',options.borderDash || []);
        this.textAlign = "center";
    },
    toObject: function() {
        return fabric.util.object.extend(this.callSuper('toObject'),{
            bubbleType: this.get('bubbleType')
        });
    },
    _initDimensions: function(ctx) {
        if(this.__skipDimension) {
            return;
        }
        if(!ctx) {
            ctx = fabric.util.createCanvasElement().getContext('2d');
            this._setTextStyles(ctx);
        }
        this._textLines = this._splitTextIntoLines();
        this._clearCache();
        this.width = (this._getTextWidth(ctx) || this.cursorWidth || MIN_TEXT_WIDTH) + 5; // here add 5 pix
        this.height = this._getTextHeight(ctx) + 5; // here add 5 pix
    },
    renderCursorOrSelection: function() {
        if(!this.active || !this.isEditing) {
            return;
        }
        var chars = this.text.split(''),
            boundaries,ctx;
        if(this.canvas && this.canvas.contextTop) {
            ctx = this.canvas.contextTop;
            ctx.save();
            ctx.transform.apply(ctx,this.canvas.viewportTransform);
            this.transform(ctx);
            this.transformMatrix && ctx.transform.apply(ctx,this.transformMatrix);
            this._clearTextArea(ctx);
        }
        else {
            ctx = this.ctx;
            ctx.save();
        }
        ctx.translate(0,2); // here add 2 pix for spacing
        if(this.selectionStart === this.selectionEnd) {
            boundaries = this._getCursorBoundaries(chars,'cursor');
            this.renderCursor(boundaries,ctx);
        }
        else {
            boundaries = this._getCursorBoundaries(chars,'selection');
            this.renderSelection(chars,boundaries,ctx);
        }
        ctx.restore();
    },
    _renderText: function(ctx) {
        ctx.save();
        ctx.translate(0,2); // here add 2 pix for spacing
        this._renderTextFill(ctx);
        this._renderTextStroke(ctx);
        ctx.restore();
    },
    _render: function(ctx,noTransform) {
        var w = this.width,
            h = this.height,
            x = noTransform ? this.left : -this.width / 2,
            y = noTransform ? this.top : -this.height / 2;
        ctx.save();
        ctx.fillStyle = this.backColor;
        ctx.strokeStyle = this.borderColor;
        ctx.lineWidth = this.borderWidth;
        switch(this.bubbleType) {
            case "Circle":
                ctx.arc(0,0,bounds.width > bounds.height ? bounds.width * .5 : bounds.height * .5,0,2 * Math.PI);
                break;
            case "DoubleCircle":

                break;
            default:
                ctx.rect(x,y,w,h);
        }
        this._renderFill(ctx);
        this._renderStroke(ctx);
        ctx.restore();
        this.callSuper('_render',ctx);
    }
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've created a class that extend IText and i want to draw a border like selection.

The class code below : (fiddle exemple)

var LabeledBubble = fabric.util.createClass(fabric.IText,{
   type: 'labeledBubble',
   initialize: function(options) {
     options || (options = {});

     this.callSuper('initialize',options);
     this.set('bubbleType',options.bubbleType || 'Rect');
     this.set('backColor',options.backColor || '#FFF');
     this.set('borderColor',options.borderColor || '#000');
     this.set('borderWidth',options.borderWidth || 1);
     this.set('borderDash',options.borderDash || []);
     this.textAlign = "center";
  },
  toObject: function() {
    return fabric.util.object.extend(this.callSuper('toObject'),{
      bubbleType: this.get('bubbleType')
    });
  },
  _render: function(ctx,noTransform) {
    var w = this.width,
        h = this.height,
        x = noTransform ? this.left : -this.width / 2,
        y = noTransform ? this.top : -this.height / 2;
    ctx.save();
    ctx.fillStyle = "#FF0000";
    ctx.strokeStyle = "#000000";
    ctx.lineWidth = 2;
    ctx.fillRect(x, y, w, h);
    ctx.strokeRect(x, y, w, h);
    ctx.restore();
    this.callSuper('_render',ctx);
  }
});

But the result is not what i want.

The result :

I want that :

Thanks in advance.

Body:
I found a solution :

var LabeledBubble = fabric.util.createClass(fabric.IText,{
    type: 'labeledBubble',
    initialize: function(options) {
        options || (options = {});

        this.callSuper('initialize',options);
        this.set('bubbleType',options.bubbleType || 'Rect');
        this.set('backColor',options.backColor || '#FFF');
        this.set('borderColor',options.borderColor || '#000');
        this.set('borderWidth',options.borderWidth || 1);
        this.set('borderDash',options.borderDash || []);
        this.textAlign = "center";
    },
    toObject: function() {
        return fabric.util.object.extend(this.callSuper('toObject'),{
            bubbleType: this.get('bubbleType')
        });
    },
    _initDimensions: function(ctx) {
        if(this.__skipDimension) {
            return;
        }
        if(!ctx) {
            ctx = fabric.util.createCanvasElement().getContext('2d');
            this._setTextStyles(ctx);
        }
        this._textLines = this._splitTextIntoLines();
        this._clearCache();
        this.width = (this._getTextWidth(ctx) || this.cursorWidth || MIN_TEXT_WIDTH) + 5; // here add 5 pix
        this.height = this._getTextHeight(ctx) + 5; // here add 5 pix
    },
    renderCursorOrSelection: function() {
        if(!this.active || !this.isEditing) {
            return;
        }
        var chars = this.text.split(''),
            boundaries,ctx;
        if(this.canvas && this.canvas.contextTop) {
            ctx = this.canvas.contextTop;
            ctx.save();
            ctx.transform.apply(ctx,this.canvas.viewportTransform);
            this.transform(ctx);
            this.transformMatrix && ctx.transform.apply(ctx,this.transformMatrix);
            this._clearTextArea(ctx);
        }
        else {
            ctx = this.ctx;
            ctx.save();
        }
        ctx.translate(0,2); // here add 2 pix for spacing
        if(this.selectionStart === this.selectionEnd) {
            boundaries = this._getCursorBoundaries(chars,'cursor');
            this.renderCursor(boundaries,ctx);
        }
        else {
            boundaries = this._getCursorBoundaries(chars,'selection');
            this.renderSelection(chars,boundaries,ctx);
        }
        ctx.restore();
    },
    _renderText: function(ctx) {
        ctx.save();
        ctx.translate(0,2); // here add 2 pix for spacing
        this._renderTextFill(ctx);
        this._renderTextStroke(ctx);
        ctx.restore();
    },
    _render: function(ctx,noTransform) {
        var w = this.width,
            h = this.height,
            x = noTransform ? this.left : -this.width / 2,
            y = noTransform ? this.top : -this.height / 2;
        ctx.save();
        ctx.fillStyle = this.backColor;
        ctx.strokeStyle = this.borderColor;
        ctx.lineWidth = this.borderWidth;
        switch(this.bubbleType) {
            case "Circle":
                ctx.arc(0,0,bounds.width > bounds.height ? bounds.width * .5 : bounds.height * .5,0,2 * Math.PI);
                break;
            case "DoubleCircle":

                break;
            default:
                ctx.rect(x,y,w,h);
        }
        this._renderFill(ctx);
        this._renderStroke(ctx);
        ctx.restore();
        this.callSuper('_render',ctx);
    }
});


问:
How to add an icon to an iOS static uitableview cell in the storyboard
I've created a UITableView with three static cells. This is serving as a submenu for a "More..." section. I would like to have an icon for each of the three cells but there does not seem to be any way to control the size and position of the label in the content view so as to move it over to the right and thus leave room for the icon on the left. The label does not seem to move nor can it be resized.

Is there any way to do this in the storyboard? If absolutely necessary, I could do this in code, but I'd prefer to just accomplish this in the storyboard if possible.

Here's a screenshot of what I want.

答: Just go to your cell's Attributes inspector, set cell style to Basic. Add your desired image to image section.


问:
How to compose and send an SNMP response in C
There are many demo net-snmp programs which receive SNMP response from agent and parse it. But, I want the opposite functionality, suppose I want to send an SNMP Response PDU using UDP/IP. I already have the values I want to send to the manager (e.g., sysName.0 = "ABCDEFGH").

Can someone point me to some API's which will accomplish this.

答:
The thing you want is calling an SNMP agent.
If we take an SNMP v2c, the SNMP response PDU is nearly same as request's one, but it has other request type field and non-null values for variable binding.
For plain C I don't know an easy way to write simple SNMP agent as standalone program - only make your own parser and serializer and work with network on your own. Using net-snmp you can write agent module or submodule to use with net-snmp daemon (http://www.net-snmp.org/tutorial/tutorial-5/toolkit/). Also could take perl and write custom handler for traps (as trap receiver) and other requests (as agent) as net-snmp has embedded perl interpreter
Or, if you can use c++ you could take agent++ library ( https://agentpp.com/ ) and write standalone SNMP agent program.


问:
Rails, store multiple complicated relations into single hash record
Im studying rails associations.

suppose, i have a table which has massive associations.

```<code>Sample.rb

has_many :sample_assoas
has_many :assoas through: :sample_assoa

has_many :sample_assobs
has_many :assobs through: :sample_assob

has_many :sample_assocs
has_many :assocs through: :sample_assoc

and so on...
</code>```

in this case, i though due to complicated relations, the process will be very slow. (because rails should keep matching relations to get result.)

so i thought, what if i can store all the relational data to single hash to get faster result.

```<code>Samples schema
id :integer
name :string
hash :something...?
</code>```

i found postgresql "hstore" stores data in a hash.

but is it good idea to store this way?

or do you have any suggestions?

thanks

答:
First of all a model can have any number or association. It won't affect processing time. hstore can not replace association, both are intended for different functionality.

Associations are used to simplify query building. Consider:

```<code>class ModelA < ActiveRecord::Base
  has_many :modelbs
end

class ModelB < ActiveRecord::Base
  belongs :modela
end
</code>```

You can find ModelB record associated with ModelA like below:

```<code>@modela = ModelA.find(xxx)
@modelbs = ModelB.where(modela_id: @modela.id)
</code>```

Using association simply write:

```<code>@modela = ModelA.find(xxx)
@modelbs = @modela.modelbs
</code>```

hstore are used to save value in hash format. so they are not intended to use as association. In most cases we don't want to save record in all associated table. So we should add association. If you use hstore in such case most of values will set to nil.

You need to manually iterate hash to get desired result in case of hstore.

Body:
Im studying rails associations.

suppose, i have a table which has massive associations.

Sample.rb

has_many :sample_assoas
has_many :assoas through: :sample_assoa

has_many :sample_assobs
has_many :assobs through: :sample_assob

has_many :sample_assocs
has_many :assocs through: :sample_assoc

and so on...

in this case, i though due to complicated relations, the process will be very slow. (because rails should keep matching relations to get result.)

so i thought, what if i can store all the relational data to single hash to get faster result.

Samples schema
id :integer
name :string
hash :something...?

i found postgresql "hstore" stores data in a hash.

but is it good idea to store this way?

or do you have any suggestions?

thanks

Body:
First of all a model can have any number or association. It won't affect processing time. hstore can not replace association, both are intended for different functionality.

Associations are used to simplify query building. Consider:

class ModelA < ActiveRecord::Base
  has_many :modelbs
end

class ModelB < ActiveRecord::Base
  belongs :modela
end

You can find ModelB record associated with ModelA like below:

@modela = ModelA.find(xxx)
@modelbs = ModelB.where(modela_id: @modela.id)

Using association simply write:

@modela = ModelA.find(xxx)
@modelbs = @modela.modelbs

hstore are used to save value in hash format. so they are not intended to use as association. In most cases we don't want to save record in all associated table. So we should add association. If you use hstore in such case most of values will set to nil.

You need to manually iterate hash to get desired result in case of hstore.


问:
calling main method inside main in java
Can we call main method inside main?

```<code>public static void main(String[] args) {
    main({"a","b","c"});
}
</code>```

Tried to google.Can't find the link.
Sorry if the question is trivial

答:
You can simply pass the argument like main(new String[1]) - this line will call main method of your program. But if you pass "new String[-1]" this will give NegativeArraySizeException. Here I'mm giving an example of Nested Inner Class where I am calling the Main method:

```<code>class Outer
{
    static class NestedInner
    {

        public static void main(String[] args)
        {
            System.out.println("inside main method of Nested class");

        }//inner main
    }//NestedInner
    public static void main(String[] args)
    {

        NestedInner.main(new String[1] );//**calling of Main method**
        System.out.println("Hello World!");
    }//outer main
}//Outer
</code>```

Output:-
inside main method of Nested class

Hello World!

Title: calling main method inside main in java

Body:
Can we call main method inside main?

public static void main(String[] args) {
    main({"a","b","c"});
}

Tried to google.Can't find the link.
Sorry if the question is trivial

Body:
You can simply pass the argument like main(new String[1]) - this line will call main method of your program. But if you pass "new String[-1]" this will give NegativeArraySizeException. Here I'mm giving an example of Nested Inner Class where I am calling the Main method:

class Outer
{
    static class NestedInner
    {

        public static void main(String[] args)
        {
            System.out.println("inside main method of Nested class");

        }//inner main
    }//NestedInner
    public static void main(String[] args)
    {

        NestedInner.main(new String[1] );//**calling of Main method**
        System.out.println("Hello World!");
    }//outer main
}//Outer

Output:-
inside main method of Nested class

Hello World!


问:
How to train HAAR Classifier from 3d model in OpenCV?
I am trying to train a HAAR Cascade for car detection from a Drone.
Because of the viewing angle of the drone, I need to detect the car from many angles, So I need to train the classifier for that.
I have many 3d car models of the cars I want to detect, Can I use them to train the classifier instead of getting images from the internet ?

The car may be not moving, so I can't use motion as a parameter.

答:
there are many questions here.
First, to train for many angles seems to be not really optimal for me, maybe you could check some more simple approaches like in this paper about car detection
https://www.tnt.uni-hannover.de/papers/data/977/scia2013_baumann.pdf

Second, yes, you can train on synthetic data, but there will be no noise as in real life and your classifier could be much less effective finally on real data. But usually to generate synthetic DB is fast, so why not to try.


问:
Naming a FK for a Post Author
I have the following tables

```<code>create table dbo.Users (
  UserId int identity not null,
  Name nvarchar (400) not null
)

create table dbo.Posts (
  PostId int identity not null,
  UserId int not null,
  Title nvarchar (400) not null,
  Content nvarchar (max) not null,
)
</code>```

On table Posts UserId is the author of the post and it is a FK to Users.UserId PK.

In this situations should I name the column UserId which is clear what the relation is or AuthorId describing of it is withing the post?

What is the most common approach for this naming?

答:
I always use the names of the tables in the foreign key name, the foreign key field I usually name the same as in the refering table.

In this example that would be

```<code>create table dbo.Users (
  UserId int identity not null,
  Name nvarchar (400) not null,

  constraint PK_UserId primary key (UserId)
)

create table dbo.Posts (
  PostId int identity not null,
  UserId int not null,
  Title nvarchar (400) not null,
  Content nvarchar (max) not null,

  constraint PK_PostId primary key (PostId),
  constraint FK_Posts_Users foreign key (UserId) references Users (UserId)
)
</code>```

Title: Naming a FK for a Post Author

Body:
I have the following tables

create table dbo.Users (
  UserId int identity not null,
  Name nvarchar (400) not null
)

create table dbo.Posts (
  PostId int identity not null,
  UserId int not null,
  Title nvarchar (400) not null,
  Content nvarchar (max) not null,
)

On table Posts UserId is the author of the post and it is a FK to Users.UserId PK.

In this situations should I name the column UserId which is clear what the relation is or AuthorId describing of it is withing the post?

What is the most common approach for this naming?

Body:
I always use the names of the tables in the foreign key name, the foreign key field I usually name the same as in the refering table.

In this example that would be

create table dbo.Users (
  UserId int identity not null,
  Name nvarchar (400) not null,

  constraint PK_UserId primary key (UserId)
)

create table dbo.Posts (
  PostId int identity not null,
  UserId int not null,
  Title nvarchar (400) not null,
  Content nvarchar (max) not null,

  constraint PK_PostId primary key (PostId),
  constraint FK_Posts_Users foreign key (UserId) references Users (UserId)
)


问:
Full Calendar Width
I am currently using the Calendar on a wordpess website with restricted width on the page due to widgets restricting width on the right hand side.

This is causing the events to be squashed up in the week view, can I :

Disable the Sunday day so that the other 6 days are wider

Can I make each day wider and use a scroll bar along the bottom for the week view ?

Are these two options possible ? If so how can I achieve this

答:
Disabling Sunday is probably possible, although I haven't done it before and I can bet you it's going to require extensive php coding to achieve.

The easiest, to my mind, would be to play around with the CSS of the calendar widget. Here's my suggestions:

You could make each day (which'll be
an
 tag) wider;

Give that widget a set width /
height; and lastly

Set the parent (either the tag, or
the containing tag) CSS to
overflow: scroll.

It won't be pretty (unless you use Javascript/jQuery), but it'll work...

Hope it helps...

ContentLicense: CC BY-SA 2.5

Title: Full Calendar Width

Body:
Disabling Sunday is probably possible, although I haven't done it before and I can bet you it's going to require extensive php coding to achieve.

The easiest, to my mind, would be to play around with the CSS of the calendar widget. Here's my suggestions:

You could make each day (which'll be
an <li> tag) wider;

Give that widget a set width /
height; and lastly

Set the parent (either the tag, or
the containing tag) CSS to
overflow: scroll.

It won't be pretty (unless you use Javascript/jQuery), but it'll work...

Hope it helps...


问:
Why it's asked to move mouse over blank area while generating key in putty gen?
Recently I installed putty gen for my windows, and while generating a key, something like this appeared:

Asking me to move the mouse over the blank area.

I know it may sound trivial, but I was curious to know what actually happens behind the scenes?

Thanks in advance.

答:
To generate an encryption key, you need random data.

You have to get the random data from somewhere, and if you generate it with a computer algorithm that doesn't take external input it will be more predictable.

Windows takes user input as random data to compensate.


问:
Shiny selectizeInput: on click remove the initial selected value
i would like to remove the initial value (selected=) from selectizeInput when the user click on the widget.

Here is a sample code:

```<code>library(shiny)
library(dplyr)

ui= fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectizeInput(inputId= "cyl", label= "cyl",
                     choices= NULL,
                     selected= sort(unique(mtcars$cyl))[1],
                     multiple=T)
    ),
    mainPanel(
      tableOutput("tab")
    )
  )
)

server= function(input, output,session) {

  updateSelectizeInput(session = session,inputId ="cyl",choices=sort(unique(mtcars$cyl)),selected=sort(unique(mtcars$cyl))[1], server = TRUE)

  df_filtered= reactive({
    mtcars %>%
    {if (is.null(input$cyl)) . else filter(., cyl %in% input$cyl)}
  })
  output$tab= renderTable(df_filtered())
}

shinyApp(ui, server)
</code>```

Just a bit of explanation on base of sample code:

The initial selected value in selectizeInput "cyl" is 4. When the user press on this widget, i would like that the value 4 is removed and the selected option is cleared. Any ideas?

*I have used the function updateSelectizeInput in server because in my shiny app choice selection is very big leading to too long loading time

答:
You can use shinyjs::onclick to call updateSelectizeInput when the user clicks on the selectize field, eg:

```<code>library(shiny)
library(dplyr)
library(shinyjs)

ui= fluidPage(
  useShinyjs(),
  sidebarLayout(
    sidebarPanel(
      selectizeInput(inputId= "cyl", label= "cyl",
                     choices= NULL,
                     selected= sort(unique(mtcars$cyl))[1],
                     multiple=T)
    ),
    mainPanel(
      tableOutput("tab")
    )
  )
)

server= function(input, output,session) {

  updateSelectizeInput(session = session,inputId ="cyl",choices=sort(unique(mtcars$cyl)),selected=sort(unique(mtcars$cyl))[1], server = TRUE)

  df_filtered= reactive({
    mtcars %>%
    {if (is.null(input$cyl)) . else filter(., cyl %in% input$cyl)}
  })
  output$tab= renderTable(df_filtered())

  onclick("cyl", {
    updateSelectizeInput(session, "cyl", selected = "")
  })
}

shinyApp(ui, server)
</code>```

Body:
i would like to remove the initial value (selected=) from selectizeInput when the user click on the widget.

Here is a sample code:

library(shiny)
library(dplyr)

ui= fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectizeInput(inputId= "cyl", label= "cyl",
                     choices= NULL,
                     selected= sort(unique(mtcars$cyl))[1],
                     multiple=T)
    ),
    mainPanel(
      tableOutput("tab")
    )
  )
)

server= function(input, output,session) {

  updateSelectizeInput(session = session,inputId ="cyl",choices=sort(unique(mtcars$cyl)),selected=sort(unique(mtcars$cyl))[1], server = TRUE)

  df_filtered= reactive({
    mtcars %>%
    {if (is.null(input$cyl)) . else filter(., cyl %in% input$cyl)}
  })
  output$tab= renderTable(df_filtered())
}

shinyApp(ui, server)

Just a bit of explanation on base of sample code:

The initial selected value in selectizeInput "cyl" is 4. When the user press on this widget, i would like that the value 4 is removed and the selected option is cleared. Any ideas?

*I have used the function updateSelectizeInput in server because in my shiny app choice selection is very big leading to too long loading time

Body:
You can use shinyjs::onclick to call updateSelectizeInput when the user clicks on the selectize field, eg:

library(shiny)
library(dplyr)
library(shinyjs)

ui= fluidPage(
  useShinyjs(),
  sidebarLayout(
    sidebarPanel(
      selectizeInput(inputId= "cyl", label= "cyl",
                     choices= NULL,
                     selected= sort(unique(mtcars$cyl))[1],
                     multiple=T)
    ),
    mainPanel(
      tableOutput("tab")
    )
  )
)

server= function(input, output,session) {

  updateSelectizeInput(session = session,inputId ="cyl",choices=sort(unique(mtcars$cyl)),selected=sort(unique(mtcars$cyl))[1], server = TRUE)

  df_filtered= reactive({
    mtcars %>%
    {if (is.null(input$cyl)) . else filter(., cyl %in% input$cyl)}
  })
  output$tab= renderTable(df_filtered())

  onclick("cyl", {
    updateSelectizeInput(session, "cyl", selected = "")
  })
}

shinyApp(ui, server)


问:
Teamcity build chain templating
We have set of different web application projects, which is delivered by Teamcity to different environments. At this moment, we are doing all-in-one builds: compile, package and deploy at once; all based on a templates.

Now I am investigating a way to separate concenrs: one build tests and produces package, another - delivers. Naturally, both builds are having own templates. Is there a way to template this build chain - so, when I choose some meta-template - both builds will be created with present Artifact dependencies?

答:
Sadly not. What we've had to do is clone the build chains. We've put in place a mechanism which makes sure the set-ups of the different chains do not diverge.

Another option, admittedly ugly, is to set up a single build chain and let each of your projects pretend that it's a separate VCS branch. In this case there's a single set-up (for the single build chain) and to view the history of a given project you filter by that project "branch". Needless to say, that's not how branches should be used and you may run into some issue down the line.

Title: Teamcity build chain templating


问:
How to create a free standing patch without source control?
I need to patch libidn2 on Solaris. libidn2 was fetched from GNU's website with wget. Its not provided by Sun and its not in source control.

The library does not use glibc, and it does not have the function error (int status, int errnum, const char *format, ...). I made a copy of the original source file and I have a diff with a similar function:

```<code>solaris:libidn2-0.16$ diff -u src/idn2.c.bu src/idn2.c
--- src/idn2.c.bu       2017-03-29 00:20:08.621934160 -0400
+++ src/idn2.c  2017-03-29 01:25:12.488402745 -0400
@@ -31,7 +31,9 @@
 #include <unistr.h>

 /* Gnulib headers. */
+#ifndef __sun__
 #include "error.h"
+#endif
 #include "gettext.h"
 #define _(String) dgettext (PACKAGE, String)
 #include "progname.h"
@@ -48,6 +50,18 @@
      year.  */
   "Copyright %s %d Simon Josefsson.";

+#if defined(__sun__)
+static void
+error (int status, int errnum, const char *format, ...)
+{
+    va_list args;
+    va_start(args, format);
+    vfprintf(stderr, format, args);
+    va_end(args);
+    exit(status);
+}
+#endif
+
 static void
 usage (int status)
 {
</code>```

I've been reading through the diff(1) and patch(1) man pages, but I'm not quite getting what needs to be done. I don't believe I've found a discussion of the task (maybe I am not seeing the forest through the trees).

My question is, how can I turn this into a free standing patch? That is, how can I turn it into something to apply after a fresh download and unpack of libidn2?

答:
This might not be the correct answer, but the quote won't fit into a comment, and my experience with patch is that the output from diff is the "freestanding patch".

You can run patch --dry-run  < your.diff.output from most likely the base directory of the expanded libidn2 source tarball to see what would happen if you apply your diff output with patch.

In my installed copy of Solaris 11, patch appears to be GNU patch as it has the --dry-run option.  The Solaris 11.2 patch man page has this excerpt for creating patches:

NOTES FOR PATCH SENDERS

There are several things you should bear in mind if you  are
       going to be sending out patches.

Create your patch systematically.  A good method is the command  diff -Naur old new  where old and new identify the old
       and new directories.  The names old and new should not  contain  any  slashes.   The diff command's headers should have
       dates and times in Universal  Time  using  traditional  Unix
       format, so that patch recipients can use the -Z or --set-utc
       option.  Here is an example command, using Bourne shell syn-
       tax:

```<code>                LC_ALL=C TZ=UTC0 diff -Naur gcc-2.7 gcc-2.8
</code>```

Tell your recipients how to apply the patch by telling  them
       which  directory  to  cd to, and which patch options to use.
       The option string -Np1 is recommended.  Test your  procedure
       by pretending to be a recipient and applying your patch to a
       copy of the original files.

...

Body:
I need to patch libidn2 on Solaris. libidn2 was fetched from GNU's website with wget. Its not provided by Sun and its not in source control.

The library does not use glibc, and it does not have the function error (int status, int errnum, const char *format, ...). I made a copy of the original source file and I have a diff with a similar function:

solaris:libidn2-0.16$ diff -u src/idn2.c.bu src/idn2.c
--- src/idn2.c.bu       2017-03-29 00:20:08.621934160 -0400
+++ src/idn2.c  2017-03-29 01:25:12.488402745 -0400
@@ -31,7 +31,9 @@
 #include <unistr.h>

 /* Gnulib headers. */
+#ifndef __sun__
 #include "error.h"
+#endif
 #include "gettext.h"
 #define _(String) dgettext (PACKAGE, String)
 #include "progname.h"
@@ -48,6 +50,18 @@
      year.  */
   "Copyright %s %d Simon Josefsson.";

+#if defined(__sun__)
+static void
+error (int status, int errnum, const char *format, ...)
+{
+    va_list args;
+    va_start(args, format);
+    vfprintf(stderr, format, args);
+    va_end(args);
+    exit(status);
+}
+#endif
+
 static void
 usage (int status)
 {

I've been reading through the diff(1) and patch(1) man pages, but I'm not quite getting what needs to be done. I don't believe I've found a discussion of the task (maybe I am not seeing the forest through the trees).

My question is, how can I turn this into a free standing patch? That is, how can I turn it into something to apply after a fresh download and unpack of libidn2?

Body:
This might not be the correct answer, but the quote won't fit into a comment, and my experience with patch is that the output from diff is the "freestanding patch".

You can run patch --dry-run  < your.diff.output from most likely the base directory of the expanded libidn2 source tarball to see what would happen if you apply your diff output with patch.

In my installed copy of Solaris 11, patch appears to be GNU patch as it has the --dry-run option.  The Solaris 11.2 patch man page has this excerpt for creating patches:

NOTES FOR PATCH SENDERS

There are several things you should bear in mind if you  are
       going to be sending out patches.

Create your patch systematically.  A good method is the command  diff -Naur old new  where old and new identify the old
       and new directories.  The names old and new should not  contain  any  slashes.   The diff command's headers should have
       dates and times in Universal  Time  using  traditional  Unix
       format, so that patch recipients can use the -Z or --set-utc
       option.  Here is an example command, using Bourne shell syn-
       tax:

                LC_ALL=C TZ=UTC0 diff -Naur gcc-2.7 gcc-2.8

Tell your recipients how to apply the patch by telling  them
       which  directory  to  cd to, and which patch options to use.
       The option string -Np1 is recommended.  Test your  procedure
       by pretending to be a recipient and applying your patch to a
       copy of the original files.

...


问:
HTML picture in div won't fill out body completely
I want to use a picture (jpg) as a background for my page.

This is how I tried to tackle the problem :
Create the body, inside the body put a div with the id backgroundWallpaper.
Inside the div i put the image.
The problem is though that it's completely filled out to the site (horizontal) and also to the top but at the bottom there is a small gap between the picture and the browser. I changed the body background to crimson red to demonstrate you the gap. I use the latest version of safari as my browser. This is my code :
index.html

```<code><!DOCTYPE html>
 <html>
  <head>
   <meta charset="utf-8">
   <title>name</title>
   <linkrel="stylesheet"
   href"http://meyerweb.com/eric/tools/css/reset/reset.css">
   <link rel="stylesheet" href="main.css">
  </head>
  <body>
   <div id="backgroundWallpaper">
    <img src=".../img/1.jpg" alt="image could not be loaded">
   </div>
  </body>
 </html>
</code>```

This is my css file

```<code>body {
 background: crimson;
 margin: 0;
 padding: 0;
}

#backgroundWallpaper img {
 max-width: 100%;
}
</code>```

答:
Use below code for image to make image block element, image is a default  inline element and its has some attribute. That why you get extra space.

```<code>#backgroundWallpaper img{
  display:block
}
</code>```

I hope it will helps you.

Body:
I want to use a picture (jpg) as a background for my page.

This is how I tried to tackle the problem :
Create the body, inside the body put a div with the id backgroundWallpaper.
Inside the div i put the image.
The problem is though that it's completely filled out to the site (horizontal) and also to the top but at the bottom there is a small gap between the picture and the browser. I changed the body background to crimson red to demonstrate you the gap. I use the latest version of safari as my browser. This is my code :
index.html

<!DOCTYPE html>

   <meta charset="utf-8">
   <title>name</title>
   <linkrel="stylesheet"
   href"http://meyerweb.com/eric/tools/css/reset/reset.css">
   <link rel="stylesheet" href="main.css">

This is my css file

body {
 background: crimson;
 margin: 0;
 padding: 0;
}

#backgroundWallpaper img {
 max-width: 100%;
}

Body:
Use below code for image to make image block element, image is a default  inline element and its has some attribute. That why you get extra space.

#backgroundWallpaper img{
  display:block
}

I hope it will helps you.


问:
Why does my oracle date field does not fall within the queried range?
I have this sql query :

```<code>select email_id, to_char(last_update_date, 'YYYY-MM-DD hh:mi:ss')
from profile_table
where last_update_date < sysdate and
      last_update_date > sysdate -1;
</code>```

Which returns result

```<code>                EMAIL_ID   TO_CHAR(last_update_date, 'YYYY-MM-DD hh:mi:ss')
------------------------   ------------------------------------------------
       email_007@abc.com                                2017-03-28 12:00:04
       nachppx@gmail.com                                2017-03-28 03:45:26
       QM_SFGD@yahoo.com                                2017-03-29 08:24:12
j.w.booth@rocketmail.com                                2017-03-29 11:16:00
</code>```

However, I am pretty sure that that query is missing record that should be within that 'where' range, because when I issue this :

```<code>select email_id, to_char(last_update_date, 'YYYY-MM-DD hh:mi:ss')
from profile_table
where email_id = 'kgunash@gmail.com'
</code>```

it returns

```<code>                EMAIL_ID   TO_CHAR(last_update_date, 'YYYY-MM-DD hh:mi:ss')
------------------------   ------------------------------------------------
       kgunash@gmail.com                                2017-03-29 05:53:33
</code>```

My sysdate during execution is as below :

```<code>select to_char(sysdate,'YYYY-MM-DD hh:mm:ss'), to_char(sysdate-1,'YYYY-MM-DD hh:mm:ss')
from dual
</code>```

```<code>TO_CHAR(SYSDATE,'YYYY-MM-DD HH:MI:SS')   TO_CHAR(SYSDATE-1,'YYYY-MM-DD HH:MI:SS')
-------------------------------------   ---------------------------------------
                  2017-03-29 11:12:19                       2017-03-28 11:12:19
</code>```

Obviously 2017-03-29 05:53:33 should fall between 2017-03-29 11:12:19 and 2017-03-28 11:12:19. Anyone got any idea what's going on?

答:
Your output uses 12 hour clock without AM/PM modifier. If the missing record is stamped 2017-03-29 05:53:33 PM is in PM then it would be later than 2017-03-29 11:12:19 AM and so correctly excluded from your result set.

Easiest way to check would be to use HH24 format mask when displaying the dates.

Body:
I have this sql query :

select email_id, to_char(last_update_date, 'YYYY-MM-DD hh:mi:ss')
from profile_table
where last_update_date < sysdate and
      last_update_date > sysdate -1;

Which returns result

                EMAIL_ID   TO_CHAR(last_update_date, 'YYYY-MM-DD hh:mi:ss')
------------------------   ------------------------------------------------
       email_007@abc.com                                2017-03-28 12:00:04
       nachppx@gmail.com                                2017-03-28 03:45:26
       QM_SFGD@yahoo.com                                2017-03-29 08:24:12
j.w.booth@rocketmail.com                                2017-03-29 11:16:00

However, I am pretty sure that that query is missing record that should be within that 'where' range, because when I issue this :

select email_id, to_char(last_update_date, 'YYYY-MM-DD hh:mi:ss')
from profile_table
where email_id = 'kgunash@gmail.com'

it returns

                EMAIL_ID   TO_CHAR(last_update_date, 'YYYY-MM-DD hh:mi:ss')
------------------------   ------------------------------------------------
       kgunash@gmail.com                                2017-03-29 05:53:33

My sysdate during execution is as below :

select to_char(sysdate,'YYYY-MM-DD hh:mm:ss'), to_char(sysdate-1,'YYYY-MM-DD hh:mm:ss')
from dual

TO_CHAR(SYSDATE,'YYYY-MM-DD HH:MI:SS')   TO_CHAR(SYSDATE-1,'YYYY-MM-DD HH:MI:SS')
-------------------------------------   ---------------------------------------
                  2017-03-29 11:12:19                       2017-03-28 11:12:19

Obviously 2017-03-29 05:53:33 should fall between 2017-03-29 11:12:19 and 2017-03-28 11:12:19. Anyone got any idea what's going on?


问:
How to get the rows of a dataframe together (selcted row bottom up)
I explain my question with an example. For example, if I am in the row number 5 (following table), how can I get the rows before 5 that have the same P_P value. The point is the row index of the selected rows should be sequential.
For example in the case of following table, I need to get only rows 3 and 4 (since between the row 1 and the rest of the rows there is row number 2 with different P_P.)
FYI, I could use for loop to do it but I want to avoid it.

Thanks

```<code>ID   Contest   P_P   Time
1      UMA      A    2015
2      DOIS     B    2016
3      DOIS     A    2016
4      UMA      A    2017
5      DOIS     A    2017
</code>```

答:
```<code>row <- 5

## get the subset with P_P = p-p of row
subset <- subset(df[(row-1):1,], P_P == df[row,]$P_P)

## check the difference
a <- which(abs(diff(subset$ID)) != 1)

subset[1:a[1],]

# ID Contest P_P Time
# 4  4     UMA   A 2017
# 3  3    DOIS   A 2016
</code>```

Body:
I explain my question with an example. For example, if I am in the row number 5 (following table), how can I get the rows before 5 that have the same P_P value. The point is the row index of the selected rows should be sequential.
For example in the case of following table, I need to get only rows 3 and 4 (since between the row 1 and the rest of the rows there is row number 2 with different P_P.)
FYI, I could use for loop to do it but I want to avoid it.

Thanks

ID   Contest   P_P   Time
1      UMA      A    2015
2      DOIS     B    2016
3      DOIS     A    2016
4      UMA      A    2017
5      DOIS     A    2017


问:
How to put data points at center with matplotlib?
I'm plotting subplots using pyplot and I want the same scale on the y axis for all subplots. I can do that tinkering with ax.get_ylim and ax.set_ylim:

```<code>if ax3.get_ylim()[1]-ax3.get_ylim()[0] < ax1.get_ylim()[1]-ax1.get_ylim()[0]:
    ax3.set_ylim(ax1.get_ylim())
else:
    ax1.set_ylim(ax3.get_ylim())
</code>```

The problem is I end up with plots where the data points are not centered. I can't upload an image to show what I mean, but when I apply set_ylim to one of the subplots the points end up very close to the bottom or to the top of the plot, which is inconvenient.
How to center my data without changing the scale (i.e. without changing ymax-ymin)?

A subsidiary question: I find that the default y-limits are sometimes too tight, is there an option to automatically increase the padding between the axis limits and the data limits?

I can't seem to find a simple answer to these questions in the documentation. Any help would be appreciated.

答:
You are looking for a way to share the axes. See, e.g. the shared_axis_demo.

In order to apply the margins to all plots in the script, you may use rcParams.

Here is an example:

```<code>import matplotlib.pyplot as plt
import numpy as np
#set margins for all plots in this script.
plt.rcParams["axes.xmargin"] = 0.1
plt.rcParams["axes.ymargin"] = 0.1

#produce subplots with shared axes
fig, axes = plt.subplots(2,2, sharex=True, sharey=True)

for i, ax in enumerate(axes.flatten()):
    x = np.random.normal(i, size=10)
    y = np.random.normal(4-i, size=10)
    ax.scatter(x,y)

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

Body:
I'm plotting subplots using pyplot and I want the same scale on the y axis for all subplots. I can do that tinkering with ax.get_ylim and ax.set_ylim:

if ax3.get_ylim()[1]-ax3.get_ylim()[0] < ax1.get_ylim()[1]-ax1.get_ylim()[0]:
    ax3.set_ylim(ax1.get_ylim())
else:
    ax1.set_ylim(ax3.get_ylim())

The problem is I end up with plots where the data points are not centered. I can't upload an image to show what I mean, but when I apply set_ylim to one of the subplots the points end up very close to the bottom or to the top of the plot, which is inconvenient.
How to center my data without changing the scale (i.e. without changing ymax-ymin)?

A subsidiary question: I find that the default y-limits are sometimes too tight, is there an option to automatically increase the padding between the axis limits and the data limits?

I can't seem to find a simple answer to these questions in the documentation. Any help would be appreciated.

Body:
You are looking for a way to share the axes. See, e.g. the shared_axis_demo.

In order to apply the margins to all plots in the script, you may use rcParams.

Here is an example:

import matplotlib.pyplot as plt
import numpy as np
#set margins for all plots in this script.
plt.rcParams["axes.xmargin"] = 0.1
plt.rcParams["axes.ymargin"] = 0.1

#produce subplots with shared axes
fig, axes = plt.subplots(2,2, sharex=True, sharey=True)

for i, ax in enumerate(axes.flatten()):
    x = np.random.normal(i, size=10)
    y = np.random.normal(4-i, size=10)
    ax.scatter(x,y)

plt.show()


问:
Haskell, List as input for a function, How?
I've been given the following question in my coursework;

Define a function

```<code>flatten :: [(Char,Int)] -> String
</code>```

that flattens a list of pairs of characters and digits to a string. For example:

```<code>flatten [('a',5),('b',4),('c',2)]
"a5b4c2"
flatten [('d',9),('d',3)]
"d9d3"
</code>```

My problem is that whenever I attempt to define this function i get a type error relating the the [(Char, Int)] input. For example;

```<code>Couldn't match type '(Char, Int)' with '[Char]'
Expected type: [[Char]]
Actual type: [(Char, Int)]
</code>```

I've tried more ways of writing this definition in more ways than I can count, so I don't have any particular code to show, or any particular error ( I kept getting different ones...so many). All i have so far is;

```<code>flatten :: [(Char, Int)] -> String
flatten [] = []
</code>```

i figure my next line should go something like;

```<code>flatten ???? = concat (????)
</code>```

but I have no idea what to put in place of these question marks and Google search/class notes give no examples to follow.
any ideas?

答:
You might also use foldl to make your intention very clear:

```<code>a=[('a',5),('b',4),('c',2)]
f b (x,y)=b++[x]++(show y)
result=foldl f "" a
</code>```

Or you can make it a one-liner:

Solution 1:

```<code>foldl (\b (x,y)->b++[x]++(show y)) "" a
</code>```

Solution 2:

```<code>concat $ map (\(x,y)->[x]++show y) a
</code>```

Solution 3: (Being more efficient compared to solution 1)

```<code>foldr (\(x,y) b->b++[x]++(show y)) "" a
</code>```

Body:
I've been given the following question in my coursework;

Define a function

flatten :: [(Char,Int)] -> String

that flattens a list of pairs of characters and digits to a string. For example:

flatten [('a',5),('b',4),('c',2)]
"a5b4c2"
flatten [('d',9),('d',3)]
"d9d3"

My problem is that whenever I attempt to define this function i get a type error relating the the [(Char, Int)] input. For example;

Couldn't match type '(Char, Int)' with '[Char]'
Expected type: [[Char]]
Actual type: [(Char, Int)]

I've tried more ways of writing this definition in more ways than I can count, so I don't have any particular code to show, or any particular error ( I kept getting different ones...so many). All i have so far is;

flatten :: [(Char, Int)] -> String
flatten [] = []

i figure my next line should go something like;

flatten ???? = concat (????)

but I have no idea what to put in place of these question marks and Google search/class notes give no examples to follow.
any ideas?

Body:
You might also use foldl to make your intention very clear:

a=[('a',5),('b',4),('c',2)]
f b (x,y)=b++[x]++(show y)
result=foldl f "" a

Or you can make it a one-liner:

Solution 1:

foldl (\b (x,y)->b++[x]++(show y)) "" a

Solution 2:

concat $ map (\(x,y)->[x]++show y) a

Solution 3: (Being more efficient compared to solution 1)

foldr (\(x,y) b->b++[x]++(show y)) "" a


问:
How to LEFT JOIN the wp_terms, wp_term_relationships, wp_term_taxonomy and wp_termmeta tables in WordPress?
For reporting purposes and to flatten the data I want to join all the WordPress tables that contain information related to terms.

I really don't use join statements very much so I don't know how to do it. I'm guessing that it would look something like this:

```<code>SELECT wp_terms.term_id, wp_terms.name, wp_term.slug, wp_term_relationships.object_id, wp_term_relationships.term_taxonomy_id, wp_term_taxonomy.term_id, wp_term_taxonomy.taxonomy, wp_term_taxonomy.description, wp_term_taxonomy.parent.parent, wp_termmeta.term_id, wp_termmeta.meta_key, wp_termmeta.meta_value.
FROM wp_terms, wp_term_relationships, wp_term_taxonomy, wp_termmeta
LEFT JOIN wp_term_relationships ON wp_terms.term_id = wp_term_relationships.term_taxonomy_id
LEFT JOIN wp_term_taxonomy ON term_taxonomy_id
LEFT JOIN wp_termmeta on term_id;
</code>```

Any help is appreciated.

答:
What I did was just fix your query. Check if this is what you need.</p>

```<code>SELECT wp_terms.term_id, wp_terms.name, wp_term_relationships.object_id, wp_term_relationships.term_taxonomy_id, wp_term_taxonomy.term_id, wp_term_taxonomy.taxonomy, wp_term_taxonomy.description, wp_term_taxonomy.parent, wp_termmeta.term_id, wp_termmeta.meta_key, wp_termmeta.meta_value
FROM wp_terms
LEFT JOIN wp_term_relationships ON wp_terms.term_id = wp_term_relationships.term_taxonomy_id
LEFT JOIN wp_term_taxonomy ON wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id
LEFT JOIN wp_termmeta on wp_termmeta.term_id = wp_terms.term_id
</code>```

Body:
For reporting purposes and to flatten the data I want to join all the WordPress tables that contain information related to terms.

I really don't use join statements very much so I don't know how to do it. I'm guessing that it would look something like this:

SELECT wp_terms.term_id, wp_terms.name, wp_term.slug, wp_term_relationships.object_id, wp_term_relationships.term_taxonomy_id, wp_term_taxonomy.term_id, wp_term_taxonomy.taxonomy, wp_term_taxonomy.description, wp_term_taxonomy.parent.parent, wp_termmeta.term_id, wp_termmeta.meta_key, wp_termmeta.meta_value.
FROM wp_terms, wp_term_relationships, wp_term_taxonomy, wp_termmeta
LEFT JOIN wp_term_relationships ON wp_terms.term_id = wp_term_relationships.term_taxonomy_id
LEFT JOIN wp_term_taxonomy ON term_taxonomy_id
LEFT JOIN wp_termmeta on term_id;

Any help is appreciated.

Body:
What I did was just fix your query. Check if this is what you need.

SELECT wp_terms.term_id, wp_terms.name, wp_term_relationships.object_id, wp_term_relationships.term_taxonomy_id, wp_term_taxonomy.term_id, wp_term_taxonomy.taxonomy, wp_term_taxonomy.description, wp_term_taxonomy.parent, wp_termmeta.term_id, wp_termmeta.meta_key, wp_termmeta.meta_value
FROM wp_terms
LEFT JOIN wp_term_relationships ON wp_terms.term_id = wp_term_relationships.term_taxonomy_id
LEFT JOIN wp_term_taxonomy ON wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id
LEFT JOIN wp_termmeta on wp_termmeta.term_id = wp_terms.term_id


问:
Pojo values are not being retrieved correctly
I have a ArrayList of POJOs that I populate from a result set retrieved from JDBC, when in the first System.out.print statement in the while loop, the data is retrieved perfectly using the getStatus method, however, when checking in the loop right after that one, the return value of getStatus is null.

P.S. status field is a String object with plain old getters and setters, nothing fancy.

```<code>while (result.next()) {
    POJO recordPojo = new POJO();
    recordPojo.setRefNo(result.getString(3));
    recordPojo.setSubmittedBy(result.getString(1));
    recordPojo.setCreatedDate(result.getDate(2).toString());
    recordPojo.setGuid(result.getString(4));
    recordPojo.setStatus(result.getString(5));
    System.out.println(" DBOPERATIONS  RESULT Ref No ----" + result.getString(3) + "      ===== " + result.getString(5) + " ====== " + recordPojo.getStatus());
    arryObj.add(recordPojo);
}
POJO x;
for (int k = 0; k < arryObj.size(); k++) {
    x = (POJO) arryObj.get(k);
    System.out.println(" DBOPERATIONS Ref No ----" + x.getRefNo() + "      ===== " + x.getSubject());
}
</code>```

答:
I consider this like a typo (Subject is not Status), but I will give you a short explication: I think you are wrong in your Second System.out.println() of your loop x.getSubject(), you don't ever fill this field before with your result, so it's clear it is null.

So you have two options:

fill this field when you loop your result

Or print the correct field instead of x.getSubject(), you should to print the x.getStatus() (they are not the same)

Body:
I have a ArrayList of POJOs that I populate from a result set retrieved from JDBC, when in the first System.out.print statement in the while loop, the data is retrieved perfectly using the getStatus method, however, when checking in the loop right after that one, the return value of getStatus is null.

P.S. status field is a String object with plain old getters and setters, nothing fancy.

while (result.next()) {
    POJO recordPojo = new POJO();
    recordPojo.setRefNo(result.getString(3));
    recordPojo.setSubmittedBy(result.getString(1));
    recordPojo.setCreatedDate(result.getDate(2).toString());
    recordPojo.setGuid(result.getString(4));
    recordPojo.setStatus(result.getString(5));
    System.out.println(" DBOPERATIONS  RESULT Ref No ----" + result.getString(3) + "      ===== " + result.getString(5) + " ====== " + recordPojo.getStatus());
    arryObj.add(recordPojo);
}
POJO x;
for (int k = 0; k < arryObj.size(); k++) {
    x = (POJO) arryObj.get(k);
    System.out.println(" DBOPERATIONS Ref No ----" + x.getRefNo() + "      ===== " + x.getSubject());
}


问:
passing variable from $(document).ready(function(){} to $(window).load(function() {}
Just imagine if I managed to create percent_pass at document.ready, how can I pass that var to window.load?

$(document).ready(function() {
  jQuery(function() {
    var question_count = $('.question-body').length;
    var question_percent = (1 / question_count) * 100;
    var color_percent = (300 / question_count);
    var percent_pass = 0;

    $('.answers input').click(function() {
      if ($(this).data('clicked') == false) {
        $(this).data('clicked', true);

        var old_height = $('.percent-solve').css('height');
        var new_height = parseInt(old_height) + color_percent;
        percent_pass += question_percent;

        if (percent_pass > 100) {
          percent_pass = 100;
        }
        $(".percentshow").html("%" + percent_pass);
        $('.count').text(percent_pass);
        $('.percent-solve').css('height', new_height + 'px');
        $('.count').each(function() {
          $(this).prop('Counter', percent_pass - question_percent).animate({
            Counter: $(this).text()
          }, {
            duration: 500,
            easing: 'swing',
            step: function(now) {
              $(this).text(Math.ceil(now));
            }
          });
        });
        if (Math.ceil(percent_pass) == 100) {
          $('.end-test').css('color', '#ff9803');
        }
      }

      var q_count = $(this).parents('.question-body').attr("id");
      q_count = parseInt(q_count) + 1;
      $('.question-body').removeClass('open-question');
      $.scrollTo($('#' + q_count), 500, {
        onAfter: function() {
          $('#' + q_count).addClass('open-question');
        }
      });
    });
  });
});

$(window).load(function() {
  doughnutWidget.options = {
    container: $('#container'),
    width: 100,
    height: 100,
    class: 'myClass',
    cutout: 50
  };

  doughnutWidget.render(data());

  setInterval(init, 2000);
});

function init() {
  doughnutWidget.render(data());
}

function data() {
  var data = {
    pending: {
      val: Math.round(percent_pass),
      color: '#57B4F2',
    },
    delivered: {
      val: Math.round(percent_pass),
      color: '#6DED5C'
    },
    delayed: {
      val: Math.round(percent_pass),
      color: '#E63329',
    }
  };

  return data;
}```

答:
Try to place var percent_pass = 0; outside of your $(document).ready() function.
Your issue is with the scope of your variable.
Since it is defined in the callback function of ready() it is only available in its corresponding scope.

By placing var percent_pass = 0; outside of the callback function you change its scope to global. Try the following snippet

var percent_pass; // declaration of the variable placed outside of any function => global variable

$(document).ready(function(){

    jQuery(function(){

        percent_pass = 0; // just assign a value.

        });
   });

$(window).load(function() {
  doughnutWidget.options = {
    container: $('#container'),
    width: 100,
    height: 100,
    class: 'myClass',
    cutout: 50
  };

  doughnutWidget.render(data());

  setInterval(init, 2000);
});

function init() {
  doughnutWidget.render(data());
}

function data() {

 var data = {
    pending: {
      val: Math.round(percent_pass),
      color: '#57B4F2',

    },
    delivered: {
      val: Math.round(percent_pass),
      color: '#6DED5C'
    },
    delayed: {
      val: Math.round(percent_pass),
      color: '#E63329',
    }
  };

  return data;
}```


问:
Wildcard subdomains htaccess rule?
I already setup the dns zone to point *.user.domain.com, It works fine but i get the known default cpanel page.

I believe that i have to put something in the htaccess to forward the subdomains requests to a php page.

Example

```<code>simon.user.domain.com -> hello.php?user=simon
</code>```

I've tried the following rules but they don't work:

```<code>RewriteCond %{HTTP_HOST} ^(^.*)\.user.domain.com
RewriteRule (.*)  hello.php?user=%1
</code>```

I've put it in the domain.com public html but as i said it's not working.

Any Ideas?

Thank you

答:
Rewrite cond is Perl compatiable regular expression, so no ^ in  parentheses!

```<code>RewriteCond %{HTTP_HOST} ^(.*)\.user.domain.com
</code>```

Title: Wildcard subdomains htaccess rule?

Body:
I already setup the dns zone to point *.user.domain.com, It works fine but i get the known default cpanel page.

I believe that i have to put something in the htaccess to forward the subdomains requests to a php page.

Example

simon.user.domain.com -> hello.php?user=simon

I've tried the following rules but they don't work:

RewriteCond %{HTTP_HOST} ^(^.*)\.user.domain.com
RewriteRule (.*)  hello.php?user=%1

I've put it in the domain.com public html but as i said it's not working.

Any Ideas?

Thank you

Body:
Rewrite cond is Perl compatiable regular expression, so no ^ in  parentheses!

RewriteCond %{HTTP_HOST} ^(.*)\.user.domain.com


问:
Is it possible somehow to create the form for each patrial on the index page in Rails without javascript?
invites_controller.rb

```<code>def index
  @invites = Invites.all
end
</code>```

invite.rb

```<code>has_one :answer
</code>```

answers_controller.rb

```<code>def new
  @invite = Invite.find(params[:invite_id])
  @answer = @invite.build_answer
end

def create
  @invite = Invite.find(params[:invite_id])
  @answer = @invite.create_answer
  redirect_to :back
end
</code>```

answer.rb

```<code>belongs_to :invite
</code>```

routes.rb

```<code>resources :invites, only: [:index] do
  resources :answers, only: [:new, :create]
end
</code>```

Is it possible to create invites/index.html where for each line-item will be exist working form for answer without any javascript?

With some logic like this:

```<code><% @invites.each do |i| %>
  <%= form_for(i, i.build_answer) do |f| %>
    <%= f.hidden_field :accept, value: true  %>
    <%= f.submit "accept" %>
  <% end %>
<% end %>
</code>```

What are the routing and the rendering of forms will be?

ps: I can solve my problem by creating accept column at Invite model and simply updating each line item like this

```<code><% @invites.each do |i| %>
  <%= form_for(i) do |f| %>
    <%= f.hidden_field :accept, value: true  %>
    <%= f.submit "accept" %>
  <% end %>
<% end %>
</code>```

but interesting about other way))

答:
Yes, you can achieve it as </p>

```<code><% @invites.each do |i| %>
  <%= form_for([i,i.answer.build]) do |f| %>
    <%= f.text_field :name_of_you_answer_field %>
    <%= f.submit %>
  <% end %>
<% end %>
</code>```

Body:
invites_controller.rb

def index
  @invites = Invites.all
end

invite.rb

has_one :answer

answers_controller.rb

def new
  @invite = Invite.find(params[:invite_id])
  @answer = @invite.build_answer
end

def create
  @invite = Invite.find(params[:invite_id])
  @answer = @invite.create_answer
  redirect_to :back
end

answer.rb

belongs_to :invite

routes.rb

resources :invites, only: [:index] do
  resources :answers, only: [:new, :create]
end

Is it possible to create invites/index.html where for each line-item will be exist working form for answer without any javascript?

With some logic like this:

<% @invites.each do |i| %>
  <%= form_for(i, i.build_answer) do |f| %>
    <%= f.hidden_field :accept, value: true  %>
    <%= f.submit "accept" %>
  <% end %>
<% end %>

What are the routing and the rendering of forms will be?

ps: I can solve my problem by creating accept column at Invite model and simply updating each line item like this

<% @invites.each do |i| %>
  <%= form_for(i) do |f| %>
    <%= f.hidden_field :accept, value: true  %>
    <%= f.submit "accept" %>
  <% end %>
<% end %>

but interesting about other way))

Body:
Yes, you can achieve it as

<% @invites.each do |i| %>
  <%= form_for([i,i.answer.build]) do |f| %>
    <%= f.text_field :name_of_you_answer_field %>
    <%= f.submit %>
  <% end %>
<% end %>


问:
Symfony 2 Error: Call to a member function andWhere() on array
I'm trying to execute a QueryBuilder query, but it doesn't like the "andWhere" syntax in the for loop. I don't think it likes anything in the for loop. It's supposed to check if any of the array elements equals "x" so that it filters the search results based on that.</p>

```<code>$repository = $this->getDoctrine()->getRepository('AppBundle:Shrubs');

$query = $repository->createQueryBuilder('p');

$shrubs = $query
    ->where($query->expr()->like('p.botanicalname', ':botanicalname'))
    ->setParameter('botanicalname', '%' . $botanicalname . '%')
    ->andwhere($query->expr()->like('p.commonname', ':commonname'))
    ->setParameter('commonname', '%' . $commonname . '%')
    ->orderBy('p.commonname', 'ASC')
    ->getQuery()
    ->getResult();

$checkfor = array("wetsoil"=>"Tolerates Wet Soil",
    "borderlinehardy"=>"Borderline Hardy",
    "moistsoil"=>"Prefers Moist Soil";

reset($checkfor);

foreach ($checkfor as $key => $value) {
    if (${$key} == "x") {
        $shrubs = $shrubs->andWhere('$key = x')
            ->setParameter('x', $key)
            ->getQuery()
            ->getResult();
        return $this->render('shrubs/searchresults.html.twig', array(
            'shrubs' => $shrubs,));
    }
}

return $this->render('shrubs/searchresults.html.twig', array(
    'shrubs' => $shrubs
</code>```

答:
Your $shrubs variable is the $query result, you call ->getQuery()->getResult()

Your code fixed would look like

```<code>$repository = $this->getDoctrine()->getRepository('AppBundle:Shrubs');

$query = $repository->createQueryBuilder('p');

$query
    ->where($query->expr()->like('p.botanicalname', ':botanicalname'))
    ->setParameter('botanicalname', '%' . $botanicalname . '%')
    ->andwhere($query->expr()->like('p.commonname', ':commonname'))
    ->setParameter('commonname', '%' . $commonname . '%')
    ->orderBy('p.commonname', 'ASC')
    ; // Remove ->getQuery() and->getResult()

$checkfor = array("wetsoil"=>"Tolerates Wet Soil",
    "borderlinehardy"=>"Borderline Hardy",
    "moistsoil"=>"Prefers Moist Soil";

reset($checkfor);

foreach ($checkfor as $key => $value) {
    if (${$key} == "x") {
        $shrubs = $query->andWhere('$key = x')
            ->setParameter('x', $key)
            ->getQuery()
            ->getResult();
        return $this->render('shrubs/searchresults.html.twig', array(
            'shrubs' => $shrubs,));
    }
}

$shrubs = $query->getQuery()->getResult();// Execute the query here

return $this->render('shrubs/searchresults.html.twig', array(
    'shrubs' => $shrubs
);
</code>```

Body:
I'm trying to execute a QueryBuilder query, but it doesn't like the "andWhere" syntax in the for loop. I don't think it likes anything in the for loop. It's supposed to check if any of the array elements equals "x" so that it filters the search results based on that.

$repository = $this->getDoctrine()->getRepository('AppBundle:Shrubs');

$query = $repository->createQueryBuilder('p');

$shrubs = $query
    ->where($query->expr()->like('p.botanicalname', ':botanicalname'))
    ->setParameter('botanicalname', '%' . $botanicalname . '%')
    ->andwhere($query->expr()->like('p.commonname', ':commonname'))
    ->setParameter('commonname', '%' . $commonname . '%')
    ->orderBy('p.commonname', 'ASC')
    ->getQuery()
    ->getResult();

$checkfor = array("wetsoil"=>"Tolerates Wet Soil",
    "borderlinehardy"=>"Borderline Hardy",
    "moistsoil"=>"Prefers Moist Soil";

reset($checkfor);

foreach ($checkfor as $key => $value) {
    if (${$key} == "x") {
        $shrubs = $shrubs->andWhere('$key = x')
            ->setParameter('x', $key)
            ->getQuery()
            ->getResult();
        return $this->render('shrubs/searchresults.html.twig', array(
            'shrubs' => $shrubs,));
    }
}

return $this->render('shrubs/searchresults.html.twig', array(
    'shrubs' => $shrubs

Body:
Your $shrubs variable is the $query result, you call ->getQuery()->getResult()

Your code fixed would look like

$repository = $this->getDoctrine()->getRepository('AppBundle:Shrubs');

$query = $repository->createQueryBuilder('p');

$query
    ->where($query->expr()->like('p.botanicalname', ':botanicalname'))
    ->setParameter('botanicalname', '%' . $botanicalname . '%')
    ->andwhere($query->expr()->like('p.commonname', ':commonname'))
    ->setParameter('commonname', '%' . $commonname . '%')
    ->orderBy('p.commonname', 'ASC')
    ; // Remove ->getQuery() and->getResult()

$checkfor = array("wetsoil"=>"Tolerates Wet Soil",
    "borderlinehardy"=>"Borderline Hardy",
    "moistsoil"=>"Prefers Moist Soil";

reset($checkfor);

foreach ($checkfor as $key => $value) {
    if (${$key} == "x") {
        $shrubs = $query->andWhere('$key = x')
            ->setParameter('x', $key)
            ->getQuery()
            ->getResult();
        return $this->render('shrubs/searchresults.html.twig', array(
            'shrubs' => $shrubs,));
    }
}

$shrubs = $query->getQuery()->getResult();// Execute the query here

return $this->render('shrubs/searchresults.html.twig', array(
    'shrubs' => $shrubs
);


问:
textIsSelectable not working with Edittext
I have seen many question like this here and lots of solution but nothing is working for me. below is my EditText xml

```<code>        <EditText
        android:id="@+id/summary_edittextview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="10dp"
        android:lines="15"
        android:maxLength="1000"
        android:textIsSelectable="true"
        android:textSize="16dp"
        android:backgroundTint="@color/colorPrimaryDark"/>
</code>```

I tried to do textIsSelectable=true which makes edittext disable and nothing happens, I tried using cursorVisible=true but that also does not solve my problem. Please help i want to allow user to copy text which is inside EditText

More Details:-
This EditText is under layout of fragment and I am using this style as app theme

```<code>  <style name="AppTheme.Dark" parent="Theme.AppCompat.Light.NoActionBar">
</code>```

even if i remove textIsSelectable=true it doesn't work. Please help me where i am doing mistake.

答:
As @Ashwin Mothilal said What do you want to do?

OK fine. FYI, textIsSelectable is indicates that the content of a non-editable TextView can be selected.

(An EditText is always selectable, so textIsSelectable is not necessary for an EditText.)

If you DO add android:textIsSelectable to a EditText the text IS selectable, but the field is NOT editable, nor is the cursor visible.

Body:
I have seen many question like this here and lots of solution but nothing is working for me. below is my EditText xml

        <EditText
        android:id="@+id/summary_edittextview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="10dp"
        android:lines="15"
        android:maxLength="1000"
        android:textIsSelectable="true"
        android:textSize="16dp"
        android:backgroundTint="@color/colorPrimaryDark"/>

I tried to do textIsSelectable=true which makes edittext disable and nothing happens, I tried using cursorVisible=true but that also does not solve my problem. Please help i want to allow user to copy text which is inside EditText

More Details:-
This EditText is under layout of fragment and I am using this style as app theme


问:
multiple HTML5 canvas with Neurosky sensor input is not working
I have created multiple html5 canvas using instantiation mode in P5JS. I am using Neurosky mindwave EEG sensor to activate and deactivate canvas one by one. Neurosky mindwave EEG sensor can detect user's eye blink which I am using as input. When user blinks, it should activate one canvas and deactivate another canvas and vice-versa.I am using Neurosky mindwave EEG sensor to activate and deactivate canvas one by one. Neurosky mindwave EEG sensor can detect user's eye blink which I am using as input. When user blinks, it should activate one canvas and deactivate another canvas and vice-versa.

Just to check if my code logic works, I used mouse pressed input to switch between the canvas and it worked perfectly. But, when I used it with the sensor it didn't work.

What I did - I have created multiple HTML5 canvas using instantiation mode in P5JS. I have used node-neurosky node module to capture the eyeblink data from the sensor. Node Module

What worked - When I launch the app it takes the eye blink as input for the first time and activate the another canvas but when I blink again it doesn't deactivate the current canvas and activate another canvas. I have tried printing flags to check the code and it is doing fine. Eyeblink gets detected every time when I blink but it doesn't switch the canvas.

What didn't work - When I tried to use eye blink strength directly into the sketch.js it didn't work then I created another boolean variable eyeclick which also didn't work.

sketch.js

```<code>var stateTwo, stateOne = true;
// sketch one -----------------------------------

var first = new p5(firstSketch, "canvasOne");

function firstSketch(p) {

    p.setup = function() {
        p.createCanvas(400, 250);
    }
    p.draw = function() {
        p.background(255, 10, 100);
        p.fill(255);
        p.ellipse(p.width / 2, p.height / 2, 50, 50);
        if (eyeclicked) {
            stateOne = false;
            stateTwo = true;
            console.log(" canvas <-- one");
            // k = 0;
            eyeclicked = false;
        }
        if (stateOne) {
            $('#canvasOne').css('opacity', '1');
            $('#canvasTwo').css('opacity', '0.5');
            // console.log("canvas One");
            p.fill(255, 0, 0);
            p.ellipse(p.random(p.width), p.random(p.height), 50, 50);
        }
    }
}

// sketch two -----------------------------------

var second = new p5(secondSketch, "canvasTwo");

function secondSketch(p) {

    p.setup = function() {
        p.createCanvas(400, 250);
    }
    p.draw = function() {
        p.background(60, 250, 100);
        p.fill(0);
        p.ellipse(p.width / 2, p.height / 2, 50, 50);

        if (eyeclicked) {
            stateOne = true;
            stateTwo = false;
            console.log(" canvas <-- two");
            //  k = 0;
            eyeclicked = false;
        }

        if (stateTwo) {
            $('#canvasOne').css('opacity', '0.5');
            $('#canvasTwo').css('opacity', '1');
            // console.log("canvas Two");
            p.fill(0, 0, 255);
            p.ellipse(p.random(p.width), p.random(p.height), 50, 50);
        }
    }
}
</code>```

NodeCode to connect with sensor connect.js

```<code> var attention = 0;
 var meditation = 0;
 var blink;
 var poorSignalLevel = 0;
 var eyeclicked = false;

 if ("WebSocket" in window) {
     console.log("WebSocket is supported by your Browser. Proceed.");
     // $('#connect-controls').show();
 }

 var ws = new WebSocket("ws://127.0.0.1:8080");
 ws.onopen = function() {
     console.log('opened connection');
     ws.send("Hello from websocket client!");
 };

 // whenever websocket server transmit a message, do this stuff
 ws.onmessage = function(evt) {
     // parse the data (sent as string) into a standard JSON object (much easier to use)
     var data = JSON.parse(evt.data);
     // handle "eSense" data
     if (data.eSense) {
         $('#brain').css({
             opacity: 1
         });
         attention = data.eSense.attention;
         meditation = data.eSense.meditation;
         // brainProgress('#focusProgress', attention);
         // brainProgress('#medProgress', meditation);
         $("#focus").text(attention);
         $("#meditation").text(meditation);
     }

     // handle "blinkStrength" data
     if (data.blinkStrength) {
         blink = data.blinkStrength;
         var blinkcol = "white";
         var eyeVal = map_range(blink, 0, 255, 0, 100);
         $('#eyeBlinkStrength').text(parseInt(eyeVal));
         if (blink > 40) {
             //blinkcol = "rgba(102,211,43,1.0)";
             eyeclicked = true;
             //  k++;
             console.log(blink + " " + eyeclicked);
         } else blinkcol = "white";
         $('#eyeBlink').css({
             width: eyeVal,
             height: eyeVal,
             background: blinkcol
         });
     } else {
         blink = 0;
         eyeclicked = false;
     }

     // handle "poorSignal" data
     if (data.poorSignalLevel != null) {
         poorSignalLevel = parseInt(data.poorSignalLevel);
     }
 };

 // when websocket closes connection, do this stuff
 ws.onclose = function() {
     // websocket is closed.
     console.log("Connection is closed...");
 };

 function map_range(value, low1, high1, low2, high2) {
     return low2 + (high2 - low2) * (value - low1) / (high1 - low1);
 }
</code>```

EDIT CODE PEN DEMO

Mouse Input Based Code which demonstrate the logic of switching between multiple canvas. It works perfectly. Try to click into the center circle

```<code>var stateTwo, stateOne = true;
var eyeIsBlinked;
// sketch one -----------------------------------

var first = new p5(firstSketch, "canvasOne");

function firstSketch(p) {

    p.setup = function() {
        p.createCanvas(400, 250);
    }
    p.draw = function() {
        p.background(255, 10, 100);
        p.fill(255);
        p.ellipse(p.width / 2, p.height / 2, 50, 50);
        if (p.mouseIsPressed && p.dist(p.mouseX, p.mouseY, p.width / 2, p.height / 2) < 50) {
            stateOne = false;
            stateTwo = true;
            console.log(" <-- one");
            // k = 0;
            // window.eyeIsBlinked = false;
            // blink = 0;
        }
        if (stateOne) {
            $('#canvasOne').css('opacity', '1');
            $('#canvasTwo').css('opacity', '0.5');
            // console.log("canvas One");
            p.fill(255, 0, 0);
            p.ellipse(p.random(p.width), p.random(p.height), 50, 50);
        }
    }
}

// sketch two -----------------------------------

var second = new p5(secondSketch, "canvasTwo");

function secondSketch(p) {

    p.setup = function() {
        p.createCanvas(400, 250);
    }
    p.draw = function() {
        p.background(60, 250, 100);
        p.fill(0);
        p.ellipse(p.width / 2, p.height / 2, 50, 50);

        if (p.mouseIsPressed && p.dist(p.mouseX, p.mouseY, p.width / 2, p.height / 2) < 50) {
            stateOne = true;
            stateTwo = false;
            console.log(" <-- two");
            //  k = 0;
            //  window.eyeIsBlinked = false;
            //blink = 0;
        }

        if (stateTwo) {
            $('#canvasOne').css('opacity', '0.5');
            $('#canvasTwo').css('opacity', '1');
            // console.log("canvas Two");
            p.fill(0, 0, 255);
            p.ellipse(p.random(p.width), p.random(p.height), 50, 50);
        }
    }
}
</code>```

答:
I don't know how your project works. But I guess the problem might be a scope problem. Both files are using the eyeclicked variable, but they might be using two different variables. Try to make sure that they're using the same variable by using it inside the window global variable.

So instead of eyeclicked use window.eyeclicked.

Body:
I have created multiple html5 canvas using instantiation mode in P5JS. I am using Neurosky mindwave EEG sensor to activate and deactivate canvas one by one. Neurosky mindwave EEG sensor can detect user's eye blink which I am using as input. When user blinks, it should activate one canvas and deactivate another canvas and vice-versa.I am using Neurosky mindwave EEG sensor to activate and deactivate canvas one by one. Neurosky mindwave EEG sensor can detect user's eye blink which I am using as input. When user blinks, it should activate one canvas and deactivate another canvas and vice-versa.

Just to check if my code logic works, I used mouse pressed input to switch between the canvas and it worked perfectly. But, when I used it with the sensor it didn't work.

What I did - I have created multiple HTML5 canvas using instantiation mode in P5JS. I have used node-neurosky node module to capture the eyeblink data from the sensor. Node Module

What worked - When I launch the app it takes the eye blink as input for the first time and activate the another canvas but when I blink again it doesn't deactivate the current canvas and activate another canvas. I have tried printing flags to check the code and it is doing fine. Eyeblink gets detected every time when I blink but it doesn't switch the canvas.

What didn't work - When I tried to use eye blink strength directly into the sketch.js it didn't work then I created another boolean variable eyeclick which also didn't work.

sketch.js

var stateTwo, stateOne = true;
// sketch one -----------------------------------

var first = new p5(firstSketch, "canvasOne");

function firstSketch(p) {

    p.setup = function() {
        p.createCanvas(400, 250);
    }
    p.draw = function() {
        p.background(255, 10, 100);
        p.fill(255);
        p.ellipse(p.width / 2, p.height / 2, 50, 50);
        if (eyeclicked) {
            stateOne = false;
            stateTwo = true;
            console.log(" canvas <-- one");
            // k = 0;
            eyeclicked = false;
        }
        if (stateOne) {
            $('#canvasOne').css('opacity', '1');
            $('#canvasTwo').css('opacity', '0.5');
            // console.log("canvas One");
            p.fill(255, 0, 0);
            p.ellipse(p.random(p.width), p.random(p.height), 50, 50);
        }
    }
}

// sketch two -----------------------------------

var second = new p5(secondSketch, "canvasTwo");

function secondSketch(p) {

    p.setup = function() {
        p.createCanvas(400, 250);
    }
    p.draw = function() {
        p.background(60, 250, 100);
        p.fill(0);
        p.ellipse(p.width / 2, p.height / 2, 50, 50);

        if (eyeclicked) {
            stateOne = true;
            stateTwo = false;
            console.log(" canvas <-- two");
            //  k = 0;
            eyeclicked = false;
        }

        if (stateTwo) {
            $('#canvasOne').css('opacity', '0.5');
            $('#canvasTwo').css('opacity', '1');
            // console.log("canvas Two");
            p.fill(0, 0, 255);
            p.ellipse(p.random(p.width), p.random(p.height), 50, 50);
        }
    }
}

NodeCode to connect with sensor connect.js

 var attention = 0;
 var meditation = 0;
 var blink;
 var poorSignalLevel = 0;
 var eyeclicked = false;

 if ("WebSocket" in window) {
     console.log("WebSocket is supported by your Browser. Proceed.");
     // $('#connect-controls').show();
 }

 var ws = new WebSocket("ws://127.0.0.1:8080");
 ws.onopen = function() {
     console.log('opened connection');
     ws.send("Hello from websocket client!");
 };

 // whenever websocket server transmit a message, do this stuff
 ws.onmessage = function(evt) {
     // parse the data (sent as string) into a standard JSON object (much easier to use)
     var data = JSON.parse(evt.data);
     // handle "eSense" data
     if (data.eSense) {
         $('#brain').css({
             opacity: 1
         });
         attention = data.eSense.attention;
         meditation = data.eSense.meditation;
         // brainProgress('#focusProgress', attention);
         // brainProgress('#medProgress', meditation);
         $("#focus").text(attention);
         $("#meditation").text(meditation);
     }

     // handle "blinkStrength" data
     if (data.blinkStrength) {
         blink = data.blinkStrength;
         var blinkcol = "white";
         var eyeVal = map_range(blink, 0, 255, 0, 100);
         $('#eyeBlinkStrength').text(parseInt(eyeVal));
         if (blink > 40) {
             //blinkcol = "rgba(102,211,43,1.0)";
             eyeclicked = true;
             //  k++;
             console.log(blink + " " + eyeclicked);
         } else blinkcol = "white";
         $('#eyeBlink').css({
             width: eyeVal,
             height: eyeVal,
             background: blinkcol
         });
     } else {
         blink = 0;
         eyeclicked = false;
     }

     // handle "poorSignal" data
     if (data.poorSignalLevel != null) {
         poorSignalLevel = parseInt(data.poorSignalLevel);
     }
 };

 // when websocket closes connection, do this stuff
 ws.onclose = function() {
     // websocket is closed.
     console.log("Connection is closed...");
 };

 function map_range(value, low1, high1, low2, high2) {
     return low2 + (high2 - low2) * (value - low1) / (high1 - low1);
 }

EDIT CODE PEN DEMO

Mouse Input Based Code which demonstrate the logic of switching between multiple canvas. It works perfectly. Try to click into the center circle

var stateTwo, stateOne = true;
var eyeIsBlinked;
// sketch one -----------------------------------

var first = new p5(firstSketch, "canvasOne");

function firstSketch(p) {

    p.setup = function() {
        p.createCanvas(400, 250);
    }
    p.draw = function() {
        p.background(255, 10, 100);
        p.fill(255);
        p.ellipse(p.width / 2, p.height / 2, 50, 50);
        if (p.mouseIsPressed && p.dist(p.mouseX, p.mouseY, p.width / 2, p.height / 2) < 50) {
            stateOne = false;
            stateTwo = true;
            console.log(" <-- one");
            // k = 0;
            // window.eyeIsBlinked = false;
            // blink = 0;
        }
        if (stateOne) {
            $('#canvasOne').css('opacity', '1');
            $('#canvasTwo').css('opacity', '0.5');
            // console.log("canvas One");
            p.fill(255, 0, 0);
            p.ellipse(p.random(p.width), p.random(p.height), 50, 50);
        }
    }
}

// sketch two -----------------------------------

var second = new p5(secondSketch, "canvasTwo");

function secondSketch(p) {

    p.setup = function() {
        p.createCanvas(400, 250);
    }
    p.draw = function() {
        p.background(60, 250, 100);
        p.fill(0);
        p.ellipse(p.width / 2, p.height / 2, 50, 50);

        if (p.mouseIsPressed && p.dist(p.mouseX, p.mouseY, p.width / 2, p.height / 2) < 50) {
            stateOne = true;
            stateTwo = false;
            console.log(" <-- two");
            //  k = 0;
            //  window.eyeIsBlinked = false;
            //blink = 0;
        }

        if (stateTwo) {
            $('#canvasOne').css('opacity', '0.5');
            $('#canvasTwo').css('opacity', '1');
            // console.log("canvas Two");
            p.fill(0, 0, 255);
            p.ellipse(p.random(p.width), p.random(p.height), 50, 50);
        }
    }
}