问:
Retrieving/setting values of UIView Objects in Array
I have a UIView class called Keyboard in my ViewController to create customizable piano keyboard diagrams:

```<code>class Key: UIView {
    var keyType = 0
    var keyTypeArray = ["A", "Bb", "B", "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab"]
    // error key type: 0
    // white key types: 1, 3, 4, 6, 8, 9, 11
    // black key types: 2, 5, 7, 10, 12

    init() {
        super.init(frame: CGRect())
        self.backgroundColor = .white

        self.layer.borderWidth = 1
        self.clipsToBounds = false
        self.layer.shadowOffset = CGSize(width: 5, height: 5)
        self.layer.shadowOpacity = 1.0
        self.layer.shadowRadius = 5
        self.layer.shadowColor = UIColor(red: 44.0/255.0, green: 62.0/255.0, blue: 80.0/255.0, alpha: 1.0).cgColor
        self.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
    }

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

   class Keyboard: UIView {
        let initialKey: Int
        let numberOfKeys: Int
        var scale: Double

        var keys = [Key]()
        var numWhiteKeys = 0
        var numBlackKeys = 0
        var startingX: CGFloat = 100.0
        var startingY: CGFloat = 200.0
        var zPos: CGFloat

        var keyboardDimensions = [23.0, 24.0, 14.0, 91.0, 52.0]
        //        narrowWhiteKeyWidth = 23.0
        //        wideWhiteKeyWidth = 24.0
        //        blackKeyWidth = 14.0
        //        whiteKeyHeight = 91.0
        //        blackKeyHeight = 52.0

        var blackOffsetsArray = [20.0, 38.0, 14.0, 19.0, 36.0, 13.0, 17.0]
        var whiteOffsetsArray = [3.0, 9.0, 5.0, 11.0, 7.0]
        var nextBlackKeyPos = [41.0, 28.0, 41.0, 27.0, 27.0]

        init(startingX: CGFloat, startingY: CGFloat, initialKey: Int, numberOfKeys: Int, scale: Double, zPos: CGFloat) {
            self.startingX = startingX
            self.startingY = startingY
            self.initialKey = initialKey
            self.numberOfKeys = numberOfKeys
            self.scale = scale
            self.zPos = zPos
            super.init(frame: CGRect())
        }

        @discardableResult
        func addKeys() -> [UIView] {
            for (index, _) in blackOffsetsArray.enumerated() {
                blackOffsetsArray[index] *= scale
            }
            for (index, _) in whiteOffsetsArray.enumerated() {
                whiteOffsetsArray[index] *= scale
            }
            for (index, _) in nextBlackKeyPos.enumerated() {
                nextBlackKeyPos[index] *= scale
            }
            for (index, _) in keyboardDimensions.enumerated() {
                keyboardDimensions[index] *= scale
            }

            var counter = initialKey
            var whiteKeys = [Key]()
            var blackKeys = [Key]()
            var wXPos = CGFloat()
            var bXPos = CGFloat()

            let blackOffsetsDict = [1: 0, 3: 1, 4: 2, 6: 3, 8: 4, 9: 5, 11: 6]
            let whiteOffsetsDict = [2: 0, 5: 1, 7: 2, 10: 3, 12: 4]

            switch  initialKey {
            case 1, 3, 4, 6, 8, 9, 11:
                wXPos = startingX
                if let offsetNum = blackOffsetsDict[initialKey] {
                    bXPos = startingX + CGFloat(blackOffsetsArray[offsetNum])
                }
            case 2, 5, 7, 10, 12:
                bXPos = startingX
                if let offsetNum = whiteOffsetsDict[initialKey] {
                    wXPos = startingX + CGFloat(whiteOffsetsArray[offsetNum])
                }
            default:
                print("Error!")
            }

            while counter <= (numberOfKeys + initialKey - 1)   {
                var keyNum = Int()
                let timesIn = Int(counter/12)
                let key = Key()

                key.layer.shadowOffset = CGSize(width: 5*CGFloat(scale), height: 5*CGFloat(scale))
                key.layer.shadowRadius = 5*CGFloat(scale)

                if counter <= 12 {
                    keyNum = counter
                } else if counter > 12 && (counter % 12) != 0 {
                    keyNum = counter - (12 * (timesIn))
                } else {
                    keyNum = counter - (12 * (timesIn - 1))
                }

                switch keyNum {
                case 1, 3, 4, 6, 8, 9, 11:
                    keys.append(key)
                    whiteKeys.append(key)
                    self.numWhiteKeys += 1
                    key.backgroundColor = UIColor.white
                    key.layer.cornerRadius = 5*CGFloat(scale)
                    key.layer.borderColor = UIColor.black.cgColor
                    key.layer.zPosition = zPos
//                    print("keyNum is \(keyNum), counter is \(counter)")

                    switch keyNum {
                    case 1, 4, 8, 11:
                        key.frame = CGRect(x: Double(wXPos), y: Double(startingY), width: keyboardDimensions[0], height: keyboardDimensions[3])

                        switch keyNum {
                        case 1:
//                            print("  A")
                            key.keyType = 1
                        case 4:
//                            print("  C")
                            key.keyType = 4
                        case 8:
//                            print("  E")
                            key.keyType = 8
                        case 11:
//                            print("  G")
                            key.keyType = 11
                        default:
                            key.keyType = 0
                            print("  Error!")
                        }
                    case 3, 6, 9:
                        key.frame = CGRect(x: Double(wXPos), y: Double(startingY), width: keyboardDimensions[1], height: keyboardDimensions[3])

                        switch keyNum {
                        case 3:
//                            print("  B")
                            key.keyType = 3
                        case 6:
//                            print("  D")
                            key.keyType = 6
                        case 9:
//                            print("  F")
                            key.keyType = 9
                        default:
                            key.keyType = 0
                            print("  Error!")
                        }
                    default:
                        key.keyType = 0
                        print("  Error!")
                    }

                    wXPos += key.frame.width

                case 2, 5, 7, 10, 12:
                    self.numBlackKeys += 1
                    key.layer.zPosition = zPos + 1
                    key.layer.cornerRadius = 2.5*CGFloat(scale)
                    key.layer.borderColor = UIColor.black.cgColor
                    key.backgroundColor = UIColor.darkGray
                    key.layer.shadowOffset = CGSize(width: 2*CGFloat(scale), height: 2*CGFloat(scale))
                    key.layer.shadowRadius = 2*CGFloat(scale)
                    key.layer.shadowOpacity = 1.0
//                    print("keyNum is \(keyNum), counter is \(counter)")

                    key.frame = CGRect(x: Double(bXPos), y: Double(startingY), width: keyboardDimensions[2], height: keyboardDimensions[4])

                    switch keyNum {
                    case 2:
//                        print("  Bb")
                        key.keyType = 2
                        bXPos += CGFloat(nextBlackKeyPos[0])
                    case 5:
//                        print("  Db")
                        key.keyType = 5
                        bXPos += CGFloat(nextBlackKeyPos[1])
                    case 7:
//                        print("  Eb")
                        key.keyType = 7
                        bXPos += CGFloat(nextBlackKeyPos[2])
                    case 10:
//                        print("  Gb")
                        key.keyType = 10
                        bXPos += CGFloat(nextBlackKeyPos[3])
                    case 12:
//                        print("  Ab")
                        key.keyType = 12
                        bXPos += CGFloat(nextBlackKeyPos[4])
                    default:
                        key.keyType = 0
                        print("  Error!")
                    }

                    keys.append(key)
                    blackKeys.append(key)
                default:
                    key.keyType = 0
                    print("Key # is \(keyNum). Error!")
                }
                counter += 1
            }

            return keys
        }

        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
</code>```

And then I have an addKeyboard function that creates each keyboard and adds it to a keyboards array:

```<code>var keyboards = [Keyboard]()

    func addKeyboard(startingX: CGFloat, startingY: CGFloat, initialKey: Int, numberOfKeys: Int, scale: Double, zPos: CGFloat) {

        let myKeyboard = Keyboard(startingX: startingX, startingY: startingY, initialKey: initialKey, numberOfKeys: numberOfKeys, scale: scale, zPos: zPos)
        myKeyboard.addKeys()
        myKeyboard.layer.zPosition = zPos
        var i = 0
        while i < myKeyboard.keys.count {
            view.addSubview(myKeyboard.keys[i])
            i += 1
        }
        keyboards.append(myKeyboard)
    }
</code>```

Finally, in viewDidLoad, I can call addKeyboard like so:

```<code>addKeyboard(startingX: 250, startingY: 30, initialKey: 9, numberOfKeys: 7, scale: 1.0, zPos: 2)
addKeyboard(startingX: 150, startingY: 100, initialKey: 4, numberOfKeys: 5, scale: 0.5, zPos: 2)
</code>```

etc. (5 more keyboards)

My problem is when I retrieve my keyboards array and try to change any of the keyboards' values. The array returns a bunch of UIViews with frames of (0 0; 0  0), and I can't change any parameters from viewDidLoad.

This:

```<code>print(keyboards)
keyboards[5].scale = 2.0
print(keyboards[5].scale)
print(keyboards[5].frame)
</code>```

yields this:

```<code>[<_TtCC17drawKeyboardTest314ViewController8Keyboard: 0x7f9f9b2002e0; frame = (0 0; 0 0); layer = <CALayer: 0x60400003f4c0>>, <_TtCC17drawKeyboardTest314ViewController8Keyboard: 0x7f9f9b105390; frame = (0 0; 0 0); layer = <CALayer: 0x6000002225c0>>
</code>```

etc.

and the print(keyboards[5].scale) yields 2.0 but the actual size doesn't change (results of last 2 print() calls above).

```<code>2.0
(0.0, 0.0, 0.0, 0.0)
</code>```

How do I change things so that I after I add my Keyboards to the keyboards array, I can then get the proper values and change them as needed (for example, resize, move around, highlight certain keys)?

Thanks so much.

Jake

答:
Couple issues...

You are defining a class Keyboard: UIView, and within that class you are creating (and setting frames for) a bunch of class Key: UIView.

However, you are adding those Keys as subviews of the main view of your ViewController, when you should be adding them as subviews of the Keyboard view. You would then add the keyboard to your main .view. (Note: you'll also need to set the frame of the keyboard object to contain its keys).

Your code is not doing anything when you change the .scale property.

One option is to add a "resize()" type function, and either call that directly, or call it automatically when you change the scale property. Perhaps like so:

```<code>var scale: Double {
    didSet {
        self.resize()
    }
}
</code>```

As a side note, you will likely get better results - and I expect it will be easier in the long run - to use auto-sizing and constraints rather than explicit positions and sizes for the "keys".

Body:
I have a UIView class called Keyboard in my ViewController to create customizable piano keyboard diagrams:

class Key: UIView {
    var keyType = 0
    var keyTypeArray = ["A", "Bb", "B", "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab"]
    // error key type: 0
    // white key types: 1, 3, 4, 6, 8, 9, 11
    // black key types: 2, 5, 7, 10, 12

    init() {
        super.init(frame: CGRect())
        self.backgroundColor = .white

        self.layer.borderWidth = 1
        self.clipsToBounds = false
        self.layer.shadowOffset = CGSize(width: 5, height: 5)
        self.layer.shadowOpacity = 1.0
        self.layer.shadowRadius = 5
        self.layer.shadowColor = UIColor(red: 44.0/255.0, green: 62.0/255.0, blue: 80.0/255.0, alpha: 1.0).cgColor
        self.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
    }

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

   class Keyboard: UIView {
        let initialKey: Int
        let numberOfKeys: Int
        var scale: Double

        var keys = [Key]()
        var numWhiteKeys = 0
        var numBlackKeys = 0
        var startingX: CGFloat = 100.0
        var startingY: CGFloat = 200.0
        var zPos: CGFloat

        var keyboardDimensions = [23.0, 24.0, 14.0, 91.0, 52.0]
        //        narrowWhiteKeyWidth = 23.0
        //        wideWhiteKeyWidth = 24.0
        //        blackKeyWidth = 14.0
        //        whiteKeyHeight = 91.0
        //        blackKeyHeight = 52.0

        var blackOffsetsArray = [20.0, 38.0, 14.0, 19.0, 36.0, 13.0, 17.0]
        var whiteOffsetsArray = [3.0, 9.0, 5.0, 11.0, 7.0]
        var nextBlackKeyPos = [41.0, 28.0, 41.0, 27.0, 27.0]

        init(startingX: CGFloat, startingY: CGFloat, initialKey: Int, numberOfKeys: Int, scale: Double, zPos: CGFloat) {
            self.startingX = startingX
            self.startingY = startingY
            self.initialKey = initialKey
            self.numberOfKeys = numberOfKeys
            self.scale = scale
            self.zPos = zPos
            super.init(frame: CGRect())
        }

        @discardableResult
        func addKeys() -> [UIView] {
            for (index, _) in blackOffsetsArray.enumerated() {
                blackOffsetsArray[index] *= scale
            }
            for (index, _) in whiteOffsetsArray.enumerated() {
                whiteOffsetsArray[index] *= scale
            }
            for (index, _) in nextBlackKeyPos.enumerated() {
                nextBlackKeyPos[index] *= scale
            }
            for (index, _) in keyboardDimensions.enumerated() {
                keyboardDimensions[index] *= scale
            }

            var counter = initialKey
            var whiteKeys = [Key]()
            var blackKeys = [Key]()
            var wXPos = CGFloat()
            var bXPos = CGFloat()

            let blackOffsetsDict = [1: 0, 3: 1, 4: 2, 6: 3, 8: 4, 9: 5, 11: 6]
            let whiteOffsetsDict = [2: 0, 5: 1, 7: 2, 10: 3, 12: 4]

            switch  initialKey {
            case 1, 3, 4, 6, 8, 9, 11:
                wXPos = startingX
                if let offsetNum = blackOffsetsDict[initialKey] {
                    bXPos = startingX + CGFloat(blackOffsetsArray[offsetNum])
                }
            case 2, 5, 7, 10, 12:
                bXPos = startingX
                if let offsetNum = whiteOffsetsDict[initialKey] {
                    wXPos = startingX + CGFloat(whiteOffsetsArray[offsetNum])
                }
            default:
                print("Error!")
            }

            while counter <= (numberOfKeys + initialKey - 1)   {
                var keyNum = Int()
                let timesIn = Int(counter/12)
                let key = Key()

                key.layer.shadowOffset = CGSize(width: 5*CGFloat(scale), height: 5*CGFloat(scale))
                key.layer.shadowRadius = 5*CGFloat(scale)

                if counter <= 12 {
                    keyNum = counter
                } else if counter > 12 && (counter % 12) != 0 {
                    keyNum = counter - (12 * (timesIn))
                } else {
                    keyNum = counter - (12 * (timesIn - 1))
                }

                switch keyNum {
                case 1, 3, 4, 6, 8, 9, 11:
                    keys.append(key)
                    whiteKeys.append(key)
                    self.numWhiteKeys += 1
                    key.backgroundColor = UIColor.white
                    key.layer.cornerRadius = 5*CGFloat(scale)
                    key.layer.borderColor = UIColor.black.cgColor
                    key.layer.zPosition = zPos
//                    print("keyNum is \(keyNum), counter is \(counter)")

                    switch keyNum {
                    case 1, 4, 8, 11:
                        key.frame = CGRect(x: Double(wXPos), y: Double(startingY), width: keyboardDimensions[0], height: keyboardDimensions[3])

                        switch keyNum {
                        case 1:
//                            print("  A")
                            key.keyType = 1
                        case 4:
//                            print("  C")
                            key.keyType = 4
                        case 8:
//                            print("  E")
                            key.keyType = 8
                        case 11:
//                            print("  G")
                            key.keyType = 11
                        default:
                            key.keyType = 0
                            print("  Error!")
                        }
                    case 3, 6, 9:
                        key.frame = CGRect(x: Double(wXPos), y: Double(startingY), width: keyboardDimensions[1], height: keyboardDimensions[3])

                        switch keyNum {
                        case 3:
//                            print("  B")
                            key.keyType = 3
                        case 6:
//                            print("  D")
                            key.keyType = 6
                        case 9:
//                            print("  F")
                            key.keyType = 9
                        default:
                            key.keyType = 0
                            print("  Error!")
                        }
                    default:
                        key.keyType = 0
                        print("  Error!")
                    }

                    wXPos += key.frame.width

                case 2, 5, 7, 10, 12:
                    self.numBlackKeys += 1
                    key.layer.zPosition = zPos + 1
                    key.layer.cornerRadius = 2.5*CGFloat(scale)
                    key.layer.borderColor = UIColor.black.cgColor
                    key.backgroundColor = UIColor.darkGray
                    key.layer.shadowOffset = CGSize(width: 2*CGFloat(scale), height: 2*CGFloat(scale))
                    key.layer.shadowRadius = 2*CGFloat(scale)
                    key.layer.shadowOpacity = 1.0
//                    print("keyNum is \(keyNum), counter is \(counter)")

                    key.frame = CGRect(x: Double(bXPos), y: Double(startingY), width: keyboardDimensions[2], height: keyboardDimensions[4])

                    switch keyNum {
                    case 2:
//                        print("  Bb")
                        key.keyType = 2
                        bXPos += CGFloat(nextBlackKeyPos[0])
                    case 5:
//                        print("  Db")
                        key.keyType = 5
                        bXPos += CGFloat(nextBlackKeyPos[1])
                    case 7:
//                        print("  Eb")
                        key.keyType = 7
                        bXPos += CGFloat(nextBlackKeyPos[2])
                    case 10:
//                        print("  Gb")
                        key.keyType = 10
                        bXPos += CGFloat(nextBlackKeyPos[3])
                    case 12:
//                        print("  Ab")
                        key.keyType = 12
                        bXPos += CGFloat(nextBlackKeyPos[4])
                    default:
                        key.keyType = 0
                        print("  Error!")
                    }

                    keys.append(key)
                    blackKeys.append(key)
                default:
                    key.keyType = 0
                    print("Key # is \(keyNum). Error!")
                }
                counter += 1
            }

            return keys
        }

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

And then I have an addKeyboard function that creates each keyboard and adds it to a keyboards array:

var keyboards = [Keyboard]()

    func addKeyboard(startingX: CGFloat, startingY: CGFloat, initialKey: Int, numberOfKeys: Int, scale: Double, zPos: CGFloat) {

        let myKeyboard = Keyboard(startingX: startingX, startingY: startingY, initialKey: initialKey, numberOfKeys: numberOfKeys, scale: scale, zPos: zPos)
        myKeyboard.addKeys()
        myKeyboard.layer.zPosition = zPos
        var i = 0
        while i < myKeyboard.keys.count {
            view.addSubview(myKeyboard.keys[i])
            i += 1
        }
        keyboards.append(myKeyboard)
    }

Finally, in viewDidLoad, I can call addKeyboard like so:

addKeyboard(startingX: 250, startingY: 30, initialKey: 9, numberOfKeys: 7, scale: 1.0, zPos: 2)
addKeyboard(startingX: 150, startingY: 100, initialKey: 4, numberOfKeys: 5, scale: 0.5, zPos: 2)

etc. (5 more keyboards)

My problem is when I retrieve my keyboards array and try to change any of the keyboards' values. The array returns a bunch of UIViews with frames of (0 0; 0  0), and I can't change any parameters from viewDidLoad.

This:

print(keyboards)
keyboards[5].scale = 2.0
print(keyboards[5].scale)
print(keyboards[5].frame)

yields this:

[<_TtCC17drawKeyboardTest314ViewController8Keyboard: 0x7f9f9b2002e0; frame = (0 0; 0 0); layer = <CALayer: 0x60400003f4c0>>, <_TtCC17drawKeyboardTest314ViewController8Keyboard: 0x7f9f9b105390; frame = (0 0; 0 0); layer = <CALayer: 0x6000002225c0>>

etc.

and the print(keyboards[5].scale) yields 2.0 but the actual size doesn't change (results of last 2 print() calls above).

2.0
(0.0, 0.0, 0.0, 0.0)

How do I change things so that I after I add my Keyboards to the keyboards array, I can then get the proper values and change them as needed (for example, resize, move around, highlight certain keys)?

Thanks so much.

Jake

Body:
Couple issues...

You are defining a class Keyboard: UIView, and within that class you are creating (and setting frames for) a bunch of class Key: UIView.

However, you are adding those Keys as subviews of the main view of your ViewController, when you should be adding them as subviews of the Keyboard view. You would then add the keyboard to your main .view. (Note: you'll also need to set the frame of the keyboard object to contain its keys).

Your code is not doing anything when you change the .scale property.

One option is to add a "resize()" type function, and either call that directly, or call it automatically when you change the scale property. Perhaps like so:

var scale: Double {
    didSet {
        self.resize()
    }
}

As a side note, you will likely get better results - and I expect it will be easier in the long run - to use auto-sizing and constraints rather than explicit positions and sizes for the "keys".


来源: stackexchange

问:
how to know density of device?
As we can get the resolution in android, but how can we know the density of the device (screen) ?

thanks

答:
Execute the following code:

```<code>float scale = getApplicationContext().getResources().getDisplayMetrics().density;
</code>```

and check the value of scale:

0.75 means low density

1.0 means standard (medium) density

1.5 means high (large) density

2.0 means extra high density

3.0 means extra extra high density

4.0 means extra extra extra high density

See the documentation for more info.

ContentLicense: CC BY-SA 4.0

Title: how to know density of device?

Body:
Execute the following code:

float scale = getApplicationContext().getResources().getDisplayMetrics().density;

and check the value of scale:

0.75 means low density

1.0 means standard (medium) density

1.5 means high (large) density

2.0 means extra high density

3.0 means extra extra high density

4.0 means extra extra extra high density

See the documentation for more info.

ContentLicense: CC BY-SA 3.0


问:
Two Columns Auto Height Background Colour
I'm probably missing something really simple here. I have two columns which keep the same height, depending on which div has more content inside of it, however the background colour does not extend on the shorter column; the columns change to a vertical layout when the display is smaller with the use of media queries. How can I get the background colour of the left column to extend to the bottom of the div?

#pageContainer {
        width: 100%;
        text-align: center;
    }

    #pageContainer p {
        line-height: 10px;
    }

    .sectionContainer {
        width: 80%;
        margin: 0 auto;
        display: table;
    }

    .leftColumn {
        display: table-cell;
        float: left;
        width: 50%;
        background-color: #4F4F4F;
        color: #FFFFFF;
    }

    .rightColumn {
        display: table-cell;
        float: left;
        width: 50%;
        background-color: #EEEEEE;
        color: #000000;

    }

    @media all and (max-width: 768px) {
        .sectionContainer {
            width: 100%;
        }

        .leftColumn {
            width: 100%;
        }

        .rightColumn {
            width: 100%;
        }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="pageContainer">
  <div class="sectionContainer">
    <div class="leftColumn">
      <h1>Left Column</h1>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
    </div>
    <div class="rightColumn">
      <h1>Right Column</h1>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
    </div>
  </div>
</div></code>```

I have included a CodePen to show the problem: https://codepen.io/Macast/pen/ZaZrNz

Thanks!

答:
Adding height:100% to both sectionContainer and leftColumn classes seems to fix it.

#pageContainer {
        width: 100%;
        text-align: center;
    }

    #pageContainer p {
        line-height: 10px;
    }

    .sectionContainer {
        width: 80%;
        margin: 0 auto;
        display: table;
        height:100%;
    }

    .leftColumn {
        display: table-cell;
        float: left;
        width: 50%;
        background-color: #4F4F4F;
        color: #FFFFFF;
        height:100%;
    }

    .rightColumn {
        display: table-cell;
        float: left;
        width: 50%;
        background-color: #EEEEEE;
        color: #000000;

    }

    @media all and (max-width: 768px) {
        .sectionContainer {
            width: 100%;
        }

        .leftColumn {
            width: 100%;
        }

        .rightColumn {
            width: 100%;
        }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="pageContainer">
  <div class="sectionContainer">
    <div class="leftColumn">
      <h1>Left Column</h1>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
    </div>
    <div class="rightColumn">
      <h1>Right Column</h1>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
    </div>
  </div>
</div></code>```

Body:
I'm probably missing something really simple here. I have two columns which keep the same height, depending on which div has more content inside of it, however the background colour does not extend on the shorter column; the columns change to a vertical layout when the display is smaller with the use of media queries. How can I get the background colour of the left column to extend to the bottom of the div?

#pageContainer {
        width: 100%;
        text-align: center;
    }

    #pageContainer p {
        line-height: 10px;
    }

    .sectionContainer {
        width: 80%;
        margin: 0 auto;
        display: table;
    }

    .leftColumn {
        display: table-cell;
        float: left;
        width: 50%;
        background-color: #4F4F4F;
        color: #FFFFFF;
    }

    .rightColumn {
        display: table-cell;
        float: left;
        width: 50%;
        background-color: #EEEEEE;
        color: #000000;

    }

    @media all and (max-width: 768px) {
        .sectionContainer {
            width: 100%;
        }

        .leftColumn {
            width: 100%;
        }

        .rightColumn {
            width: 100%;
        }
    }

Left Column

Left Column

Left Column

Left Column

Left Column

Left Column

Left Column

Left Column

Left Column

Left Column

Left Column

Right Column

Right Column

Right Column

Right Column

Right Column

Right Column

Right Column

Right Column

Right Column

Right Column

Right Column

Right Column

Right Column

I have included a CodePen to show the problem: https://codepen.io/Macast/pen/ZaZrNz

Thanks!

Body:
Adding height:100% to both sectionContainer and leftColumn classes seems to fix it.

#pageContainer {
        width: 100%;
        text-align: center;
    }

    #pageContainer p {
        line-height: 10px;
    }

    .sectionContainer {
        width: 80%;
        margin: 0 auto;
        display: table;
        height:100%;
    }

    .leftColumn {
        display: table-cell;
        float: left;
        width: 50%;
        background-color: #4F4F4F;
        color: #FFFFFF;
        height:100%;
    }

    .rightColumn {
        display: table-cell;
        float: left;
        width: 50%;
        background-color: #EEEEEE;
        color: #000000;

    }

    @media all and (max-width: 768px) {
        .sectionContainer {
            width: 100%;
        }

        .leftColumn {
            width: 100%;
        }

        .rightColumn {
            width: 100%;
        }
    }

<div id="pageContainer">
  <div class="sectionContainer">
    <div class="leftColumn">
      <h1>Left Column</h1>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
      <p>Left Column</p>
    </div>
    <div class="rightColumn">
      <h1>Right Column</h1>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
      <p>Right Column</p>
    </div>
  </div>
</div>


问:
Change image if radio button is selected
I have these two radio buttons where I have hidden the input marks and replaced them with images:

```<code><div class="card-block center-style">
    <div class="form-check inline-style">
        <label class="form-check-label question-label">
            <input type="radio" class="form-check-input" name="ps-qna-1" id="ps-form-1" value="Homeowner">
            <div class="shadow-active">
                <div class="circle"><img src="images/homeowner.png" id="img-1"><span>Homeowner</span></div>
            </div>
        </label>
    </div>
    <div class="form-check inline-style">
        <label class="form-check-label question-label">
            <input type="radio" class="form-check-input" name="ps-qna-1" id="ps-form-2" value="Business">
            <div class="shadow-active">
                <div class="circle"><img src="images/business_servicer.png" id="img-2"><span>Business/Servicer</span></div>
            </div>
        </label>
    </div>
</div>
</code>```

I need the images to swap out if the radio button is selected. If not, I need the image to stay what it is in the HTML. I have this for my JQuery:

```<code>$(document).ready(function() {
$('input[name="ps-qna-1"]:radio').click(function(){
    if ($('input[name=ps-qna-1]:checked').val() == "Homeowner") {
        $("#img-1").attr("src","images/homeowner-active.png");

    } else if ($('input[name=ps-qna-1]:checked').val() == "Business") {
        $("#img-2").attr("src","images/business-servicer-active.png");

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

But my code is not working. It is not swapping out the images. What am I doing wrong here? Any help is good. Thanks!

I have added two pictures of what the radio buttons look like before selection and how it looks after one is selected. but I need that house image swapped out to a different house image with color in it. Hope this wasn't too confusing.

答:
When you add the -active URL to one image, add the normal URL to the other.

```<code>$(document).ready(function() {
    $('input[name="ps-qna-1"]:radio').click(function(){
        switch($(this).val()) {
        case "Homeowner":
            $("#img-1").attr("src","images/homeowner-active.png");
            $("#img-2").attr("src","images/business-service.png");
            break;
        case "Business":
            $("#img-1").attr("src","images/homeowner.png");
            $("#img-2").attr("src","images/business-servicer-active.png");
            break;
        }
    });
});
</code>```

Body:
I have these two radio buttons where I have hidden the input marks and replaced them with images:

            <input type="radio" class="form-check-input" name="ps-qna-1" id="ps-form-1" value="Homeowner">

Homeowner

            <input type="radio" class="form-check-input" name="ps-qna-1" id="ps-form-2" value="Business">

Business/Servicer

I need the images to swap out if the radio button is selected. If not, I need the image to stay what it is in the HTML. I have this for my JQuery:

$(document).ready(function() {
$('input[name="ps-qna-1"]:radio').click(function(){
    if ($('input[name=ps-qna-1]:checked').val() == "Homeowner") {
        $("#img-1").attr("src","images/homeowner-active.png");

    } else if ($('input[name=ps-qna-1]:checked').val() == "Business") {
        $("#img-2").attr("src","images/business-servicer-active.png");

    }
});
});

But my code is not working. It is not swapping out the images. What am I doing wrong here? Any help is good. Thanks!

I have added two pictures of what the radio buttons look like before selection and how it looks after one is selected. but I need that house image swapped out to a different house image with color in it. Hope this wasn't too confusing.

Body:
When you add the -active URL to one image, add the normal URL to the other.

$(document).ready(function() {
    $('input[name="ps-qna-1"]:radio').click(function(){
        switch($(this).val()) {
        case "Homeowner":
            $("#img-1").attr("src","images/homeowner-active.png");
            $("#img-2").attr("src","images/business-service.png");
            break;
        case "Business":
            $("#img-1").attr("src","images/homeowner.png");
            $("#img-2").attr("src","images/business-servicer-active.png");
            break;
        }
    });
});


问:
.map() is not a function Error on Mapping Dynamically created Object
I am trying to map a dynamically created Object to an Array like this

```<code>          params.junctionBarriers = dojo.toJson(junctionBarriers);
          // printing the object in the console (Please look at attached image)
          console.log(params.junctionBarriers);

          var value = [];
          var data = params.junctionBarriers.map(function (s) {
             value.push(webMercatorUtils.xyToLngLat(s.x, s.y, true));
              return s;
          })
</code>```

but I am getting this error

params.junctionBarriers.map is not a function

As you can see from the image the params.junctionBarriers is dynamically loaded but the .map() is not valid. Why is this, and how I can fix it?

答:
Actually dojo.toJson() is the same as JSON.stringify(), which is converting your array to a JSON string here. So the problem is that you were trying to call .map() on a string.

That's why you got the error:

params.junctionBarriers.map is not a function

So you need to make your .map() call before transforming your object to a JSON string.

Body:
I am trying to map a dynamically created Object to an Array like this

          params.junctionBarriers = dojo.toJson(junctionBarriers);
          // printing the object in the console (Please look at attached image)
          console.log(params.junctionBarriers);

          var value = [];
          var data = params.junctionBarriers.map(function (s) {
             value.push(webMercatorUtils.xyToLngLat(s.x, s.y, true));
              return s;
          })

but I am getting this error

params.junctionBarriers.map is not a function

As you can see from the image the params.junctionBarriers is dynamically loaded but the .map() is not valid. Why is this, and how I can fix it?


问:
Realtime backtick output processing
I don't know if this is possible but I'm working on sending the output of a command over sockets so it will be shown on both the client and server computer while the command is running. When I try to use backticks the output isn't saved into the variable until the command completes which is bad for when I run a command that takes a long time.

Question: Is there a way to scan the output on a line by line basis by say spawning another process and having it "watch" a variable?

Edit: This is what I tried with open

```<code>open DATA, "pause |" or die "Failed: $!";
while( defined(my $line = <DATA>)){
    chomp($line);
    print "$line\n";
}
</code>```

I would like the output to be shown before the command completes.

答:
You have the right approach.

```<code>my @cmd = ( 'perl', '-e', '$|=1; for (1..5) { print "$_\n"; sleep 1; }' );

open(my $pipe, '-|', @cmd)
   or die("Can't launch child: $!\n");

while (defined( my $line = <$pipe> )) {
    chomp($line);
    print "<$line>\n";
}
</code>```

When writing to STDOUT, most programs flush their output when a newline is encountered when STDOUT is a terminal ("line buffering"). Most programs fall back to block outputting chunks of 4 KiB or 8 KiB when STDOUT isn't a terminal ("block buffering"). That's why I had to use $|=1; in the child program in the example above.

Programs that behave as described can be fooled into using line buffering using pseudo-terminal instead of a pipe.

```<code>my @cmd = ( 'unbuffer', 'perl', '-e', 'for (1..5) { print "$_\n"; sleep 1; }' );

open(my $pipe, '-|', @cmd)
   or die("Can't launch child: $!\n");

while (defined( my $line = <$pipe> )) {
    chomp($line);
    print "<$line>\n";
}
</code>```

IPC::Run provides a native method of creating pseudo-terminals.

```<code>use IPC::Run qw( run );

my @cmd = ( 'perl', '-e', 'for (1..5) { print "$_\n"; sleep 1; }' );

my $buf = '';
run(\@cmd, '>pty>', sub {
    $buf .= $_[0];
    while ($buf =~ s/^(.*)\r\n//) {
        print "<$1>\n";
    }
});
</code>```

Title: Realtime backtick output processing

Body:
I don't know if this is possible but I'm working on sending the output of a command over sockets so it will be shown on both the client and server computer while the command is running. When I try to use backticks the output isn't saved into the variable until the command completes which is bad for when I run a command that takes a long time.

Question: Is there a way to scan the output on a line by line basis by say spawning another process and having it "watch" a variable?

Edit: This is what I tried with open

open DATA, "pause |" or die "Failed: $!";
while( defined(my $line = <DATA>)){
    chomp($line);
    print "$line\n";
}

I would like the output to be shown before the command completes.

Body:
You have the right approach.

my @cmd = ( 'perl', '-e', '$|=1; for (1..5) { print "$_\n"; sleep 1; }' );

open(my $pipe, '-|', @cmd)
   or die("Can't launch child: $!\n");

while (defined( my $line = <$pipe> )) {
    chomp($line);
    print "<$line>\n";
}

When writing to STDOUT, most programs flush their output when a newline is encountered when STDOUT is a terminal ("line buffering"). Most programs fall back to block outputting chunks of 4 KiB or 8 KiB when STDOUT isn't a terminal ("block buffering"). That's why I had to use $|=1; in the child program in the example above.

Programs that behave as described can be fooled into using line buffering using pseudo-terminal instead of a pipe.

my @cmd = ( 'unbuffer', 'perl', '-e', 'for (1..5) { print "$_\n"; sleep 1; }' );

open(my $pipe, '-|', @cmd)
   or die("Can't launch child: $!\n");

while (defined( my $line = <$pipe> )) {
    chomp($line);
    print "<$line>\n";
}

IPC::Run provides a native method of creating pseudo-terminals.

use IPC::Run qw( run );

my @cmd = ( 'perl', '-e', 'for (1..5) { print "$_\n"; sleep 1; }' );

my $buf = '';
run(\@cmd, '>pty>', sub {
    $buf .= $_[0];
    while ($buf =~ s/^(.*)\r\n//) {
        print "<$1>\n";
    }
});


问:
ruby gem can search for, but not install some gems
I'm currently trying to setup a ruby environment to develop a logstash plugin. This ruby installation is absolutely untouched (I've installed ruby 2.4.2 with DevKit on Windows)

I can search and find the logstash-devutils gem:

```<code>$ gem search devutils

*** REMOTE GEMS ***

devutils (0.0.1)
devutils-docs (0.0.1)
devutils-guard (0.0.1)
devutils-metrics (0.0.2)
logstash-devutils (1.3.6 java)
</code>```

But if I try to install it I get an error:

```<code>$ gem install logstash-devutils
ERROR:  Could not find a valid gem 'logstash-devutils' (>= 0) in any repository
ERROR:  Possible alternatives: logstash-input-xls, logstash-input-irc, logstash-output-xls, logstash-input-sqs, logstash_rails
</code>```

While trying to download and install the gem manually I've found some other gems with a similar behaviour (I didn't examine it until the and):

logstash-core

logstash-core-plugin-api

manticore

Furthermore I get the error in 2 diffrent VMs (both linux with different ruby versions, I think 1.9.x and 2.3.x).

Also an update of gem itself didn't change something.

I'm not new to ruby but I've never observed something like this.

Just to make it clear: There are gems (e.g. bundler) that can be installed as expected.

答:
Previously asked and answered: Could not find gem 'logstash-devutils (>= 0) ruby' in any of the gem sources

Specifically, the java tag on the gem version means it requires a java-based Ruby interpreter. So the default ruby (MRI) won’t work. You need to be running JRuby (which you can more easily install, and not mess with your other Ruby projects, using a Ruby manager such as RVM).

Body:
I'm currently trying to setup a ruby environment to develop a logstash plugin. This ruby installation is absolutely untouched (I've installed ruby 2.4.2 with DevKit on Windows)

I can search and find the logstash-devutils gem:

$ gem search devutils

*** REMOTE GEMS ***

devutils (0.0.1)
devutils-docs (0.0.1)
devutils-guard (0.0.1)
devutils-metrics (0.0.2)
logstash-devutils (1.3.6 java)

But if I try to install it I get an error:

$ gem install logstash-devutils
ERROR:  Could not find a valid gem 'logstash-devutils' (>= 0) in any repository
ERROR:  Possible alternatives: logstash-input-xls, logstash-input-irc, logstash-output-xls, logstash-input-sqs, logstash_rails

While trying to download and install the gem manually I've found some other gems with a similar behaviour (I didn't examine it until the and):

logstash-core

logstash-core-plugin-api

manticore

Furthermore I get the error in 2 diffrent VMs (both linux with different ruby versions, I think 1.9.x and 2.3.x).

Also an update of gem itself didn't change something.

I'm not new to ruby but I've never observed something like this.

Just to make it clear: There are gems (e.g. bundler) that can be installed as expected.


问:
android constrain layout support different screen size
Dears am trying to use constrain layout with percentage to support different screen sizes its working fine if am only using pictures or button but when i add text its not appearing on small screen even though i add it as match parent with center gravity.
i added the xml code..
can you help me if i can use this method to support different screen sizes or i have to create different xml files.

EDIT I

The screen sizes is LDPI API 22 240 × 320: ldpi 22 Android 5.1 (Google APIs) and MDPI Small API 22 320 × 480: mdpi 22 Android 5.1 (Google APIs)

The Layout:

```<code><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/green_background"
tools:context="com.yaacoach.gymapp.StartExercise">

<android.support.constraint.Guideline
    android:id="@+id/guideline16"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.18" />

<android.support.constraint.Guideline
    android:id="@+id/guideline36"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.2" />

<android.support.constraint.Guideline
    android:id="@+id/guideline37"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentStart="true"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.8" />

<android.support.constraint.Guideline
    android:id="@+id/guideline38"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.03" />

<android.support.constraint.Guideline
    android:id="@+id/guideline40"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.08" />

<android.support.constraint.Guideline
    android:id="@+id/guideline41"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.92" />

<android.support.constraint.Guideline
    android:id="@+id/guideline42"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.27" />

<Button
    android:id="@+id/btn_start"
    style="@style/Base.TextAppearance.AppCompat.Medium"
    android:gravity="center"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginTop="2dp"
    android:background="@drawable/stopwatchstyle"
    android:text="start"
    app:layout_constraintBottom_toTopOf="@+id/guideline43"
    app:layout_constraintEnd_toStartOf="@+id/guideline47"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline39"
    app:layout_constraintVertical_bias="0.833" />

<android.support.constraint.Guideline
    android:id="@+id/guideline43"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.93" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/rv_startExercise_information"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/guideline39"
    app:layout_constraintEnd_toStartOf="@+id/guideline41"
    app:layout_constraintStart_toStartOf="@+id/guideline40"
    app:layout_constraintTop_toTopOf="@+id/guideline42" />

<android.support.constraint.Guideline
    android:id="@+id/guideline39"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.86" />

<android.support.constraint.Guideline
    android:id="@+id/guideline45"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.25" />

<android.support.constraint.ConstraintLayout
    android:id="@+id/CL_stopWatch"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:background="@drawable/stopwatchstyle"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true"
    android:foregroundGravity="center"
    app:layout_constraintBottom_toTopOf="@+id/guideline45"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline38"
    app:layout_constraintVertical_bias="1.0">

</android.support.constraint.ConstraintLayout>

<Chronometer
    android:id="@+id/chronometer2"
    style="@android:style/TextAppearance.DeviceDefault.Medium"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:gravity="center"
    android:textColor="@color/btnbrainiac"
    android:textStyle="bold"
    app:layout_constraintBottom_toTopOf="@+id/guideline46"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline38" />

<android.support.constraint.Guideline
    android:id="@+id/guideline46"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.11" />

<android.support.constraint.Guideline
    android:id="@+id/guideline47"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.4" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/rv_start_exercise_weight_rep"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/guideline45"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintStart_toStartOf="@+id/guideline47"
    app:layout_constraintTop_toTopOf="@+id/guideline46" />

<TextView
    android:id="@+id/textView2"
    style="@android:style/TextAppearance.DeviceDefault.Small"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="@string/Weight"
    app:layout_constraintBottom_toTopOf="@+id/guideline16"
    app:layout_constraintEnd_toStartOf="@+id/guideline47"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline46" />

<TextView
    android:id="@+id/textView4"
    style="@android:style/TextAppearance.DeviceDefault.Small"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="@string/repetition"
    app:layout_constraintBottom_toTopOf="@+id/guideline45"
    app:layout_constraintEnd_toStartOf="@+id/guideline47"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline16" />

<Button
    android:id="@+id/btn_StartExercies_Pause"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginTop="2dp"
    android:background="@drawable/stopwatchstyle"
    android:text="Button"
    app:layout_constraintBottom_toTopOf="@+id/guideline43"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="@+id/guideline47"
    app:layout_constraintTop_toTopOf="@+id/guideline39"
    app:layout_constraintVertical_bias="0.0" />
</code>```

答:
the screen sizes is
LDPI API 22     240 × 320: ldpi 22  Android 5.1 (Google APIs)
and
MDPI Small API 22       320 × 480: mdpi 22  Android 5.1 (Google APIs)</p>

Body:
Dears am trying to use constrain layout with percentage to support different screen sizes its working fine if am only using pictures or button but when i add text its not appearing on small screen even though i add it as match parent with center gravity.
i added the xml code..
can you help me if i can use this method to support different screen sizes or i have to create different xml files.

EDIT I

The screen sizes is LDPI API 22 240 × 320: ldpi 22 Android 5.1 (Google APIs) and MDPI Small API 22 320 × 480: mdpi 22 Android 5.1 (Google APIs)

The Layout:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/green_background"
tools:context="com.yaacoach.gymapp.StartExercise">

<android.support.constraint.Guideline
    android:id="@+id/guideline16"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.18" />

<android.support.constraint.Guideline
    android:id="@+id/guideline36"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.2" />

<android.support.constraint.Guideline
    android:id="@+id/guideline37"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentStart="true"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.8" />

<android.support.constraint.Guideline
    android:id="@+id/guideline38"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.03" />

<android.support.constraint.Guideline
    android:id="@+id/guideline40"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.08" />

<android.support.constraint.Guideline
    android:id="@+id/guideline41"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.92" />

<android.support.constraint.Guideline
    android:id="@+id/guideline42"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.27" />

<Button
    android:id="@+id/btn_start"
    style="@style/Base.TextAppearance.AppCompat.Medium"
    android:gravity="center"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginTop="2dp"
    android:background="@drawable/stopwatchstyle"
    android:text="start"
    app:layout_constraintBottom_toTopOf="@+id/guideline43"
    app:layout_constraintEnd_toStartOf="@+id/guideline47"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline39"
    app:layout_constraintVertical_bias="0.833" />

<android.support.constraint.Guideline
    android:id="@+id/guideline43"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.93" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/rv_startExercise_information"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/guideline39"
    app:layout_constraintEnd_toStartOf="@+id/guideline41"
    app:layout_constraintStart_toStartOf="@+id/guideline40"
    app:layout_constraintTop_toTopOf="@+id/guideline42" />

<android.support.constraint.Guideline
    android:id="@+id/guideline39"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.86" />

<android.support.constraint.Guideline
    android:id="@+id/guideline45"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.25" />

<android.support.constraint.ConstraintLayout
    android:id="@+id/CL_stopWatch"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:background="@drawable/stopwatchstyle"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true"
    android:foregroundGravity="center"
    app:layout_constraintBottom_toTopOf="@+id/guideline45"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline38"
    app:layout_constraintVertical_bias="1.0">

</android.support.constraint.ConstraintLayout>

<Chronometer
    android:id="@+id/chronometer2"
    style="@android:style/TextAppearance.DeviceDefault.Medium"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:gravity="center"
    android:textColor="@color/btnbrainiac"
    android:textStyle="bold"
    app:layout_constraintBottom_toTopOf="@+id/guideline46"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline38" />

<android.support.constraint.Guideline
    android:id="@+id/guideline46"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.11" />

<android.support.constraint.Guideline
    android:id="@+id/guideline47"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.4" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/rv_start_exercise_weight_rep"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/guideline45"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintStart_toStartOf="@+id/guideline47"
    app:layout_constraintTop_toTopOf="@+id/guideline46" />

<TextView
    android:id="@+id/textView2"
    style="@android:style/TextAppearance.DeviceDefault.Small"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="@string/Weight"
    app:layout_constraintBottom_toTopOf="@+id/guideline16"
    app:layout_constraintEnd_toStartOf="@+id/guideline47"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline46" />

<TextView
    android:id="@+id/textView4"
    style="@android:style/TextAppearance.DeviceDefault.Small"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="@string/repetition"
    app:layout_constraintBottom_toTopOf="@+id/guideline45"
    app:layout_constraintEnd_toStartOf="@+id/guideline47"
    app:layout_constraintStart_toStartOf="@+id/guideline36"
    app:layout_constraintTop_toTopOf="@+id/guideline16" />

<Button
    android:id="@+id/btn_StartExercies_Pause"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginTop="2dp"
    android:background="@drawable/stopwatchstyle"
    android:text="Button"
    app:layout_constraintBottom_toTopOf="@+id/guideline43"
    app:layout_constraintEnd_toStartOf="@+id/guideline37"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="@+id/guideline47"
    app:layout_constraintTop_toTopOf="@+id/guideline39"
    app:layout_constraintVertical_bias="0.0" />


问:
Insert Data from Form to MySQL database, javascript and flask

I am creating a web app for nearby events, and one of the important features is the option to create events. As of now I have a modal that contains a form. I'm having trouble taking the inputs of the form on submit and adding it to the database, using javascript and a python flask web app.

Here is my html:

```<code>    <!-- Modal -->
<div id="eventInput" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Create an Event</h4>
        <button type="button" class="close" data-dismiss="modal">×</button>
        <h4 class="modal-title"></h4>
      </div>
    <form>
      <div class="modal-body">
            <div class="form-group">
                <input autocomplete="off" autofocus class="form-control" name="title" placeholder="Event Name" type="text"/>
            </div>
            <div class="form-group">
                <input autocomplete="off" autofocus class="form-control" name="description" placeholder="Description" type="text"/>
            </div>
            <div class="form-group">
                Start date and time:
                <input autocomplete="off" autofocus class="form-control" name="start" placeholder="Start date and time" type="datetime-local"/>
            </div>
            <div class="form-group">
                End date and time:
                <input autocomplete="off" autofocus class="form-control" name="end" placeholder="End date and time" type="datetime-local"/>
            </div>
            <div class="form-group">
                <input autocomplete="off" autofocus class="form-control" name="place" placeholder="Location Name" type="text"/>
            </div>

            Please use <a href="https://www.google.com/maps">Google Maps</a> to determine the accurate latitude and longitude of your event location
            <div class="form-group">
                <input autocomplete="off" autofocus class="form-control" name="lat" placeholder="Location Latitude" type="number"/>
            </div>
            <div class="form-group">
                <input autocomplete="off" autofocus class="form-control" name="long" placeholder="Location Longitude" type="text"/>
            </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Create Event</button>
      </div>

    </form>
    </div>

  </div>
</div>
</code>```

Javascript:

```<code>   $(function() {
    $('submit').click(function() {
        var event = {
        'title': document.getElementById('title').value,
        'description': document.getElementById('description').value,
        'start': document.getElementById('start').value,
        'end': document.getElementById('end').value,
        'place': document.getElementById('place').value
       };
        $.ajax({
            url: '/createEvent',
            data: $('form').serialize(),
            type: 'POST',
            success: function(response) {
                console.log(response);
            },
            error: function(error) {
                console.log(error);
            }
        });
    });
});
</code>```

And python:

```<code># Add Event to database
@app.route('/createEvent', methods=['POST'])
def createvent() :
    title =  request.form['title'];
    description = request.form['description'];
    place = request.form['place'];
    start = request.form['start'];
    end = request.form['end'];
    db.execute("INSERT INTO events (user_id, title, description, place, start, end) VALUES (:user, :title, :description, :place, :start, :end)",
                user=session["user_id"], title=title, description=description, place=place, start=start, end=end)
    return render_template("list.html")
</code>```

答:
You need to add an Id to your form and, and remove the onsubmit event and use it only in jquery.
all  your forms element doesn't have id attribute add them like this :

the html :

```<code><div id="eventInput" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Create an Event</h4>
        <button type="button" class="close" data-dismiss="modal">×</button>
        <h4 class="modal-title"></h4>
      </div>
    <form  id="target" action="/destination">
      <div class="modal-body">
            <div class="form-group">
                <input autocomplete="off" autofocus class="form-control" name="title"   id= "title" placeholder="Event Name" type="text"/>
            </div>
            <div class="form-group">
                <input autocomplete="off" autofocus class="form-control" name="description"  id ="description" placeholder="Description" type="text"/>
            </div>
            <div class="form-group">
                Start date and time:
                <input autocomplete="off" autofocus class="form-control" name="start" id="start" placeholder="Start date and time" type="datetime-local"/>
            </div>
            <div class="form-group">
                End date and time:
                <input autocomplete="off" autofocus class="form-control" name="end" id ="end" placeholder="End date and time" type="datetime-local"/>
            </div>
            <div class="form-group">
                <input autocomplete="off" autofocus class="form-control" name="place" id ="place" placeholder="Location Name" type="text"/>
            </div>

            Please use <a href="https://www.google.com/maps">Google Maps</a> to determine the accurate latitude and longitude of your event location
            <div class="form-group">
                <input autocomplete="off" autofocus class="form-control" name="lat" id="lat" placeholder="Location Latitude" type="number"/>
            </div>
            <div class="form-group">
                <input autocomplete="off" autofocus class="form-control" name="long" id="long" placeholder="Location Longitude" type="text"/>
            </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Create Event</button>
      </div>

    </form>
    </div>
</code>```

and your javascript like this :

```<code>$( "#target" ).submit(function( event ) {
  event.preventDefault();
  var new_event = {
        'title': document.getElementById('title').value,
        'description': document.getElementById('description').value,
        'start': document.getElementById('start').value,
        'end': document.getElementById('end').value,
        'place': document.getElementById('place').value
       };
       console.log(new_event);

$.ajax({
        url: '/createEvent',
        data: $('form').serialize(),
        type: 'POST',
        success: function(response) {
            console.log(response);
        },
        error: function(error) {
            console.log(error);
        }
    });

});
</code>```

Body:
I am creating a web app for nearby events, and one of the important features is the option to create events. As of now I have a modal that contains a form. I'm having trouble taking the inputs of the form on submit and adding it to the database, using javascript and a python flask web app.

Here is my html:

Create an Event

        <button type="button" class="close" data-dismiss="modal">×</button>

    <form>

                <input autocomplete="off" autofocus class="form-control" name="title" placeholder="Event Name" type="text"/>

                <input autocomplete="off" autofocus class="form-control" name="description" placeholder="Description" type="text"/>

                Start date and time:
                <input autocomplete="off" autofocus class="form-control" name="start" placeholder="Start date and time" type="datetime-local"/>

                End date and time:
                <input autocomplete="off" autofocus class="form-control" name="end" placeholder="End date and time" type="datetime-local"/>

                <input autocomplete="off" autofocus class="form-control" name="place" placeholder="Location Name" type="text"/>

            Please use Google Maps to determine the accurate latitude and longitude of your event location

                <input autocomplete="off" autofocus class="form-control" name="lat" placeholder="Location Latitude" type="number"/>

                <input autocomplete="off" autofocus class="form-control" name="long" placeholder="Location Longitude" type="text"/>

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Create Event</button>

    </form>

Javascript:

   $(function() {
    $('submit').click(function() {
        var event = {
        'title': document.getElementById('title').value,
        'description': document.getElementById('description').value,
        'start': document.getElementById('start').value,
        'end': document.getElementById('end').value,
        'place': document.getElementById('place').value
       };
        $.ajax({
            url: '/createEvent',
            data: $('form').serialize(),
            type: 'POST',
            success: function(response) {
                console.log(response);
            },
            error: function(error) {
                console.log(error);
            }
        });
    });
});

And python:

# Add Event to database
@app.route('/createEvent', methods=['POST'])
def createvent() :
    title =  request.form['title'];
    description = request.form['description'];
    place = request.form['place'];
    start = request.form['start'];
    end = request.form['end'];
    db.execute("INSERT INTO events (user_id, title, description, place, start, end) VALUES (:user, :title, :description, :place, :start, :end)",
                user=session["user_id"], title=title, description=description, place=place, start=start, end=end)
    return render_template("list.html")

Body:
You need to add an Id to your form and, and remove the onsubmit event and use it only in jquery.
all  your forms element doesn't have id attribute add them like this :

the html :

<div id="eventInput" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Create an Event</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title"></h4>
      </div>
    <form  id="target" action="/destination">
      <div class="modal-body">
            <div class="form-group">
                <input autocomplete="off" autofocus class="form-control" name="title"   id= "title" placeholder="Event Name" type="text"/>
            </div>
            <div class="form-group">
                <input autocomplete="off" autofocus class="form-control" name="description"  id ="description" placeholder="Description" type="text"/>
            </div>
            <div class="form-group">
                Start date and time:
                <input autocomplete="off" autofocus class="form-control" name="start" id="start" placeholder="Start date and time" type="datetime-local"/>
            </div>
            <div class="form-group">
                End date and time:
                <input autocomplete="off" autofocus class="form-control" name="end" id ="end" placeholder="End date and time" type="datetime-local"/>
            </div>
            <div class="form-group">
                <input autocomplete="off" autofocus class="form-control" name="place" id ="place" placeholder="Location Name" type="text"/>
            </div>

            Please use <a href="https://www.google.com/maps">Google Maps</a> to determine the accurate latitude and longitude of your event location
            <div class="form-group">
                <input autocomplete="off" autofocus class="form-control" name="lat" id="lat" placeholder="Location Latitude" type="number"/>
            </div>
            <div class="form-group">
                <input autocomplete="off" autofocus class="form-control" name="long" id="long" placeholder="Location Longitude" type="text"/>
            </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Create Event</button>
      </div>

    </form>
    </div>

and your javascript like this :

$( "#target" ).submit(function( event ) {
  event.preventDefault();
  var new_event = {
        'title': document.getElementById('title').value,
        'description': document.getElementById('description').value,
        'start': document.getElementById('start').value,
        'end': document.getElementById('end').value,
        'place': document.getElementById('place').value
       };
       console.log(new_event);

$.ajax({
        url: '/createEvent',
        data: $('form').serialize(),
        type: 'POST',
        success: function(response) {
            console.log(response);
        },
        error: function(error) {
            console.log(error);
        }
    });

});


问:
assign agrv[i] from lines in file using python
example input.dat

```<code>[settings]
port = 1234
host = abc.com
</code>```

How can I parse the file, and assign
1234 to agrv[1],
abc.com to argv[2] and so on

here is what i tried:

```<code>$python p.py input.dat
Traceback (most recent call last):
  File "p.py", line 8, in <module>
    print config['settings']['host']
AttributeError: ConfigParser instance has no attribute '__getitem__'
</code>```

p.py

```<code>  #!/usr/bin/env python
    import sys
    import ConfigParser

    if __name__ == '__main__':
        config = ConfigParser.ConfigParser()
        config.read(sys.argv[1])
        print config['settings']['host']
        print config['settings']['port']
</code>```

I don't want to use python3 if I can help it.

答:
ConfigParser does not support dict-like lookup. After parsing the file, you retrieve values using its get() method, which takes two arguments, the names of the section and option. So:

```<code>config = ConfigParser.ConfigParser()
config.read(sys.argv[1])
print config.get('settings', 'host')
print config.get('settings', 'port')
</code>```

More info here: https://docs.python.org/2/library/configparser.html#configparser-objects

Body:
example input.dat

[settings]
port = 1234
host = abc.com

How can I parse the file, and assign
1234 to agrv[1],
abc.com to argv[2] and so on

here is what i tried:

$python p.py input.dat
Traceback (most recent call last):
  File "p.py", line 8, in <module>
    print config['settings']['host']
AttributeError: ConfigParser instance has no attribute '__getitem__'

p.py

  #!/usr/bin/env python
    import sys
    import ConfigParser

    if __name__ == '__main__':
        config = ConfigParser.ConfigParser()
        config.read(sys.argv[1])
        print config['settings']['host']
        print config['settings']['port']

I don't want to use python3 if I can help it.

Body:
ConfigParser does not support dict-like lookup. After parsing the file, you retrieve values using its get() method, which takes two arguments, the names of the section and option. So:

config = ConfigParser.ConfigParser()
config.read(sys.argv[1])
print config.get('settings', 'host')
print config.get('settings', 'port')

More info here: https://docs.python.org/2/library/configparser.html#configparser-objects


问:
limit digits in var multiplication total
I have this:

var ivu = (total3);
document.getElementById("project_pay_total_field4").value = "$" +  total3 * 0.07  ;

The multiplication produces this:

$10.080000000000002

--Its too long and when done in regular calculator it only says 10.08; how can i fix that?

Here is the function:

```<code><script type = "text/javascript">

function project_pay_detail() {
var rate = document.getElementById("project_rate_field").value;
var time = document.getElementById("project_time_field").value;
var total1 = (rate * time);
document.getElementById("project_pay_total_field").value = "$" + total1 + ".00";

var rate = document.getElementById("project_rate_field2").value;
var time = document.getElementById("project_time_field2").value;
var total2 = (rate * time);
document.getElementById("project_pay_total_field2").value = "$" + total2 + ".00";

var total3 = (total1 + total2);
document.getElementById("project_pay_total_field3").value = "$" +  total3 + ".00" ;

var ivu = (total3);
document.getElementById("project_pay_total_field4").value = "$" +  total3 * 0.07  ;
}

</script>
</code>```

Heres is the form

```<div id="project_pay">Pay Rate<input type="text" name="project_rate_field" id="project_rate_field" class="field" value="" /></div>

<div id="project_pay">Total Hours<input type="text" name="project_time_field" id="project_time_field" class="field" value="" /></div>

<div id="project_pay">Project Total<input type="text" name="project_pay_total_field" id="project_pay_total_field" class="field" readonly="readonly" value="" /></div>
<input name="project_pay_details_calculate" type="button" value="Calculate1" onClick="project_pay_detail()" /></input>

<br>
<div id="project_pay">Pay Rate2<input type="text" name="project_rate_field2" id="project_rate_field2" class="field" value="" /></div>

<div id="project_pay">Total Hours2<input type="text" name="project_time_field2" id="project_time_field2" class="field" value="" /></div>

<div id="project_pay">Project Total2<input type="text" name="project_pay_total_field2" id="project_pay_total_field2" class="field" title="0.00" readonly="readonly" value="" /></div>

<input name="project_pay_details_refresh" type="button" value="Calculate2" onClick="project_pay_detail()" /></input>

<div id="project_pay">Total<input type="text" name="project_pay_total_field3" id="project_pay_total_field3" class="field" title="0.00" readonly="readonly" value="" /></div>
<div id="project_pay">Ivu<input type="text" name="project_pay_total_field4" id="project_pay_total_field4" class="field" title="0.00" readonly="readonly" value="" /></div>
</div>
</code>```

答:
```<code>
total3 = Math.round(total3 * 100) / 100;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have this:

var ivu = (total3);
document.getElementById("project_pay_total_field4").value = "$" +  total3 * 0.07  ;

The multiplication produces this:

$10.080000000000002

--Its too long and when done in regular calculator it only says 10.08; how can i fix that?

Here is the function:

Heres is the form

Pay Rate<input type="text" name="project_rate_field" id="project_rate_field" class="field" value="" />

Total Hours<input type="text" name="project_time_field" id="project_time_field" class="field" value="" />

Project Total<input type="text" name="project_pay_total_field" id="project_pay_total_field" class="field" readonly="readonly" value="" />

<input name="project_pay_details_calculate" type="button" value="Calculate1" onClick="project_pay_detail()" /></input>

Pay Rate2<input type="text" name="project_rate_field2" id="project_rate_field2" class="field" value="" />

Total Hours2<input type="text" name="project_time_field2" id="project_time_field2" class="field" value="" />

Project Total2<input type="text" name="project_pay_total_field2" id="project_pay_total_field2" class="field" title="0.00" readonly="readonly" value="" />

<input name="project_pay_details_refresh" type="button" value="Calculate2" onClick="project_pay_detail()" /></input>

Total<input type="text" name="project_pay_total_field3" id="project_pay_total_field3" class="field" title="0.00" readonly="readonly" value="" />

Ivu<input type="text" name="project_pay_total_field4" id="project_pay_total_field4" class="field" title="0.00" readonly="readonly" value="" />


问:
Getting error message with koa.js + axios
I am using koa.js for back-end and axios for http requests in front-end. I want to set up error message in koa.js and get the error message in front-end, but I get only default error message "Request failed with status code 500"

koa.js api call

```<code>module.exports.addIntr = async (ctx, next) => {
  const intrObj = ctx.request.body;
  try {
    intrObj = await compileOneInterest(intrObj);
    ctx.response.body = intrObj;
  } catch (err) {
    const statusCode = err.status || 500;
    ctx.throw(statusCode, err.message);
  }
};
</code>```

http request with axios

```<code>export function addInter(interObj) {
  return (dispatch) => {
    const url = `${API_ADDRESS}/ep/${10}/intr/`;

    axios({
      method: 'post',
      url,
      data: interObj,
      // params: {
      //   auth: AccessStore.getToken(),
      // },
    })
      .then((response) => {
        dispatch(addIntrSuccess(response.data));
      })
      .catch((error) => {
        dispatch(handlePoiError(error.message));
        console.log(error.response);
        console.log(error.request);
        console.log(error.message);
      });
  };
}
</code>```

答:
1) Main issue compileOneInterest function throws array instead Error object. On your screenshot err is [{message: 'Sorry, that page does not exist', code: 34}]. Your try block is running:

```<code>const statusCode = err.status || 500; // undefined || 500
ctx.throw(statusCode, err.message); // ctx.throw(500, undefined);
</code>```

So you see default message.

2) You use error-like object instead new Error('message') or CustomError('message', 34)

```<code>class CustomError extends Error {
  constructor(message, code) {
    super(message);
    this.code = code;
  }
}
</code>```

Best practise is throw Errors or custom Error object.

3) Your statusCode calculation use err.status instead err.code.

Body:
I am using koa.js for back-end and axios for http requests in front-end. I want to set up error message in koa.js and get the error message in front-end, but I get only default error message "Request failed with status code 500"

koa.js api call

module.exports.addIntr = async (ctx, next) => {
  const intrObj = ctx.request.body;
  try {
    intrObj = await compileOneInterest(intrObj);
    ctx.response.body = intrObj;
  } catch (err) {
    const statusCode = err.status || 500;
    ctx.throw(statusCode, err.message);
  }
};

http request with axios

export function addInter(interObj) {
  return (dispatch) => {
    const url = `${API_ADDRESS}/ep/${10}/intr/`;

    axios({
      method: 'post',
      url,
      data: interObj,
      // params: {
      //   auth: AccessStore.getToken(),
      // },
    })
      .then((response) => {
        dispatch(addIntrSuccess(response.data));
      })
      .catch((error) => {
        dispatch(handlePoiError(error.message));
        console.log(error.response);
        console.log(error.request);
        console.log(error.message);
      });
  };
}

Body:
1) Main issue compileOneInterest function throws array instead Error object. On your screenshot err is [{message: 'Sorry, that page does not exist', code: 34}]. Your try block is running:

const statusCode = err.status || 500; // undefined || 500
ctx.throw(statusCode, err.message); // ctx.throw(500, undefined);

So you see default message.

2) You use error-like object instead new Error('message') or CustomError('message', 34)

class CustomError extends Error {
  constructor(message, code) {
    super(message);
    this.code = code;
  }
}

Best practise is throw Errors or custom Error object.

3) Your statusCode calculation use err.status instead err.code.


问:
Angular 2 Unit Tests: Cannot find name 'describe'
I'm following this tutorial from angular.io

As they said, I've created hero.spec.ts file to create unit tests:

```<code>import { Hero } from './hero';
describe('Hero', () => {
  it('has name', () => {
    let hero: Hero = {id: 1, name: 'Super Cat'};
    expect(hero.name).toEqual('Super Cat');
  });
  it('has id', () => {
    let hero: Hero = {id: 1, name: 'Super Cat'};
    expect(hero.id).toEqual(1);
  });
});
</code>```

Unit Tests work like a charm. The problem is: I see some errors, which are mentioned in tutorial:

Our editor and the compiler may complain that they don’t know what it
and expect are because they lack the typing files that describe
Jasmine. We can ignore those annoying complaints for now as they are
harmless.

And they indeed ignored it. Even though those errors are harmless, it doesn't look good in my output console when I receive bunch of them.

Example of what I get:

Cannot find name 'describe'.

Cannot find name 'it'.

Cannot find name 'expect'.

What can I do to fix it?

答:
In my case, the solution was to remove the typeRoots in my tsconfig.json.

As you can read in the TypeScript doc

If typeRoots is specified, only packages under typeRoots will be included.

Body:
I'm following this tutorial from angular.io

As they said, I've created hero.spec.ts file to create unit tests:

import { Hero } from './hero';
describe('Hero', () => {
  it('has name', () => {
    let hero: Hero = {id: 1, name: 'Super Cat'};
    expect(hero.name).toEqual('Super Cat');
  });
  it('has id', () => {
    let hero: Hero = {id: 1, name: 'Super Cat'};
    expect(hero.id).toEqual(1);
  });
});

Unit Tests work like a charm. The problem is: I see some errors, which are mentioned in tutorial:

Our editor and the compiler may complain that they don’t know what it
and expect are because they lack the typing files that describe
Jasmine. We can ignore those annoying complaints for now as they are
harmless.

And they indeed ignored it. Even though those errors are harmless, it doesn't look good in my output console when I receive bunch of them.

Example of what I get:

Cannot find name 'describe'.

Cannot find name 'it'.

Cannot find name 'expect'.

What can I do to fix it?


问:
How to take screenshot with transparent windows WPF
I need your help please.

I want to take a screenshot of all my screens except for the app screen, the app screen background is transparent but I don't want my elemnts in the screen shot.

The current code that I am using is:

```<code>System.Drawing.Bitmap bm = new System.Drawing.Bitmap(Convert.ToInt32(System.Windows.SystemParameters.PrimaryScreenWidth), Convert.ToInt32(System.Windows.SystemParameters.PrimaryScreenHeight));
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bm);
g.CopyFromScreen(0, 0, 0, 0, bm.Size);
</code>```

I am writing in WPF.

Thatnk's for your help!

答: You're going to have to hide your window, take the screenshot, then show it again. </p>

Body:
I need your help please.

I want to take a screenshot of all my screens except for the app screen, the app screen background is transparent but I don't want my elemnts in the screen shot.

The current code that I am using is:

System.Drawing.Bitmap bm = new System.Drawing.Bitmap(Convert.ToInt32(System.Windows.SystemParameters.PrimaryScreenWidth), Convert.ToInt32(System.Windows.SystemParameters.PrimaryScreenHeight));
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bm);
g.CopyFromScreen(0, 0, 0, 0, bm.Size);

I am writing in WPF.

Thatnk's for your help!


问:
JavaScript: Invert color on all elements of a page
Note: I am keeping an up-to-date version of the bookmarklet in my question which works well and is based on Jacob's answer.  If you are looking for a bookmarklet to use, use that one. See leosok's fantastic answer if you just want something amazing that works on chrome.

I want to be able to invert the color of all the elements on a page with a JavaScript bookmarklet.  I know that to invert a color you subtract each of the RGB hex values from 255(xFF), but beyond that I am unsure of how to proceed.

How can I accomplish this?

Using jQuery is acceptable, and it only needs to work on Chrome, although if it worked in Firefox that'd be a plus.

This is excluding images - background, text and links colors should all be inverted.  Basically anything that gets its color from CSS.

UPDATE
Here is an updated bookmarklet that fixes the nested element issue and will work on a lot of different sites (including this one)

UPDATE2
Added some support for transparency, handling elements that have default background-color rgba(0, 0, 0, 0).  More sites should be working now with the updated one.

```<code>javascript: (function ($) {
    function load_script(src, callback) {
        var s = document.createElement('script');
        s.src = src;
        s.onload = callback;
        document.getElementsByTagName('head')[0].appendChild(s);
    }

    function invertElement() {
        var colorProperties = ['color', 'background-color'];
        var color = null;
        for (var prop in colorProperties) {
            prop = colorProperties[prop];
            if (!$(this).css(prop)) continue;
            if ($(this).data(prop) != $(this).css(prop)) continue;

            if (($(this).css(prop) === 'rgba(0, 0, 0, 0)') || ($(this).css(prop) === 'transparent')) {
                if ($(this).is('body')) {
                    $(this).css(prop, 'black');
                    continue;
                } else {
                    continue;
                }
            }
            color = new RGBColor($(this).css(prop));
            if (color.ok) {
                $(this).css(prop, 'rgb(' + (255 - color.r) + ',' + (255 - color.g) + ',' + (255 - color.b) + ')');
            }
            color = null;
        }
    }

    function setColorData() {
        var colorProperties = ['color', 'background-color'];
        for (var prop in colorProperties) {
            prop = colorProperties[prop];
            $(this).data(prop, $(this).css(prop));
        }
    }

    function invertColors() {
        $(document).live('DOMNodeInserted', function(e) {
            var $toInvert = $(e.target).find('*').andSelf();
            $toInvert.each(setColorData);
            $toInvert.each(invertElement);
        });
        $('*').each(setColorData);
        $('*').each(invertElement);
        $('iframe').each(function () {
            $(this).contents().find('*').each(setColorData);
            $(this).contents().find('*').each(invertElement);
        });
    }
    load_script('http://www.phpied.com/files/rgbcolor/rgbcolor.js', function () {
        if (!window.jQuery) load_script('https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', invertColors);
        else invertColors();
    });

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

Now works with most sites I've tried.  Background images can pose a problem, however.

答:
First things first, grab the awesome RGBColor class here.

Here goes:

jsFiddle example

```<code>//set up color properties to iterate through
var colorProperties = ['color', 'background-color'];

//iterate through every element in reverse order...
$("*").get().reverse().each(function() {
    var color = null;

    for (var prop in colorProperties) {
        prop = colorProperties[prop];

        //if we can't find this property or it's null, continue
        if (!$(this).css(prop)) continue;

        //create RGBColor object
        color = new RGBColor($(this).css(prop));

        if (color.ok) {
            //good to go, let's build up this RGB baby!
            //subtract each color component from 255
            $(this).css(prop, 'rgb(' + (255 - color.r) + ', ' + (255 - color.g) + ', ' + (255 - color.b) + ')');
        }
        color = null; //some cleanup
    }
});
</code>```

Screenshot:

EDIT: Here's a bookmarklet you can now copy-paste into your browser (http://jsfiddle.net/F7HqS/1/)

```<code>javascript:function load_script(src,callback){var s=document.createElement('script');s.src=src;s.onload=callback;document.getElementsByTagName('head')[0].appendChild(s);}function invertColors(){var colorProperties=['color','background-color'];$('*').each(function(){var color=null;for(var prop in colorProperties){prop=colorProperties[prop];if(!$(this).css(prop))continue;color=new RGBColor($(this).css(prop));if(color.ok){$(this).css(prop,'rgb('+(255-color.r)+','+(255-color.g)+','+(255-color.b)+')');}color=null;}});}load_script('http://www.phpied.com/files/rgbcolor/rgbcolor.js',function(){if(!window.jQuery)load_script('https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js',invertColors);else invertColors();});
</code>```

Body:
Note: I am keeping an up-to-date version of the bookmarklet in my question which works well and is based on Jacob's answer.  If you are looking for a bookmarklet to use, use that one. See leosok's fantastic answer if you just want something amazing that works on chrome.

I want to be able to invert the color of all the elements on a page with a JavaScript bookmarklet.  I know that to invert a color you subtract each of the RGB hex values from 255(xFF), but beyond that I am unsure of how to proceed.

How can I accomplish this?

Using jQuery is acceptable, and it only needs to work on Chrome, although if it worked in Firefox that'd be a plus.

This is excluding images - background, text and links colors should all be inverted.  Basically anything that gets its color from CSS.

UPDATE
Here is an updated bookmarklet that fixes the nested element issue and will work on a lot of different sites (including this one)

UPDATE2
Added some support for transparency, handling elements that have default background-color rgba(0, 0, 0, 0).  More sites should be working now with the updated one.

javascript: (function ($) {
    function load_script(src, callback) {
        var s = document.createElement('script');
        s.src = src;
        s.onload = callback;
        document.getElementsByTagName('head')[0].appendChild(s);
    }

    function invertElement() {
        var colorProperties = ['color', 'background-color'];
        var color = null;
        for (var prop in colorProperties) {
            prop = colorProperties[prop];
            if (!$(this).css(prop)) continue;
            if ($(this).data(prop) != $(this).css(prop)) continue;

            if (($(this).css(prop) === 'rgba(0, 0, 0, 0)') || ($(this).css(prop) === 'transparent')) {
                if ($(this).is('body')) {
                    $(this).css(prop, 'black');
                    continue;
                } else {
                    continue;
                }
            }
            color = new RGBColor($(this).css(prop));
            if (color.ok) {
                $(this).css(prop, 'rgb(' + (255 - color.r) + ',' + (255 - color.g) + ',' + (255 - color.b) + ')');
            }
            color = null;
        }
    }

    function setColorData() {
        var colorProperties = ['color', 'background-color'];
        for (var prop in colorProperties) {
            prop = colorProperties[prop];
            $(this).data(prop, $(this).css(prop));
        }
    }

    function invertColors() {
        $(document).live('DOMNodeInserted', function(e) {
            var $toInvert = $(e.target).find('*').andSelf();
            $toInvert.each(setColorData);
            $toInvert.each(invertElement);
        });
        $('*').each(setColorData);
        $('*').each(invertElement);
        $('iframe').each(function () {
            $(this).contents().find('*').each(setColorData);
            $(this).contents().find('*').each(invertElement);
        });
    }
    load_script('http://www.phpied.com/files/rgbcolor/rgbcolor.js', function () {
        if (!window.jQuery) load_script('https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', invertColors);
        else invertColors();
    });

})(jQuery);

Now works with most sites I've tried.  Background images can pose a problem, however.

Body:
First things first, grab the awesome RGBColor class here.

Here goes:

jsFiddle example

//set up color properties to iterate through
var colorProperties = ['color', 'background-color'];

//iterate through every element in reverse order...
$("*").get().reverse().each(function() {
    var color = null;

    for (var prop in colorProperties) {
        prop = colorProperties[prop];

        //if we can't find this property or it's null, continue
        if (!$(this).css(prop)) continue;

        //create RGBColor object
        color = new RGBColor($(this).css(prop));

        if (color.ok) {
            //good to go, let's build up this RGB baby!
            //subtract each color component from 255
            $(this).css(prop, 'rgb(' + (255 - color.r) + ', ' + (255 - color.g) + ', ' + (255 - color.b) + ')');
        }
        color = null; //some cleanup
    }
});

Screenshot:

EDIT: Here's a bookmarklet you can now copy-paste into your browser (http://jsfiddle.net/F7HqS/1/)

javascript:function load_script(src,callback){var s=document.createElement('script');s.src=src;s.onload=callback;document.getElementsByTagName('head')[0].appendChild(s);}function invertColors(){var colorProperties=['color','background-color'];$('*').each(function(){var color=null;for(var prop in colorProperties){prop=colorProperties[prop];if(!$(this).css(prop))continue;color=new RGBColor($(this).css(prop));if(color.ok){$(this).css(prop,'rgb('+(255-color.r)+','+(255-color.g)+','+(255-color.b)+')');}color=null;}});}load_script('http://www.phpied.com/files/rgbcolor/rgbcolor.js',function(){if(!window.jQuery)load_script('https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js',invertColors);else invertColors();});