问:
Create spinning circle loading animation
I'm trying to create a spinning circle loader animation like in the following Android project (https://github.com/pedant/sweet-alert-dialog).

I don't need the entire popup dialog - just the spinning part. It changes colors and spins indefinitly (until I choose to dismiss it).

I'm kind of new to swift and I've never been the kind to do animations. Here's what I have so far (found code in similar project for iOS):

The layers setup:

```<code>    outlineLayer.position = CGPointMake(0,
        0);
    outlineLayer.path = outlineCircle
    outlineLayer.fillColor = UIColor.clearColor().CGColor;
    outlineLayer.strokeColor = UIColor(red: 150.0/255.0, green: 216.0/255.0, blue: 115.0/255.0, alpha: 1.0).CGColor;
    outlineLayer.lineCap = kCALineCapRound
    outlineLayer.lineWidth = 4;
    outlineLayer.opacity = 0.1
    self.layer.addSublayer(outlineLayer)

    circleLayer.position = CGPointMake(0,
        0);
    circleLayer.path = path
    circleLayer.fillColor = UIColor.clearColor().CGColor;
    circleLayer.strokeColor = UIColor(red: 150.0/255.0, green: 216.0/255.0, blue: 115.0/255.0, alpha: 1.0).CGColor;
    circleLayer.lineCap = kCALineCapRound
    circleLayer.lineWidth = 4;
    circleLayer.actions = [
        "strokeStart": NSNull(),
        "strokeEnd": NSNull(),
        "transform": NSNull()
    ]
    self.layer.addSublayer(circleLayer)
</code>```

Animation:

```<code>let strokeStart = CABasicAnimation(keyPath: "strokeStart")
    let strokeEnd = CABasicAnimation(keyPath: "strokeEnd")
    let factor = 0.545
    let timing = CAMediaTimingFunction(controlPoints: 0.3, 0.6, 0.8, 1.2)

    strokeEnd.fromValue = 0.00
    strokeEnd.toValue = 0.93
    strokeEnd.duration = 10.0 * factor
    strokeEnd.timingFunction = timing
    strokeEnd.autoreverses = true

    strokeStart.fromValue = 0.0
    strokeStart.toValue = 0.68
    strokeStart.duration =  10.0 * factor
    strokeStart.beginTime =  CACurrentMediaTime() + 3.0 * factor
    strokeStart.fillMode = kCAFillModeBackwards
    strokeStart.timingFunction = timing
    strokeStart.repeatCount = HUGE

    circleLayer.strokeStart = 0.68
    circleLayer.strokeEnd = 0.93

    self.circleLayer.addAnimation(strokeEnd, forKey: "strokeEnd")
    self.circleLayer.addAnimation(strokeStart, forKey: "strokeStart")
</code>```

but what I have is not nearly close and I have no idea where to go from here. What I'm doing is changing a value and running seeing how it affects but I feel like I'm lost here.

How can I achieve such animation like in the example?

答:
Try out my three custom Loader screen very simple :

Write below code in Viewcontoller.swift file

```<code>class ViewController: UIViewController {

var signView = SignView(frame: CGRect.zero)
var testView = TestView(frame: CGRect.zero)
var testView1 = TestView1(frame: CGRect.zero)

override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = UIColor.orange
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
      addSignView()
    //addTestView()
    //addTestView1()
}

func addSignView() {
    signView.frame = CGRect(x: 0,
                            y: 0,
                            width: UIScreen.main.bounds.size.width,
                            height: UIScreen.main.bounds.size.height)
    self.view.addSubview(signView)
    signView.addAnimationLayer()
}

func addTestView() {
    let boxSize: CGFloat = 200.0

    testView.frame = CGRect(x: 16,
                            y: 350,
                            width: boxSize,
                            height: boxSize)
    self.view.addSubview(testView)
    testView.addAnimationLayer()
}

func addTestView1() {

    testView1.frame = CGRect(x: 0,
                            y: 0,
                            width: UIScreen.main.bounds.size.width,
                            height: UIScreen.main.bounds.size.height)
    self.view.addSubview(testView1)
    testView1.addAnimationLayer()
}}
</code>```

Now Add 3 Files inherit with UiView named > SignView , TestView and TestView1

Code for SignView.swift file

```<code>class SignView: UIView {

let upCircleLayer = CAShapeLayer.init()
var path = UIBezierPath.init()
var animationDuration : Double = 2
var frameHeight : CGFloat = 50.0

override init(frame: CGRect) {
    super.init(frame: frame)

    self.backgroundColor = UIColor.black.withAlphaComponent(0.5)
}

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

var signWavePath : UIBezierPath {
    var clockCycle = true
    let yPoint = self.frame.size.height/2
    frameHeight =  self.frame.size.width/6
    for x in 1...24{

        if x%2 != 0 {

            let xpath =  UIBezierPath(arcCenter: CGPoint(x: CGFloat(x)*frameHeight/2, y: yPoint),
                         radius: frameHeight/2,
                         startAngle: 180.0 * .pi/180.0,
                         endAngle: 0.0,
                         clockwise: clockCycle)
            path.append(xpath)

            if(clockCycle){
                clockCycle = false
            }
            else{
                clockCycle = true
            }

        }
    }

    return path;
}

func addAnimationLayer() {

    // Add Upper Circle Layer
    upCircleLayer.fillColor = UIColor.clear.cgColor
    upCircleLayer.strokeColor = UIColor.white.cgColor
    upCircleLayer.lineWidth = 8.0
    upCircleLayer.path = signWavePath.cgPath
    layer.addSublayer(upCircleLayer)

    animateStrokeUpCircle()

    Timer.scheduledTimer(timeInterval: animationDuration, target: self, selector: #selector(animateStrokeUpCircle), userInfo: nil, repeats: true)
}

func animateStrokeUpCircle() {

    let strokeAnimation: CABasicAnimation = CABasicAnimation(keyPath: "strokeEnd")
        strokeAnimation.fromValue = 0.0
        strokeAnimation.toValue = 1.0
        strokeAnimation.duration = animationDuration
        strokeAnimation.isRemovedOnCompletion = false
        upCircleLayer.add(strokeAnimation, forKey: nil)

        expand1()
}
func expand1() {

        let expandAnimation: CABasicAnimation = CABasicAnimation(keyPath: "position")
        expandAnimation.fromValue = [0,sin(self.frame.width)]
        expandAnimation.toValue = [-self.frame.width,cos(self.frame.width)]
        expandAnimation.duration = animationDuration
        expandAnimation.fillMode = kCAFillModeForwards
        expandAnimation.isRemovedOnCompletion = false
        upCircleLayer.add(expandAnimation, forKey: nil)
}
</code>```

}

Code for TestView File :

```<code>class TestView: UIView {

let upCircleLayer = CAShapeLayer.init()
let downCircleLayer = CAShapeLayer.init()

var path1 = UIBezierPath.init()
var path2 = UIBezierPath.init()

var animationDirection : Bool = true

override init(frame: CGRect) {
    super.init(frame: frame)
    self.backgroundColor = UIColor.clear
}

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

var up1Circle: UIBezierPath {
    return UIBezierPath(arcCenter: CGPoint(x: self.frame.size.width/4, y: self.frame.size.height/2),
                        radius: self.frame.size.height/4,
                        startAngle: 180.0 * .pi/180.0,
                        endAngle: 0.0,
                        clockwise: true)
}
var down2Circle: UIBezierPath {
    return UIBezierPath(arcCenter: CGPoint(x: 3*self.frame.size.width/4, y: self.frame.size.height/2),
                        radius: self.frame.size.height/4,
                        startAngle: 180.0 * .pi/180.0,
                        endAngle: 0.0,
                        clockwise: false)
}

var up22Circle: UIBezierPath {
    return UIBezierPath(arcCenter: CGPoint(x: 3*self.frame.size.width/4, y: self.frame.size.height/2),
                        radius: self.frame.size.height/4,
                        startAngle: 180.0 * .pi/180.0,
                        endAngle: 0.0,
                        clockwise: true)
}
var down11Circle: UIBezierPath {
    return UIBezierPath(arcCenter: CGPoint(x: self.frame.size.width/4, y: self.frame.size.height/2),
                        radius: self.frame.size.height/4,
                        startAngle: 180.0 * .pi/180.0,
                        endAngle: 0.0,
                        clockwise: false)
}

var up2Circle: UIBezierPath {
    return UIBezierPath(arcCenter: CGPoint(x: 3*self.frame.size.width/4, y: self.frame.size.height/2),
                        radius: self.frame.size.height/4,
                        startAngle: 0.0,
                        endAngle: 180.0 * .pi/180.0,
                        clockwise: true)
}
var down1Circle: UIBezierPath {
    return UIBezierPath(arcCenter: CGPoint(x: self.frame.size.width/4, y: self.frame.size.height/2),
                        radius: self.frame.size.height/4,
                        startAngle: 0.0,
                        endAngle: 180.0 * .pi/180.0,
                        clockwise: false)
}

func addAnimationLayer() {

    path1.append(up1Circle);
    path1.append(down2Circle);

    path2.append(down11Circle)
    path2.append(up22Circle)

    // Add Upper Circle Layer
    upCircleLayer.fillColor = UIColor.clear.cgColor
    upCircleLayer.strokeColor = UIColor.black.cgColor
    upCircleLayer.lineWidth = 8.0
    upCircleLayer.path = path1.cgPath
    layer.addSublayer(upCircleLayer)

     Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(expand1), userInfo: nil, repeats: true)

}

func expand() {

    if animationDirection{
        //upCircleLayer.path = path1.cgPath
        let expandAnimation: CABasicAnimation = CABasicAnimation(keyPath: "path")
        expandAnimation.fromValue = path1.cgPath
        expandAnimation.toValue = path2.cgPath
        expandAnimation.duration = 1.5
        //expandAnimation.fillMode = kCAFillModeForwards
        expandAnimation.isRemovedOnCompletion = false
        upCircleLayer.add(expandAnimation, forKey: nil)

        animationDirection = false
    }
    else{
        //upCircleLayer.path = path2.cgPath
        let expandAnimation: CABasicAnimation = CABasicAnimation(keyPath: "path")
        expandAnimation.fromValue = path2.cgPath
        expandAnimation.toValue = path1.cgPath
        expandAnimation.duration = 1.5
        //expandAnimation.fillMode = kCAFillModeForwards
        expandAnimation.isRemovedOnCompletion = false
        upCircleLayer.add(expandAnimation, forKey: nil)
        animationDirection = true
    }

}

func expand1() {

    let expandAnimation: CABasicAnimation = CABasicAnimation(keyPath: "position")
    expandAnimation.fromValue = [0,self.frame.height/2]
    expandAnimation.toValue = 500
    expandAnimation.duration = 2.0
    expandAnimation.fillMode = kCAFillModeForwards
    expandAnimation.isRemovedOnCompletion = false
    upCircleLayer.add(expandAnimation, forKey: nil)
}
</code>```

}

And Code for TestView1.swift file

class TestView1: UIView {

```<code>let animationLayer = CAShapeLayer.init()

var path1 = UIBezierPath.init()
var path2 = UIBezierPath.init()
var path = UIBezierPath.init()
var circleRadius : CGFloat = 26.0;
var centerLineHeight : CGFloat = 40.0
var animationDuration : Double = 2.0

var animationDirection : Bool = true

override init(frame: CGRect) {
    super.init(frame: frame)
    self.backgroundColor = UIColor.black
}

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

var centerMainLine: UIBezierPath {
    let frameSize = self.frame.size
    let centerLine = UIBezierPath()
    centerLine.move(to: CGPoint(x: frameSize.width/2, y: frameSize.height/2 - centerLineHeight/2))
    centerLine.addLine(to: CGPoint(x: frameSize.width/2, y: frameSize.height/2 + centerLineHeight/2))
    return centerLine
}

var upLeftCircle: UIBezierPath {
    let frameSize = self.frame.size
    let halfCircle = UIBezierPath(arcCenter: CGPoint(x: frameSize.width/2 - circleRadius, y: frameSize.height/2 - centerLineHeight/2),
                        radius: circleRadius,
                        startAngle: 180.0 * .pi/180.0,
                        endAngle: 0.0,
                        clockwise: true)
    return halfCircle
}
var upRightCircle: UIBezierPath {
    let frameSize = self.frame.size
    let halfCircle = UIBezierPath(arcCenter: CGPoint(x: frameSize.width/2 + circleRadius, y: frameSize.height/2 - centerLineHeight/2),
                                  radius: circleRadius,
                                  startAngle: 180.0 * .pi/180.0,
                                  endAngle: 0.0,
                                  clockwise: true)
    return halfCircle
}
var downLeftCircle: UIBezierPath {
    let frameSize = self.frame.size
    let halfCircle = UIBezierPath(arcCenter: CGPoint(x: frameSize.width/2 - circleRadius, y: frameSize.height/2 + centerLineHeight/2),
                                  radius: circleRadius,
                                  startAngle: 180.0 * .pi/180.0,
                                  endAngle: 0.0,
                                  clockwise: false)
    return halfCircle
}
var downRightCircle: UIBezierPath {
    let frameSize = self.frame.size
    let halfCircle = UIBezierPath(arcCenter: CGPoint(x: frameSize.width/2 + circleRadius, y: frameSize.height/2 + centerLineHeight/2),
                                  radius: circleRadius,
                                  startAngle: 180.0 * .pi/180.0,
                                  endAngle: 0.0,
                                  clockwise: false)
    return halfCircle
}

func drawUpCircle(centerPoint:CGPoint, radiusValue:CGFloat) -> UIBezierPath {

    let halfCircle = UIBezierPath(arcCenter: centerPoint,
                                  radius: radiusValue,
                                  startAngle: 180.0 * .pi/180.0,
                                  endAngle: 0.0,
                                  clockwise: true)
    return halfCircle
}
func drawDownCircle(centerPoint:CGPoint,radiusValue:CGFloat) -> UIBezierPath {

    let halfCircle = UIBezierPath(arcCenter: centerPoint,
                                  radius: radiusValue,
                                  startAngle: 180.0 * .pi/180.0,
                                  endAngle: 0.0,
                                  clockwise: false)
    return halfCircle
}
func drawLine(fromPoint:CGPoint,toPoint:CGPoint) -> UIBezierPath {

    let line = UIBezierPath()
    line.move(to: fromPoint)
    line.addLine(to: toPoint)
    return line
}

func addAnimationLayer() {

    createPathOne()
    createPathTwo()
    createPath()

    // set Animation Layer design
    animationLayer.fillColor = UIColor.clear.cgColor
    animationLayer.strokeColor = UIColor.white.cgColor
    animationLayer.lineWidth = 8.0
    animationLayer.path = path.cgPath
    layer.addSublayer(animationLayer)
    expand1()
    Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(expand1), userInfo: nil, repeats: true)
}
func expand1() {

    let expandAnimation: CABasicAnimation = CABasicAnimation(keyPath: "position")
    expandAnimation.fromValue = [0,0]
    expandAnimation.toValue = [-2000,0]
    expandAnimation.duration = 10.0
    expandAnimation.fillMode = kCAFillModeForwards
    expandAnimation.isRemovedOnCompletion = false
    animationLayer.add(expandAnimation, forKey: nil)
}
func expand() {
    animationLayer.path = centerMainLine.cgPath
    if animationDirection{

        let expandAnimation: CABasicAnimation = CABasicAnimation(keyPath: "path")
        expandAnimation.fromValue = path1.cgPath
        expandAnimation.toValue = path2.cgPath
        expandAnimation.duration = animationDuration
        expandAnimation.fillMode = kCAFillModeBackwards
        expandAnimation.isRemovedOnCompletion = false
        animationLayer.add(expandAnimation, forKey: nil)

        animationDirection = false
    }
    else{
        let expandAnimation: CABasicAnimation = CABasicAnimation(keyPath: "path")
        expandAnimation.fromValue = path2.cgPath
        expandAnimation.toValue = path1.cgPath
        expandAnimation.duration = animationDuration
        expandAnimation.fillMode = kCAFillModeForwards
        expandAnimation.isRemovedOnCompletion = false
        animationLayer.add(expandAnimation, forKey: nil)

        animationDirection = true
    }
}

func createPathOne(){

    path1.append(upLeftCircle);
    path1.append(centerMainLine);
    path1.append(downRightCircle)

}
func createPathTwo(){
    path2.append(downLeftCircle);
    path2.append(centerMainLine);
    path2.append(upRightCircle)
}

func createPath()  {
    let frameSize = self.frame.size;

    let lineHeight1 : CGFloat = 30
    let lineHeight2 : CGFloat = 20

    let radius1 : CGFloat = 40.0
    let radius2 : CGFloat = 20.0

    var lastPoint : CGPoint = CGPoint(x:0.0,y:frameSize.height/2 - lineHeight1/2)
    for i in 1...10{

        let p1 = drawUpCircle(centerPoint: CGPoint(x: lastPoint.x + radius1, y: lastPoint.y  ), radiusValue: radius1)
        lastPoint = p1.currentPoint;

        let p2 = drawLine(fromPoint: lastPoint , toPoint: CGPoint(x:lastPoint.x, y: lastPoint.y+lineHeight1))
        lastPoint = p2.currentPoint;

        let p3 = drawDownCircle(centerPoint: CGPoint(x:lastPoint.x + radius1, y: lastPoint.y), radiusValue: radius1)
        lastPoint = p3.currentPoint;

        let p4 = drawLine(fromPoint: lastPoint, toPoint: CGPoint(x:lastPoint.x, y: lastPoint.y - lineHeight2))
        lastPoint = p4.currentPoint;

        let p5 = drawUpCircle(centerPoint: CGPoint(x:lastPoint.x + radius2, y: lastPoint.y), radiusValue: radius2)
        lastPoint = p5.currentPoint;

        let p6 = drawLine(fromPoint: lastPoint, toPoint: CGPoint(x:lastPoint.x, y: lastPoint.y + lineHeight2))
        lastPoint = p6.currentPoint;

        let p7 = drawDownCircle(centerPoint: CGPoint(x:lastPoint.x + radius2, y: lastPoint.y), radiusValue: radius2)
        lastPoint = p7.currentPoint

        let p8  = drawLine(fromPoint: lastPoint, toPoint: CGPoint(x:lastPoint.x, y: lastPoint.y - lineHeight1))
        lastPoint = p8.currentPoint;

        path.append(p1)
        path.append(p2)
        path.append(p3)
        path.append(p4)
        path.append(p5)
        path.append(p6)
        path.append(p7)
        path.append(p8)

    }

}
</code>```

}

Now run the code to check the Animation Loader. Comment/Uncomment other 2 loader method in viewDidAppear method of viewcontroller.

Enjoy!!

Body:
I'm trying to create a spinning circle loader animation like in the following Android project (https://github.com/pedant/sweet-alert-dialog).

I don't need the entire popup dialog - just the spinning part. It changes colors and spins indefinitly (until I choose to dismiss it).

I'm kind of new to swift and I've never been the kind to do animations. Here's what I have so far (found code in similar project for iOS):

The layers setup:

    outlineLayer.position = CGPointMake(0,
        0);
    outlineLayer.path = outlineCircle
    outlineLayer.fillColor = UIColor.clearColor().CGColor;
    outlineLayer.strokeColor = UIColor(red: 150.0/255.0, green: 216.0/255.0, blue: 115.0/255.0, alpha: 1.0).CGColor;
    outlineLayer.lineCap = kCALineCapRound
    outlineLayer.lineWidth = 4;
    outlineLayer.opacity = 0.1
    self.layer.addSublayer(outlineLayer)

    circleLayer.position = CGPointMake(0,
        0);
    circleLayer.path = path
    circleLayer.fillColor = UIColor.clearColor().CGColor;
    circleLayer.strokeColor = UIColor(red: 150.0/255.0, green: 216.0/255.0, blue: 115.0/255.0, alpha: 1.0).CGColor;
    circleLayer.lineCap = kCALineCapRound
    circleLayer.lineWidth = 4;
    circleLayer.actions = [
        "strokeStart": NSNull(),
        "strokeEnd": NSNull(),
        "transform": NSNull()
    ]
    self.layer.addSublayer(circleLayer)

Animation:

let strokeStart = CABasicAnimation(keyPath: "strokeStart")
    let strokeEnd = CABasicAnimation(keyPath: "strokeEnd")
    let factor = 0.545
    let timing = CAMediaTimingFunction(controlPoints: 0.3, 0.6, 0.8, 1.2)

    strokeEnd.fromValue = 0.00
    strokeEnd.toValue = 0.93
    strokeEnd.duration = 10.0 * factor
    strokeEnd.timingFunction = timing
    strokeEnd.autoreverses = true

    strokeStart.fromValue = 0.0
    strokeStart.toValue = 0.68
    strokeStart.duration =  10.0 * factor
    strokeStart.beginTime =  CACurrentMediaTime() + 3.0 * factor
    strokeStart.fillMode = kCAFillModeBackwards
    strokeStart.timingFunction = timing
    strokeStart.repeatCount = HUGE

    circleLayer.strokeStart = 0.68
    circleLayer.strokeEnd = 0.93

    self.circleLayer.addAnimation(strokeEnd, forKey: "strokeEnd")
    self.circleLayer.addAnimation(strokeStart, forKey: "strokeStart")

but what I have is not nearly close and I have no idea where to go from here. What I'm doing is changing a value and running seeing how it affects but I feel like I'm lost here.

How can I achieve such animation like in the example?

Body:
Try out my three custom Loader screen very simple :

Write below code in Viewcontoller.swift file

class ViewController: UIViewController {

var signView = SignView(frame: CGRect.zero)
var testView = TestView(frame: CGRect.zero)
var testView1 = TestView1(frame: CGRect.zero)

override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = UIColor.orange
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
      addSignView()
    //addTestView()
    //addTestView1()
}

func addSignView() {
    signView.frame = CGRect(x: 0,
                            y: 0,
                            width: UIScreen.main.bounds.size.width,
                            height: UIScreen.main.bounds.size.height)
    self.view.addSubview(signView)
    signView.addAnimationLayer()
}

func addTestView() {
    let boxSize: CGFloat = 200.0

    testView.frame = CGRect(x: 16,
                            y: 350,
                            width: boxSize,
                            height: boxSize)
    self.view.addSubview(testView)
    testView.addAnimationLayer()
}

func addTestView1() {

    testView1.frame = CGRect(x: 0,
                            y: 0,
                            width: UIScreen.main.bounds.size.width,
                            height: UIScreen.main.bounds.size.height)
    self.view.addSubview(testView1)
    testView1.addAnimationLayer()
}}

Now Add 3 Files inherit with UiView named > SignView , TestView and TestView1

Code for SignView.swift file

class SignView: UIView {

let upCircleLayer = CAShapeLayer.init()
var path = UIBezierPath.init()
var animationDuration : Double = 2
var frameHeight : CGFloat = 50.0

override init(frame: CGRect) {
    super.init(frame: frame)

    self.backgroundColor = UIColor.black.withAlphaComponent(0.5)
}

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

var signWavePath : UIBezierPath {
    var clockCycle = true
    let yPoint = self.frame.size.height/2
    frameHeight =  self.frame.size.width/6
    for x in 1...24{

        if x%2 != 0 {

            let xpath =  UIBezierPath(arcCenter: CGPoint(x: CGFloat(x)*frameHeight/2, y: yPoint),
                         radius: frameHeight/2,
                         startAngle: 180.0 * .pi/180.0,
                         endAngle: 0.0,
                         clockwise: clockCycle)
            path.append(xpath)

            if(clockCycle){
                clockCycle = false
            }
            else{
                clockCycle = true
            }

        }
    }

    return path;
}

func addAnimationLayer() {

    // Add Upper Circle Layer
    upCircleLayer.fillColor = UIColor.clear.cgColor
    upCircleLayer.strokeColor = UIColor.white.cgColor
    upCircleLayer.lineWidth = 8.0
    upCircleLayer.path = signWavePath.cgPath
    layer.addSublayer(upCircleLayer)

    animateStrokeUpCircle()

    Timer.scheduledTimer(timeInterval: animationDuration, target: self, selector: #selector(animateStrokeUpCircle), userInfo: nil, repeats: true)
}

func animateStrokeUpCircle() {

    let strokeAnimation: CABasicAnimation = CABasicAnimation(keyPath: "strokeEnd")
        strokeAnimation.fromValue = 0.0
        strokeAnimation.toValue = 1.0
        strokeAnimation.duration = animationDuration
        strokeAnimation.isRemovedOnCompletion = false
        upCircleLayer.add(strokeAnimation, forKey: nil)

        expand1()
}
func expand1() {

        let expandAnimation: CABasicAnimation = CABasicAnimation(keyPath: "position")
        expandAnimation.fromValue = [0,sin(self.frame.width)]
        expandAnimation.toValue = [-self.frame.width,cos(self.frame.width)]
        expandAnimation.duration = animationDuration
        expandAnimation.fillMode = kCAFillModeForwards
        expandAnimation.isRemovedOnCompletion = false
        upCircleLayer.add(expandAnimation, forKey: nil)
}

}

Code for TestView File :

class TestView: UIView {

let upCircleLayer = CAShapeLayer.init()
let downCircleLayer = CAShapeLayer.init()

var path1 = UIBezierPath.init()
var path2 = UIBezierPath.init()

var animationDirection : Bool = true

override init(frame: CGRect) {
    super.init(frame: frame)
    self.backgroundColor = UIColor.clear
}

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

var up1Circle: UIBezierPath {
    return UIBezierPath(arcCenter: CGPoint(x: self.frame.size.width/4, y: self.frame.size.height/2),
                        radius: self.frame.size.height/4,
                        startAngle: 180.0 * .pi/180.0,
                        endAngle: 0.0,
                        clockwise: true)
}
var down2Circle: UIBezierPath {
    return UIBezierPath(arcCenter: CGPoint(x: 3*self.frame.size.width/4, y: self.frame.size.height/2),
                        radius: self.frame.size.height/4,
                        startAngle: 180.0 * .pi/180.0,
                        endAngle: 0.0,
                        clockwise: false)
}

var up22Circle: UIBezierPath {
    return UIBezierPath(arcCenter: CGPoint(x: 3*self.frame.size.width/4, y: self.frame.size.height/2),
                        radius: self.frame.size.height/4,
                        startAngle: 180.0 * .pi/180.0,
                        endAngle: 0.0,
                        clockwise: true)
}
var down11Circle: UIBezierPath {
    return UIBezierPath(arcCenter: CGPoint(x: self.frame.size.width/4, y: self.frame.size.height/2),
                        radius: self.frame.size.height/4,
                        startAngle: 180.0 * .pi/180.0,
                        endAngle: 0.0,
                        clockwise: false)
}

var up2Circle: UIBezierPath {
    return UIBezierPath(arcCenter: CGPoint(x: 3*self.frame.size.width/4, y: self.frame.size.height/2),
                        radius: self.frame.size.height/4,
                        startAngle: 0.0,
                        endAngle: 180.0 * .pi/180.0,
                        clockwise: true)
}
var down1Circle: UIBezierPath {
    return UIBezierPath(arcCenter: CGPoint(x: self.frame.size.width/4, y: self.frame.size.height/2),
                        radius: self.frame.size.height/4,
                        startAngle: 0.0,
                        endAngle: 180.0 * .pi/180.0,
                        clockwise: false)
}

func addAnimationLayer() {

    path1.append(up1Circle);
    path1.append(down2Circle);

    path2.append(down11Circle)
    path2.append(up22Circle)

    // Add Upper Circle Layer
    upCircleLayer.fillColor = UIColor.clear.cgColor
    upCircleLayer.strokeColor = UIColor.black.cgColor
    upCircleLayer.lineWidth = 8.0
    upCircleLayer.path = path1.cgPath
    layer.addSublayer(upCircleLayer)

     Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(expand1), userInfo: nil, repeats: true)

}

func expand() {

    if animationDirection{
        //upCircleLayer.path = path1.cgPath
        let expandAnimation: CABasicAnimation = CABasicAnimation(keyPath: "path")
        expandAnimation.fromValue = path1.cgPath
        expandAnimation.toValue = path2.cgPath
        expandAnimation.duration = 1.5
        //expandAnimation.fillMode = kCAFillModeForwards
        expandAnimation.isRemovedOnCompletion = false
        upCircleLayer.add(expandAnimation, forKey: nil)

        animationDirection = false
    }
    else{
        //upCircleLayer.path = path2.cgPath
        let expandAnimation: CABasicAnimation = CABasicAnimation(keyPath: "path")
        expandAnimation.fromValue = path2.cgPath
        expandAnimation.toValue = path1.cgPath
        expandAnimation.duration = 1.5
        //expandAnimation.fillMode = kCAFillModeForwards
        expandAnimation.isRemovedOnCompletion = false
        upCircleLayer.add(expandAnimation, forKey: nil)
        animationDirection = true
    }

}

func expand1() {

    let expandAnimation: CABasicAnimation = CABasicAnimation(keyPath: "position")
    expandAnimation.fromValue = [0,self.frame.height/2]
    expandAnimation.toValue = 500
    expandAnimation.duration = 2.0
    expandAnimation.fillMode = kCAFillModeForwards
    expandAnimation.isRemovedOnCompletion = false
    upCircleLayer.add(expandAnimation, forKey: nil)
}

}

And Code for TestView1.swift file

class TestView1: UIView {

let animationLayer = CAShapeLayer.init()

var path1 = UIBezierPath.init()
var path2 = UIBezierPath.init()
var path = UIBezierPath.init()
var circleRadius : CGFloat = 26.0;
var centerLineHeight : CGFloat = 40.0
var animationDuration : Double = 2.0

var animationDirection : Bool = true

override init(frame: CGRect) {
    super.init(frame: frame)
    self.backgroundColor = UIColor.black
}

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

var centerMainLine: UIBezierPath {
    let frameSize = self.frame.size
    let centerLine = UIBezierPath()
    centerLine.move(to: CGPoint(x: frameSize.width/2, y: frameSize.height/2 - centerLineHeight/2))
    centerLine.addLine(to: CGPoint(x: frameSize.width/2, y: frameSize.height/2 + centerLineHeight/2))
    return centerLine
}

var upLeftCircle: UIBezierPath {
    let frameSize = self.frame.size
    let halfCircle = UIBezierPath(arcCenter: CGPoint(x: frameSize.width/2 - circleRadius, y: frameSize.height/2 - centerLineHeight/2),
                        radius: circleRadius,
                        startAngle: 180.0 * .pi/180.0,
                        endAngle: 0.0,
                        clockwise: true)
    return halfCircle
}
var upRightCircle: UIBezierPath {
    let frameSize = self.frame.size
    let halfCircle = UIBezierPath(arcCenter: CGPoint(x: frameSize.width/2 + circleRadius, y: frameSize.height/2 - centerLineHeight/2),
                                  radius: circleRadius,
                                  startAngle: 180.0 * .pi/180.0,
                                  endAngle: 0.0,
                                  clockwise: true)
    return halfCircle
}
var downLeftCircle: UIBezierPath {
    let frameSize = self.frame.size
    let halfCircle = UIBezierPath(arcCenter: CGPoint(x: frameSize.width/2 - circleRadius, y: frameSize.height/2 + centerLineHeight/2),
                                  radius: circleRadius,
                                  startAngle: 180.0 * .pi/180.0,
                                  endAngle: 0.0,
                                  clockwise: false)
    return halfCircle
}
var downRightCircle: UIBezierPath {
    let frameSize = self.frame.size
    let halfCircle = UIBezierPath(arcCenter: CGPoint(x: frameSize.width/2 + circleRadius, y: frameSize.height/2 + centerLineHeight/2),
                                  radius: circleRadius,
                                  startAngle: 180.0 * .pi/180.0,
                                  endAngle: 0.0,
                                  clockwise: false)
    return halfCircle
}

func drawUpCircle(centerPoint:CGPoint, radiusValue:CGFloat) -> UIBezierPath {

    let halfCircle = UIBezierPath(arcCenter: centerPoint,
                                  radius: radiusValue,
                                  startAngle: 180.0 * .pi/180.0,
                                  endAngle: 0.0,
                                  clockwise: true)
    return halfCircle
}
func drawDownCircle(centerPoint:CGPoint,radiusValue:CGFloat) -> UIBezierPath {

    let halfCircle = UIBezierPath(arcCenter: centerPoint,
                                  radius: radiusValue,
                                  startAngle: 180.0 * .pi/180.0,
                                  endAngle: 0.0,
                                  clockwise: false)
    return halfCircle
}
func drawLine(fromPoint:CGPoint,toPoint:CGPoint) -> UIBezierPath {

    let line = UIBezierPath()
    line.move(to: fromPoint)
    line.addLine(to: toPoint)
    return line
}

func addAnimationLayer() {

    createPathOne()
    createPathTwo()
    createPath()

    // set Animation Layer design
    animationLayer.fillColor = UIColor.clear.cgColor
    animationLayer.strokeColor = UIColor.white.cgColor
    animationLayer.lineWidth = 8.0
    animationLayer.path = path.cgPath
    layer.addSublayer(animationLayer)
    expand1()
    Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(expand1), userInfo: nil, repeats: true)
}
func expand1() {

    let expandAnimation: CABasicAnimation = CABasicAnimation(keyPath: "position")
    expandAnimation.fromValue = [0,0]
    expandAnimation.toValue = [-2000,0]
    expandAnimation.duration = 10.0
    expandAnimation.fillMode = kCAFillModeForwards
    expandAnimation.isRemovedOnCompletion = false
    animationLayer.add(expandAnimation, forKey: nil)
}
func expand() {
    animationLayer.path = centerMainLine.cgPath
    if animationDirection{

        let expandAnimation: CABasicAnimation = CABasicAnimation(keyPath: "path")
        expandAnimation.fromValue = path1.cgPath
        expandAnimation.toValue = path2.cgPath
        expandAnimation.duration = animationDuration
        expandAnimation.fillMode = kCAFillModeBackwards
        expandAnimation.isRemovedOnCompletion = false
        animationLayer.add(expandAnimation, forKey: nil)

        animationDirection = false
    }
    else{
        let expandAnimation: CABasicAnimation = CABasicAnimation(keyPath: "path")
        expandAnimation.fromValue = path2.cgPath
        expandAnimation.toValue = path1.cgPath
        expandAnimation.duration = animationDuration
        expandAnimation.fillMode = kCAFillModeForwards
        expandAnimation.isRemovedOnCompletion = false
        animationLayer.add(expandAnimation, forKey: nil)

        animationDirection = true
    }
}

func createPathOne(){

    path1.append(upLeftCircle);
    path1.append(centerMainLine);
    path1.append(downRightCircle)

}
func createPathTwo(){
    path2.append(downLeftCircle);
    path2.append(centerMainLine);
    path2.append(upRightCircle)
}

func createPath()  {
    let frameSize = self.frame.size;

    let lineHeight1 : CGFloat = 30
    let lineHeight2 : CGFloat = 20

    let radius1 : CGFloat = 40.0
    let radius2 : CGFloat = 20.0

    var lastPoint : CGPoint = CGPoint(x:0.0,y:frameSize.height/2 - lineHeight1/2)
    for i in 1...10{

        let p1 = drawUpCircle(centerPoint: CGPoint(x: lastPoint.x + radius1, y: lastPoint.y  ), radiusValue: radius1)
        lastPoint = p1.currentPoint;

        let p2 = drawLine(fromPoint: lastPoint , toPoint: CGPoint(x:lastPoint.x, y: lastPoint.y+lineHeight1))
        lastPoint = p2.currentPoint;

        let p3 = drawDownCircle(centerPoint: CGPoint(x:lastPoint.x + radius1, y: lastPoint.y), radiusValue: radius1)
        lastPoint = p3.currentPoint;

        let p4 = drawLine(fromPoint: lastPoint, toPoint: CGPoint(x:lastPoint.x, y: lastPoint.y - lineHeight2))
        lastPoint = p4.currentPoint;

        let p5 = drawUpCircle(centerPoint: CGPoint(x:lastPoint.x + radius2, y: lastPoint.y), radiusValue: radius2)
        lastPoint = p5.currentPoint;

        let p6 = drawLine(fromPoint: lastPoint, toPoint: CGPoint(x:lastPoint.x, y: lastPoint.y + lineHeight2))
        lastPoint = p6.currentPoint;

        let p7 = drawDownCircle(centerPoint: CGPoint(x:lastPoint.x + radius2, y: lastPoint.y), radiusValue: radius2)
        lastPoint = p7.currentPoint

        let p8  = drawLine(fromPoint: lastPoint, toPoint: CGPoint(x:lastPoint.x, y: lastPoint.y - lineHeight1))
        lastPoint = p8.currentPoint;

        path.append(p1)
        path.append(p2)
        path.append(p3)
        path.append(p4)
        path.append(p5)
        path.append(p6)
        path.append(p7)
        path.append(p8)

    }

}

}

Now run the code to check the Animation Loader. Comment/Uncomment other 2 loader method in viewDidAppear method of viewcontroller.

Enjoy!!


来源: stackexchange

问:
Infinite scrolling with will_paginate. Issue removing element
I'm implementing infinite scroll with will_paginate and ajax. Whenever I press the 'load more' elements, it brings me the next 4 elements in the collection. At the moment, everything is ok. But when I remove some element of some page, the next page has been already established in the 'load more' button; because of this, the next time I press the 'load more' button, one element is skipped. Does anybody know how can I solve this? (Sorry about my english)</p>

答:
What is happening is that pagination isn't eager loading the next set, but instead is doing an offset count

```<code>initial index + page_length * (page number - 1)
limit page_length
</code>```

When you delete an element it forward shifts the index of every element after it in the database for this query. Which leaves your front end element indexes at a different state than the backend has.

You will need to re-load every "page" starting with the one containing the deleted element and work to the latest loaded "page" to get the front end to have the same element indexes that the back end has.

ContentLicense: CC BY-SA 3.0

Body:
What is happening is that pagination isn't eager loading the next set, but instead is doing an offset count

initial index + page_length * (page number - 1)
limit page_length

When you delete an element it forward shifts the index of every element after it in the database for this query. Which leaves your front end element indexes at a different state than the backend has.

You will need to re-load every "page" starting with the one containing the deleted element and work to the latest loaded "page" to get the front end to have the same element indexes that the back end has.


问:
output differences between 2 texts when lines are dissimilar
I am relatively new to Python so apologies in advance for sounding a bit ditzy sometimes. I'll try took google and attempt your tips as much as I can before asking even more questions.
Here is my situation: I am working with R and stylometry to find out the (likely) authorship of a text. What I'd like to do is see if there is a difference in the stylometry of a novel in the second edition, after one of the (assumed) co-authors died and therefore could not have contributed. In order to research that I need

Text edition 1

Text edition 2

and for python to output

words that appear in text 1 but not in text 2

words that appear in text 2 but not in text 1

And I would like to have the words each time they appear so not just 'the' once, but every time the program encounters it when it differs from the first edition (yep I know I'm asking for a lot sorry)

I have tried approaching this via

```<code>file1 = open("FRANKENST18.txt", "r")
file2 = open("FRANKENST31.txt", "r")
file3 = open("frankoutput.txt", "w")
list1 = file1.readlines()
list2 = file2.readlines()
file3.write("here: \n")
for i in list1:
    for j in list2:
        if  i==j:
            file3.write(i)
</code>```

but of course this doesn't work because the texts are two giant balls of texts and not separate lines that can be compared, plus the first text has far more lines than the second one. Is there a way to go from lines to 'words' or the text in general to overcome that? Can I put an entire novel in a string lol? I assume not.
I have also attempted to use difflib, but I've only started coding a few weeks ago and I find it quite complicated. For example, I used fraxel's script as a base for:

```<code>from difflib import Differ

s1 = open("FRANKENST18.txt", "r")
s1 = open("FRANKENST31.txt", "r")

def appendBoldChanges(s1, s2):
#"Adds <b></b> tags to words that are changed"
    l1 = s1.split(' ')
    l2 = s2.split(' ')
dif = list(Differ().compare(l1, l2))
return " ".join(['<b>'+i[2:]+'</b>' if i[:1] == '+' else i[2:] for i in dif
                                                       if not i[:1] in '-?'])

print appendBoldChanges
</code>```

but I couldn't get it to work.

So my question is is there any way to output the differences between texts that are not similar in lines like this? It sounded quite do-able but I've greatly underestimated how difficult I found Python haha.
Thanks for reading, any help is appreciated!

EDIT: posting my current code just in case it might help fellow learners that are googling for answers:

```<code>file1 = open("1stein.txt")
originaltext1 = file1.read()
wordlist1={}

import string
text1 = [x.strip(string.punctuation) for x in originaltext1.split()]
text1 = [x.lower() for x in text1]

for word1 in text1:
    if word1 not in wordlist1:
        wordlist1[word1] = 1
    else:
        wordlist1[word1] += 1

for k,v in sorted(wordlist1.items()):
    #print "%s %s" % (k, v)
    col1 = ("%s %s" % (k, v))
    print col1

file2 = open("2stein.txt")
originaltext2 = file2.read()
wordlist2={}

import string
text2 = [x.strip(string.punctuation) for x in originaltext2.split()]
text2 = [x.lower() for x in text2]

for word2 in text2:
    if word2 not in wordlist2:
        wordlist2[word2] = 1
    else:
        wordlist2[word2] += 1

for k,v in sorted(wordlist2.items()):
    #print "%s %s" % (k, v)
    col2 = ("%s %s" % (k, v))
    print col2
</code>```

what I hope still to edit and output is something like this:
using the dictionaries' key and value system (applied to col1 and col2): {apple 3, bridge 7, chair 5} - {apple 1, bridge 9, chair 5} = {apple 2, bridge -2, chair 5}?

答:
I'm not completely sure if you're trying to compare the differences in words as they occur or lines as they occur, however one way you could do this is by using a dictionary. If you want to see which lines change you could split the lines on periods by doing something like:

```<code>text = 'this is a sentence. this is another sentence.'
sentences = text.split('.')
</code>```

This will split the string you have (which contains the entire text I assume) on the periods and will return an array (or list) of all the sentences.

You can then create a dictionary with dict = {}, loop over each sentence in the previously created array, make it a key in the dictionary with a corresponding value (could be anything since most sentences probably don't occur more than once). After doing this for the first version you can go through the second version and check which sentences are the same. Here is some code that will give you a start (assuming version1 contains all the sentences from the first version):

```<code>for sentence in version1:
    dict[sentence] = 1                     #put a counter for e
</code>```

You can then loop over the second version and check if the same sentence is found in the first, with something like:

```<code>  for sentence in version2:
       if sentence in dict:            #if the sentence is in the dictionary
            pass
            #or do whatever you want here
       else:                           #if the sentence isn't
            print(sentence)
</code>```

Again not sure if this is what you're looking for but hope it helps

Body:
I am relatively new to Python so apologies in advance for sounding a bit ditzy sometimes. I'll try took google and attempt your tips as much as I can before asking even more questions.
Here is my situation: I am working with R and stylometry to find out the (likely) authorship of a text. What I'd like to do is see if there is a difference in the stylometry of a novel in the second edition, after one of the (assumed) co-authors died and therefore could not have contributed. In order to research that I need

Text edition 1

Text edition 2

and for python to output

words that appear in text 1 but not in text 2

words that appear in text 2 but not in text 1

And I would like to have the words each time they appear so not just 'the' once, but every time the program encounters it when it differs from the first edition (yep I know I'm asking for a lot sorry)

I have tried approaching this via

file1 = open("FRANKENST18.txt", "r")
file2 = open("FRANKENST31.txt", "r")
file3 = open("frankoutput.txt", "w")
list1 = file1.readlines()
list2 = file2.readlines()
file3.write("here: \n")
for i in list1:
    for j in list2:
        if  i==j:
            file3.write(i)

but of course this doesn't work because the texts are two giant balls of texts and not separate lines that can be compared, plus the first text has far more lines than the second one. Is there a way to go from lines to 'words' or the text in general to overcome that? Can I put an entire novel in a string lol? I assume not.
I have also attempted to use difflib, but I've only started coding a few weeks ago and I find it quite complicated. For example, I used fraxel's script as a base for:

from difflib import Differ

s1 = open("FRANKENST18.txt", "r")
s1 = open("FRANKENST31.txt", "r")

def appendBoldChanges(s1, s2):
#"Adds  tags to words that are changed"
    l1 = s1.split(' ')
    l2 = s2.split(' ')
dif = list(Differ().compare(l1, l2))
return " ".join([''+i[2:]+'' if i[:1] == '+' else i[2:] for i in dif
                                                       if not i[:1] in '-?'])

print appendBoldChanges

but I couldn't get it to work.

So my question is is there any way to output the differences between texts that are not similar in lines like this? It sounded quite do-able but I've greatly underestimated how difficult I found Python haha.
Thanks for reading, any help is appreciated!

EDIT: posting my current code just in case it might help fellow learners that are googling for answers:

file1 = open("1stein.txt")
originaltext1 = file1.read()
wordlist1={}

import string
text1 = [x.strip(string.punctuation) for x in originaltext1.split()]
text1 = [x.lower() for x in text1]

for word1 in text1:
    if word1 not in wordlist1:
        wordlist1[word1] = 1
    else:
        wordlist1[word1] += 1

for k,v in sorted(wordlist1.items()):
    #print "%s %s" % (k, v)
    col1 = ("%s %s" % (k, v))
    print col1

file2 = open("2stein.txt")
originaltext2 = file2.read()
wordlist2={}

import string
text2 = [x.strip(string.punctuation) for x in originaltext2.split()]
text2 = [x.lower() for x in text2]

for word2 in text2:
    if word2 not in wordlist2:
        wordlist2[word2] = 1
    else:
        wordlist2[word2] += 1

for k,v in sorted(wordlist2.items()):
    #print "%s %s" % (k, v)
    col2 = ("%s %s" % (k, v))
    print col2

what I hope still to edit and output is something like this:
using the dictionaries' key and value system (applied to col1 and col2): {apple 3, bridge 7, chair 5} - {apple 1, bridge 9, chair 5} = {apple 2, bridge -2, chair 5}?

Body:
I'm not completely sure if you're trying to compare the differences in words as they occur or lines as they occur, however one way you could do this is by using a dictionary. If you want to see which lines change you could split the lines on periods by doing something like:

text = 'this is a sentence. this is another sentence.'
sentences = text.split('.')

This will split the string you have (which contains the entire text I assume) on the periods and will return an array (or list) of all the sentences.

You can then create a dictionary with dict = {}, loop over each sentence in the previously created array, make it a key in the dictionary with a corresponding value (could be anything since most sentences probably don't occur more than once). After doing this for the first version you can go through the second version and check which sentences are the same. Here is some code that will give you a start (assuming version1 contains all the sentences from the first version):

for sentence in version1:
    dict[sentence] = 1                     #put a counter for e

You can then loop over the second version and check if the same sentence is found in the first, with something like:

  for sentence in version2:
       if sentence in dict:            #if the sentence is in the dictionary
            pass
            #or do whatever you want here
       else:                           #if the sentence isn't
            print(sentence)

Again not sure if this is what you're looking for but hope it helps


问:
Asp.Net Core HTML Helper does not select the value it is provided
I am trying to add a Select List to my view. In the razor template I have:

```<code>@foreach (var item in Model.ProjectRecordGroupParsed)
{
    <div>
        <!-- Code: @item.Code -->
        @Html.DropDownList("ProjectRecordGroup", new SelectList(AllProjectRecordGroups, "Code", "Name", item.Code), "Select Project Record Group", htmlAttributes: new { @class = "form-control" })
    </div>
}
</code>```

The result of this is a drop down with the values from AllProjectRecordGroup which does contain this option:

```<code><option value="MARKPROJECT">MARK Project</option>
</code>```

and the comment line contains this:

```<code><!-- Code: MARKPROJECT -->
</code>```

So, I am wondering what is going on here? Why is the value not selected?

答:
To make this work, I had to change this line to make the ID unique:

```<code>@Html.DropDownList("ProjectRecordGroup", new SelectList(
</code>```

It now works with this change:

```<code>@Html.DropDownList($"ProjectRecordGroup{item.Code}", new SelectList(
</code>```

Body:
I am trying to add a Select List to my view. In the razor template I have:

@foreach (var item in Model.ProjectRecordGroupParsed)
{

        @Html.DropDownList("ProjectRecordGroup", new SelectList(AllProjectRecordGroups, "Code", "Name", item.Code), "Select Project Record Group", htmlAttributes: new { @class = "form-control" })

}

The result of this is a drop down with the values from AllProjectRecordGroup which does contain this option:

<option value="MARKPROJECT">MARK Project</option>

and the comment line contains this:

So, I am wondering what is going on here? Why is the value not selected?

Body:
To make this work, I had to change this line to make the ID unique:

@Html.DropDownList("ProjectRecordGroup", new SelectList(

It now works with this change:

@Html.DropDownList($"ProjectRecordGroup{item.Code}", new SelectList(


问:
Spark-ML writing custom Model, Transformer
This is on Spark 2.0.1

I'm trying to compile and use the SimpleIndexer example from here.

import org.apache.spark.ml.param._
import org.apache.spark.ml.util._
import org.apache.spark.ml._

import org.apache.spark.sql._
import org.apache.spark.sql.types._
import org.apache.spark.sql.functions._

trait SimpleIndexerParams extends Params {
  final val inputCol= new Param[String](this, "inputCol", "The input column")
  final val outputCol = new Param[String](this, "outputCol", "The output column")
}

class SimpleIndexer(override val uid: String) extends Estimator[SimpleIndexerModel] with SimpleIndexerParams {

  def setInputCol(value: String) = set(inputCol, value)

  def setOutputCol(value: String) = set(outputCol, value)

  def this() = this(Identifiable.randomUID("simpleindexer"))

  override def copy(extra: ParamMap): SimpleIndexer = {
    defaultCopy(extra)
  }

  override def transformSchema(schema: StructType): StructType = {
    // Check that the input type is a string
    val idx = schema.fieldIndex($(inputCol))
    val field = schema.fields(idx)
    if (field.dataType != StringType) {
      throw new Exception(s"Input type ${field.dataType} did not match input type StringType")
    }
    // Add the return field
    schema.add(StructField($(outputCol), IntegerType, false))
  }

  override def fit(dataset: Dataset[_]): SimpleIndexerModel = {
    import dataset.sparkSession.implicits._
    val words = dataset.select(dataset($(inputCol)).as[String]).distinct
      .collect()
    new SimpleIndexerModel(uid, words)
 ; }
}

class SimpleIndexerModel(
  override val uid: String, words: Array[String]) extends Model[SimpleIndexerModel] with SimpleIndexerParams {

  override def copy(extra: ParamMap): SimpleIndexerModel = {
    defaultCopy(extra)
  }

  private val labelToIndex: Map[String, Double] = words.zipWithIndex.
    map{case (x, y) => (x, y.toDouble)}.toMap

  override def transformSchema(schema: StructType): StructType = {
    // Check that the input type is a string
    val idx = schema.fieldIndex($(inputCol))
    val field = schema.fields(idx)
    if (field.dataType != StringType) {
      throw new Exception(s"Input type ${field.dataType} did not match input type StringType")
    }
    // Add the return field
    schema.add(StructField($(outputCol), IntegerType, false))
  }

  override def transform(dataset: Dataset[_]): DataFrame = {
    val indexer = udf { label: String => labelToIndex(label) }
    dataset.select(col("*"),
      indexer(dataset($(inputCol)).cast(StringType)).as($(outputCol)))
  }
}
```

<p>However, I'm getting an error during transformation:</p>

<pre class="lang-scala prettyprint-override"><code>val df = Seq(
  (10, "hello"),
  (20, "World"),
  (30, "goodbye"),
  (40, "sky")
).toDF("id", "phrase")

val si = new SimpleIndexer().setInputCol("phrase").setOutputCol("phrase_idx").fit(df)

si.transform(df).show(false)

// java.util.NoSuchElementException: Failed to find a default value for inputCol
</code>```

Any idea how to fix it?

答:
Okay, I figured out by going into the source code for CountVectorizer. Looks like I need to replace new SimpleIndexerModel(uid, words) with copyValues(new SimpleIndexerModel(uid, words).setParent(this)). So the new fit method becomes

  override def fit(dataset: Dataset[_]): SimpleIndexerModel = {
    import dataset.sparkSession.implicits._
    val words = dataset.select(dataset($(inputCol)).as[String]).distinct
      .collect()
    //new SimpleIndexerModel(uid, words)
    copyValues(new SimpleIndexerModel(uid, words).setParent(this))
  }
```

<p>With this, the params are recognized, and transform happens neatly.</p>

<pre class="lang-scala prettyprint-override"><code>val si = new SimpleIndexer().setInputCol("phrase").setOutputCol("phrase_idx").fit(df)

si.explainParams
// res3: String =
// inputCol: The input column (current: phrase)
// outputCol: The output column (current: phrase_idx)

si.transform(df).show(false)
// +---+-------+----------+
// |id |phrase |phrase_idx|
// +---+-------+----------+
// |10 |hello  |1.0       |
// |20 |World  |0.0       |
// |30 |goodbye|3.0       |
// |40 |sky    |2.0       |
// +---+-------+----------+
</code>```

Body:
This is on Spark 2.0.1

I'm trying to compile and use the SimpleIndexer example from here.

import org.apache.spark.ml.param._
import org.apache.spark.ml.util._
import org.apache.spark.ml._

import org.apache.spark.sql._
import org.apache.spark.sql.types._
import org.apache.spark.sql.functions._

trait SimpleIndexerParams extends Params {
  final val inputCol= new Param[String](this, "inputCol", "The input column")
  final val outputCol = new Param[String](this, "outputCol", "The output column")
}

class SimpleIndexer(override val uid: String) extends Estimator[SimpleIndexerModel] with SimpleIndexerParams {

  def setInputCol(value: String) = set(inputCol, value)

  def setOutputCol(value: String) = set(outputCol, value)

  def this() = this(Identifiable.randomUID("simpleindexer"))

  override def copy(extra: ParamMap): SimpleIndexer = {
    defaultCopy(extra)
  }

  override def transformSchema(schema: StructType): StructType = {
    // Check that the input type is a string
    val idx = schema.fieldIndex($(inputCol))
    val field = schema.fields(idx)
    if (field.dataType != StringType) {
      throw new Exception(s"Input type ${field.dataType} did not match input type StringType")
    }
    // Add the return field
    schema.add(StructField($(outputCol), IntegerType, false))
  }

  override def fit(dataset: Dataset[_]): SimpleIndexerModel = {
    import dataset.sparkSession.implicits._
    val words = dataset.select(dataset($(inputCol)).as[String]).distinct
      .collect()
    new SimpleIndexerModel(uid, words)
 ; }
}

class SimpleIndexerModel(
  override val uid: String, words: Array[String]) extends Model[SimpleIndexerModel] with SimpleIndexerParams {

  override def copy(extra: ParamMap): SimpleIndexerModel = {
    defaultCopy(extra)
  }

  private val labelToIndex: Map[String, Double] = words.zipWithIndex.
    map{case (x, y) => (x, y.toDouble)}.toMap

  override def transformSchema(schema: StructType): StructType = {
    // Check that the input type is a string
    val idx = schema.fieldIndex($(inputCol))
    val field = schema.fields(idx)
    if (field.dataType != StringType) {
      throw new Exception(s"Input type ${field.dataType} did not match input type StringType")
    }
    // Add the return field
    schema.add(StructField($(outputCol), IntegerType, false))
  }

  override def transform(dataset: Dataset[_]): DataFrame = {
    val indexer = udf { label: String => labelToIndex(label) }
    dataset.select(col("*"),
      indexer(dataset($(inputCol)).cast(StringType)).as($(outputCol)))
  }
}

However, I'm getting an error during transformation:

val df = Seq(
  (10, "hello"),
  (20, "World"),
  (30, "goodbye"),
  (40, "sky")
).toDF("id", "phrase")

val si = new SimpleIndexer().setInputCol("phrase").setOutputCol("phrase_idx").fit(df)

si.transform(df).show(false)

// java.util.NoSuchElementException: Failed to find a default value for inputCol

Any idea how to fix it?

Body:
Okay, I figured out by going into the source code for CountVectorizer. Looks like I need to replace new SimpleIndexerModel(uid, words) with copyValues(new SimpleIndexerModel(uid, words).setParent(this)). So the new fit method becomes

  override def fit(dataset: Dataset[_]): SimpleIndexerModel = {
    import dataset.sparkSession.implicits._
    val words = dataset.select(dataset($(inputCol)).as[String]).distinct
      .collect()
    //new SimpleIndexerModel(uid, words)
    copyValues(new SimpleIndexerModel(uid, words).setParent(this))
  }

With this, the params are recognized, and transform happens neatly.

val si = new SimpleIndexer().setInputCol("phrase").setOutputCol("phrase_idx").fit(df)

si.explainParams
// res3: String =
// inputCol: The input column (current: phrase)
// outputCol: The output column (current: phrase_idx)

si.transform(df).show(false)
// +---+-------+----------+
// |id |phrase |phrase_idx|
// +---+-------+----------+
// |10 |hello  |1.0       |
// |20 |World  |0.0       |
// |30 |goodbye|3.0       |
// |40 |sky    |2.0       |
// +---+-------+----------+


问:
How to use a css selector wildcard if the id values keep changing
How to use a css selector wildcard if the id values keep changing?

```<code> <td role="gridcell" style="text-align:center;" title="**Edit**  |  Copy</a" aria-describedby="list4_action"><a href="mac1/notification/edit?id=**12374**">Edit</a>  |  <a href="/mac1/notification/copy?id=12374">Copy</a></td>
</code>```

This is in a table where the id # 12374 changes for every new row . I was looking for selenium to click the EDIT button .

When i use cssSelector:a[href*='/mac1/notication/edit?$id='*] the test is failing with the message

Caused by: org.openqa.selenium.InvalidSelectorException: The given selector a[href*='/mac/notication/edit?$id='*] is either invalid or does not result in a WebElement. The following error occurred:
  InvalidSelectorError: An invalid or illegal selector was specified

答:
Try with the following CSS selector,
      </p>

```<code>a[href^='/mac1/notification/edit?id=']
</code>```

Body:
How to use a css selector wildcard if the id values keep changing?

 <td role="gridcell" style="text-align:center;" title="**Edit**  |  CopyEdit  |  Copy

This is in a table where the id # 12374 changes for every new row . I was looking for selenium to click the EDIT button .

When i use cssSelector:a[href*='/mac1/notication/edit?$id='*] the test is failing with the message

Caused by: org.openqa.selenium.InvalidSelectorException: The given selector a[href*='/mac/notication/edit?$id='*] is either invalid or does not result in a WebElement. The following error occurred:
  InvalidSelectorError: An invalid or illegal selector was specified

Body:
Try with the following CSS selector,

a[href^='/mac1/notification/edit?id=']


问:
Video tag on react with create-react-app project
I am having problem adding a local video to my project as

```<code><video src={import(src/assets/abc.mp4)} type="video/mp4"/>
</code>```

I have researched and found out about

web pack configuration

to make this possible but i can't figure out how to introduce it to create-react-app project.

I can't go cloud hosting for my videos because i need it on mobile version as well.please can anyone help?

答:
The syntax you’re trying to use (dynamic import()) is for code splitting, not for adding files.

I’m not sure why you were looking for Webpack configuration, as this is supported out of the box.

Please follow the official documentation that explains how to import assets:

```<code>// Assuming abc.mp4 is in the same folder as this component
import myVideo from './abc.mp4';
// This will become a string with the path to the video at build time

// Your component definition
export default function MyComponent() {
  return <video src={myVideo} type="video/mp4" />;
}
</code>```

Body:
I am having problem adding a local video to my project as

<video src={import(src/assets/abc.mp4)} type="video/mp4"/>

I have researched and found out about

web pack configuration

to make this possible but i can't figure out how to introduce it to create-react-app project.

I can't go cloud hosting for my videos because i need it on mobile version as well.please can anyone help?

Body:
The syntax you’re trying to use (dynamic import()) is for code splitting, not for adding files.

I’m not sure why you were looking for Webpack configuration, as this is supported out of the box.

Please follow the official documentation that explains how to import assets:

// Assuming abc.mp4 is in the same folder as this component
import myVideo from './abc.mp4';
// This will become a string with the path to the video at build time

// Your component definition
export default function MyComponent() {
  return <video src={myVideo} type="video/mp4" />;
}


问:
Get only latest HTTP headers on redirection
Curl follows redirections nicely:

```<code>$fp = fopen($header, 'wb');
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_WRITEHEADER, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$content = curl_exec($ch);
curl_close($ch);
fclose($fp);
</code>```

... but the header collection includes headers from all intermediate requests:

```<code>HTTP/1.1 301 Moved Permanently
Date: Wed, 05 Jul 2017 16:39:31 GMT
Server: Apache/2.4.25 (Win64) OpenSSL/1.0.2k PHP/7.1.4
X-Powered-By: PHP/7.1.4
Location: http://example.net/
Content-Length: 14
Content-Type: text/html; charset=UTF-8

HTTP/1.1 301 Moved Permanently
Date: Wed, 05 Jul 2017 16:39:31 GMT
Server: Apache/2.4.25 (Win64) OpenSSL/1.0.2k PHP/7.1.4
X-Powered-By: PHP/7.1.4
Location: http://example.org/
Content-Length: 14
Content-Type: text/html; charset=UTF-8

HTTP/1.1 200 OK
Date: Wed, 05 Jul 2017 16:39:31 GMT
Server: Apache/2.4.25 (Win64) OpenSSL/1.0.2k PHP/7.1.4
X-Powered-By: PHP/7.1.4
Content-Length: 5
Content-Type: text/html; charset=UTF-8
</code>```

Since I'm often only interested in whatever I've finally fetched that's rather inconvenient because I need to parse the entire header set.

Is there a builtin setting/mechanism to discard previous headers on redirection or text parsing is the only way?

答:
Using the curl_getinfo function you can get the actual URL after the redirect:

```<code>CURLINFO_EFFECTIVE_URL
</code>```

Usage example:

```<code>$last_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
if ($last_url === '...') {
    ...
}
</code>```

Body:
Curl follows redirections nicely:

$fp = fopen($header, 'wb');
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_WRITEHEADER, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$content = curl_exec($ch);
curl_close($ch);
fclose($fp);

... but the header collection includes headers from all intermediate requests:

HTTP/1.1 301 Moved Permanently
Date: Wed, 05 Jul 2017 16:39:31 GMT
Server: Apache/2.4.25 (Win64) OpenSSL/1.0.2k PHP/7.1.4
X-Powered-By: PHP/7.1.4
Location: http://example.net/
Content-Length: 14
Content-Type: text/html; charset=UTF-8

HTTP/1.1 301 Moved Permanently
Date: Wed, 05 Jul 2017 16:39:31 GMT
Server: Apache/2.4.25 (Win64) OpenSSL/1.0.2k PHP/7.1.4
X-Powered-By: PHP/7.1.4
Location: http://example.org/
Content-Length: 14
Content-Type: text/html; charset=UTF-8

HTTP/1.1 200 OK
Date: Wed, 05 Jul 2017 16:39:31 GMT
Server: Apache/2.4.25 (Win64) OpenSSL/1.0.2k PHP/7.1.4
X-Powered-By: PHP/7.1.4
Content-Length: 5
Content-Type: text/html; charset=UTF-8

Since I'm often only interested in whatever I've finally fetched that's rather inconvenient because I need to parse the entire header set.

Is there a builtin setting/mechanism to discard previous headers on redirection or text parsing is the only way?

Body:
Using the curl_getinfo function you can get the actual URL after the redirect:

CURLINFO_EFFECTIVE_URL

Usage example:

$last_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
if ($last_url === '...') {
    ...
}


问:
Odoo - How to create custom global configuration file
I am using Odoo 10-e. I came from .net what i want to do is that i need to create my custom setting configuration file in Odoo like we have AppSettings file in asp.net where we set some static key values to use them in project. How to create that kind of file and how can i access that file in python code or xml files ?

答:
Create a class that inherits from res.config.settings (so you can edit the record):

class farmacia_pedido_config_settings(models.TransientModel):
   _inherit = 'res.config.settings'
   _name = 'farmacia.config.settings'

   lista_precios_defecto = fields.Many2one(
    'product.pricelist',
    string='Lista de precios por defecto')
```

<ol start="2">
<li>Associate with the view:</li>
</ol>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<openerp>
<data>
    <record id="view_farmacia_configuration" model="ir.ui.view">
        <field name="name">farmacia config settings</field>
        <field name="model">farmacia.config.settings</field>
        <field name="arch" type="xml">
            <form string="Farmacia" class="oe_form_configuration">
                <header>
                    <button string="Aplicar" type="object" name="execute" class="oe_highlight"/>
                    <button string="Cancelar" type="object" name="cancel" class="oe_link"/>
                </header>

                <field name="lista_precios_defecto" class="oe_inline"/>

                </group>
                </form>
        </field>
    </record>

    <record id="action_farmacia_configuration" model="ir.actions.act_window">
        <field name="name">Farmacia</field>
        <field name="type">ir.actions.act_window</field>
        <field name="res_model">farmacia.config.settings</field>
        <field name="view_mode">form</field>
        <field name="target">inline</field>
    </record>

    <menuitem id="menu_farmacia_config" name="Farmacia" parent="base.menu_config"
        sequence="3" action="action_farmacia_configuration"/>

</data>
</openerp>
</code>```

Save in a file accessing via python (this is uglier)

config = ConfigParser()
your_file = os.getenv("HOME")+os.path.sep+"your_file.conf"
if os.path.isfile(your_file):
    config.read(your_file)
else:
    raise models.except_orm(
        'Error',
        "File not found " + os.getcwd())
```

Body:
Create a class that inherits from res.config.settings (so you can edit the record):

class farmacia_pedido_config_settings(models.TransientModel):
   _inherit = 'res.config.settings'
   _name = 'farmacia.config.settings'

   lista_precios_defecto = fields.Many2one(
    'product.pricelist',
    string='Lista de precios por defecto')

Associate with the view:

<?xml version="1.0" encoding="utf-8"?>
<openerp>
<data>
    <record id="view_farmacia_configuration" model="ir.ui.view">
        <field name="name">farmacia config settings</field>
        <field name="model">farmacia.config.settings</field>
        <field name="arch" type="xml">
            <form string="Farmacia" class="oe_form_configuration">
                <header>
                    <button string="Aplicar" type="object" name="execute" class="oe_highlight"/>
                    <button string="Cancelar" type="object" name="cancel" class="oe_link"/>
                </header>

                <field name="lista_precios_defecto" class="oe_inline"/>

                </group>
                </form>
        </field>
    </record>

    <record id="action_farmacia_configuration" model="ir.actions.act_window">
        <field name="name">Farmacia</field>
        <field name="type">ir.actions.act_window</field>
        <field name="res_model">farmacia.config.settings</field>
        <field name="view_mode">form</field>
        <field name="target">inline</field>
    </record>

    <menuitem id="menu_farmacia_config" name="Farmacia" parent="base.menu_config"
        sequence="3" action="action_farmacia_configuration"/>

</data>
</openerp>

Save in a file accessing via python (this is uglier)

config = ConfigParser()
your_file = os.getenv("HOME")+os.path.sep+"your_file.conf"
if os.path.isfile(your_file):
    config.read(your_file)
else:
    raise models.except_orm(
        'Error',
        "File not found " + os.getcwd())

ContentLicense: CC BY-SA 4.0


问:
Javascript: How can every set of numbers in an array be extracted?
I have a csv file output in this format

that correspond the values of this firebase DB.

what I want to do is run each ID through firebase DB to find a match.

strategy

Read csv file data
   Omit the word ID and extract every 8 numbers (which is the length of the ID numbers)
   Run the extracted ID values through firebase to find match and print snapshot.

this is the function that generates the file readout
        var IDArr = [];

```<code>      var fileInput = document.getElementById("csv");

      readFile = function () {

              console.log("file uploaded")
              var reader = new FileReader();
              reader.onload = function () {
      reader.readAsBinaryString(fileInput.files[0]);
          };

           if (fileInput){
                fileInput.addEventListener('change', readFile);
      }
</code>```

How do I implement the strategy above? A sample code will be greatly appreciated

答:
I was able to figure out the answer.</p>

```<code>  for (var i=0; i < numbers.length; i++) {

                    var dbRef = firebase.database().ref().child('Agents').child(numbers[i]);

                       dbRef.on('value', snapshot => {
                          console.log(snapshot.val());
                        });

                        alert(numbers[i]);
                      }
</code>```

Body:
I have a csv file output in this format

that correspond the values of this firebase DB.

what I want to do is run each ID through firebase DB to find a match.

strategy

Read csv file data
   Omit the word ID and extract every 8 numbers (which is the length of the ID numbers)
   Run the extracted ID values through firebase to find match and print snapshot.

this is the function that generates the file readout
        var IDArr = [];

      var fileInput = document.getElementById("csv");

      readFile = function () {

              console.log("file uploaded")
              var reader = new FileReader();
              reader.onload = function () {
      reader.readAsBinaryString(fileInput.files[0]);
          };

           if (fileInput){
                fileInput.addEventListener('change', readFile);
      }

How do I implement the strategy above? A sample code will be greatly appreciated

Body:
I was able to figure out the answer.

  for (var i=0; i < numbers.length; i++) {

                    var dbRef = firebase.database().ref().child('Agents').child(numbers[i]);

                       dbRef.on('value', snapshot => {
                          console.log(snapshot.val());
                        });

                        alert(numbers[i]);
                      }


问:
jQuery UI dialog form, not sending correct variable
I'm loading a customer info page using jQuery. There's a list of customers with a link next to it:

```<code><a href="#" onclick="load_customer(<?php echo $c->id; ?>);return false;">View</a>
</code>```

That triggers this function:

```<code>function load_customer(id) {
  $("#dashboard").load('get_info/' + id);
}
</code>```

That works perfectly. On the page I'm loading, I have a jQuery UI modal dialog form for adding new information.

```<code><div id="addinfo">
  <form><input type="hidden" name="customer_id" value="<?php echo $c->id; ?>" /></form>
</div>
</code>```

My javascript:

```<code>  $("#addinfobutton").click(function(){
            $("#addinfo").dialog("open");
            return false;
   });
   $("#addinfo").dialog({
            autoOpen:false,
            width:400,
            height:550,
            modal: true
   });
</code>```

When you select a customer the first time, it populates the hidden field correctly, but then it stays the same even after selecting other customers.

I thought that by loading a new customer page, the form would reset as well... but apparently it's being stored/cached somewhere. If I echo the ID anywhere else in the page, it shows correctly... just not in the "addinfo" div.

Any help/suggestions would be appreciated! Thanks!

答:
After some more researching, it seems the dialog is being cached client-side after it's called. So to get around that, I just added the customerId to the end of the popup div's ID name... so each customer page will have a unique dialog ID.

However, if it's caching each of those dialogs, won't there be a performance loss if you open quite a few? How can you clear them without having to do a full page refresh?

ContentLicense: CC BY-SA 2.5

Body:
I'm loading a customer info page using jQuery. There's a list of customers with a link next to it:

<a href="#" onclick="load_customer(<?php echo $c->id; ?>);return false;">View

That triggers this function:

function load_customer(id) {
  $("#dashboard").load('get_info/' + id);
}

That works perfectly. On the page I'm loading, I have a jQuery UI modal dialog form for adding new information.

  <form><input type="hidden" name="customer_id" value="<?php echo $c->id; ?>" /></form>

My javascript:

  $("#addinfobutton").click(function(){
            $("#addinfo").dialog("open");
            return false;
   });
   $("#addinfo").dialog({
            autoOpen:false,
            width:400,
            height:550,
            modal: true
   });

When you select a customer the first time, it populates the hidden field correctly, but then it stays the same even after selecting other customers.

I thought that by loading a new customer page, the form would reset as well... but apparently it's being stored/cached somewhere. If I echo the ID anywhere else in the page, it shows correctly... just not in the "addinfo" div.

Any help/suggestions would be appreciated! Thanks!


问:
OnLocationChanged() is not automatically called. The location is not stored in the database
I have a gpsTracker java class which contains the onLocationChanged() method. I want to link my MainActivity's OnCreate function with this onLocationChanged() method.

```<code>public void onLocationChanged(Location newlocation) {

    Log.d("latitude", "old" + Double.toString(this.location.getLatitude()));
    Log.d("Longitude", "old " +
     Double.toString(this.location.getLatitude()));
    Log.i("info","LOCATION CHANGED");
    Log.d("latitude", "NEW: CHANGED TO KOLKATA" +
    Double.toString(newlocation.getLatitude()));
    Log.d("Longitude", "NEW: CHANGED TO KOLKATA " +
     Double.toString(newlocation.getLatitude()));
    this.location = newlocation;
    JSONObject locationChange = new JSONObject();
    getLocationName(location.getLatitude(), location.getLongitude());
    try {
        locationChange.put("userid",
       PreferenceManager.getInstance().getUserId());
        locationChange.put("location", addressString);
        locationChange.put("connection",
        PreferenceManager.getInstance().getConnectAllow() ? "1" : "0");
        locationChange.put("connection", "0");
        locationChange.put("notification",
    PreferenceManager.getInstance().getPushNotiAllow() ? "0" : "1");

        Log.d(TAG, "LOCATION CHANGED BY GPS FUNCTION: " + locationChange);

        RequestHandler.getInstance().postWithHeader(null,
      getString(R.string.baseurl) + getString(R.string.settings),
      locationChange, this,
    AppConstants.ApiRequestCodeKey.SAVE_APP_SETTINGS);
     }catch (JSONException e) {
                      e.printStackTrace();
         }
  }
public void getLocationName(double latitude, double longitude) {
    Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
    try {
        addresses = geocoder.getFromLocation(latitude, longitude, 1);
        addressString = addresses.get(0).getAddressLine(0)
                + addresses.get(0).getAddressLine(1) + " ";
    } catch (IOException e) {
        e.printStackTrace();
    }
}>
</code>```

The onCreate function in the MainActivity() contains this.

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_home_frame);

utils.mixpanelTrack(this, "Reached Home Page");
 homeFragObj = this;
    initViews();
    initSetup();
    initListeners();
    loadData();
>
</code>```

答:
```<code>Class A{
 Context ctx;
 public A(Context ctx){
  this.ctx=ctx;
 }
 //your rest code
}
</code>```

In MainActivity:
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

```<code>setContentView(R.layout.activity_home_frame);

utils.mixpanelTrack(this, "Reached Home Page");
 homeFragObj = this;
 initViews();
 initSetup();
 initListeners();
 loadData();
 A a=new A(this);//Making an Obj
 a.onLocationChanged(location);//your method invocation
</code>```

Hope this helps.

Body:
I have a gpsTracker java class which contains the onLocationChanged() method. I want to link my MainActivity's OnCreate function with this onLocationChanged() method.

public void onLocationChanged(Location newlocation) {

    Log.d("latitude", "old" + Double.toString(this.location.getLatitude()));
    Log.d("Longitude", "old " +
     Double.toString(this.location.getLatitude()));
    Log.i("info","LOCATION CHANGED");
    Log.d("latitude", "NEW: CHANGED TO KOLKATA" +
    Double.toString(newlocation.getLatitude()));
    Log.d("Longitude", "NEW: CHANGED TO KOLKATA " +
     Double.toString(newlocation.getLatitude()));
    this.location = newlocation;
    JSONObject locationChange = new JSONObject();
    getLocationName(location.getLatitude(), location.getLongitude());
    try {
        locationChange.put("userid",
       PreferenceManager.getInstance().getUserId());
        locationChange.put("location", addressString);
        locationChange.put("connection",
        PreferenceManager.getInstance().getConnectAllow() ? "1" : "0");
        locationChange.put("connection", "0");
        locationChange.put("notification",
    PreferenceManager.getInstance().getPushNotiAllow() ? "0" : "1");

        Log.d(TAG, "LOCATION CHANGED BY GPS FUNCTION: " + locationChange);

        RequestHandler.getInstance().postWithHeader(null,
      getString(R.string.baseurl) + getString(R.string.settings),
      locationChange, this,
    AppConstants.ApiRequestCodeKey.SAVE_APP_SETTINGS);
     }catch (JSONException e) {
                      e.printStackTrace();
         }
  }
public void getLocationName(double latitude, double longitude) {
    Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
    try {
        addresses = geocoder.getFromLocation(latitude, longitude, 1);
        addressString = addresses.get(0).getAddressLine(0)
                + addresses.get(0).getAddressLine(1) + " ";
    } catch (IOException e) {
        e.printStackTrace();
    }
}>

The onCreate function in the MainActivity() contains this.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_home_frame);

utils.mixpanelTrack(this, "Reached Home Page");
 homeFragObj = this;
    initViews();
    initSetup();
    initListeners();
    loadData();
>

Body:
Class A{
 Context ctx;
 public A(Context ctx){
  this.ctx=ctx;
 }
 //your rest code
}

In MainActivity:
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

setContentView(R.layout.activity_home_frame);

utils.mixpanelTrack(this, "Reached Home Page");
 homeFragObj = this;
 initViews();
 initSetup();
 initListeners();
 loadData();
 A a=new A(this);//Making an Obj
 a.onLocationChanged(location);//your method invocation

Hope this helps.


问:
android how to create my own Activity and extend it?
I need to create a base class that extends Activity which does some common tasks in my application and extend my activities from it,in the following form:

public BaseActivity extends Activity{....}

public SubActivity extends BaseActivity{...}

in SubActivity I need to give values to some variables and UI components defined in BaseActivity, I may need to define a different layout for SubActivity according to some flag value,  also(in SubActivity ) I want to execute asyncTask that is defined in BaseActivity.

is this possible? if yes, is there any tutorial that may help?
thank you in advance

答:
This question already has very good answers.

However. my answer is for those people who are looking for some working example.

Here is the full working ->  CODE

We are not doing anything new here, it is just like any other inheritance scenario (You want some common behavior at multiple places but you want to write that behavior only once).

ADVANTAGE:
It does provide better code readability, maintainability and blah blah. But are not after these -ibility, They won't matter to you if your brain runs like a gazelle.

We are after the real power of inheritance “CONTROL”. (That’s what happens in real life too. Parent controlling child :) ) .

In my example, I have two Activities MainActivity and OtherActivity.
Both Activities has a different layout but I want both of them to start with some animation or some welcome message.

Our first task is to find out the common behavior.
here -> Start Activity with animation.

We have found the common “thing”, now we will write that behavior in BaseClass (AnimationActivity).

MainActivity and OtherActivity will inherit AnimationActivity.

So the code would look like   `

BaseActivity

```<code>AnimationActivity {

  startAnimation()
  {
    ....
  }
}
</code>```

Child Activities

```<code>MainActivity extends AnimationActivity{

}

OtherActivity extends AnimationActivity{

}
</code>```

This design approach provides a lot of Control and Flexibility (POWER OF MODIFIER).

1) CONTROL: Keep animation method inside onCreate()
When you decide that Activities should be started with Animation.
Keep your method inside onCreate(Bundle bundle) method. Now just by changing the modifier, you can control the child Activities.

If you keep modifier as

final: Child activities will start with parent Animation.

abstract: Child activities will have to give their own animation.

no modifier: Child activities can have their own animation by overriding animation method, Otherwise the child will have parent animation.

2)Flexibility: Don't keep animation method inside onCreate()
You can provide child activities flexibility by not keeping animation method inside onCreate(Bundle bundle).
Now activities can have the flexibility to have parent Animation or their own animation or no animation at all.

Hope it helps.

Happy learning.

`

Body:
This question already has very good answers.

However. my answer is for those people who are looking for some working example.

Here is the full working ->  CODE

We are not doing anything new here, it is just like any other inheritance scenario (You want some common behavior at multiple places but you want to write that behavior only once).

ADVANTAGE:
It does provide better code readability, maintainability and blah blah. But are not after these -ibility, They won't matter to you if your brain runs like a gazelle.

We are after the real power of inheritance “CONTROL”. (That’s what happens in real life too. Parent controlling child :) ) .

In my example, I have two Activities MainActivity and OtherActivity.
Both Activities has a different layout but I want both of them to start with some animation or some welcome message.

Our first task is to find out the common behavior.
here -> Start Activity with animation.

We have found the common “thing”, now we will write that behavior in BaseClass (AnimationActivity).

MainActivity and OtherActivity will inherit AnimationActivity.

So the code would look like   `

BaseActivity

AnimationActivity {

  startAnimation()
  {
    ....
  }
}

Child Activities

MainActivity extends AnimationActivity{

}

OtherActivity extends AnimationActivity{

}

This design approach provides a lot of Control and Flexibility (POWER OF MODIFIER).

1) CONTROL: Keep animation method inside onCreate()
When you decide that Activities should be started with Animation.
Keep your method inside onCreate(Bundle bundle) method. Now just by changing the modifier, you can control the child Activities.

If you keep modifier as

final: Child activities will start with parent Animation.

abstract: Child activities will have to give their own animation.

no modifier: Child activities can have their own animation by overriding animation method, Otherwise the child will have parent animation.

2)Flexibility: Don't keep animation method inside onCreate()
You can provide child activities flexibility by not keeping animation method inside onCreate(Bundle bundle).
Now activities can have the flexibility to have parent Animation or their own animation or no animation at all.

Hope it helps.

Happy learning.

`


问:
How to fill image without stretching the image
Site URL: http://theneonplanet.com.au/home-2-2/

Hi, I am working on this wordpress website. I use divi theme but I manually change things with css.

second section image

this is currently placed in the recent stories section.

The problem is that the post image is placed correctly but it is stretched inside the div and it looks very strange; the picture is not suppose to be this thin.
I want the image to be filled inside the div. which means it doen't need to be the same width of the div but it has to fill the space.

is there any code solution for this?
I tried object-fit, and min and max height. both didn't work..

答:
There are multiple ways to make an image fill a div element using CSS. The easiest way would be to set the image as the background-image of the div and set the background-size to cover. You can also set the background-position to align the image.

```<code>div {
    background-image: url("image.jpg");
    background-size: cover;
    background-position: center;
}
</code>```

But in your case, you seem to be using a WordPress plug-in which inserts the image as an img tag inside the div and stretching the image to the size of the div. So we can use the object-fit CSS property on the img element to make the image fill the size of the img element.

Your code will look something like this.

```<code>#tesco-slider .et_pb_slide_image img {
    object-fit: cover;
    object-position: center;
}
</code>```

Just as with the background-image approach, object-fit: cover will make your image fill the size of the img tag and object-position: center will align the image to the center.

Body:
There are multiple ways to make an image fill a div element using CSS. The easiest way would be to set the image as the background-image of the div and set the background-size to cover. You can also set the background-position to align the image.

div {
    background-image: url("image.jpg");
    background-size: cover;
    background-position: center;
}

But in your case, you seem to be using a WordPress plug-in which inserts the image as an img tag inside the div and stretching the image to the size of the div. So we can use the object-fit CSS property on the img element to make the image fill the size of the img element.

Your code will look something like this.

#tesco-slider .et_pb_slide_image img {
    object-fit: cover;
    object-position: center;
}

Just as with the background-image approach, object-fit: cover will make your image fill the size of the img tag and object-position: center will align the image to the center.


问:
Transform elements in column with the column name as argument
I'm trying to modify the data in a data set based on a vector of columns to change. That way I could factorize the treatment based on a config file which would have the list of columns to change as a variable.

Ideally, I'd like to be able to use ddply like that :

```<code>column <- "var2"
df <- ddply(df, .(), transform, column = func(column))
</code>```

The output would be the same dataframe but in the column "B", each letter would have an "A" added behind it

Which would change each element of the column var2 by the element through func (func here is used to trim a chr in a particular way). I've tried several solutions, like :

```<code>df[do.call(func, df[,column]), ]
</code>```

which doesn't accept the df[,column] as argument (not a list), or

```<code>param = c("var1", "var2")
for(p in param){
    df <- df[func(df[,p]),]
}
</code>```

which destroys the other data, or

```<code>df[, column] <- lapply(df[, column], func)
</code>```

Which doesn't work because it takes the whole column as argument instead of changing each element 1 by 1. I'm kinda out of ideas on how to make this treatment more automatic.

Example :

```<code>df <- data.frame(A=1:10, B=letters[2:11])
colname <- "B"
addA <- function(text) { paste0(text, "A") }
</code>```

And I would like to do something like this :

```<code>df <- ddply(df, .(), transform, colname = addA(colname))
</code>```

Though if the solution does not use ddply, it's not an issue, it's just what I'm the most used to

答:
You could use mutate_at from package dplyr for this.

```<code>library(dplyr)

mutate_at(df, colname, addA)

    A  B
1   1 bA
2   2 cA
3   3 dA
4   4 eA
5   5 fA
6   6 gA
7   7 hA
8   8 iA
9   9 jA
10 10 kA
</code>```

Body:
I'm trying to modify the data in a data set based on a vector of columns to change. That way I could factorize the treatment based on a config file which would have the list of columns to change as a variable.

Ideally, I'd like to be able to use ddply like that :

column <- "var2"
df <- ddply(df, .(), transform, column = func(column))

The output would be the same dataframe but in the column "B", each letter would have an "A" added behind it

Which would change each element of the column var2 by the element through func (func here is used to trim a chr in a particular way). I've tried several solutions, like :

df[do.call(func, df[,column]), ]

which doesn't accept the df[,column] as argument (not a list), or

param = c("var1", "var2")
for(p in param){
    df <- df[func(df[,p]),]
}

which destroys the other data, or

df[, column] <- lapply(df[, column], func)

Which doesn't work because it takes the whole column as argument instead of changing each element 1 by 1. I'm kinda out of ideas on how to make this treatment more automatic.

Example :

df <- data.frame(A=1:10, B=letters[2:11])
colname <- "B"
addA <- function(text) { paste0(text, "A") }

And I would like to do something like this :

df <- ddply(df, .(), transform, colname = addA(colname))

Though if the solution does not use ddply, it's not an issue, it's just what I'm the most used to

Body:
You could use mutate_at from package dplyr for this.

library(dplyr)

mutate_at(df, colname, addA)

    A  B
1   1 bA
2   2 cA
3   3 dA
4   4 eA
5   5 fA
6   6 gA
7   7 hA
8   8 iA
9   9 jA
10 10 kA


问:
QTableView, how to change dragging multiple items display
I have a QTableView with my own implemented QAbstractItemModel, in which I can drag and drop multiple items inside. My problem is that when dragging the items and while trying to drop them in a destination cell, it is not so obvious for the user what the result is going to be. For example, I have the following,but I would prefer sth like the default widows displaying, which makes all 3 items like one item:

my QT Table

vs

windows dragging n dropping folders

答:
Taking this tutorial as a reference, the mousePressEvent method is overwritten, and a new QPixmap is placed in QDrag:

```<code>void mousePressEvent(QMouseEvent *event){
    if (event->button() == Qt::LeftButton){

        QDrag *drag = new QDrag(this);
        drag->setMimeData(new QMimeData());
        drag->setPixmap(QPixmap("image.png"));

        drag->exec();
    }
    QTableView::mousePressEvent(event);
}
</code>```

Output:

Body:
Taking this tutorial as a reference, the mousePressEvent method is overwritten, and a new QPixmap is placed in QDrag:

void mousePressEvent(QMouseEvent *event){
    if (event->button() == Qt::LeftButton){

        QDrag *drag = new QDrag(this);
        drag->setMimeData(new QMimeData());
        drag->setPixmap(QPixmap("image.png"));

        drag->exec();
    }
    QTableView::mousePressEvent(event);
}

Output:


问:
Finding if an element is in an array using C (syntax issue)
I'm trying to write a function that checks if an element is an array in C. I have a function here, but it always returns 0, so any debugging help would be appreciated:</p>

```<code>#include <stdio.h>
int array[] = {1, 2, 3};
int *parray = &array;
int j;
int n = sizeof(array)/sizeof(array[0]);

int ifInList(int array[], int n){
    for (j = 0; j < n; j++){
        if (array[j] == n){
           return 1;
        }
    }
    return 0;
}

int main(){
    printf("The number is %d \n", ifInList(&array[n], 1));
    return 0;
}
</code>```

答:
While you already have good answers for your problem, continuing from my comment, always try and avoid the use of global variables. Declaring variables within proper scope avoids a number of potential problems and name collisions as your projects become larger. You can easily declare all of your variables within main() and pass them as parameters as required to make them available in other parts of your code. A quick example would be:

```<code>#include <stdio.h>

int ifinlist (int *array, size_t nelem, int n){

    for (size_t j = 0; j < nelem; j++)
        if (array[j] == n)
        return 1;

    return 0;
}

int main (void) {

    int array[] = {1, 3, 5},
        n = sizeof array / sizeof *array;

    for (int i = 0; i <= array[n - 1]; i++)
        printf ("The number '%d' %s present\n",
            i, ifinlist (array, n, i) ? "is" : "is not");

    return 0;
}
</code>```

Example Use/Output

Trivial output for the code would be:

```<code>$ ./bin/array_inlist
The number '0' is not present
The number '1' is present
The number '2' is not present
The number '3' is present
The number '4' is not present
The number '5' is present
</code>```

Good luck with your coding.

Body:
I'm trying to write a function that checks if an element is an array in C. I have a function here, but it always returns 0, so any debugging help would be appreciated:

#include <stdio.h>
int array[] = {1, 2, 3};
int *parray = &array;
int j;
int n = sizeof(array)/sizeof(array[0]);

int ifInList(int array[], int n){
    for (j = 0; j < n; j++){
        if (array[j] == n){
           return 1;
        }
    }
    return 0;
}

int main(){
    printf("The number is %d \n", ifInList(&array[n], 1));
    return 0;
}

Body:
While you already have good answers for your problem, continuing from my comment, always try and avoid the use of global variables. Declaring variables within proper scope avoids a number of potential problems and name collisions as your projects become larger. You can easily declare all of your variables within main() and pass them as parameters as required to make them available in other parts of your code. A quick example would be:

#include <stdio.h>

int ifinlist (int *array, size_t nelem, int n){

    for (size_t j = 0; j < nelem; j++)
        if (array[j] == n)
        return 1;

    return 0;
}

int main (void) {

    int array[] = {1, 3, 5},
        n = sizeof array / sizeof *array;

    for (int i = 0; i <= array[n - 1]; i++)
        printf ("The number '%d' %s present\n",
            i, ifinlist (array, n, i) ? "is" : "is not");

    return 0;
}

Example Use/Output

Trivial output for the code would be:

$ ./bin/array_inlist
The number '0' is not present
The number '1' is present
The number '2' is not present
The number '3' is present
The number '4' is not present
The number '5' is present

Good luck with your coding.


问:
Insert a symbol ">" between the characters in a list of strings
I have a column in Excel like this:

```<code>ABC
BCD
BA
</code>```

How can I put the symbols ">" between every letters in the strings? The expected output should be like this:

```<code>A>B>C
B>C>D
B>A
</code>```

Or could we do this in Matlab ?

答:
If you have only ASCII characters, you can try this simple UDF:

```<code>Function insertChar(s As String, c As String) As String
  insertChar = Join(Split(StrConv(s, vbUnicode), vbNullChar), c)
End Function
</code>```

Test:

```<code>A1: abcd;'.
B1: =insertChar(A1, ">")   ----->   a>b>c>d>;>'>.>
</code>```

Body:
I have a column in Excel like this:

ABC
BCD
BA

How can I put the symbols ">" between every letters in the strings? The expected output should be like this:

A>B>C
B>C>D
B>A

Or could we do this in Matlab ?

Body:
If you have only ASCII characters, you can try this simple UDF:

Function insertChar(s As String, c As String) As String
  insertChar = Join(Split(StrConv(s, vbUnicode), vbNullChar), c)
End Function

Test:

A1: abcd;'.
B1: =insertChar(A1, ">")   ----->   a>b>c>d>;>'>.>