问:
spritekit: unable to detect collision
so i tried to use skphysicscontact but when the "cat" and "spinnynode" collides there is no output from them, even when there is physical interaction

on another note, why can't the timer function work? it doesn't seem to call out the function at all.

please help, I'm a newbie. Thanks

```<code>import SpriteKit
import GameplayKit
import UIKit
import Foundation

struct physicsCollision {
static let cat: UInt32 = 1
static let spinnyNode: UInt32 = 2
}

class GameScene: SKScene, SKPhysicsContactDelegate {

var entities = [GKEntity]()
var graphs = [String : GKGraph]()
var catTimer = Timer()
var score = 0

private var lastUpdateTime : TimeInterval = 0
private var label : SKLabelNode?
private var spinnyNode : SKShapeNode?

let meow = SKAction.playSoundFileNamed("cat meow", waitForCompletion: false)

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

//random range

func randomInRange(lo: Float, hi : Float) -> Float{
    return lo + Float(arc4random_uniform(UInt32(hi - lo + 1)))
}

//spawn cat

func spawnCat(){

    // x coordinate between MinX (left) and MaxX (right):
    let randomX = randomInRange(lo: Float(self.frame.minX + 5), hi: Float(self.frame.maxX + 5))

    let startPoint = CGPoint(x: CGFloat(randomX), y: self.frame.height * 1.2)
    let endPoint = CGPoint(x: CGFloat(randomX), y:self.frame.height * -0.5)
    let cat = SKSpriteNode(imageNamed: "before right")

    cat.name = "cat"
    cat.setScale(0.3)
    cat.position = startPoint
    cat.zPosition = 1
    cat.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: cat.size.width, height: cat.size.height))
    cat.physicsBody?.affectedByGravity = false
    cat.physicsBody?.categoryBitMask = physicsCollision.cat
    cat.physicsBody?.contactTestBitMask = physicsCollision.spinnyNode
    cat.physicsBody?.collisionBitMask = physicsCollision.spinnyNode
    cat.physicsBody?.isDynamic = false
    self.addChild(cat)

    let moveCat = SKAction.move(to: endPoint, duration: 5)
    let deleteCat = SKAction.removeFromParent()
    let catSequence = SKAction.sequence([moveCat, meow, deleteCat])
    cat.run(catSequence)

}

//contact func

func didBeginContact(contact:SKPhysicsContact){

    var firstBody = SKPhysicsBody()
    var secondBody = SKPhysicsBody()

    if contact.bodyA.node?.name == "cat"
    {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    }
    else{
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }
 if firstBody.node?.name == "cat" && (secondBody.node?.name)! == "skinnynode"{
    print("contacted")

    }
}

override func sceneDidLoad() {

    self.physicsWorld.contactDelegate = self

    self.lastUpdateTime = 0

    //spawn cat at intervals,, time interval to decrease when points increase, use if loop

    catTimer = Timer.init(timeInterval: 1 , target: self, selector: Selector(("cat")), userInfo: nil, repeats: true)

    // Create shape node to use during mouse interaction
    let w = (self.size.width + self.size.height) * 0.05
    self.spinnyNode = SKShapeNode.init(rectOf: CGSize.init(width: w, height: w), cornerRadius: w * 0.5)
    spinnyNode?.name = "spinnynode"
    spinnyNode?.physicsBody = SKPhysicsBody(circleOfRadius: 0.5)
    spinnyNode?.physicsBody?.affectedByGravity = false
    spinnyNode?.zPosition = 1
    spinnyNode?.physicsBody?.categoryBitMask = physicsCollision.spinnyNode
    if let spinnyNode = self.spinnyNode{
        spinnyNode.lineWidth = 1.5
        spinnyNode.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(Double.pi), duration: 1)))
        spinnyNode.run(SKAction.sequence([SKAction.wait(forDuration: 0.5),
                                          SKAction.fadeOut(withDuration: 0.3),
                                          SKAction.removeFromParent()]))
                                        }

    //create score label
    let scoreLabel = UILabel(frame: CGRect(x:((self.frame.height) * 0.5) , y:((self.frame.width) * 0.3), width: (self.frame.size.width)/3, height: 30))
    scoreLabel.center = CGPoint(x: (self.frame.size.width)/1.6 , y: (self.frame.size.height)/2)
    scoreLabel.textColor = UIColor.white
    scoreLabel.text = "\(score)"
    self.view?.addSubview(scoreLabel)

                                }

func touchDown(atPoint pos : CGPoint) {
    if let n = self.spinnyNode?.copy() as! SKShapeNode? {
        n.position = pos
        n.strokeColor = SKColor.green
        self.addChild(n)
    }
}

func touchMoved(toPoint pos : CGPoint) {
    if let n = self.spinnyNode?.copy() as! SKShapeNode? {
        n.position = pos
        n.strokeColor = SKColor.purple
        self.addChild(n)

    }
}

func touchUp(atPoint pos : CGPoint) {
    if let n = self.spinnyNode?.copy() as! SKShapeNode? {
        n.position = pos
        n.strokeColor = SKColor.red
        self.addChild(n)
    }
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

            spawnCat()
            if let label = self.label {
            label.run(SKAction.init(named: "Pulse")!, withKey: "fadeInOut")

    }

    for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches { self.touchMoved(toPoint: t.location(in: self)) }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}

override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered

    // Initialize _lastUpdateTime if it has not already been
    if (self.lastUpdateTime == 0) {
        self.lastUpdateTime = currentTime
    }

    // Calculate time since last update
    let dt = currentTime - self.lastUpdateTime

    // Update entities
    for entity in self.entities {
        entity.update(deltaTime: dt)
    }

    self.lastUpdateTime = currentTime
}
</code>```

}

答:
Have you tried using the categoryBitMask method of the SKPhysicsContactDelegate? You may be able to fix your issue by going into the GameScene.sks file and assigning the Category Mask to a number other than the default. Do this for both of your bodies, but assign different values for each of the bodies.

Then, inside your GameScene.swift, your didBegin contact function might look something like this:

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

//set these values to the same number in your GameScene.sks file
let catCategory = 2
let skinnyNodeCategory = 3

func didBegin(_ contact: SKPhysicsContact) {

    let bodyA = contact.bodyA
    let bodyB = contact.bodyB

    //check to see if the bodies in contact match
    //the category mask numbers you defined
    //here the conditional is set to say that either of the bodies
    //in contact match the categoryBitMask number set in the GameScene.sks file

    //using && may not work depending on how the categoryBitMask identifiers
    //are assigned by the physicsContactDelegate

    if bodyA.categoryBitMask == catCategory || bodyB.categoryBitMask == catCategory {

        print("contacted")

        }
    }
}

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered
}
}
</code>```

Title: spritekit: unable to detect collision

Body:
so i tried to use skphysicscontact but when the "cat" and "spinnynode" collides there is no output from them, even when there is physical interaction

on another note, why can't the timer function work? it doesn't seem to call out the function at all.

please help, I'm a newbie. Thanks

import SpriteKit
import GameplayKit
import UIKit
import Foundation

struct physicsCollision {
static let cat: UInt32 = 1
static let spinnyNode: UInt32 = 2
}

class GameScene: SKScene, SKPhysicsContactDelegate {

var entities = [GKEntity]()
var graphs = [String : GKGraph]()
var catTimer = Timer()
var score = 0

private var lastUpdateTime : TimeInterval = 0
private var label : SKLabelNode?
private var spinnyNode : SKShapeNode?

let meow = SKAction.playSoundFileNamed("cat meow", waitForCompletion: false)

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

//random range

func randomInRange(lo: Float, hi : Float) -> Float{
    return lo + Float(arc4random_uniform(UInt32(hi - lo + 1)))
}

//spawn cat

func spawnCat(){

    // x coordinate between MinX (left) and MaxX (right):
    let randomX = randomInRange(lo: Float(self.frame.minX + 5), hi: Float(self.frame.maxX + 5))

    let startPoint = CGPoint(x: CGFloat(randomX), y: self.frame.height * 1.2)
    let endPoint = CGPoint(x: CGFloat(randomX), y:self.frame.height * -0.5)
    let cat = SKSpriteNode(imageNamed: "before right")

    cat.name = "cat"
    cat.setScale(0.3)
    cat.position = startPoint
    cat.zPosition = 1
    cat.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: cat.size.width, height: cat.size.height))
    cat.physicsBody?.affectedByGravity = false
    cat.physicsBody?.categoryBitMask = physicsCollision.cat
    cat.physicsBody?.contactTestBitMask = physicsCollision.spinnyNode
    cat.physicsBody?.collisionBitMask = physicsCollision.spinnyNode
    cat.physicsBody?.isDynamic = false
    self.addChild(cat)

    let moveCat = SKAction.move(to: endPoint, duration: 5)
    let deleteCat = SKAction.removeFromParent()
    let catSequence = SKAction.sequence([moveCat, meow, deleteCat])
    cat.run(catSequence)

}

//contact func

func didBeginContact(contact:SKPhysicsContact){

    var firstBody = SKPhysicsBody()
    var secondBody = SKPhysicsBody()

    if contact.bodyA.node?.name == "cat"
    {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    }
    else{
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }
 if firstBody.node?.name == "cat" && (secondBody.node?.name)! == "skinnynode"{
    print("contacted")

    }
}

override func sceneDidLoad() {

    self.physicsWorld.contactDelegate = self

    self.lastUpdateTime = 0

    //spawn cat at intervals,, time interval to decrease when points increase, use if loop

    catTimer = Timer.init(timeInterval: 1 , target: self, selector: Selector(("cat")), userInfo: nil, repeats: true)

    // Create shape node to use during mouse interaction
    let w = (self.size.width + self.size.height) * 0.05
    self.spinnyNode = SKShapeNode.init(rectOf: CGSize.init(width: w, height: w), cornerRadius: w * 0.5)
    spinnyNode?.name = "spinnynode"
    spinnyNode?.physicsBody = SKPhysicsBody(circleOfRadius: 0.5)
    spinnyNode?.physicsBody?.affectedByGravity = false
    spinnyNode?.zPosition = 1
    spinnyNode?.physicsBody?.categoryBitMask = physicsCollision.spinnyNode
    if let spinnyNode = self.spinnyNode{
        spinnyNode.lineWidth = 1.5
        spinnyNode.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(Double.pi), duration: 1)))
        spinnyNode.run(SKAction.sequence([SKAction.wait(forDuration: 0.5),
                                          SKAction.fadeOut(withDuration: 0.3),
                                          SKAction.removeFromParent()]))
                                        }

    //create score label
    let scoreLabel = UILabel(frame: CGRect(x:((self.frame.height) * 0.5) , y:((self.frame.width) * 0.3), width: (self.frame.size.width)/3, height: 30))
    scoreLabel.center = CGPoint(x: (self.frame.size.width)/1.6 , y: (self.frame.size.height)/2)
    scoreLabel.textColor = UIColor.white
    scoreLabel.text = "\(score)"
    self.view?.addSubview(scoreLabel)

                                }

func touchDown(atPoint pos : CGPoint) {
    if let n = self.spinnyNode?.copy() as! SKShapeNode? {
        n.position = pos
        n.strokeColor = SKColor.green
        self.addChild(n)
    }
}

func touchMoved(toPoint pos : CGPoint) {
    if let n = self.spinnyNode?.copy() as! SKShapeNode? {
        n.position = pos
        n.strokeColor = SKColor.purple
        self.addChild(n)

    }
}

func touchUp(atPoint pos : CGPoint) {
    if let n = self.spinnyNode?.copy() as! SKShapeNode? {
        n.position = pos
        n.strokeColor = SKColor.red
        self.addChild(n)
    }
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

            spawnCat()
            if let label = self.label {
            label.run(SKAction.init(named: "Pulse")!, withKey: "fadeInOut")

    }

    for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches { self.touchMoved(toPoint: t.location(in: self)) }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}

override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered

    // Initialize _lastUpdateTime if it has not already been
    if (self.lastUpdateTime == 0) {
        self.lastUpdateTime = currentTime
    }

    // Calculate time since last update
    let dt = currentTime - self.lastUpdateTime

    // Update entities
    for entity in self.entities {
        entity.update(deltaTime: dt)
    }

    self.lastUpdateTime = currentTime
}

}

Body:
Have you tried using the categoryBitMask method of the SKPhysicsContactDelegate? You may be able to fix your issue by going into the GameScene.sks file and assigning the Category Mask to a number other than the default. Do this for both of your bodies, but assign different values for each of the bodies.

Then, inside your GameScene.swift, your didBegin contact function might look something like this:

class GameScene: SKScene, SKPhysicsContactDelegate {

//set these values to the same number in your GameScene.sks file
let catCategory = 2
let skinnyNodeCategory = 3

func didBegin(_ contact: SKPhysicsContact) {

    let bodyA = contact.bodyA
    let bodyB = contact.bodyB

    //check to see if the bodies in contact match
    //the category mask numbers you defined
    //here the conditional is set to say that either of the bodies
    //in contact match the categoryBitMask number set in the GameScene.sks file

    //using && may not work depending on how the categoryBitMask identifiers
    //are assigned by the physicsContactDelegate

    if bodyA.categoryBitMask == catCategory || bodyB.categoryBitMask == catCategory {

        print("contacted")

        }
    }
}

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered
}
}


来源: stackexchange

问:
angular/node.js POST for payumoney integration
I'm using angular/node.js stack for payumoney integration.

On the angular side, an order is placed using $http.post to a route endpoint at the server side (node.js) as follows:

```<code>$http.post('/placeOrder',order).success(function(data, status, headers, config){
      //handle responses on client side
      console.log("Successfully POSTED to payment gateway");
      window.location = "https://test.payu.in/_payment";
    }).error(function(data, status, headers, config) {
      console.log("Error in posting");
   });
</code>```

The actual heavy lifting is done on the node.js (server side):

```<code>router.post('/placeOrder', function(req, res, next){

hash_data = MERCHANT_KEY+'|'+txnid+'|'+amount+'|'+productinfo+'|'+firstname+'|'+email+'|'+udf1+'|'+udf2+'|'+udf3+'|'+udf4+'|'+udf5+'||||||'+SALT;

var data = querystring.stringify({

      'key': MERCHANT_KEY,
      'txnid': txnid,
      'amount': amount,
      'productinfo': productinfo,
      'firstname': firstname,
      'email': email,
      'phone': phone,
      'surl': SUCCESS_URL,
      'furl': FAILURE_URL,
      'curl': FAILURE_URL,
      'hash': hash,
      'service_provider': SERVICE_PROVIDER
      //'salt': SALT
    });

    //POST options
    var POST_OPTIONS = {
        hostname: PAYU_BASE_URL,
        port: 443,
        path: '/_payment',
        method: 'POST',
        //json: true,
        agent: false,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            //'Content-Length': Buffer.byteLength(data)
            'Content-Length': data.length
        }
    };

    var resp_status = "";

    var req = https.request(POST_OPTIONS, function(response) {
        console.log('STATUS: ' + response.statusCode);
        console.log('HEADERS: ' + JSON.stringify(response.headers));
        response.setEncoding('utf8');
        response.on('data', function (chunk) {
            console.log("body: " + chunk);
            resp_status = 200;
            res.json(chunk);
        });
        response.on('error', function (err) {
            console.log("Got error: " + err.message);
            resp_status = 500;
            return res.send(err);
        });
    });
    req.end(data);
</code>```

However, this doesn't seem to work as the POST doesnt seem to work using this approach. While debugging on the browser through the network tab, I always see:

Request URL:https://test.payu.in/_payment
Request Method:GET
Status Code:200 OK

Also, the test payment page (https://test.payu.in/_payment) shows:
"Error Reason
One or more mandatory parameters are missing in the transaction request."

Any help would be appreciated!!

答:
How did I implement this..

Use Jquery and create a Form

Use sha512 to create hashcode. (bower install js-sha512)

```<code> var hashString = this.merchantKey+'|'+ options.uid +'|'+ options.totalPrice + '|'+'options.uid + '|' +
        options.recipient_name + '|'+ options.email +'|||||||||||'+ this.merchantSalt ;

    var hash = sha512(hashString);

    var key1 = $('<input></input>').attr('type', 'hidden').attr('name', "key").val("merchantKey");

    var key2 = $('<input></input>').attr('type', 'hidden').attr('name', "txnid").val(options.uid);

    var key3 = $('<input></input>').attr('type', 'hidden').attr('name', "amount").val(options.totalPrice);

    var key4 = $('<input></input>').attr('type', 'hidden').attr('name', "productinfo").val(options.uid);

    var key5 = $('<input></input>').attr('type', 'hidden').attr('name', "firstname").val(options.recipient_name);

    var key6 = $('<input></input>').attr('type', 'hidden').attr('name', "email").val(options.email);

    var key7 = $('<input></input>').attr('type', 'hidden').attr('name', "phone").val(options.phone);

    var key8 = $('<input></input>').attr('type', 'hidden').attr('name', "surl").val("http://192.168.43.121/payment/success");

    var key9 = $('<input></input>').attr('type', 'hidden').attr('name', "furl").val("http://192.168.43.121/payment/error");

    var key10 = $('<input></input>').attr('type', 'hidden').attr('name', "hash").val(hash);

    var key11 = $('<input></input>').attr('type', 'hidden').attr('name', "service_provider").val("payu_paisa");

    var form = $('<form/></form>');

    form.attr("id", "payuform");

    form.attr("action", this.payumoneyLink );

    form.attr("method", "POST");

    form.attr("style", "display:none;");

    form.append(key1, key2, key3, key4, key5, key6, key7, key8, key9,key10, key11);

    $("body").append(form);

    // submit form

    form.submit();
</code>```

This is my first answer on StacksOverflow. Hope it helps!

ContentLicense: CC BY-SA 3.0

Body:
I'm using angular/node.js stack for payumoney integration.

On the angular side, an order is placed using $http.post to a route endpoint at the server side (node.js) as follows:

$http.post('/placeOrder',order).success(function(data, status, headers, config){
      //handle responses on client side
      console.log("Successfully POSTED to payment gateway");
      window.location = "https://test.payu.in/_payment";
    }).error(function(data, status, headers, config) {
      console.log("Error in posting");
   });

The actual heavy lifting is done on the node.js (server side):

router.post('/placeOrder', function(req, res, next){

hash_data = MERCHANT_KEY+'|'+txnid+'|'+amount+'|'+productinfo+'|'+firstname+'|'+email+'|'+udf1+'|'+udf2+'|'+udf3+'|'+udf4+'|'+udf5+'||||||'+SALT;

var data = querystring.stringify({

      'key': MERCHANT_KEY,
      'txnid': txnid,
      'amount': amount,
      'productinfo': productinfo,
      'firstname': firstname,
      'email': email,
      'phone': phone,
      'surl': SUCCESS_URL,
      'furl': FAILURE_URL,
      'curl': FAILURE_URL,
      'hash': hash,
      'service_provider': SERVICE_PROVIDER
      //'salt': SALT
    });

    //POST options
    var POST_OPTIONS = {
        hostname: PAYU_BASE_URL,
        port: 443,
        path: '/_payment',
        method: 'POST',
        //json: true,
        agent: false,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            //'Content-Length': Buffer.byteLength(data)
            'Content-Length': data.length
        }
    };

    var resp_status = "";

    var req = https.request(POST_OPTIONS, function(response) {
        console.log('STATUS: ' + response.statusCode);
        console.log('HEADERS: ' + JSON.stringify(response.headers));
        response.setEncoding('utf8');
        response.on('data', function (chunk) {
            console.log("body: " + chunk);
            resp_status = 200;
            res.json(chunk);
        });
        response.on('error', function (err) {
            console.log("Got error: " + err.message);
            resp_status = 500;
            return res.send(err);
        });
    });
    req.end(data);

However, this doesn't seem to work as the POST doesnt seem to work using this approach. While debugging on the browser through the network tab, I always see:

Request URL:https://test.payu.in/_payment
Request Method:GET
Status Code:200 OK

Also, the test payment page (https://test.payu.in/_payment) shows:
"Error Reason
One or more mandatory parameters are missing in the transaction request."

Any help would be appreciated!!

Body:
How did I implement this..

Use Jquery and create a Form

Use sha512 to create hashcode. (bower install js-sha512)

 var hashString = this.merchantKey+'|'+ options.uid +'|'+ options.totalPrice + '|'+'options.uid + '|' +
        options.recipient_name + '|'+ options.email +'|||||||||||'+ this.merchantSalt ;

    var hash = sha512(hashString);

    var key1 = $('<input></input>').attr('type', 'hidden').attr('name', "key").val("merchantKey");

    var key2 = $('<input></input>').attr('type', 'hidden').attr('name', "txnid").val(options.uid);

    var key3 = $('<input></input>').attr('type', 'hidden').attr('name', "amount").val(options.totalPrice);

    var key4 = $('<input></input>').attr('type', 'hidden').attr('name', "productinfo").val(options.uid);

    var key5 = $('<input></input>').attr('type', 'hidden').attr('name', "firstname").val(options.recipient_name);

    var key6 = $('<input></input>').attr('type', 'hidden').attr('name', "email").val(options.email);

    var key7 = $('<input></input>').attr('type', 'hidden').attr('name', "phone").val(options.phone);

    var key8 = $('<input></input>').attr('type', 'hidden').attr('name', "surl").val("http://192.168.43.121/payment/success");

    var key9 = $('<input></input>').attr('type', 'hidden').attr('name', "furl").val("http://192.168.43.121/payment/error");

    var key10 = $('<input></input>').attr('type', 'hidden').attr('name', "hash").val(hash);

    var key11 = $('<input></input>').attr('type', 'hidden').attr('name', "service_provider").val("payu_paisa");

    var form = $('<form/></form>');

    form.attr("id", "payuform");

    form.attr("action", this.payumoneyLink );

    form.attr("method", "POST");

    form.attr("style", "display:none;");

    form.append(key1, key2, key3, key4, key5, key6, key7, key8, key9,key10, key11);

    $("body").append(form);

    // submit form

    form.submit();

This is my first answer on StacksOverflow. Hope it helps!


问:
ExtJS 6 Use custom filter function within memory proxy
I have a store configured with memory proxy with enablePaging: true. Store's remoteFilter and remoteSort set to true so filtering and sorting requests handled by proxy.

When I filter my store by multiple fields I want to use OR condition, not AND.

Without memory proxy paging I could use remoteFilter: false and custom filter function like:

```<code>store.filterBy(function (record)
{
    for (var i = 0; i < searchFields.length; ++i) {
        if (record.get(searchFields[i]).toLowerCase().indexOf(searchText) !== -1) {
            return true;
        }
    }
    return false;
});
</code>```

But how I can achieve this with enabled paging? Override memory proxy?

答:
You can override the memory proxy to suit your needs, or, if you only wish to find a string in one of the fields specified in searchFields, you can add a 'virtual' field to the model with the convert method specified.

For example:

```<code>// Extend Ext.data.Model or create it. Dealer's choice.
Ext.define('MyLocalModel', {
    extend: 'Ext.data.model',
    fields: [
        ...
        {
            name: 'searchField',
            type: 'string',
            convert: function(value, record) {
                // Get search fields somewhere
                var resultArray = [];
                for (var i = 0; i < searchFields.length; ++i) {
                    var searchField = searchFields[i];
                    var fieldValue = record.get(searchField);
                    resultArray.push(fieldValue);
                }

                // Join by a string that would not normally be searched
                // so that field values 'foo' and 'bar' are not valid when searching 'ooba'
                var result = resultArray.join('**');
                return result;
            }
        }
    ]
});
</code>```

All you need to do in the store then is:

```<code>store.filter('searchField', searchText);
</code>```

It's not exactly what you are searching for, but it should get the job done.

Body:
I have a store configured with memory proxy with enablePaging: true. Store's remoteFilter and remoteSort set to true so filtering and sorting requests handled by proxy.

When I filter my store by multiple fields I want to use OR condition, not AND.

Without memory proxy paging I could use remoteFilter: false and custom filter function like:

store.filterBy(function (record)
{
    for (var i = 0; i < searchFields.length; ++i) {
        if (record.get(searchFields[i]).toLowerCase().indexOf(searchText) !== -1) {
            return true;
        }
    }
    return false;
});

But how I can achieve this with enabled paging? Override memory proxy?

Body:
You can override the memory proxy to suit your needs, or, if you only wish to find a string in one of the fields specified in searchFields, you can add a 'virtual' field to the model with the convert method specified.

For example:

// Extend Ext.data.Model or create it. Dealer's choice.
Ext.define('MyLocalModel', {
    extend: 'Ext.data.model',
    fields: [
        ...
        {
            name: 'searchField',
            type: 'string',
            convert: function(value, record) {
                // Get search fields somewhere
                var resultArray = [];
                for (var i = 0; i < searchFields.length; ++i) {
                    var searchField = searchFields[i];
                    var fieldValue = record.get(searchField);
                    resultArray.push(fieldValue);
                }

                // Join by a string that would not normally be searched
                // so that field values 'foo' and 'bar' are not valid when searching 'ooba'
                var result = resultArray.join('**');
                return result;
            }
        }
    ]
});

All you need to do in the store then is:

store.filter('searchField', searchText);

It's not exactly what you are searching for, but it should get the job done.


问:
Javascript force recalculate value of object property
I would like to re-use an "object", however, one of the object's properties values should be recalculated every time the object is accessed.

In my code I have a library which can basically make a list of card views from a data url. This list of card views is added to a page. There are two types of lists: Active Buildings list and Archived Buildings list. Switching between these two lists is done by pressing a button, which triggers the "rerender" function of the repeater shown below.

Archived Buildings should not be clickable. I pass along some configuration options to my library where I handle the relevant parts. However, because of the way I invoke the card view library, the value of the enableClick configuration option is always set to what the state was like at the load of the page.

Example of how the code looks:

```<code>$(function () {
    var buildingsContainer = $('#buildings');
    buildingsContainer.repeater({
        url: function () {
            var activeFilter = buildingFilter.find('.btn-primary').data('status');
            return '/Building/All?status=' + activeFilter;
        },
        renderItem: cardTemplates(buildingsContainer).building({
            activateBuildingUrl: '@(Url.Action("ActivateBuilding", "Building"))/{Id}',
            editUrl: '@(Url.Action("Edit", "Building"))/{Id}',
            deleteBuildingUrl: '@(Url.Action("SoftDeleteBuilding", "Building"))/{Id}',
            enableClick: getActiveFilter() === 'Active'
        })
    })
});

function getActiveFilter() {
    var buildingFilter = $('#buildingFilter');
    return buildingFilter.find('.btn-primary').data('status');
}
</code>```

No matter what the currently pressed button is, enableClick is always set to what it was when the page opened.

To better demonstrate my problem, I have created a JSFiddle:
https://jsfiddle.net/e3xnbxov/

In this JSFiddle, you see I have a options object with a value property. In the button's click listeners I print this value. However, it always remains on Active, even though I switch between Active and Archived. How can I make it so the value of the property is recalculated?

答:
This is just meant to be an addition to lpg's answer.

Another way would be to use a getter function which behaves like lpg's value function but can be used like a normal property:

$(function() {
  var options = {
    // define a getter for the property 'value'
    get value () {
      return $('#container').find('.btn-primary').data('status');
    }
  };
  var container = $('#container');
  container.find('.btn').click(function() {
    container.find('.btn').removeClass('btn-primary').addClass('btn-default');
    $(this).addClass('btn-primary');
    console.log(options.value); // use the property for the property 'value'
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<div id="container">
  <button class="btn btn-sm btn-primary" data-status="Active">Active</button>
  <button class="btn btn-sm btn-default" data-status="Archived">Archived</button>
</div></code>```

Body:
I would like to re-use an "object", however, one of the object's properties values should be recalculated every time the object is accessed.

In my code I have a library which can basically make a list of card views from a data url. This list of card views is added to a page. There are two types of lists: Active Buildings list and Archived Buildings list. Switching between these two lists is done by pressing a button, which triggers the "rerender" function of the repeater shown below.

Archived Buildings should not be clickable. I pass along some configuration options to my library where I handle the relevant parts. However, because of the way I invoke the card view library, the value of the enableClick configuration option is always set to what the state was like at the load of the page.

Example of how the code looks:

$(function () {
    var buildingsContainer = $('#buildings');
    buildingsContainer.repeater({
        url: function () {
            var activeFilter = buildingFilter.find('.btn-primary').data('status');
            return '/Building/All?status=' + activeFilter;
        },
        renderItem: cardTemplates(buildingsContainer).building({
            activateBuildingUrl: '@(Url.Action("ActivateBuilding", "Building"))/{Id}',
            editUrl: '@(Url.Action("Edit", "Building"))/{Id}',
            deleteBuildingUrl: '@(Url.Action("SoftDeleteBuilding", "Building"))/{Id}',
            enableClick: getActiveFilter() === 'Active'
        })
    })
});

function getActiveFilter() {
    var buildingFilter = $('#buildingFilter');
    return buildingFilter.find('.btn-primary').data('status');
}

No matter what the currently pressed button is, enableClick is always set to what it was when the page opened.

To better demonstrate my problem, I have created a JSFiddle:
https://jsfiddle.net/e3xnbxov/

In this JSFiddle, you see I have a options object with a value property. In the button's click listeners I print this value. However, it always remains on Active, even though I switch between Active and Archived. How can I make it so the value of the property is recalculated?

Body:
This is just meant to be an addition to lpg's answer.

Another way would be to use a getter function which behaves like lpg's value function but can be used like a normal property:

$(function() {
  var options = {
    // define a getter for the property 'value'
    get value () {
      return $('#container').find('.btn-primary').data('status');
    }
  };
  var container = $('#container');
  container.find('.btn').click(function() {
    container.find('.btn').removeClass('btn-primary').addClass('btn-default');
    $(this).addClass('btn-primary');
    console.log(options.value); // use the property for the property 'value'
  });
});

<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<div id="container">
  <button class="btn btn-sm btn-primary" data-status="Active">Active</button>
  <button class="btn btn-sm btn-default" data-status="Archived">Archived</button>
</div>


问:
How does this Haskell code work? fmap fmap (,) <*> Just . reverse
Would someone help explain/breakdown the following code:

```<code>λ> fmap fmap (,) <*> Just . reverse $ "stackoverflow"
Just ("stackoverflow","wolfrevokcats")
</code>```

It would be great if someone could walk me through their process of understanding the mechanics of this kind of code.

答:
Let's try to decode this pointless style obfuscation:

```<code>fmap fmap (,) <*> Just . reverse $ "stackoverflow"
</code>```

First step: how this is parsed? Well, $ has low precedence, so it's

```<code>(fmap fmap (,) <*> Just . reverse) $ "stackoverflow"
</code>```

Also, I guess that the infix <*> has a lower precedence than . (one could check using the documentation or :i in GHCi). So, we get

```<code>((fmap fmap (,)) <*> (Just . reverse)) $ "stackoverflow"
</code>```

Let's beta-reduce the $

```<code>((fmap fmap (,)) <*> (Just . reverse)) "stackoverflow"
</code>```

So, the result of <*> is a function. This means that we are working in the (->) a applicative. There, (<*>) = \x y z -> x z (y z) AKA the S combinator from lambda calculus. We can beta-reduce that:

```<code>(\z -> (fmap fmap (,)) z ((Just . reverse) z)) "stackoverflow"
</code>```

More betas, removing parentheses when we can:

```<code>fmap fmap (,) "stackoverflow" ((Just . reverse) "stackoverflow")
</code>```

More simplification:

```<code>fmap fmap (,) "stackoverflow" (Just (reverse "stackoverflow"))
fmap fmap (,) "stackoverflow" (Just "wolfrevokcats")
</code>```

Now, the fmap fmap (,) part. The (,) argument is a function, so this means that the first fmap is working in the (->) a functor. There, fmap = (.). So, it's just obfuscation for

```<code>(.) fmap (,) "stackoverflow" (Just "wolfrevokcats")
(fmap . (,)) "stackoverflow" (Just "wolfrevokcats")
(fmap ((,) "stackoverflow")) (Just "wolfrevokcats")
fmap ((,) "stackoverflow") (Just "wolfrevokcats")
</code>```

Now, the second argument of fmap is of type Maybe String, so the fmap is working in the Maybe functor. There, fmap f (Just x) = Just (f x). We get

```<code>Just (((,) "stackoverflow") "wolfrevokcats")
Just ((,) "stackoverflow" "wolfrevokcats")
Just ("stackoverflow", "wolfrevokcats")
</code>```

Conclusion: pointless code is often pointless. To decode this snippet we had to run the type inferer in our head, recall three specific instances (even if they are pretty standard), and cope with precedence. No one should ever use this style except for deliberate obfuscation. (Surely not as a hiring puzzle!)

Body:
Would someone help explain/breakdown the following code:

λ> fmap fmap (,) <*> Just . reverse $ "stackoverflow"
Just ("stackoverflow","wolfrevokcats")

It would be great if someone could walk me through their process of understanding the mechanics of this kind of code.

Body:
Let's try to decode this pointless style obfuscation:

fmap fmap (,) <*> Just . reverse $ "stackoverflow"

First step: how this is parsed? Well, $ has low precedence, so it's

(fmap fmap (,) <*> Just . reverse) $ "stackoverflow"

Also, I guess that the infix <*> has a lower precedence than . (one could check using the documentation or :i in GHCi). So, we get

((fmap fmap (,)) <*> (Just . reverse)) $ "stackoverflow"

Let's beta-reduce the $

((fmap fmap (,)) <*> (Just . reverse)) "stackoverflow"

So, the result of <*> is a function. This means that we are working in the (->) a applicative. There, (<*>) = \x y z -> x z (y z) AKA the S combinator from lambda calculus. We can beta-reduce that:

(\z -> (fmap fmap (,)) z ((Just . reverse) z)) "stackoverflow"

More betas, removing parentheses when we can:

fmap fmap (,) "stackoverflow" ((Just . reverse) "stackoverflow")

More simplification:

fmap fmap (,) "stackoverflow" (Just (reverse "stackoverflow"))
fmap fmap (,) "stackoverflow" (Just "wolfrevokcats")

Now, the fmap fmap (,) part. The (,) argument is a function, so this means that the first fmap is working in the (->) a functor. There, fmap = (.). So, it's just obfuscation for

(.) fmap (,) "stackoverflow" (Just "wolfrevokcats")
(fmap . (,)) "stackoverflow" (Just "wolfrevokcats")
(fmap ((,) "stackoverflow")) (Just "wolfrevokcats")
fmap ((,) "stackoverflow") (Just "wolfrevokcats")

Now, the second argument of fmap is of type Maybe String, so the fmap is working in the Maybe functor. There, fmap f (Just x) = Just (f x). We get

Just (((,) "stackoverflow") "wolfrevokcats")
Just ((,) "stackoverflow" "wolfrevokcats")
Just ("stackoverflow", "wolfrevokcats")

Conclusion: pointless code is often pointless. To decode this snippet we had to run the type inferer in our head, recall three specific instances (even if they are pretty standard), and cope with precedence. No one should ever use this style except for deliberate obfuscation. (Surely not as a hiring puzzle!)


问:
VBA Outlook Run-time error '438': Object doesn't support this property or method
I am trying to run this to macro to move an email attachment from a folder in my inbox (called toolkit downloads) into a folder on my desktop and rename the attachment.

I get

Run-time error '438': Object doesn't support this property or method

```<code>Sub OSP()

Dim oOutlook As Outlook.Application
Dim oNs As Outlook.NameSpace 'Main Outlook Today
Dim oFldrSb As Outlook.MAPIFolder 'Sub Folder in Outlook Today
Dim oFldrSbSb As Outlook.MAPIFolder 'Sub in Sub Folder
Dim oFldrSbSbsb As Outlook.MAPIFolder 'Sub in Sub in Sub Folder

Dim oMessage As Object
Dim sPathName As String
Dim oAttachment As Outlook.Attachment
Dim Ictr As Integer
Dim iAttachCnt As Integer

sPathName = "H:\Desktop\Toolkit Downloads\" 'My Folder Path where to save attachments

Set oOutlook = New Outlook.Application
Set oNs = oOutlook.GetNamespace("MAPI")
Set oFldrSb = oNs.Folders("Joe.Bloggs@test.co.uk")
Set oFldrSbSb = oFldrSb.Folders("Inbox")
Set oFldrSbSbsb = oFldrSbSb.Folders("Toolkit Downloads")

For Each oMessage In oFldrSbSbsb.Items

    With oMessage.Attachments
        iAttachCnt = .Count

        If iAttachCnt > 0 Then
            For Ictr = 1 To iAttachCnt
                .Item(Ictr).SaveAsFile sPathName _
                & .Item(Ictr).Parent
            Next Ictr
        End If
    End With

DoEvents

Next oMessage

SaveAttachments = True

MsgBox "All Indepol Download files have been moved !!" & vbCrLf & vbCrLf & "It worked... Yahoo"

End Sub
</code>```

答:
First of all, there is no need to create a new Outlook Application instance if you run the VBA macro in Outlook:

```<code>Set oOutlook = New Outlook.Application
</code>```

Instead, use the Application property available in the defualt module.

The SaveAsFile method of the Attachment class accepts a string which stands for the location at which to save the attachment. Make sure a string is passed there.

In general, I'd suggest debugging the code line by line and find which property or method exactly generates an error. You may find the Getting Started with VBA in Outlook 2010 article helpful.

Body:
I am trying to run this to macro to move an email attachment from a folder in my inbox (called toolkit downloads) into a folder on my desktop and rename the attachment.

I get

Run-time error '438': Object doesn't support this property or method

Sub OSP()

Dim oOutlook As Outlook.Application
Dim oNs As Outlook.NameSpace 'Main Outlook Today
Dim oFldrSb As Outlook.MAPIFolder 'Sub Folder in Outlook Today
Dim oFldrSbSb As Outlook.MAPIFolder 'Sub in Sub Folder
Dim oFldrSbSbsb As Outlook.MAPIFolder 'Sub in Sub in Sub Folder

Dim oMessage As Object
Dim sPathName As String
Dim oAttachment As Outlook.Attachment
Dim Ictr As Integer
Dim iAttachCnt As Integer

sPathName = "H:\Desktop\Toolkit Downloads\" 'My Folder Path where to save attachments

Set oOutlook = New Outlook.Application
Set oNs = oOutlook.GetNamespace("MAPI")
Set oFldrSb = oNs.Folders("Joe.Bloggs@test.co.uk")
Set oFldrSbSb = oFldrSb.Folders("Inbox")
Set oFldrSbSbsb = oFldrSbSb.Folders("Toolkit Downloads")

For Each oMessage In oFldrSbSbsb.Items

    With oMessage.Attachments
        iAttachCnt = .Count

        If iAttachCnt > 0 Then
            For Ictr = 1 To iAttachCnt
                .Item(Ictr).SaveAsFile sPathName _
                & .Item(Ictr).Parent
            Next Ictr
        End If
    End With

DoEvents

Next oMessage

SaveAttachments = True

MsgBox "All Indepol Download files have been moved !!" & vbCrLf & vbCrLf & "It worked... Yahoo"

End Sub

Body:
First of all, there is no need to create a new Outlook Application instance if you run the VBA macro in Outlook:

Set oOutlook = New Outlook.Application

Instead, use the Application property available in the defualt module.

The SaveAsFile method of the Attachment class accepts a string which stands for the location at which to save the attachment. Make sure a string is passed there.

In general, I'd suggest debugging the code line by line and find which property or method exactly generates an error. You may find the Getting Started with VBA in Outlook 2010 article helpful.


问:
Manually telling my ListBox's scrollbar where to be
```<code>private void button2_Click(object sender, EventArgs e)
{
    listBox1.AutoScrollOffset.Y = 10;
}
</code>```

I'm trying to manually set the location of my vertical scrollbar using code during runtime. This is what I've tried.

The .Y property says: "Gets or sets the Y coordinate of this point". Why doesn't this compile and give me an exception:

Error 1   Cannot modify the return value
  of
  'System.Windows.Forms.Control.AutoScrollOffset'
  because it is not a variable

答:
This is a crucial difference between value types and reference types.  AutoScrollOffset is of type Point, a struct which makes it a value type.  When you use the property getter, you get a copy of the value.  Setting the Y property only sets the property on the copy.  The C# compiler can recognize this particular usage problem.  But not this one:

```<code>private void button2_Click(object sender, EventArgs e)
{
    var offset = listBox1.AutoScrollOffset;
    offset.Y = 10;     // Compiles, but doesn't work
}
</code>```

To make it work if you have to assign the property with a value of type Point:

```<code>private void button2_Click(object sender, EventArgs e)
{
    listBox1.AutoScrollOffset = new Point(listBox1.AutoScrollOffset.X, 10);
}
</code>```

Which does not actually work to scroll the listbox, it will only affect the position of the control when it is embedded in a scrollable container, like Panel.  Check ScrollControlIntoView for reference.

Assign the TopIndex property instead.

OwnerDisplayName: delete

ContentLicense: CC BY-SA 2.5

Body:
private void button2_Click(object sender, EventArgs e)
{
    listBox1.AutoScrollOffset.Y = 10;
}

I'm trying to manually set the location of my vertical scrollbar using code during runtime. This is what I've tried.

The .Y property says: "Gets or sets the Y coordinate of this point". Why doesn't this compile and give me an exception:

Error 1   Cannot modify the return value
  of
  'System.Windows.Forms.Control.AutoScrollOffset'
  because it is not a variable

Body:
This is a crucial difference between value types and reference types.  AutoScrollOffset is of type Point, a struct which makes it a value type.  When you use the property getter, you get a copy of the value.  Setting the Y property only sets the property on the copy.  The C# compiler can recognize this particular usage problem.  But not this one:

private void button2_Click(object sender, EventArgs e)
{
    var offset = listBox1.AutoScrollOffset;
    offset.Y = 10;     // Compiles, but doesn't work
}

To make it work if you have to assign the property with a value of type Point:

private void button2_Click(object sender, EventArgs e)
{
    listBox1.AutoScrollOffset = new Point(listBox1.AutoScrollOffset.X, 10);
}

Which does not actually work to scroll the listbox, it will only affect the position of the control when it is embedded in a scrollable container, like Panel.  Check ScrollControlIntoView for reference.

Assign the TopIndex property instead.


问:
How can I export AgGrid data in case of infinite row model (infinite scrolling) in react
How can I export AgGrid data in case of infinite row model (infinite scrolling) in react.
For the normal row models it is being done in this way:

this.gridOptions.api.exportDataAsCsv(params);

What about infinite row model case?

答:
Here is the solution that I've implemented.
Grid footers, multiple headers is not considered here.
This code is for simple grid with headers and rows under it.
In case of infinite scrolling and dynamic columns (in some cases columns can be changed).</p>

```<code>var LINE_SEPARATOR = '\r\n';
var COLUMN_SEPARATOR = ',';
var fileName = 'export.csv';

let csvString = '';
let columnsToExport = this.gridOptions.api.columnController.getAllDisplayedColumns();

// adding column headers.
columnsToExport.map((column) => {
  csvString+= column.colDef.headerName;
  csvString+= COLUMN_SEPARATOR;
});
csvString+= LINE_SEPARATOR;

// adding content of data currently loaded in the grid.
this.gridOptions.api.forEachNode( function(node) {
  node.columnController.allDisplayedColumns.map((column) => {
    let cellContent = node.valueService.getValue(column, node);
    csvString+= (cellContent != null) ? cellContent : "";
    csvString+= COLUMN_SEPARATOR;
  });
  csvString+= LINE_SEPARATOR;
});

// for Excel, we need \ufeff at the start
var blobObj = new Blob(["\ufeff", csvString], {
    type: "text/csv;charset=utf-8;"
});
// Internet Explorer
if (window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blobObj, fileName);
}
else {
    // Chrome
    var downloadLink = document.createElement("a");
    downloadLink.href = window.URL.createObjectURL(blobObj);
    downloadLink.download = fileName;
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
}
</code>```

Body:
Here is the solution that I've implemented.
Grid footers, multiple headers is not considered here.
This code is for simple grid with headers and rows under it.
In case of infinite scrolling and dynamic columns (in some cases columns can be changed).

var LINE_SEPARATOR = '\r\n';
var COLUMN_SEPARATOR = ',';
var fileName = 'export.csv';

let csvString = '';
let columnsToExport = this.gridOptions.api.columnController.getAllDisplayedColumns();

// adding column headers.
columnsToExport.map((column) => {
  csvString+= column.colDef.headerName;
  csvString+= COLUMN_SEPARATOR;
});
csvString+= LINE_SEPARATOR;

// adding content of data currently loaded in the grid.
this.gridOptions.api.forEachNode( function(node) {
  node.columnController.allDisplayedColumns.map((column) => {
    let cellContent = node.valueService.getValue(column, node);
    csvString+= (cellContent != null) ? cellContent : "";
    csvString+= COLUMN_SEPARATOR;
  });
  csvString+= LINE_SEPARATOR;
});

// for Excel, we need \ufeff at the start
var blobObj = new Blob(["\ufeff", csvString], {
    type: "text/csv;charset=utf-8;"
});
// Internet Explorer
if (window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blobObj, fileName);
}
else {
    // Chrome
    var downloadLink = document.createElement("a");
    downloadLink.href = window.URL.createObjectURL(blobObj);
    downloadLink.download = fileName;
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
}


问:
Why std::move is not working with std::list
I am unable to compile the below program.

```<code>void toSin(std::list<double>&& list)
{
    std::for_each(list.begin(), list.end(), [](double& x)
    {
        x = sin(x);
    });
}

int main()
{
    std::list<double> list;
    const double pi = 3.141592;
    const double epsilon = 0.0000001;
    for (double x = 0.0; x < 2 * pi + epsilon; x = x + pi / 16)
    {
        list.push_back(x);
    }
    // Start thread
    std::thread th(toSin, std::move(list));
    th.join();
    return 0;
}
</code>```

I get > error C2664: 'void (std::list<double,std::allocator<_Ty>> &&)' : cannot convert argument 1 from 'std::list<double,std::allocator<_Ty>>' to 'std::list<double,std::allocator<_Ty>> &&'

答:
I feel like your compiler is wrong here.  A decayed (copied) value type should be bindable to an rvalue reference.

Anyway take a look at this quote from the documentation

3) Creates new std::thread object and associates it with a thread of execution. The new thread of execution starts executing

```<code>std::invoke(decay_copy(std::forward<Function>(f)), decay_copy(std::forward<Args>(args))...);
</code>```

Basically anything you pass as an argument to the constructor of std::thread will be copied as a function argument to the function.

Also know that your function will work just fine if you make it accept the std::list variable by value instead of by rvalue reference.  See Correct usage of rvalue references as parameters for more

If your intent is to pass a reference to a variable to a thread function, the way I do it usually is with a lambda

```<code>std::list<double> lst;
auto th = std::thread{[&lst]() {
    toSin(lst);
}};
</code>```

But you can also use std::ref for the same effect.  I just personally feel the lambda approach is clearer.

```<code>std::list<double> lst;
auto th = std::thread{toSin, std::ref(lst)};
</code>```

Also as correctly pointed out in the comments, you have a race condition in your code that you should prevent with a mutex, or wait for the thread to finish

```<code>auto th = std::thread{[&lst]() {
    toSin(lst);
}};
th.join();

// then iterate and print out
</code>```

Body:
I am unable to compile the below program.

void toSin(std::list<double>&& list)
{
    std::for_each(list.begin(), list.end(), [](double& x)
    {
        x = sin(x);
    });
}

int main()
{
    std::list<double> list;
    const double pi = 3.141592;
    const double epsilon = 0.0000001;
    for (double x = 0.0; x < 2 * pi + epsilon; x = x + pi / 16)
    {
        list.push_back(x);
    }
    // Start thread
    std::thread th(toSin, std::move(list));
    th.join();
    return 0;
}

I get > error C2664: 'void (std::list<double,std::allocator<_Ty>> &&)' : cannot convert argument 1 from 'std::list<double,std::allocator<_Ty>>' to 'std::list<double,std::allocator<_Ty>> &&'

Body:
I feel like your compiler is wrong here.  A decayed (copied) value type should be bindable to an rvalue reference.

Anyway take a look at this quote from the documentation

3) Creates new std::thread object and associates it with a thread of execution. The new thread of execution starts executing

std::invoke(decay_copy(std::forward<Function>(f)), decay_copy(std::forward<Args>(args))...);

Basically anything you pass as an argument to the constructor of std::thread will be copied as a function argument to the function.

Also know that your function will work just fine if you make it accept the std::list variable by value instead of by rvalue reference.  See Correct usage of rvalue references as parameters for more

If your intent is to pass a reference to a variable to a thread function, the way I do it usually is with a lambda

std::list<double> lst;
auto th = std::thread{[&lst]() {
    toSin(lst);
}};

But you can also use std::ref for the same effect.  I just personally feel the lambda approach is clearer.

std::list<double> lst;
auto th = std::thread{toSin, std::ref(lst)};

Also as correctly pointed out in the comments, you have a race condition in your code that you should prevent with a mutex, or wait for the thread to finish

auto th = std::thread{[&lst]() {
    toSin(lst);
}};
th.join();

// then iterate and print out


问:
How to check foreman collecting facts from all hosts
Want to write automation script to ensure foreman collecting facts from all nodes

How to ensure foreman having facts from all nodes ?

答:
A fact is a key/value data pair that represents some aspect of node state, such as its IP address, uptime, operating system, or whether it's a virtual machine.

1. Manual process are:

a. Login to foreman UI, click Monitor->Facts

b. run facter -p on hosts

2. Automation:
   I have written below script to check facts from each hosts

```<code>#!/usr/bin/python
import requests
import json

foreman_url = "https://foreman_ip/api/hosts"
username = "admin"
password = "changeme"
node = "node1.puppet.com"
headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
}
def retrive_hostid():
  host_id = requests.get(foreman_url, headers=headers, verify=False, auth=(username, password))
  hostobj = json.loads(host_id.content)
  for s in hostobj:
     print s['host']['name']
     host_name = s['host']['name']
     url = foreman_url  + host_name + '/facts'  # check facts from each hosts
     print url
     response = requests.get(url, headers=headers, verify=False, auth=('admin', 'changeme'))
     #print response
     respobj = json.loads(response.content)
     print respobj['total'] # display total number of facts found

retrive_hostid()
</code>```

Body:
A fact is a key/value data pair that represents some aspect of node state, such as its IP address, uptime, operating system, or whether it's a virtual machine.

1. Manual process are:

a. Login to foreman UI, click Monitor->Facts

b. run facter -p on hosts

2. Automation:
   I have written below script to check facts from each hosts

#!/usr/bin/python
import requests
import json

foreman_url = "https://foreman_ip/api/hosts"
username = "admin"
password = "changeme"
node = "node1.puppet.com"
headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
}
def retrive_hostid():
  host_id = requests.get(foreman_url, headers=headers, verify=False, auth=(username, password))
  hostobj = json.loads(host_id.content)
  for s in hostobj:
     print s['host']['name']
     host_name = s['host']['name']
     url = foreman_url  + host_name + '/facts'  # check facts from each hosts
     print url
     response = requests.get(url, headers=headers, verify=False, auth=('admin', 'changeme'))
     #print response
     respobj = json.loads(response.content)
     print respobj['total'] # display total number of facts found

retrive_hostid()


问:
Detect undefined symbols in C header file
Suposse I coded a C library which provides a bunch of "public" functions, declared in a mylib.h header file. Those functions are supposedly implemented in (say) a mylib.c file which is compiled to a (say) static lib mylib.c -> mylib.o -> mylib.a.

Is there some way to detect that I forgot to provide the implementation of some declared function in mylib.h? (Yes, I know about unit testing, good practices, etc - and, yes, I understand the meaning of a plain function declaration in C).

Suppose mylib.h declares a void func1(); and this function was not coded in the provided library. This will trigger an error only  if the linker needs to use that function. Otherwise, it will compile ok and even without warnings - AFAIK. Is there a way (perhaps compiler dependent) to trigger a warning for declared but not implemented functions, or there is any other way to deal with this issue?

BTW: nm -u lists not all undefined declared functions, but only those "used" by the library, i.e., those functions that will trigger an error in the linking phase if not declared somewhere. (Which makes sense, the library object file does not know about header files, of course.)

答:
You could grep for signatures of exported function in both .h and .c, and compare the lists.
Use wc -l for counting matches, Both numbers should be equal.

Another thought, just came to my mind. It is ihmo not possible to handle it using compiler. it is not always the case, that function declares in mylib.h is implemented in mylib.c


问:
Ignore specific database while replication in mongodb replicaset
I am running a replicaset of three members, i want to ignore a specific database while replicating to secondaries.

Is is possible for mongodb, please help!!

答: No, its not possible to opt out a database from being replicated in a Mongo replication setup.</p>


问:
How to efficiently find last key and value in GTree
I need to develop a set of functions to extend glib2 GTree with:

find first element

find last

find nearest (floor, ceil, greatest less than, least greater than)

Finding first is easy. You simply stop the g_tree_foreach() calback after first. But how to find the last element without traversing the whole tree?

I thought I could use g_tree_search() with a callback that keeps returning a positive value until found, but how do I know I'm currently on the last element?

```<code>#include <stdio.h>
#include <sys/types.h>
#include <string.h>

#include <glib.h>

static
gint compare_int(gconstpointer p1, gconstpointer p2) {
    int i1 = GPOINTER_TO_INT(p1);
    int i2 = GPOINTER_TO_INT(p2);
    //printf("%d %d\n", i1, i2);
    return i1 == i2 ? 0 : i1 > i2 ? 1 : -1;
}

static
gboolean traverse(gpointer key, gpointer value, gpointer data) {
    //int ikey = GPOINTER_TO_INT(key);
    const char *sval = (const char *)value;
    printf("%s\n", sval);
    return FALSE;
}

static
gint find_last(gconstpointer p, gpointer user_data) {
    return 1;
}

static inline const char *NULS(const char *s) {
    return s ? s : "NULL";
}

int main(int argc, char *argv[]) {
    GTree *tree = g_tree_new(compare_int);
    g_tree_insert(tree, GINT_TO_POINTER(10), "ten");
    g_tree_insert(tree, GINT_TO_POINTER(-99), "minus ninety-nine");
    g_tree_insert(tree, GINT_TO_POINTER(8), "eight");
    g_tree_foreach(tree, traverse, NULL);
    printf("=======\n%s\n", NULS((const char*)g_tree_search(tree, (GCompareFunc)find_last, NULL)));
    return 0;
}
</code>```

答:
I didn't want to fully implement my own tree, because I wanted to perform advanced search on GTree instances received from 3rd-party code.

Instead I thought that Glib authors would hardly change their internal structures these days and that I could use their fields directly.

The result is the extended version of the internal function g_tree_find_node() from gtree.c. I added two parameters to control whether I want first, last or nearest node. The algorithm for nearest nodes differs from java's TreeMap, because our node doesn't have a pointer to its parent. Full code with the unit test is here: gtreeex.c.

```<code>typedef enum {
    FIND_EXACT = 0,
    FIND_FLOOR = 0x2,
    FIND_CEIL  = 0x20,
    FIND_LOWER = (FIND_FLOOR + 1),
    FIND_HIGHER = (FIND_CEIL + 1)
} find_mode;

static GTreeNode *
g_tree_find_node_ex (GTree        *tree,
                  gconstpointer key,
                  GCompareDataFunc key_compare,
                  find_mode mode
                  )
{
    GTreeNode *node;
    gint cmp;
    GTreeNode *last_lesser_node = NULL;
    GTreeNode *last_greater_node = NULL;

    node = tree->root;
    if (!node)
        return NULL;

    while (1)
        {
            cmp = key_compare (key, node->key, tree->key_compare_data);
            if (cmp == 0) {
                if (mode == FIND_LOWER) {
                    cmp = -1;
                } else if (mode == FIND_HIGHER) {
                    cmp = 1;
                } else {
                    return node;
                }
            }

            if (cmp < 0)
                {
                    if (!node->left_child) {
                        if ( (mode & FIND_FLOOR) ) {
                            return last_lesser_node; /* can be null */
                        }
                        if ( (mode & FIND_CEIL) ) {
                            return node;
                        }
                        return NULL;
                    }

                    last_greater_node = node;
                    node = node->left;
                }
            else
                {
                    if (!node->right_child) {
                        if ( (mode & FIND_CEIL) ) {
                            return last_greater_node; /* can be null */
                        }
                        if ( (mode & FIND_FLOOR) ) {
                            return node;
                        }
                        return NULL;
                    }

                    last_lesser_node = node;
                    node = node->right;
                }
        }
}
</code>```

For better performance it's possible to use preprocessor macros instead of the two new parameters, replace if with #if and include the bits header multiple times.

Body:
I need to develop a set of functions to extend glib2 GTree with:

find first element

find last

find nearest (floor, ceil, greatest less than, least greater than)

Finding first is easy. You simply stop the g_tree_foreach() calback after first. But how to find the last element without traversing the whole tree?

I thought I could use g_tree_search() with a callback that keeps returning a positive value until found, but how do I know I'm currently on the last element?

#include <stdio.h>
#include <sys/types.h>
#include <string.h>

#include <glib.h>

static
gint compare_int(gconstpointer p1, gconstpointer p2) {
    int i1 = GPOINTER_TO_INT(p1);
    int i2 = GPOINTER_TO_INT(p2);
    //printf("%d %d\n", i1, i2);
    return i1 == i2 ? 0 : i1 > i2 ? 1 : -1;
}

static
gboolean traverse(gpointer key, gpointer value, gpointer data) {
    //int ikey = GPOINTER_TO_INT(key);
    const char *sval = (const char *)value;
    printf("%s\n", sval);
    return FALSE;
}

static
gint find_last(gconstpointer p, gpointer user_data) {
    return 1;
}

static inline const char *NULS(const char *s) {
    return s ? s : "NULL";
}

int main(int argc, char *argv[]) {
    GTree *tree = g_tree_new(compare_int);
    g_tree_insert(tree, GINT_TO_POINTER(10), "ten");
    g_tree_insert(tree, GINT_TO_POINTER(-99), "minus ninety-nine");
    g_tree_insert(tree, GINT_TO_POINTER(8), "eight");
    g_tree_foreach(tree, traverse, NULL);
    printf("=======\n%s\n", NULS((const char*)g_tree_search(tree, (GCompareFunc)find_last, NULL)));
    return 0;
}

Body:
I didn't want to fully implement my own tree, because I wanted to perform advanced search on GTree instances received from 3rd-party code.

Instead I thought that Glib authors would hardly change their internal structures these days and that I could use their fields directly.

The result is the extended version of the internal function g_tree_find_node() from gtree.c. I added two parameters to control whether I want first, last or nearest node. The algorithm for nearest nodes differs from java's TreeMap, because our node doesn't have a pointer to its parent. Full code with the unit test is here: gtreeex.c.

typedef enum {
    FIND_EXACT = 0,
    FIND_FLOOR = 0x2,
    FIND_CEIL  = 0x20,
    FIND_LOWER = (FIND_FLOOR + 1),
    FIND_HIGHER = (FIND_CEIL + 1)
} find_mode;

static GTreeNode *
g_tree_find_node_ex (GTree        *tree,
                  gconstpointer key,
                  GCompareDataFunc key_compare,
                  find_mode mode
                  )
{
    GTreeNode *node;
    gint cmp;
    GTreeNode *last_lesser_node = NULL;
    GTreeNode *last_greater_node = NULL;

    node = tree->root;
    if (!node)
        return NULL;

    while (1)
        {
            cmp = key_compare (key, node->key, tree->key_compare_data);
            if (cmp == 0) {
                if (mode == FIND_LOWER) {
                    cmp = -1;
                } else if (mode == FIND_HIGHER) {
                    cmp = 1;
                } else {
                    return node;
                }
            }

            if (cmp < 0)
                {
                    if (!node->left_child) {
                        if ( (mode & FIND_FLOOR) ) {
                            return last_lesser_node; /* can be null */
                        }
                        if ( (mode & FIND_CEIL) ) {
                            return node;
                        }
                        return NULL;
                    }

                    last_greater_node = node;
                    node = node->left;
                }
            else
                {
                    if (!node->right_child) {
                        if ( (mode & FIND_CEIL) ) {
                            return last_greater_node; /* can be null */
                        }
                        if ( (mode & FIND_FLOOR) ) {
                            return node;
                        }
                        return NULL;
                    }

                    last_lesser_node = node;
                    node = node->right;
                }
        }
}

For better performance it's possible to use preprocessor macros instead of the two new parameters, replace if with #if and include the bits header multiple times.


问:
javascript absolute beginner = stuck on function returning "undefined"
Just for exercise, I'm trying to print out this pattern:

Here's the code so far:

  var even = " #";
  var odd = "# ";
  var size = 4;
  var rowCount = 1;
  var lineLength = 1;
  function writeOdd(size){
   while(lineLength<=size){
    document.write(odd)
    if(lineLength === size){
    document.write("
")
    }
    lineLength++;
   }
  }
  function writeEven(size){
   while(lineLength<=size){
    document.write(even)
    if(lineLength === size){
    document.write("
")
    }
    lineLength++;
   }
  }
   if(rowCount <= size && rowCount % 2 !== 0) {document.write(writeEven(size));}
      else if(rowCount <= size && rowCount % 2 === 0){document.write(writeOdd(size));}
  rowCount++;```

I'm stuck - first line prints out ok, second gives "undefined" and that's it.

答:
Your functions call document.write, so no need to use it when calling writeEven and writeOdd, also you're missing a while loop for incrementing rows, and lineLength should be initialzed in each function

var even = " #";
  var odd = "# ";
  var size = 4;
  var rowCount = 1;

  function writeOdd(size){
  var lineLength = 1;
   while(lineLength<=size){
    document.write(odd)
    if(lineLength === size){
    document.write("
")
    }
    lineLength++;
   }
  }
  function writeEven(size){
  var lineLength = 1;
   while(lineLength<=size){
    document.write(even)
    if(lineLength === size){
    document.write("
")
    }
    lineLength++;
   }
  }
  while (rowCount <= 5) {
   if(rowCount <= size && rowCount % 2 !== 0) {writeEven(size);}
      else if(rowCount <= size && rowCount % 2 === 0){writeOdd(size);}
  rowCount++;
}```

Body:
Just for exercise, I'm trying to print out this pattern:

Here's the code so far:

  var even = " #";
  var odd = "# ";
  var size = 4;
  var rowCount = 1;
  var lineLength = 1;
  function writeOdd(size){
   while(lineLength<=size){
    document.write(odd)
    if(lineLength === size){
    document.write("
")
    }
    lineLength++;
   }
  }
  function writeEven(size){
   while(lineLength<=size){
    document.write(even)
    if(lineLength === size){
    document.write("
")
    }
    lineLength++;
   }
  }
   if(rowCount <= size && rowCount % 2 !== 0) {document.write(writeEven(size));}
      else if(rowCount <= size && rowCount % 2 === 0){document.write(writeOdd(size));}
  rowCount++;

I'm stuck - first line prints out ok, second gives "undefined" and that's it.

Body:
Your functions call document.write, so no need to use it when calling writeEven and writeOdd, also you're missing a while loop for incrementing rows, and lineLength should be initialzed in each function

var even = "&nbsp;#";
  var odd = "#&nbsp;";
  var size = 4;
  var rowCount = 1;

  function writeOdd(size){
  var lineLength = 1;
   while(lineLength<=size){
    document.write(odd)
    if(lineLength === size){
    document.write("<br>")
    }
    lineLength++;
   }
  }
  function writeEven(size){
  var lineLength = 1;
   while(lineLength<=size){
    document.write(even)
    if(lineLength === size){
    document.write("<br>")
    }
    lineLength++;
   }
  }
  while (rowCount <= 5) {
   if(rowCount <= size && rowCount % 2 !== 0) {writeEven(size);}
      else if(rowCount <= size && rowCount % 2 === 0){writeOdd(size);}
  rowCount++;
}


问:
How to draw graph stick with rotated rectangle properly in matplotlib?
I am trying to figure out how to draw the following properly.

Lets say I have two nodes, i.e. 2 points in R^2, namely src=(x1,y1) and dst=(x2,y2).

I want to draw an edge/line between them, but starting with a box.

This is an example I created with Tikz:

src and dest are the centers of these nodes. Note that they can also be on different heights. The problem is when I try to build the box (using patches.Rectangle), I have to rotate it and then it changes its size.

Thanks in advance

答:
If you're happy to use a filled rectange for the graph with a rotated rectangle as stick, this can be emulated by a simple line, which is as thick as a scatter point at the graph edges.

```<code>import matplotlib.pyplot as plt
import numpy as np

def plot_spec_line(src, dst, length=0.3, srctext="v", dsttext="w",
                   ax=None, color="k", textcolor="k"):
    if not ax: ax=plt.gca()
    lend=src+(dst-src)*length
    ax.plot([src[0],lend[0]], [src[1],lend[1]], lw=24,solid_capstyle="butt", zorder=1, color=color )
    ax.plot([src[0],dst[0]], [src[1],dst[1]], lw=2,solid_capstyle="butt", zorder=0, color=color)
    ax.scatter([src[0],dst[0]], [src[1],dst[1]], s=24**2, marker="o", lw=2, edgecolors=color, c="w", zorder=2)
    ax.text(src[0],src[1], srctext, fontsize=12, ha="center", va="center", zorder=3, color=textcolor)
    ax.text(dst[0],dst[1], dsttext, fontsize=12, ha="center", va="center", zorder=3, color=textcolor)

s = np.array([1,1])
d = np.array([3,2])
plot_spec_line(s, d, length=0.3, srctext="v", dsttext="w")

s = np.array([1.5,0.9])
d = np.array([2.8,1.2])
plot_spec_line(s, d, length=0.2, srctext="a", dsttext="b", color="gray")

s = np.array([1,2])
d = np.array([2,1.9])
plot_spec_line(s, d, length=0.7, srctext="X", dsttext="Y", textcolor="limegreen", color="limegreen")

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

To obtain a rectangle, which can be filled or not and more imporatantly, has an edge, you can use a Rectangle.
You can rotate a rectangle by setting an appropriate transform.
It then makes sense to use a plot of equal aspect ratio, such that the Rectangle and circles are not skewed.

```<code>import matplotlib.pyplot as plt
import matplotlib.transforms
import numpy as np

def plot_spec_line(src, dst, length=0.3, radius=0.1, srctext="v", dsttext="w",
                   ax=None, color="k", textcolor="k", reccolor="w", lw=1 ):
    if not ax: ax=plt.gca()
    lend=np.sqrt(np.sum(((dst-src)*length)**2))
    s = dst-src
    angle = np.rad2deg(np.arctan2(s[1],s[0]))
    delta = np.array([0,radius])
    tr = matplotlib.transforms.Affine2D().rotate_deg_around(src[0],src[1], angle)
    t = tr + ax.transData
    rec = plt.Rectangle(src-delta, width=lend, height=radius*2, ec=color,facecolor=reccolor, transform=t, linewidth=lw)
    ax.add_patch(rec)
    ax.plot([src[0],dst[0]], [src[1],dst[1]], lw=lw,solid_capstyle="butt", zorder=0, color=color)
    circ1= plt.Circle(src, radius=radius, fill=True, facecolor="w", edgecolor=color, lw=lw)
    circ2= plt.Circle(dst, radius=radius, fill=True, facecolor="w", edgecolor=color, lw=lw)
    ax.add_patch(circ1)
    ax.add_patch(circ2)
    ax.text(src[0],src[1], srctext, fontsize=12, ha="center", va="center", zorder=3, color=textcolor)
    ax.text(dst[0],dst[1], dsttext, fontsize=12, ha="center", va="center", zorder=3, color=textcolor)

s = np.array([1,1])
d = np.array([3,2])
plot_spec_line(s, d, length=0.3, srctext="v", dsttext="w", radius=0.06,
               reccolor="plum", )

s = np.array([1.5,0.9])
d = np.array([2.8,1.2])
plot_spec_line(s, d, length=0.2, srctext="a", dsttext="b", color="gray", lw=2.5)

s = np.array([1,2])
d = np.array([2,1.9])
plot_spec_line(s, d, length=0.7, srctext="X", dsttext="Y", textcolor="limegreen",
               reccolor="palegreen", color="limegreen")

plt.margins(0.2)
plt.gca().set_aspect("equal")
plt.show()
</code>```

Body:
If you're happy to use a filled rectange for the graph with a rotated rectangle as stick, this can be emulated by a simple line, which is as thick as a scatter point at the graph edges.

import matplotlib.pyplot as plt
import numpy as np

def plot_spec_line(src, dst, length=0.3, srctext="v", dsttext="w",
                   ax=None, color="k", textcolor="k"):
    if not ax: ax=plt.gca()
    lend=src+(dst-src)*length
    ax.plot([src[0],lend[0]], [src[1],lend[1]], lw=24,solid_capstyle="butt", zorder=1, color=color )
    ax.plot([src[0],dst[0]], [src[1],dst[1]], lw=2,solid_capstyle="butt", zorder=0, color=color)
    ax.scatter([src[0],dst[0]], [src[1],dst[1]], s=24**2, marker="o", lw=2, edgecolors=color, c="w", zorder=2)
    ax.text(src[0],src[1], srctext, fontsize=12, ha="center", va="center", zorder=3, color=textcolor)
    ax.text(dst[0],dst[1], dsttext, fontsize=12, ha="center", va="center", zorder=3, color=textcolor)

s = np.array([1,1])
d = np.array([3,2])
plot_spec_line(s, d, length=0.3, srctext="v", dsttext="w")

s = np.array([1.5,0.9])
d = np.array([2.8,1.2])
plot_spec_line(s, d, length=0.2, srctext="a", dsttext="b", color="gray")

s = np.array([1,2])
d = np.array([2,1.9])
plot_spec_line(s, d, length=0.7, srctext="X", dsttext="Y", textcolor="limegreen", color="limegreen")

plt.margins(0.2)
plt.show()

To obtain a rectangle, which can be filled or not and more imporatantly, has an edge, you can use a Rectangle.
You can rotate a rectangle by setting an appropriate transform.
It then makes sense to use a plot of equal aspect ratio, such that the Rectangle and circles are not skewed.

import matplotlib.pyplot as plt
import matplotlib.transforms
import numpy as np

def plot_spec_line(src, dst, length=0.3, radius=0.1, srctext="v", dsttext="w",
                   ax=None, color="k", textcolor="k", reccolor="w", lw=1 ):
    if not ax: ax=plt.gca()
    lend=np.sqrt(np.sum(((dst-src)*length)**2))
    s = dst-src
    angle = np.rad2deg(np.arctan2(s[1],s[0]))
    delta = np.array([0,radius])
    tr = matplotlib.transforms.Affine2D().rotate_deg_around(src[0],src[1], angle)
    t = tr + ax.transData
    rec = plt.Rectangle(src-delta, width=lend, height=radius*2, ec=color,facecolor=reccolor, transform=t, linewidth=lw)
    ax.add_patch(rec)
    ax.plot([src[0],dst[0]], [src[1],dst[1]], lw=lw,solid_capstyle="butt", zorder=0, color=color)
    circ1= plt.Circle(src, radius=radius, fill=True, facecolor="w", edgecolor=color, lw=lw)
    circ2= plt.Circle(dst, radius=radius, fill=True, facecolor="w", edgecolor=color, lw=lw)
    ax.add_patch(circ1)
    ax.add_patch(circ2)
    ax.text(src[0],src[1], srctext, fontsize=12, ha="center", va="center", zorder=3, color=textcolor)
    ax.text(dst[0],dst[1], dsttext, fontsize=12, ha="center", va="center", zorder=3, color=textcolor)

s = np.array([1,1])
d = np.array([3,2])
plot_spec_line(s, d, length=0.3, srctext="v", dsttext="w", radius=0.06,
               reccolor="plum", )

s = np.array([1.5,0.9])
d = np.array([2.8,1.2])
plot_spec_line(s, d, length=0.2, srctext="a", dsttext="b", color="gray", lw=2.5)

s = np.array([1,2])
d = np.array([2,1.9])
plot_spec_line(s, d, length=0.7, srctext="X", dsttext="Y", textcolor="limegreen",
               reccolor="palegreen", color="limegreen")

plt.margins(0.2)
plt.gca().set_aspect("equal")
plt.show()


问:
How to install old SDK platform
I want to test against Android 1.3 platform instead of latest 2.2.

Here is how my Android SDK and AVD Manager look likes.

However, I was expecting (screen from http://developer.android.com/sdk/installing.html#components), so that I can select old platform.

Is there anything I had missed out?

答: Also - on the bottom of the first screen between "Delete Add-on Site..." and "Refresh" uncheck the "Display updates only" check box.</p>

Title: How to install old SDK platform


问:
Uncaught PDOException: SQLSTATE[HY093] with UPDATE
I'm trying to create a function to change a users password:

```<code>    public function ChangePassword($password)
    {
        $query = $this->db->prepare("UPDATE users SET password = :password WHERE id=:user_id");
        $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 10]);
        $query->bindParam("password", $hash, PDO::PARAM_STR);
        $query->execute();
        return true;
    }
</code>```

but it shows me the "Uncaught PDOException: SQLSTATE[HY093]". When I use

```<code>$query = $this->db->prepare("INSERT INTO users(password) VALUES (:password)");
</code>```

instead of

```<code>$query = $this->db->prepare("UPDATE users SET password = :password WHERE id=:user_id");
</code>```

it works, means I get an additional row with a password entry. I didn't find a documentation showing the proper use of UPDATE.

答:
You must provide a bound value for each parameter placeholder in your SQL string. No more, no fewer.

So you need something like this:

```<code>    $query->bindParam("user_id", $userid);
</code>```

But I notice your function doesn't have any $userid in it. You're going to need that.

Body:
I'm trying to create a function to change a users password:

    public function ChangePassword($password)
    {
        $query = $this->db->prepare("UPDATE users SET password = :password WHERE id=:user_id");
        $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 10]);
        $query->bindParam("password", $hash, PDO::PARAM_STR);
        $query->execute();
        return true;
    }

but it shows me the "Uncaught PDOException: SQLSTATE[HY093]". When I use

$query = $this->db->prepare("INSERT INTO users(password) VALUES (:password)");

instead of

$query = $this->db->prepare("UPDATE users SET password = :password WHERE id=:user_id");

it works, means I get an additional row with a password entry. I didn't find a documentation showing the proper use of UPDATE.

Body:
You must provide a bound value for each parameter placeholder in your SQL string. No more, no fewer.

So you need something like this:

    $query->bindParam("user_id", $userid);

But I notice your function doesn't have any $userid in it. You're going to need that.


答:
Do Like This:

```<code> public function ChangePassword($password,$user_id)
    {
        $query = $this->db->prepare("UPDATE users SET password = :password WHERE id=:user_id");
        $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 10]);
        $query->bindParam("password", $hash, PDO::PARAM_STR);
        $query->bindParam("user_id",$user_id);
        $query->execute();
        return true;
    }
</code>```

NOTE:  bindParam the user_id and also pass the user_id in the parameter Like this :  ChangePassword($password,$user_id)

Title: Uncaught PDOException: SQLSTATE[HY093] with UPDATE

Body:
Do Like This:

 public function ChangePassword($password,$user_id)
    {
        $query = $this->db->prepare("UPDATE users SET password = :password WHERE id=:user_id");
        $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 10]);
        $query->bindParam("password", $hash, PDO::PARAM_STR);
        $query->bindParam("user_id",$user_id);
        $query->execute();
        return true;
    }

NOTE:  bindParam the user_id and also pass the user_id in the parameter Like this :  ChangePassword($password,$user_id)


问:
static member being accessed by instance reference
I have a call to a function and the background of that call is yellow and it says "static member being accessed by instance reference," but it works perfectly without errors.

Should I have to solve that somehow or is it okay?

Here is a code sample:

```<code>class A {
    static int x = 2;
    ...
}
</code>```

Instantiation is some other file:

```<code>A a = new A();
a.x;
</code>```

答:
This warning happens when you have something like this:

```<code>class A {
 static int x = 2;
}

...

A a = new A();
a.x; // accessing static member by instance
</code>```

You should access the static member x via the class (or interface) instead:

```<code>A a = new A();
A.x;
</code>```

Static members belong to the class, not to a particular instance.

ContentLicense: CC BY-SA 4.0

Body:
I have a call to a function and the background of that call is yellow and it says "static member being accessed by instance reference," but it works perfectly without errors.

Should I have to solve that somehow or is it okay?

Here is a code sample:

class A {
    static int x = 2;
    ...
}

Instantiation is some other file:

A a = new A();
a.x;

Body:
This warning happens when you have something like this:

class A {
 static int x = 2;
}

...

A a = new A();
a.x; // accessing static member by instance

You should access the static member x via the class (or interface) instead:

A a = new A();
A.x;

Static members belong to the class, not to a particular instance.


问:
COM Integration from ALBPM - Cannot find IDispatch for '{00020906-0000-0000-C000-000000000046}'
I am trying to use the Office COM components in order to create Word and Excel documents. Unfortunately I can not achieve this because I am getting an error.

Cannot find IDispatch for
  '{00020906-0000-0000-C000-000000000046}'
  in module
  '{00020905-0000-0000-C000-000000000046}',
  v8.3

I tried reinstalling Office, my application (ALBPM) and my interface (combsvc) but it is not working.

I want to know how can I install IDispatch, or how can I know if it is installed in the correct module. Some times the error says:

Cannot find IDispatch for
  '{000209FF-0000-0000-C000-000000000046}'
  ... instead of
  00020906-0000-0000-C000-000000000046

The code I'm using generate these errors is:

```<code>wordAppl.visible = false
wordDocs = wordAppl.documents

contratoTemplate = "C:\\albpmFiles\\mandatory\\aTemplate.doc"
// .doc template
convenioTemplate = "C:\\albpmFiles\\mandatory\\ConvenioModificatorio.doc"
// .doc template
saveContrato = "C:\\albpmFiles\\temp\\"
// where to save.
saveConvenio = "C:\\albpmFiles\\temp\\"

contratoName = "NewContact.doc"
wordDoc = open(wordDocs, fileName : contratoTemplate)
bookmark = item(wordDoc.bookmarks, index : "atrDescripcion")

insertAfter bookmark.range
using text = instSolicitud.atrDescripcion
bookmark = item(wordDoc.bookmarks, index : "atrObjProveedor_atrNombre")
insertAfter bookmark.range
using text = instSolicitud.atrObjProveedor.atrNombre
bookmark = item(wordDoc.bookmarks, index : "atrObjProveedor_atrDireccion")
insertAfter bookmark.range
using text = instSolicitud.atrObjProveedor.atrDireccion
filename = saveContrato + contratoName

end

// Extras - Fin
saveAs wordDoc
using fileName = filename
</code>```

Any information you have about the IDispatch, or these registry entries, well be very appreciated, even if you can tell me where to find more info about this.

Thanks a lot.
Daniel.

答:
The code I am using is this, but I can not even see the first log, so I assume there´s an error with the conection, not with the code</p>

```<code>wordAppl.visible = false
wordDocs = wordAppl.documents

contratoTemplate = "C:\\albpmFiles\\mandatory\\aTemplate.doc"

// .doc template
convenioTemplate = "C:\\albpmFiles\\mandatory\\ConvenioModificatorio.doc"

// .doc template
saveContrato = "C:\\albpmFiles\\temp\\"

// where to save.
saveConvenio = "C:\\albpmFiles\\temp\\"

contratoName = "NewContact.doc"

wordDoc = open(wordDocs, fileName : contratoTemplate)

bookmark = item(wordDoc.bookmarks, index : "atrDescripcion")

insertAfter bookmark.range
using text = instSolicitud.atrDescripcion

bookmark = item(wordDoc.bookmarks, index : "atrObjProveedor_atrNombre")

insertAfter bookmark.range
using text = instSolicitud.atrObjProveedor.atrNombre

bookmark = item(wordDoc.bookmarks, index : "atrObjProveedor_atrDireccion")

insertAfter bookmark.range
using text = instSolicitud.atrObjProveedor.atrDireccion

filename = saveContrato + contratoName

end

// Extras - Fin
saveAs wordDoc
using fileName = filename
</code>```

OwnerDisplayName: Daniel M

LastEditorDisplayName: warren

Body:
I am trying to use the Office COM components in order to create Word and Excel documents. Unfortunately I can not achieve this because I am getting an error.

Cannot find IDispatch for
  '{00020906-0000-0000-C000-000000000046}'
  in module
  '{00020905-0000-0000-C000-000000000046}',
  v8.3

I tried reinstalling Office, my application (ALBPM) and my interface (combsvc) but it is not working.

I want to know how can I install IDispatch, or how can I know if it is installed in the correct module. Some times the error says:

Cannot find IDispatch for
  '{000209FF-0000-0000-C000-000000000046}'
  ... instead of
  00020906-0000-0000-C000-000000000046

The code I'm using generate these errors is:

wordAppl.visible = false
wordDocs = wordAppl.documents

contratoTemplate = "C:\\albpmFiles\\mandatory\\aTemplate.doc"
// .doc template
convenioTemplate = "C:\\albpmFiles\\mandatory\\ConvenioModificatorio.doc"
// .doc template
saveContrato = "C:\\albpmFiles\\temp\\"
// where to save.
saveConvenio = "C:\\albpmFiles\\temp\\"

contratoName = "NewContact.doc"
wordDoc = open(wordDocs, fileName : contratoTemplate)
bookmark = item(wordDoc.bookmarks, index : "atrDescripcion")

insertAfter bookmark.range
using text = instSolicitud.atrDescripcion
bookmark = item(wordDoc.bookmarks, index : "atrObjProveedor_atrNombre")
insertAfter bookmark.range
using text = instSolicitud.atrObjProveedor.atrNombre
bookmark = item(wordDoc.bookmarks, index : "atrObjProveedor_atrDireccion")
insertAfter bookmark.range
using text = instSolicitud.atrObjProveedor.atrDireccion
filename = saveContrato + contratoName

end

// Extras - Fin
saveAs wordDoc
using fileName = filename

Any information you have about the IDispatch, or these registry entries, well be very appreciated, even if you can tell me where to find more info about this.

Thanks a lot.
Daniel.

Body:
The code I am using is this, but I can not even see the first log, so I assume there´s an error with the conection, not with the code

wordAppl.visible = false
wordDocs = wordAppl.documents

contratoTemplate = "C:\\albpmFiles\\mandatory\\aTemplate.doc"

// .doc template
convenioTemplate = "C:\\albpmFiles\\mandatory\\ConvenioModificatorio.doc"

// .doc template
saveContrato = "C:\\albpmFiles\\temp\\"

// where to save.
saveConvenio = "C:\\albpmFiles\\temp\\"

contratoName = "NewContact.doc"

wordDoc = open(wordDocs, fileName : contratoTemplate)

bookmark = item(wordDoc.bookmarks, index : "atrDescripcion")

insertAfter bookmark.range
using text = instSolicitud.atrDescripcion

bookmark = item(wordDoc.bookmarks, index : "atrObjProveedor_atrNombre")

insertAfter bookmark.range
using text = instSolicitud.atrObjProveedor.atrNombre

bookmark = item(wordDoc.bookmarks, index : "atrObjProveedor_atrDireccion")

insertAfter bookmark.range
using text = instSolicitud.atrObjProveedor.atrDireccion

filename = saveContrato + contratoName

end

// Extras - Fin
saveAs wordDoc
using fileName = filename

LastEditorDisplayName: Daniel M


问:
What does Composable exactly mean?
I'm currently reading through EF4 Recipes, the book, by Larry Tenny and Zeeshan Hirani. I came across the word "Composable" a lot, during reading the book, & had a general sense about what the word means, but no exact definition though.

I was wondering what the exact definition is, & what makes (say for eg) a function "Composable" or not?

For more context, Check this FAQ (Look for the word "Composable" on the page, there's only one) which is pretty similar to the same context on the book..

Here's is a paragraph where I feel confused about what it means (from the book page 397):

The parameters for model defined
  functions don’t show direction. There
  are no ‘out’ parameters, only implied
  ‘in’ parameters. The reason for this
  is that model defined functions are
  composable and can be used as part of
  LINQ queries. This prevents them from
  returning values in output parameters.

答:
Composability, in this sense, means that you can further refine the query.

EF queries are very composable. So you can take a query and change it:

```<code>var q = Context.MyStuff;
q = q.Where(s => s.IsGood);
var r = from s in q select new { Id = s.Id, Description = s.Description };
r = r.OrderBy(s => s.Description);
r = r.Take(100);
</code>```

All this work will be done on the DB server, because the final query is composed of its parts, built up in the code above.

WCF Data Services, OTOH, are much more limited. You can project, and you can order, but you can't order on the projection. So the code above won't work, although it could be tweaked and re-ordered to work.

Title: What does Composable exactly mean?

Body:
Composability, in this sense, means that you can further refine the query.

EF queries are very composable. So you can take a query and change it:

var q = Context.MyStuff;
q = q.Where(s => s.IsGood);
var r = from s in q select new { Id = s.Id, Description = s.Description };
r = r.OrderBy(s => s.Description);
r = r.Take(100);

All this work will be done on the DB server, because the final query is composed of its parts, built up in the code above.

WCF Data Services, OTOH, are much more limited. You can project, and you can order, but you can't order on the projection. So the code above won't work, although it could be tweaked and re-ordered to work.


问:
C++: Adding and redefinition of default arguments in real world
There is a possibility to add or redefine default arguments of a function in C++. Let's look at the example:

```<code>void foo(int a, int b, int c = -1) {
    std::cout << "foo(" << a << ", " << b << ", " << c << ")\n";
}

int main() {
    foo(1, 2);   // output: foo(1, 2, -1)

    // void foo(int a, int b = 0, int c);
    // error: does not use default from surrounding scope

    void foo(int a, int b, int c = 30);
    foo(1, 2);   // output: foo(1, 2, 30)

    // void foo(int a, int b, int c = 35);
    // error: we cannot redefine the argument in the same scope

    // has a default argument for c from a previous declaration
    void foo(int a, int b = 20, int c);
    foo(1);      // output: foo(1, 20, 30)

    void foo(int a = 10, int b, int c);
    foo();       // output: foo(10, 20, 30)

    {
        // in inner scopes we can completely redefine them
        void foo(int a, int b = 4, int c = 8);
        foo(2);  // output: foo(2, 4, 8)
    }

    return 0;
}
</code>```

Online version to play with: http://ideone.com/vdfs3t

These possibilities are regulated by the standard in 8.3.6. More specific details are in 8.3.6/4

For non-template functions, default arguments can be added in later
  declarations of a function in the same scope. Declarations in
  different scopes have completely distinct sets of default arguments.
  That is, declarations in inner scopes do not acquire default arguments
  from declarations in outer scopes, and vice versa. In a given function
  declaration, each parameter subsequent to a parameter with a default
  argument shall have a default argument supplied in this or a previous
  declaration or shall be a function parameter pack. A default argument
  shall not be redefined by a later declaration (not even to the same
  value)
  ...

To tell the truth I never use this feature when coding in c++. I used similar code snippets several times to surprise my colleagues, but certainly not in the production code. Thus, the question is: Do you know real world examples of the code that use these features with benefits?

答:
If you cannot change some existing code or library and you really cannot be bothered to type the correct argument then changing the default argument for some scope could be a solution.

It seems like the kind of hack that could be useful when working with C++ code generated by some legacy tool. For example, if the generated code has always had hundreds calls into some external library using a default argument but now the default argument is no longer correct.

Body:
There is a possibility to add or redefine default arguments of a function in C++. Let's look at the example:

void foo(int a, int b, int c = -1) {
    std::cout << "foo(" << a << ", " << b << ", " << c << ")\n";
}

int main() {
    foo(1, 2);   // output: foo(1, 2, -1)

    // void foo(int a, int b = 0, int c);
    // error: does not use default from surrounding scope

    void foo(int a, int b, int c = 30);
    foo(1, 2);   // output: foo(1, 2, 30)

    // void foo(int a, int b, int c = 35);
    // error: we cannot redefine the argument in the same scope

    // has a default argument for c from a previous declaration
    void foo(int a, int b = 20, int c);
    foo(1);      // output: foo(1, 20, 30)

    void foo(int a = 10, int b, int c);
    foo();       // output: foo(10, 20, 30)

    {
        // in inner scopes we can completely redefine them
        void foo(int a, int b = 4, int c = 8);
        foo(2);  // output: foo(2, 4, 8)
    }

    return 0;
}

Online version to play with: http://ideone.com/vdfs3t

These possibilities are regulated by the standard in 8.3.6. More specific details are in 8.3.6/4

For non-template functions, default arguments can be added in later
  declarations of a function in the same scope. Declarations in
  different scopes have completely distinct sets of default arguments.
  That is, declarations in inner scopes do not acquire default arguments
  from declarations in outer scopes, and vice versa. In a given function
  declaration, each parameter subsequent to a parameter with a default
  argument shall have a default argument supplied in this or a previous
  declaration or shall be a function parameter pack. A default argument
  shall not be redefined by a later declaration (not even to the same
  value)
  ...

To tell the truth I never use this feature when coding in c++. I used similar code snippets several times to surprise my colleagues, but certainly not in the production code. Thus, the question is: Do you know real world examples of the code that use these features with benefits?


问:
Laravel Query issue
I have make the survey site. User post the question and other user ans them the question.My code work perfectly but the views is not good. All the question shows the user.How we can one by one show the question. User press the next button then show the next question if press the previous button show the previous question.
Any Idea for this problem Or suggest me related site </p>

答:
The easiest way to do this is with Javascript or similar.

But, I too did find this way interesting as well using php only and please check whether they could help.
How to display only one data at a time in an online quiz
OR
One quiz item per page (php/mysql quiz program)

Title: Laravel Query issue