问:
(SWIFT) error: Playground execution aborted: error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
I'm getting this error code

error: Playground execution aborted: error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.

Here's my code:

```<code>import Cocoa
import SpriteKit
import PlaygroundSupport

public class Scene: SKScene {

var point = CGPoint(x: 0,y : 0)
let viewFrame = CGRect(x:0,y:0, width: 1080, height: 1080)

override init(size: CGSize) {

    super.init(size: size)
            //these 3 lines are the problem

    let options = [NSTrackingAreaOptions.mouseMoved, NSTrackingAreaOptions.activeInKeyWindow] as NSTrackingAreaOptions
    let tracker = NSTrackingArea(rect: view, options: options, owner: self.view, userInfo: nil)
    self.view?.addTrackingArea(tracker)               //print(self.view!)

    //Intro
    let welcomeLabel = SKLabelNode(text: "Music Box")
    welcomeLabel.fontColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
    welcomeLabel.position = CGPoint(x: size.width / 2, y: size.height/2)
    welcomeLabel.fontSize = 150

    addChild(welcomeLabel)

    delay(3.0)
    {
        let fadeOutAction = SKAction.fadeAlpha(to: 0.0, duration: 1.0)
        welcomeLabel.run(fadeOutAction)
        self.demo()
    }
}

required public init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func demo() {
    let songLabel = SKLabelNode(text: "song - SONG NAME")
    songLabel.fontColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
    songLabel.position = CGPoint(x: size.width / 2, y: size.height/12)
    songLabel.fontSize = 50
    songLabel.alpha = 0.0

    addChild(songLabel)

    let fadeInAction = SKAction.fadeAlpha(to: 1.0, duration: 1.0)

    songLabel.run(fadeInAction)
    self.musicBox()
}

func musicBox() {

    let body = SKSpriteNode(imageNamed: "musicBox")
    body.size = CGSize(width: 845.0, height: 379.0)
    body.position = CGPoint(x: 535, y: 454)

    let crank = SKSpriteNode(imageNamed: "crank")
    crank.size = CGSize(width: 155.0, height: 188.0)
    crank.position = CGPoint(x: 835.0, y: 480)
    crank.anchorPoint = CGPoint(x: 0.5 , y: 0.5-0.08)

    addChild(body)
    addChild(crank)

    print(point)

    crank.run(
        SKAction.repeatForever (
            SKAction.sequence([
                SKAction.wait(forDuration: 0.1),
                SKAction.run({

                    let angle = atan2(self.point.y - crank.position.y , self.point.x - crank.position.x)
                    let rotate = SKAction.rotate(toAngle: angle - CGFloat(M_PI_2), duration: 0.25)
                    crank.run(rotate)
                    if(!(crank.frame.contains(self.point))) {
                        self.removeAction(forKey: "New Thread")
                    }
                })
                ])
        ),
        withKey: "New Thread"
    )

}

override public func mouseMoved(with event: NSEvent) {

    point = event.location(in: self)
    print(point)
}

}

//Delays Animations
func delay(_ delay:Double, closure:@escaping ()->()) {
    let when = DispatchTime.now() + delay
    DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}

let scene = Scene(size: CGSize(width: 1080, height: 1080))
scene.backgroundColor = #colorLiteral(red: 0.4078431373, green: 0.7843137255, blue: 0.6509803922, alpha: 1)
scene.scaleMode = .aspectFit

print(Thread.callStackSymbols)

let view = SKView(frame: NSRect(x: 0, y: 0, width: 1920, height: 1080))

PlaygroundPage.current.needsIndefiniteExecution = true
view.presentScene(scene)
PlaygroundPage.current.liveView = view
</code>```

The error shows up on this line:

```<code>let scene = Scene(size: CGSize.init(width: 1080, height: 1080))
</code>```

The error seems to be caused by when I declare/use my point var, but I have no clue why this would be the case.

Stack thread:

```<code> Playground execution failed: error: MusicBox WWDC17.playground:10:44: error: cannot convert value of type 'SKView?' to expected argument type 'NSRect' (aka 'CGRect')
        let tracker = NSTrackingArea(rect: view, options: options, owner: self.view, userInfo: nil)
                                           ^~~~

* thread #1: tid = 0xb837, 0x0000000101cc9360 com.apple.dt.Xcode.PlaygroundStub-macosx`executePlayground, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
  * frame #0: 0x0000000101cc9360 com.apple.dt.Xcode.PlaygroundStub-macosx`executePlayground
    frame #1: 0x0000000101cc722a com.apple.dt.Xcode.PlaygroundStub-macosx`-[PlaygroundViewBridgeService execute] + 90
    frame #2: 0x00007fff9ced43ec CoreFoundation`__invoking___ + 140
    frame #3: 0x00007fff9ced4271 CoreFoundation`-[NSInvocation invoke] + 289
    frame #4: 0x00007fff9ceed7a6 CoreFoundation`-[NSInvocation invokeWithTarget:] + 54
    frame #5: 0x00007fffb05d395b ViewBridge`__68-[NSVB_ViewServiceImplicitAnimationDecodingProxy forwardInvocation:]_block_invoke + 47
    frame #6: 0x00007fffb05f2f4c ViewBridge`__runAnimationGroup_block_invoke + 21
    frame #7: 0x00007fff9b350be2 AppKit`+[NSAnimationContext runAnimationGroup:] + 58
    frame #8: 0x00007fff9aa1e782 AppKit`+[NSAnimationContext runAnimationGroup:completionHandler:] + 85
    frame #9: 0x00007fffb05f2f28 ViewBridge`runAnimationGroup + 303
    frame #10: 0x00007fffb05d3462 ViewBridge`+[NSVB_View _animateWithAttributes:animations:completion:] + 507
    frame #11: 0x00007fffb05d38dd ViewBridge`-[NSVB_ViewServiceImplicitAnimationDecodingProxy forwardInvocation:] + 156
    frame #12: 0x00007fff9ced2daa CoreFoundation`___forwarding___ + 538
    frame #13: 0x00007fff9ced2b08 CoreFoundation`__forwarding_prep_0___ + 120
    frame #14: 0x00007fff9ced43ec CoreFoundation`__invoking___ + 140
    frame #15: 0x00007fff9ced4271 CoreFoundation`-[NSInvocation invoke] + 289
    frame #16: 0x00007fff9ceed7a6 CoreFoundation`-[NSInvocation invokeWithTarget:] + 54
    frame #17: 0x00007fffb05a135d ViewBridge`-[NSVB_QueueingProxy forwardInvocation:] + 327
    frame #18: 0x00007fff9ced2daa CoreFoundation`___forwarding___ + 538
    frame #19: 0x00007fff9ced2b08 CoreFoundation`__forwarding_prep_0___ + 120
    frame #20: 0x00007fff9ced43ec CoreFoundation`__invoking___ + 140
    frame #21: 0x00007fff9ced4271 CoreFoundation`-[NSInvocation invoke] + 289
    frame #22: 0x00007fff9ceed7a6 CoreFoundation`-[NSInvocation invokeWithTarget:] + 54
    frame #23: 0x00007fff9ced2daa CoreFoundation`___forwarding___ + 538
    frame #24: 0x00007fff9ced2b08 CoreFoundation`__forwarding_prep_0___ + 120
    frame #25: 0x00007fff9ced43ec CoreFoundation`__invoking___ + 140
    frame #26: 0x00007fff9ced4271 CoreFoundation`-[NSInvocation invoke] + 289
    frame #27: 0x00007fff9ceed7a6 CoreFoundation`-[NSInvocation invokeWithTarget:] + 54
    frame #28: 0x00007fff9ced2daa CoreFoundation`___forwarding___ + 538
    frame #29: 0x00007fff9ced2b08 CoreFoundation`__forwarding_prep_0___ + 120
    frame #30: 0x00007fff9ced43ec CoreFoundation`__invoking___ + 140
    frame #31: 0x00007fff9ced4271 CoreFoundation`-[NSInvocation invoke] + 289
    frame #32: 0x00007fffb05f752b ViewBridge`withHintInProgress + 487
    frame #33: 0x00007fffb05f725a ViewBridge`__deferNSXPCInvocationOntoMainThread_block_invoke_2 + 233
    frame #34: 0x00007fffb0578df2 ViewBridge`+[NSViewServiceApplication withHostPID:invoke:] + 46
    frame #35: 0x00007fffb05f711d ViewBridge`__deferNSXPCInvocationOntoMainThread_block_invoke + 179
    frame #36: 0x00007fffb05f6d0a ViewBridge`__deferBlockOntoMainThread_block_invoke_2 + 544
    frame #37: 0x00007fff9cef67dc CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
    frame #38: 0x00007fff9ced77e4 CoreFoundation`__CFRunLoopDoBlocks + 356
    frame #39: 0x00007fff9ced7326 CoreFoundation`__CFRunLoopRun + 1878
    frame #40: 0x00007fff9ced6974 CoreFoundation`CFRunLoopRunSpecific + 420
    frame #41: 0x00007fff9c462a5c HIToolbox`RunCurrentEventLoopInMode + 240
    frame #42: 0x00007fff9c462891 HIToolbox`ReceiveNextEventCommon + 432
    frame #43: 0x00007fff9c4626c6 HIToolbox`_BlockUntilNextEventMatchingListInModeWithFilter + 71
    frame #44: 0x00007fff9aa085b4 AppKit`_DPSNextEvent + 1120
    frame #45: 0x00007fff9b182d6b AppKit`-[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 2789
    frame #46: 0x00007fffb057a06a ViewBridge`-[NSViewServiceApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 102
    frame #47: 0x00007fff9a9fcf35 AppKit`-[NSApplication run] + 926
    frame #48: 0x00007fff9a9c7850 AppKit`NSApplicationMain + 1237
    frame #49: 0x00007fffb26888c7 libxpc.dylib`_xpc_objc_main + 775
    frame #50: 0x00007fffb26872e4 libxpc.dylib`xpc_main + 494
    frame #51: 0x00007fffb05a57eb ViewBridge`-[NSXPCSharedListener resume] + 16
    frame #52: 0x00007fffb057eeb9 ViewBridge`NSViewServiceApplicationMain + 3022
    frame #53: 0x0000000101cc93a2 com.apple.dt.Xcode.PlaygroundStub-macosx`main + 34
    frame #54: 0x00007fffb2424255 libdyld.dylib`start + 1
</code>```

答:
I found the solution. This line:

```<code>let tracker = NSTrackingArea(rect: view, options: options, owner: self.view, userInfo: nil)
</code>```

Should actually be:

```<code>let tracker = NSTrackingArea(rect: CGRect(x:0,y:0, width: 1080, height: 1080), options: options, owner: self.view, userInfo: nil)
</code>```

I assigned the rect to an SKScene, not a CGRect; such a silly mistake.

Body:
I'm getting this error code

error: Playground execution aborted: error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.

Here's my code:

import Cocoa
import SpriteKit
import PlaygroundSupport

public class Scene: SKScene {

var point = CGPoint(x: 0,y : 0)
let viewFrame = CGRect(x:0,y:0, width: 1080, height: 1080)

override init(size: CGSize) {

    super.init(size: size)
            //these 3 lines are the problem

    let options = [NSTrackingAreaOptions.mouseMoved, NSTrackingAreaOptions.activeInKeyWindow] as NSTrackingAreaOptions
    let tracker = NSTrackingArea(rect: view, options: options, owner: self.view, userInfo: nil)
    self.view?.addTrackingArea(tracker)               //print(self.view!)

    //Intro
    let welcomeLabel = SKLabelNode(text: "Music Box")
    welcomeLabel.fontColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
    welcomeLabel.position = CGPoint(x: size.width / 2, y: size.height/2)
    welcomeLabel.fontSize = 150

    addChild(welcomeLabel)

    delay(3.0)
    {
        let fadeOutAction = SKAction.fadeAlpha(to: 0.0, duration: 1.0)
        welcomeLabel.run(fadeOutAction)
        self.demo()
    }
}

required public init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func demo() {
    let songLabel = SKLabelNode(text: "song - SONG NAME")
    songLabel.fontColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
    songLabel.position = CGPoint(x: size.width / 2, y: size.height/12)
    songLabel.fontSize = 50
    songLabel.alpha = 0.0

    addChild(songLabel)

    let fadeInAction = SKAction.fadeAlpha(to: 1.0, duration: 1.0)

    songLabel.run(fadeInAction)
    self.musicBox()
}

func musicBox() {

    let body = SKSpriteNode(imageNamed: "musicBox")
    body.size = CGSize(width: 845.0, height: 379.0)
    body.position = CGPoint(x: 535, y: 454)

    let crank = SKSpriteNode(imageNamed: "crank")
    crank.size = CGSize(width: 155.0, height: 188.0)
    crank.position = CGPoint(x: 835.0, y: 480)
    crank.anchorPoint = CGPoint(x: 0.5 , y: 0.5-0.08)

    addChild(body)
    addChild(crank)

    print(point)

    crank.run(
        SKAction.repeatForever (
            SKAction.sequence([
                SKAction.wait(forDuration: 0.1),
                SKAction.run({

                    let angle = atan2(self.point.y - crank.position.y , self.point.x - crank.position.x)
                    let rotate = SKAction.rotate(toAngle: angle - CGFloat(M_PI_2), duration: 0.25)
                    crank.run(rotate)
                    if(!(crank.frame.contains(self.point))) {
                        self.removeAction(forKey: "New Thread")
                    }
                })
                ])
        ),
        withKey: "New Thread"
    )

}

override public func mouseMoved(with event: NSEvent) {

    point = event.location(in: self)
    print(point)
}

}

//Delays Animations
func delay(_ delay:Double, closure:@escaping ()->()) {
    let when = DispatchTime.now() + delay
    DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}

let scene = Scene(size: CGSize(width: 1080, height: 1080))
scene.backgroundColor = #colorLiteral(red: 0.4078431373, green: 0.7843137255, blue: 0.6509803922, alpha: 1)
scene.scaleMode = .aspectFit

print(Thread.callStackSymbols)

let view = SKView(frame: NSRect(x: 0, y: 0, width: 1920, height: 1080))

PlaygroundPage.current.needsIndefiniteExecution = true
view.presentScene(scene)
PlaygroundPage.current.liveView = view

The error shows up on this line:

let scene = Scene(size: CGSize.init(width: 1080, height: 1080))

The error seems to be caused by when I declare/use my point var, but I have no clue why this would be the case.

Stack thread:

 Playground execution failed: error: MusicBox WWDC17.playground:10:44: error: cannot convert value of type 'SKView?' to expected argument type 'NSRect' (aka 'CGRect')
        let tracker = NSTrackingArea(rect: view, options: options, owner: self.view, userInfo: nil)
                                           ^~~~

* thread #1: tid = 0xb837, 0x0000000101cc9360 com.apple.dt.Xcode.PlaygroundStub-macosx`executePlayground, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
  * frame #0: 0x0000000101cc9360 com.apple.dt.Xcode.PlaygroundStub-macosx`executePlayground
    frame #1: 0x0000000101cc722a com.apple.dt.Xcode.PlaygroundStub-macosx`-[PlaygroundViewBridgeService execute] + 90
    frame #2: 0x00007fff9ced43ec CoreFoundation`__invoking___ + 140
    frame #3: 0x00007fff9ced4271 CoreFoundation`-[NSInvocation invoke] + 289
    frame #4: 0x00007fff9ceed7a6 CoreFoundation`-[NSInvocation invokeWithTarget:] + 54
    frame #5: 0x00007fffb05d395b ViewBridge`__68-[NSVB_ViewServiceImplicitAnimationDecodingProxy forwardInvocation:]_block_invoke + 47
    frame #6: 0x00007fffb05f2f4c ViewBridge`__runAnimationGroup_block_invoke + 21
    frame #7: 0x00007fff9b350be2 AppKit`+[NSAnimationContext runAnimationGroup:] + 58
    frame #8: 0x00007fff9aa1e782 AppKit`+[NSAnimationContext runAnimationGroup:completionHandler:] + 85
    frame #9: 0x00007fffb05f2f28 ViewBridge`runAnimationGroup + 303
    frame #10: 0x00007fffb05d3462 ViewBridge`+[NSVB_View _animateWithAttributes:animations:completion:] + 507
    frame #11: 0x00007fffb05d38dd ViewBridge`-[NSVB_ViewServiceImplicitAnimationDecodingProxy forwardInvocation:] + 156
    frame #12: 0x00007fff9ced2daa CoreFoundation`___forwarding___ + 538
    frame #13: 0x00007fff9ced2b08 CoreFoundation`__forwarding_prep_0___ + 120
    frame #14: 0x00007fff9ced43ec CoreFoundation`__invoking___ + 140
    frame #15: 0x00007fff9ced4271 CoreFoundation`-[NSInvocation invoke] + 289
    frame #16: 0x00007fff9ceed7a6 CoreFoundation`-[NSInvocation invokeWithTarget:] + 54
    frame #17: 0x00007fffb05a135d ViewBridge`-[NSVB_QueueingProxy forwardInvocation:] + 327
    frame #18: 0x00007fff9ced2daa CoreFoundation`___forwarding___ + 538
    frame #19: 0x00007fff9ced2b08 CoreFoundation`__forwarding_prep_0___ + 120
    frame #20: 0x00007fff9ced43ec CoreFoundation`__invoking___ + 140
    frame #21: 0x00007fff9ced4271 CoreFoundation`-[NSInvocation invoke] + 289
    frame #22: 0x00007fff9ceed7a6 CoreFoundation`-[NSInvocation invokeWithTarget:] + 54
    frame #23: 0x00007fff9ced2daa CoreFoundation`___forwarding___ + 538
    frame #24: 0x00007fff9ced2b08 CoreFoundation`__forwarding_prep_0___ + 120
    frame #25: 0x00007fff9ced43ec CoreFoundation`__invoking___ + 140
    frame #26: 0x00007fff9ced4271 CoreFoundation`-[NSInvocation invoke] + 289
    frame #27: 0x00007fff9ceed7a6 CoreFoundation`-[NSInvocation invokeWithTarget:] + 54
    frame #28: 0x00007fff9ced2daa CoreFoundation`___forwarding___ + 538
    frame #29: 0x00007fff9ced2b08 CoreFoundation`__forwarding_prep_0___ + 120
    frame #30: 0x00007fff9ced43ec CoreFoundation`__invoking___ + 140
    frame #31: 0x00007fff9ced4271 CoreFoundation`-[NSInvocation invoke] + 289
    frame #32: 0x00007fffb05f752b ViewBridge`withHintInProgress + 487
    frame #33: 0x00007fffb05f725a ViewBridge`__deferNSXPCInvocationOntoMainThread_block_invoke_2 + 233
    frame #34: 0x00007fffb0578df2 ViewBridge`+[NSViewServiceApplication withHostPID:invoke:] + 46
    frame #35: 0x00007fffb05f711d ViewBridge`__deferNSXPCInvocationOntoMainThread_block_invoke + 179
    frame #36: 0x00007fffb05f6d0a ViewBridge`__deferBlockOntoMainThread_block_invoke_2 + 544
    frame #37: 0x00007fff9cef67dc CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
    frame #38: 0x00007fff9ced77e4 CoreFoundation`__CFRunLoopDoBlocks + 356
    frame #39: 0x00007fff9ced7326 CoreFoundation`__CFRunLoopRun + 1878
    frame #40: 0x00007fff9ced6974 CoreFoundation`CFRunLoopRunSpecific + 420
    frame #41: 0x00007fff9c462a5c HIToolbox`RunCurrentEventLoopInMode + 240
    frame #42: 0x00007fff9c462891 HIToolbox`ReceiveNextEventCommon + 432
    frame #43: 0x00007fff9c4626c6 HIToolbox`_BlockUntilNextEventMatchingListInModeWithFilter + 71
    frame #44: 0x00007fff9aa085b4 AppKit`_DPSNextEvent + 1120
    frame #45: 0x00007fff9b182d6b AppKit`-[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 2789
    frame #46: 0x00007fffb057a06a ViewBridge`-[NSViewServiceApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 102
    frame #47: 0x00007fff9a9fcf35 AppKit`-[NSApplication run] + 926
    frame #48: 0x00007fff9a9c7850 AppKit`NSApplicationMain + 1237
    frame #49: 0x00007fffb26888c7 libxpc.dylib`_xpc_objc_main + 775
    frame #50: 0x00007fffb26872e4 libxpc.dylib`xpc_main + 494
    frame #51: 0x00007fffb05a57eb ViewBridge`-[NSXPCSharedListener resume] + 16
    frame #52: 0x00007fffb057eeb9 ViewBridge`NSViewServiceApplicationMain + 3022
    frame #53: 0x0000000101cc93a2 com.apple.dt.Xcode.PlaygroundStub-macosx`main + 34
    frame #54: 0x00007fffb2424255 libdyld.dylib`start + 1

Body:
I found the solution. This line:

let tracker = NSTrackingArea(rect: view, options: options, owner: self.view, userInfo: nil)

Should actually be:

let tracker = NSTrackingArea(rect: CGRect(x:0,y:0, width: 1080, height: 1080), options: options, owner: self.view, userInfo: nil)

I assigned the rect to an SKScene, not a CGRect; such a silly mistake.


来源: stackexchange

问:
How can I count field value based on another field?
I have EmailEvent table. This is STI table which stores opens and clicks (by using type attribute). I have right now this code which provides information on how many emails use recipient address (email_address field):

```<code>EmailEvent.where("type = 'OpenEmailEvent' OR type = 'ClickEmailEvent'")
.where(email_id: email_ids).happened_between_dates(start_date, end_date)
.select("email_address, count(distinct email_id) as emails_count")
.group(:email_address).reorder(nil)
</code>```

It generates such code:

```<code>SELECT email_address, count(distinct email_id) as emails_count
FROM "email_events"
WHERE "email_events"."deleted_at" IS NULL
    AND (type = 'OpenEmailEvent' OR type = 'ClickEmailEvent')
    AND "email_events"."email_id" IN (85487, 75554, 85489, 77184, 78562, 75587, 82879, 85535, 85534)
    AND (created_at between '2017-02-28 22:52:01.000000' AND '2017-03-29 05:59:59.000000')
GROUP BY "email_events"."email_address"
</code>```

I need to provide information on how many opens and clicks there per email_address. I can't use count(id) because it'll give me both opens and clicks so I need to use type attribute somehow but I can't figure out exactly how it should work. Can somebody give me suggestion what should I do here?

答:
replace this

```<code>count(distinct email_id) as emails_count
</code>```

to  something like in SQLServer using case or IIF

```<code>sum(case when type = 'OpenEmailEvent' then 1 else 0 end)  [Opens],
sum(case when type = 'ClickEmailEvent' then 1 else 0 end)  [Click],
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have EmailEvent table. This is STI table which stores opens and clicks (by using type attribute). I have right now this code which provides information on how many emails use recipient address (email_address field):

EmailEvent.where("type = 'OpenEmailEvent' OR type = 'ClickEmailEvent'")
.where(email_id: email_ids).happened_between_dates(start_date, end_date)
.select("email_address, count(distinct email_id) as emails_count")
.group(:email_address).reorder(nil)

It generates such code:

SELECT email_address, count(distinct email_id) as emails_count
FROM "email_events"
WHERE "email_events"."deleted_at" IS NULL
    AND (type = 'OpenEmailEvent' OR type = 'ClickEmailEvent')
    AND "email_events"."email_id" IN (85487, 75554, 85489, 77184, 78562, 75587, 82879, 85535, 85534)
    AND (created_at between '2017-02-28 22:52:01.000000' AND '2017-03-29 05:59:59.000000')
GROUP BY "email_events"."email_address"

I need to provide information on how many opens and clicks there per email_address. I can't use count(id) because it'll give me both opens and clicks so I need to use type attribute somehow but I can't figure out exactly how it should work. Can somebody give me suggestion what should I do here?

Body:
replace this

count(distinct email_id) as emails_count

to  something like in SQLServer using case or IIF

sum(case when type = 'OpenEmailEvent' then 1 else 0 end)  [Opens],
sum(case when type = 'ClickEmailEvent' then 1 else 0 end)  [Click],


问:
mongodb: update query on an variable makes changes to another variable that's an array
Ran this via terminal on an existing mongodb database hosted in aws ec2 instance:

```<code>db.users.update({},{ $inc: { point_total: 100 } }, {multi:true})
</code>```

In additional to increasing variable by 100 for all users there were also entry changes to another variable (history) in the same collection.

```<code>history: [{
    c_id: String,
    created_at: {type: Date, default: Date.now },
    reason: String, //Received, Sent
    amount: String
}]
</code>```

Unwanted changes include the reason variable within history was changed from "Received" to "Sent" for various users.

As my query wasn't addressing "history", are there ideas as to what caused this?

答:
From $inc operator documentation:

The $inc operator increments a field by a specified value and has the following form: { $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }

Behavior

If the field does not exist, $inc creates the field and sets the field to the specified value. Use of the $inc operator on a field with a null value will generate an error. $inc is an atomic operation within a single document.

As you can see, the definition states that $inc operator increments only specified fields. There are no any remarks on possible side effects and changing non-specified fields.

That means there is another query (or queries) which update history field. Possibly your application or some service is doing that.

Body:
Ran this via terminal on an existing mongodb database hosted in aws ec2 instance:

db.users.update({},{ $inc: { point_total: 100 } }, {multi:true})

In additional to increasing variable by 100 for all users there were also entry changes to another variable (history) in the same collection.

history: [{
    c_id: String,
    created_at: {type: Date, default: Date.now },
    reason: String, //Received, Sent
    amount: String
}]

Unwanted changes include the reason variable within history was changed from "Received" to "Sent" for various users.

As my query wasn't addressing "history", are there ideas as to what caused this?


问:
Visiualize and analyze relations of classes in c++ project
which free tool to use for getting visualized representation classes in c++ project?</p>

答:
If it's documentation, you could try doxygen - http://www.doxygen.nl/

or are you after UML?

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 4.0


问:
How to use slack api methods in node.js
Having troubles to get my head around slack apps with node.js. I am using the Starter Botkit (Howdy), hosted on glitch (glitch.com)

What I have so far works perfectly, it starts a convo with the user, asks a few questions, one after another and ends with a summary including all answers the user gave to the bot.

```<code>module.exports = function(controller) {

 controller.hears(['reminder'], 'direct_message', function(bot, message) {

 bot.startConversation(message, function(err, convo) {
   convo.say('Ok, let me help you with that ...');

   // Ask Target
   convo.ask('Who should I remind ?', function(response, convo) {

    convo.setVar('target', response.text);
    convo.next();

   });

   // Ask About
   convo.ask('About what ?', function(response, convo) {

    convo.setVar('about', response.text);
    convo.next();

   });

   // Ask Date
   convo.ask('Date ?', function(response, convo) {

    convo.setVar('date', response.text);
    convo.next();

   });

   // Ask Time
   convo.ask('And what time ?', function(response, convo) {

    convo.setVar('time', response.text);
    convo.next();

   });

   convo.say('Got it, I should remind {{vars.target}} : {{vars.about}} on {{vars.date}} at {{vars.time}}');
   convo.next();

  });
 });
};
</code>```

Now I want to make more use of all the methods Slack is providing through the API, for example the reminders.add method. I can't find any starting point in writing a function that uses this method. Or how to include it in the code above. I am on beginner level of knowledge, please be patient with me :)

For what I understand, all the Oauth process is already taken care of within the botkit files (just need to provide all the keys, and install the app in my team)

答:
I read the BotKit docs for you and found that they show an example where you simply access the Slack api via the api property on the bot object.

https://github.com/howdyai/botkit/blob/master/readme-slack.md#working-with-slack-integrations

```<code>bot.api.channels.list({},function(err,response) {
  //Do something...
})
</code>```

Title: How to use slack api methods in node.js

Body:
Having troubles to get my head around slack apps with node.js. I am using the Starter Botkit (Howdy), hosted on glitch (glitch.com)

What I have so far works perfectly, it starts a convo with the user, asks a few questions, one after another and ends with a summary including all answers the user gave to the bot.

module.exports = function(controller) {

 controller.hears(['reminder'], 'direct_message', function(bot, message) {

 bot.startConversation(message, function(err, convo) {
   convo.say('Ok, let me help you with that ...');

   // Ask Target
   convo.ask('Who should I remind ?', function(response, convo) {

    convo.setVar('target', response.text);
    convo.next();

   });

   // Ask About
   convo.ask('About what ?', function(response, convo) {

    convo.setVar('about', response.text);
    convo.next();

   });

   // Ask Date
   convo.ask('Date ?', function(response, convo) {

    convo.setVar('date', response.text);
    convo.next();

   });

   // Ask Time
   convo.ask('And what time ?', function(response, convo) {

    convo.setVar('time', response.text);
    convo.next();

   });

   convo.say('Got it, I should remind {{vars.target}} : {{vars.about}} on {{vars.date}} at {{vars.time}}');
   convo.next();

  });
 });
};

Now I want to make more use of all the methods Slack is providing through the API, for example the reminders.add method. I can't find any starting point in writing a function that uses this method. Or how to include it in the code above. I am on beginner level of knowledge, please be patient with me :)

For what I understand, all the Oauth process is already taken care of within the botkit files (just need to provide all the keys, and install the app in my team)

Body:
I read the BotKit docs for you and found that they show an example where you simply access the Slack api via the api property on the bot object.

https://github.com/howdyai/botkit/blob/master/readme-slack.md#working-with-slack-integrations

bot.api.channels.list({},function(err,response) {
  //Do something...
})


问:
Node search in Binary Tree overflows stack
I use the following method to traverse* a binary tree of 300 000 levels:

```<code>Node* find(int v){
   if(value==v)
      return this;
   else if(right && value<v)
      return right->find(v);
   else if(left && value>v)
      return left->find(v);
}
</code>```

However I get a segmentation fault due to stack overflow.
Any ideas on how to traverse the deep tree without the overhead of recursive function calls?

*
By "traverse" I mean "search for a node with given value", not full tree traversal.

答:
Well, it can be made tail recursive at the cost of a single additional local variable and a few comparisons:</p>

```<code>Node* find(int v){
  if(value==v)
    return this;
  else if(!right && value<v)
    return NULL;
  else if(!left && value>v)
    return NULL;
  else {
    Node *tmp = NULL;
    if(value<v)
      tmp = right;
    else if(value>v)
      tmp = left;
    return tmp->find(v);
  }
}
</code>```

Body:
I use the following method to traverse* a binary tree of 300 000 levels:

Node* find(int v){
   if(value==v)
      return this;
   else if(right && value<v)
      return right->find(v);
   else if(left && value>v)
      return left->find(v);
}

However I get a segmentation fault due to stack overflow.
Any ideas on how to traverse the deep tree without the overhead of recursive function calls?

*
By "traverse" I mean "search for a node with given value", not full tree traversal.

Body:
Well, it can be made tail recursive at the cost of a single additional local variable and a few comparisons:

Node* find(int v){
  if(value==v)
    return this;
  else if(!right && value<v)
    return NULL;
  else if(!left && value>v)
    return NULL;
  else {
    Node *tmp = NULL;
    if(value<v)
      tmp = right;
    else if(value>v)
      tmp = left;
    return tmp->find(v);
  }
}


问:
how can I take a time reversal of an array and conv it in matlab
I have an h[n] = [1 1 1 -1 1] for [0:4] and I have h[-n] = [1 -1 1 1 1] for [-4:0]. so the question is since matlab index starts from 1, how do I make my array starts from 0, and how do I make the h[-n] to start from -4 so I can do convolution? please help, I am new to matlab!</p>

答:
The short answer is that you don't.

The long answer is that MATLAB has a very unique and specific manner of indexing and counting. The idea behind it is supposedly for faster and easier matrix manipulation by the user.

Given:
H = [1 1 1 -1 -1]
for all indices in order all you need to do is call
H[:]

If you want to flip the vector you should use the built in flip() command:
flip(H)

If you're attempting to iterate through a loop, then you want to use some sort of counting like:
for i=5:-1:1
     ...code...

I'd suggest reading up on array indexing as well as counting methods for loops to get a stronger understanding on the subject. These are some key points of MATLAB that you'll want to learn early if you plan on using it more in the future.


问:
SVN and Redmine project management integration
Nowadays I am using Redmine to manage my project, and I know some key integrations with svn commit log, such as:

```<code>refs #1559
</code>```

or

```<code>resolves #1565
</code>```

Does anyone know where I can find more information about this integration, or where I can configure something like spent time on my commit log?

答: There isn't much information about the integration, outside of the source itself. Automated time tracking in the commit log is a great idea, but is currently unsupported. There is an issue including a patch that has recently been scheduled for the 1.1.0 release. You could apply the patch to your redmine installation and assist the project by reporting your experience with the feature.</p>

Body:
Nowadays I am using Redmine to manage my project, and I know some key integrations with svn commit log, such as:

refs #1559

or

resolves #1565

Does anyone know where I can find more information about this integration, or where I can configure something like spent time on my commit log?


问:
Why is SQL Server casting GETDATE() to an other value than CAST('yyyy-mm-dd')?
I'm working with SQL Server for many years and I think I have a really strange thing here.

When I execute these 2 queries:

```<code>SELECT CAST(CAST('2017-03-28' AS DATETIME) AS INT)

SELECT CAST(GETDATE() AS INT), GETDATE()
</code>```

I get these outputs:

```<code>42820
42821   2017-03-28 20:49:10.360
</code>```

So I'm totally clueless about this; how can 28 march 2017 be cast to 42820 and 28 march 2017 20:49 to 42821?

To make it a little more strange, I've figured out that the point for going 1 higher is 12:00 am. I'm really lost...

Can somebody enlighten me?

Body:
I'm working with SQL Server for many years and I think I have a really strange thing here.

When I execute these 2 queries:

SELECT CAST(CAST('2017-03-28' AS DATETIME) AS INT)

SELECT CAST(GETDATE() AS INT), GETDATE()

I get these outputs:

42820
42821   2017-03-28 20:49:10.360

So I'm totally clueless about this; how can 28 march 2017 be cast to 42820 and 28 march 2017 20:49 to 42821?

To make it a little more strange, I've figured out that the point for going 1 higher is 12:00 am. I'm really lost...

Can somebody enlighten me?

Body:
Rounding to one day：

--00:00:00~12:00:00
SELECT CAST(CAST('1900-01-01 00:00:00' AS DATETIME) AS INT)
--12:00:00~24:00:00
SELECT CAST(CAST('1900-01-01 12:00:00' AS DATETIME) AS INT)

--00:00:00.000~11:59:59.994
SELECT CAST(CAST('1900-01-01 11:59:59.994' AS DATETIME) AS INT)
--11:59:59.995~23:59:59.999
SELECT CAST(CAST('1900-01-01 23:59:59.999' AS DATETIME) AS INT)


问:
Concatenating values from SQL select statement
I am doing a basic SQL select from an oracle database.

```<code>select DISTINCT spriden_pidm, a.saracmt_comment_text, spriden_id, c.saracmt_comment_text, '2017' as "YEAR", szrspdc_prog_code
from spriden, sarappd, saradap, stvapdc, saracmt a, saracmt c, szrspdc
where blah blah blah
</code>```

The following three fields are used as a key in another system I am doing an import into so I need to get the following into one field: c.saracmt_comment_text, '2017' as "YEAR", szrspdc_prog_code.

Thanks in advance for your help.

答:
Do you want to do this in PL/Sql or on the receiving end is C#/VB.NET Code?  I assume PL/Sql.

```<code>Procedute SomeName(DataOut OUT Varchar2) IS
    WResult Varchar2(4000) -- I don't know the size of 2 of the table columns involed so I use the max size of Varchar2 which is 4000
Begin

    select into wResult a.saracmt_comment_text || YEAR || szrspdc_prog_code from
    (
      select DISTINCT spriden_pidm, a.saracmt_comment_text, spriden_id,
      c.saracmt_comment_text, '2017' as "YEAR", szrspdc_prog_code from
      spriden, sarappd, saradap, stvapdc, saracmt a, saracmt c,
      szrspdc_prog_code where Conditions
    );

   DataOut := wResult;
End;
</code>```

Hope this helps.

R/
Prescott ....

Body:
I am doing a basic SQL select from an oracle database.

select DISTINCT spriden_pidm, a.saracmt_comment_text, spriden_id, c.saracmt_comment_text, '2017' as "YEAR", szrspdc_prog_code
from spriden, sarappd, saradap, stvapdc, saracmt a, saracmt c, szrspdc
where blah blah blah

The following three fields are used as a key in another system I am doing an import into so I need to get the following into one field: c.saracmt_comment_text, '2017' as "YEAR", szrspdc_prog_code.

Thanks in advance for your help.

Body:
Do you want to do this in PL/Sql or on the receiving end is C#/VB.NET Code?  I assume PL/Sql.

Procedute SomeName(DataOut OUT Varchar2) IS
    WResult Varchar2(4000) -- I don't know the size of 2 of the table columns involed so I use the max size of Varchar2 which is 4000
Begin

    select into wResult a.saracmt_comment_text || YEAR || szrspdc_prog_code from
    (
      select DISTINCT spriden_pidm, a.saracmt_comment_text, spriden_id,
      c.saracmt_comment_text, '2017' as "YEAR", szrspdc_prog_code from
      spriden, sarappd, saradap, stvapdc, saracmt a, saracmt c,
      szrspdc_prog_code where Conditions
    );

   DataOut := wResult;
End;

Hope this helps.

R/
Prescott ....


问:
UPDATE with table a and table b
```<code>TABLEA ( id - gcoins )
TABLEB ( id - prezzo )
</code>```

Should I do a kind of subtraction: at number/value of 'gcoins' subtract number/value of 'prezzo'.

I tried:

```<code>UPDATE TABLEA SET TABLEA.gcoins = TABLEA.gcoins - TABLEB.prezzo FROM TABLEA JOIN TABLEB ON TABLEA.id = TABLEB.id;
</code>```

I read this same code in this site at question in the 2010 but not work.

Error: You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'FROM TABLEA JOIN TABLEB ON TABLEA.id = TABLEB.id' at line 1

答:
Try this rewrite.</p>

```<code>UPDATE  TABLEA JOIN TABLEB
            ON TABLEA.id = TABLEB.id
SET     TABLEA.gcoins = TABLEA.gcoins - TABLEB.prezzo
</code>```

Title: UPDATE with table a and table b

Body:
TABLEA ( id - gcoins )
TABLEB ( id - prezzo )

Should I do a kind of subtraction: at number/value of 'gcoins' subtract number/value of 'prezzo'.

I tried:

UPDATE TABLEA SET TABLEA.gcoins = TABLEA.gcoins - TABLEB.prezzo FROM TABLEA JOIN TABLEB ON TABLEA.id = TABLEB.id;

I read this same code in this site at question in the 2010 but not work.

Error: You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'FROM TABLEA JOIN TABLEB ON TABLEA.id = TABLEB.id' at line 1

Body:
Try this rewrite.

UPDATE  TABLEA JOIN TABLEB
            ON TABLEA.id = TABLEB.id
SET     TABLEA.gcoins = TABLEA.gcoins - TABLEB.prezzo


问:
How should I write goroutine?
Now I have the following code:

```<code>package main

import (
    "crypto/md5"
    "encoding/hex"
    "fmt"
    "io"
    "math"
    "strconv"
)

func Md5Str(str string) string {
    m := md5.New()
    io.WriteString(m, str)
    return hex.EncodeToString(m.Sum(nil))
}

func compute(size int) int {
    num := int(math.Floor(float64(size+256*1024-1)) / 256 / 1024)
    return num
}

func out(s string) string {
    return "Hello: " + s
}

func main() {
    num := compute(4194304)
    for i := 0; i < num; i++ {
        key := Md5Str("503969280ff8679135937ad7d23b06c5" + "_" + strconv.Itoa(i))
        res := out(key + "_" + strconv.Itoa(i))
        fmt.Println(res)
    }
}
</code>```

And it can run right.

I want to concurrency run the code, because if the out function run long time and the concurrency run will save time.

答:
Thanks @zerkms, I re-wrote the following code base on Go by Example: Worker Pools

```<code>package main

import (
    "crypto/md5"
    "encoding/hex"
    "fmt"
    "io"
    "math"
    "strconv"
)

func Md5Str(str string) string {
    m := md5.New()
    io.WriteString(m, str)
    return hex.EncodeToString(m.Sum(nil))
}

func compute(size int) int {
    num := int(math.Floor(float64(size+256*1024-1)) / 256 / 1024)
    return num
}

func out(s string, jobs <-chan int, results chan<- string) {
    for j := range jobs {
        fmt.Println("Hello: " + s + strconv.Itoa(j))
        results <- s
    }
}

func main() {
    num := compute(4194304)
    jobs := make(chan int, num)
    results := make(chan string, num)

    for i := 0; i < num; i++ {
        key := Md5Str("503969280ff8679135937ad7d23b06c5" + "_" + strconv.Itoa(i))
        go out(key+"_"+strconv.Itoa(i), jobs, results)
    }

    for j := 0; j < num; j++ {
        jobs <- j
    }
    close(jobs)

    for k := 0; k < num; k++ {
        <-results
    }
}
</code>```

It can run right.

Title: How should I write goroutine?

Body:
Now I have the following code:

package main

import (
    "crypto/md5"
    "encoding/hex"
    "fmt"
    "io"
    "math"
    "strconv"
)

func Md5Str(str string) string {
    m := md5.New()
    io.WriteString(m, str)
    return hex.EncodeToString(m.Sum(nil))
}

func compute(size int) int {
    num := int(math.Floor(float64(size+256*1024-1)) / 256 / 1024)
    return num
}

func out(s string) string {
    return "Hello: " + s
}

func main() {
    num := compute(4194304)
    for i := 0; i < num; i++ {
        key := Md5Str("503969280ff8679135937ad7d23b06c5" + "_" + strconv.Itoa(i))
        res := out(key + "_" + strconv.Itoa(i))
        fmt.Println(res)
    }
}

And it can run right.

I want to concurrency run the code, because if the out function run long time and the concurrency run will save time.

Body:
Thanks @zerkms, I re-wrote the following code base on Go by Example: Worker Pools

package main

import (
    "crypto/md5"
    "encoding/hex"
    "fmt"
    "io"
    "math"
    "strconv"
)

func Md5Str(str string) string {
    m := md5.New()
    io.WriteString(m, str)
    return hex.EncodeToString(m.Sum(nil))
}

func compute(size int) int {
    num := int(math.Floor(float64(size+256*1024-1)) / 256 / 1024)
    return num
}

func out(s string, jobs <-chan int, results chan<- string) {
    for j := range jobs {
        fmt.Println("Hello: " + s + strconv.Itoa(j))
        results <- s
    }
}

func main() {
    num := compute(4194304)
    jobs := make(chan int, num)
    results := make(chan string, num)

    for i := 0; i < num; i++ {
        key := Md5Str("503969280ff8679135937ad7d23b06c5" + "_" + strconv.Itoa(i))
        go out(key+"_"+strconv.Itoa(i), jobs, results)
    }

    for j := 0; j < num; j++ {
        jobs <- j
    }
    close(jobs)

    for k := 0; k < num; k++ {
        <-results
    }
}

It can run right.


问:
AngularJS ng-repeat update does not apply when object keys stay the same?
I'm trying to make a minimal but fancy AngularJS tutorial example, and I am running into an issue where after updating the entire tree for a model (inside the scope of an ng-change update), a template that is driven by a top-level ng-repeat is not re-rendered at all.

However, if I add the code $scope.data = {} at a strategic place, it starts working; but then the display flashes instead of being nice and smooth.  And it's not a great example of how AngularJS automatic data binding works.

What am I missing; and what would be the right fix?

Exact code - select a country from the dropdown -
This jsFiddle does not work: http://jsfiddle.net/f9zxt36g/
This jsFiddle works but flickers: http://jsfiddle.net/y090my10/

```<code>var app = angular.module('factbook', []);
app.controller('loadfact', function($scope, $http) {
  $scope.country = 'europe/uk';
  $scope.safe = function safe(name) { // Makes a safe CSS class name
    return name.replace(/[_\W]+/g, '_').toLowerCase();
  };
  $scope.trunc = function trunc(text) { // Truncates text to 500 chars
    return (text.length < 500) ? text : text.substr(0, 500) + "...";
  };
  $scope.update = function() { // Handles country selection
    // $scope.data = {}; // uncomment to force rednering; an angular bug?
    $http.get('https://rawgit.com/opendatajson/factbook.json/master/' +
        $scope.country + '.json').then(function(response) {
      $scope.data = response.data;
    });
  };
  $scope.countries = [
    {id: 'europe/uk', name: 'UK'},
    {id: 'africa/eg', name: 'Egypt'},
    {id: 'east-n-southeast-asia/ch', name: 'China'}
  ];
  $scope.update();
});
</code>```

The template is driven by ng-repeat:

```<code><div ng-app="factbook" ng-controller="loadfact">
  <select ng-model="country" ng-change="update()"
      ng-options="item.id as item.name for item in countries">
  </select>
  <div ng-repeat="(heading, section) in data"
       ng-init="depth = 1"
       ng-include="'recurse.template'"></div>
  <!-- A template for nested sections with heading and body parts -->
  <script type="text/ng-template" id="recurse.template">
    <div ng-if="section.text"
         class="level{{depth}} section fact ng-class:safe(heading);">
      <div class="level{{depth}} heading factname">{{heading}}</div>
      <div class="level{{depth}} body factvalue">{{trunc(section.text)}}</div>
    </div>
    <div ng-if="!section.text"
         class="level{{depth}} section ng-class:safe(heading);">
      <div class="level{{depth}} heading">{{heading}}</div>
      <div ng-repeat="(heading, body) in section"
           ng-init="depth = depth+1; section = body;"
           ng-include="'recurse.template'"
           class="level{{depth-1}} body"></div>
    </div>
  </script>
</div>
</code>```

What am I missing?

答:
If you want to control what keys are being tracked by ng-repeat you can use a trackby statement: https://docs.angularjs.org/api/ng/directive/ngRepeat

```<code><div ng-repeat="model in collection track by model.id">
  {{model.name}}
</div>
</code>```

modifying other properties won't fire the refresh, which can be very positive for performance, or painful if you do a search/filter across all the properties of an object.

Body:
I'm trying to make a minimal but fancy AngularJS tutorial example, and I am running into an issue where after updating the entire tree for a model (inside the scope of an ng-change update), a template that is driven by a top-level ng-repeat is not re-rendered at all.

However, if I add the code $scope.data = {} at a strategic place, it starts working; but then the display flashes instead of being nice and smooth.  And it's not a great example of how AngularJS automatic data binding works.

What am I missing; and what would be the right fix?

Exact code - select a country from the dropdown -
This jsFiddle does not work: http://jsfiddle.net/f9zxt36g/
This jsFiddle works but flickers: http://jsfiddle.net/y090my10/

var app = angular.module('factbook', []);
app.controller('loadfact', function($scope, $http) {
  $scope.country = 'europe/uk';
  $scope.safe = function safe(name) { // Makes a safe CSS class name
    return name.replace(/[_\W]+/g, '_').toLowerCase();
  };
  $scope.trunc = function trunc(text) { // Truncates text to 500 chars
    return (text.length < 500) ? text : text.substr(0, 500) + "...";
  };
  $scope.update = function() { // Handles country selection
    // $scope.data = {}; // uncomment to force rednering; an angular bug?
    $http.get('https://rawgit.com/opendatajson/factbook.json/master/' +
        $scope.country + '.json').then(function(response) {
      $scope.data = response.data;
    });
  };
  $scope.countries = [
    {id: 'europe/uk', name: 'UK'},
    {id: 'africa/eg', name: 'Egypt'},
    {id: 'east-n-southeast-asia/ch', name: 'China'}
  ];
  $scope.update();
});

The template is driven by ng-repeat:

  <select ng-model="country" ng-change="update()"
      ng-options="item.id as item.name for item in countries">
  </select>

What am I missing?

Body:
If you want to control what keys are being tracked by ng-repeat you can use a trackby statement: https://docs.angularjs.org/api/ng/directive/ngRepeat

<div ng-repeat="model in collection track by model.id">
  {{model.name}}
</div>

modifying other properties won't fire the refresh, which can be very positive for performance, or painful if you do a search/filter across all the properties of an object.


问:
ReactJS state changes are not reflected in different sessions at the same time
I'm using ReactJS,Typescript and Firebase to build a web app, in which one user will be able to monitor the changes and interactions with the UI of another user. Both users can see an identical view at the same time with a few images displayed. For example, any image clicked by User1 changes its border, which should be reflected in the UI of User2.
This is doable with DOM, typescript and firebase alone, but with ReactJS I'm facing a lot of difficulties.

First question:
Is it possible to update an already created and displayed component in ReactJS without using state or props?

From what I've seen so far, I'm assuming this is not possible. So,

Second question:
I'm trying to use states alone to achieve what I explained, but it seems that whenever User1 for example changes the state, the component displayed to User1 is re-rendering alone without the component of User2 being able to capture the change in the state to re-render. Both of the components are identical.
I'm using Chrome and Firefox to run the app with the 2 users. Is there a way to achieve this with states and props alone?

I'm a beginner in this area. Any help will be much appreciated.

答:
If you centralize state management with something like redux, the application state ought to be representable as a single object. You ought to then be able to add some redux middleware to the app to push any state changes to, say, Firebase, and then read back all changes from Firebase and push them into your store (via an action).

If you do prefer to update the component without changing props instead, there is a forceUpdate method.