问:
Custom UITableViewCell With Core Text
Using the help of @yaslam  I've created in Core Text an UILabel that show Japanese text in both horizontal and vertical way with Furigana using CTRubyAnnotation. Unfortunately I've a problem. I need to use this label inside a custom cell and I need that the cell dynamically resize the height of the cell based on text. but don't work. the cell doesn't expands

Can you help me?

Thank you very much

Here's code

```<code>import UIKit

protocol SimpleVerticalGlyphViewProtocol {
}

extension SimpleVerticalGlyphViewProtocol {

    func drawContext(_ attributed:NSMutableAttributedString, textDrawRect:CGRect, isVertical:Bool) {

        guard let context = UIGraphicsGetCurrentContext() else { return }

        var path:CGPath
        if isVertical {
            context.rotate(by: .pi / 2)
            context.scaleBy(x: 1.0, y: -1.0)
            path = CGPath(rect: CGRect(x: textDrawRect.origin.y, y: textDrawRect.origin.x, width: textDrawRect.height, height: textDrawRect.width), transform: nil)
        }
        else {
            context.textMatrix = CGAffineTransform.identity
            context.translateBy(x: 0, y: textDrawRect.height)
            context.scaleBy(x: 1.0, y: -1.0)
            path = CGPath(rect: textDrawRect, transform: nil)
        }

        let framesetter = CTFramesetterCreateWithAttributedString(attributed)
        let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, attributed.length), path, nil)

        CTFrameDraw(frame, context)
    }
}

class CustomLabel: UILabel, SimpleVerticalGlyphViewProtocol {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

    override func drawText(in rect: CGRect) {
        let attributed = NSMutableAttributedString(attributedString: self.attributedText!)
        let isVertical = false // if Vertical Glyph, true.
        attributed.addAttributes([NSAttributedStringKey.verticalGlyphForm: isVertical], range: NSMakeRange(0, attributed.length))
        attributed.addAttribute(NSAttributedStringKey.font, value: UIFont(name: "Hiragino Mincho ProN", size: 27)!, range: NSMakeRange(0, attributed.length))
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineHeightMultiple = 2
        paragraphStyle.lineSpacing = 4
        attributed.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, (attributed.length)))
        drawContext(attributed, textDrawRect: rect, isVertical: isVertical)
    }
}
</code>```

TableView class

```<code>import UIKit

class TableViewController: UITableViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)

    let label = cell.viewWithTag(10) as! CustomLabel
    let attributedText = Utility.sharedInstance.furigana(String: "｜銀行《ぎんこう》と｜郵便局《ゆうびんきょく》の｜間《あいだ》の｜道《みち》をまっすぐ｜行《い》くと、｜学校《がっこう》の｜前《まえ》に｜出《で》ます。")

    label.attributedText = attributedText

    return cell
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return UITableViewAutomaticDimension
    //return 70
}
</code>```

this is the result:

答:
Using CoreText, the height of the View is not automatically determined.
Calculate drawing height of CoreText and set it to height of UIView in Cell.
Make the following settings for UITableView in storyboard.

* Check Automatic of Row Height

* Check Automatic of Estimate

For programs, it is as follows.

```<code>tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = UITableViewAutomaticDimension
</code>```

Sample code to calculate drawing height of CoreText.
I don't know whether it is the optimum code for calculating height.
Sample code is pretty sloppy so please actually refactor it.

```<code>import UIKit

class CoreTextWithTableViewController: UITableViewController {

    var texts = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // tableView.rowHeight = UITableViewAutomaticDimension // or check Automatic of Row Height in storyboard
        // tableView.estimatedRowHeight = UITableViewAutomaticDimension // or check Automatic of Estimate in storyboard

        let text = "すでに｜世界《せかい》で最も｜先進的《せんしんてき》なモバイルオペレーティングシステムであるiOSに、iOS 11が新あらたな｜基準《きじゅん》を打ち立てます。iPhoneは今まで以上に優れたものになり、iPadはかつてないほどの｜能力《のうりょく》を手に入れます。さらにこれからはどちらのデバイスにも、ゲームやアプリケーションの｜拡張現実《かくちょうげんじつ》のための驚くような｜可能性《かのうせい》が広がります。iOS 11を｜搭載《とうさい》するiPhoneとiPadは、間違いなくこれまでで最もパワフルで、最もパーソナルで、最も賢いデバイスです。"
        let text2 = "すでに｜世界《せかい》で最も｜先進的《せんしんてき》なモバイルオペレーティングシステムであるiOSに、iOS 11が新あらたな｜基準《きじゅん》を打ち立てます。iPhoneは今まで以上に優れたものになり、iPadはかつてないほどの｜能力《のうりょく》を手に入れます。"

        for _ in 0...20 {
            texts.append(text)
            texts.append(text2)
        }

        NotificationCenter.default.addObserver(self, selector: #selector(changeDirection(notification:)), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)

    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return texts.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCellWithCoreText
        let text = texts[indexPath.row]
        cell.coreTextView.text = text
        let height = cell.coreTextView.heightOfCoreText()
        cell.heightOfCoreTextView.constant = height

        // Execute redraw
        cell.coreTextView.setNeedsDisplay()

        return cell
    }
}

extension CoreTextWithTableViewController {
    @objc func changeDirection(notification: NSNotification){
        tableView.reloadData()
    }
}

class CustomCellWithCoreText: UITableViewCell {
    @IBOutlet weak var coreTextView: CustomViewWithCoreText!
    @IBOutlet weak var heightOfCoreTextView: NSLayoutConstraint!
}

class CustomViewWithCoreText: UIView, SimpleVerticalGlyphViewProtocol {

    var text: String = ""
    lazy var attributed: NSMutableAttributedString = text.attributedStringWithRuby()
    var height = CGFloat()

    override func draw(_ rect: CGRect) {
        let textDrawRect = CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.size.width, height: height)
        drawContext(attributed, textDrawRect: textDrawRect, isVertical: false)
    }

    /// get Height of CoreText Draw Rect
    func heightOfCoreText() -> CGFloat {

        // initialize height and attributed
        height = CGFloat()
        attributed = text.attributedStringWithRuby()

        // MEMO: height = CGFloat.greatestFiniteMagnitude
        let textDrawRect = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.size.width, height: CGFloat.greatestFiniteMagnitude)
        let path = CGPath(rect: textDrawRect, transform: nil)
        let framesetter = CTFramesetterCreateWithAttributedString(attributed)
        let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, attributed.length), path, nil)
        let anyArray: [AnyObject] = CTFrameGetLines(frame) as [AnyObject]
        let lines = anyArray as! [CTLine]
        for line in lines {
            var ascent = CGFloat()
            var descent = CGFloat()
            var leading = CGFloat()
            CTLineGetTypographicBounds(line, &ascent, &descent, &leading)
            height += ceil(ascent + descent + leading)
        }
        return height
    }
}
</code>```

sample image

rotate tableView

It seems that the setting value of CTParagraphStyle is not reflected in the height obtained by CTLineGetTypographicBounds.
Instead, using CTFramesetterSuggestFrameSizeWithConstraints works.

```<code>func heightOfCoreText() -> CGFloat {
    // initialize height and attributed
    height = CGFloat()
    attributed = text.attributedStringWithRuby()

    // MEMO: height = CGFloat.greatestFiniteMagnitude
    let textDrawRect = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.size.width, height: CGFloat.greatestFiniteMagnitude)
    let framesetter = CTFramesetterCreateWithAttributedString(attributed)
    let frameSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, attributed.length), nil, textDrawRect.size, nil)
    height = frameSize.height
    return height
}
</code>```

minimumLineSpacing = 10.0

lineHeightMultiple = 1.5

Title: Custom UITableViewCell With Core Text

Body:
Using the help of @yaslam  I've created in Core Text an UILabel that show Japanese text in both horizontal and vertical way with Furigana using CTRubyAnnotation. Unfortunately I've a problem. I need to use this label inside a custom cell and I need that the cell dynamically resize the height of the cell based on text. but don't work. the cell doesn't expands

Can you help me?

Thank you very much

Here's code

import UIKit

protocol SimpleVerticalGlyphViewProtocol {
}

extension SimpleVerticalGlyphViewProtocol {

    func drawContext(_ attributed:NSMutableAttributedString, textDrawRect:CGRect, isVertical:Bool) {

        guard let context = UIGraphicsGetCurrentContext() else { return }

        var path:CGPath
        if isVertical {
            context.rotate(by: .pi / 2)
            context.scaleBy(x: 1.0, y: -1.0)
            path = CGPath(rect: CGRect(x: textDrawRect.origin.y, y: textDrawRect.origin.x, width: textDrawRect.height, height: textDrawRect.width), transform: nil)
        }
        else {
            context.textMatrix = CGAffineTransform.identity
            context.translateBy(x: 0, y: textDrawRect.height)
            context.scaleBy(x: 1.0, y: -1.0)
            path = CGPath(rect: textDrawRect, transform: nil)
        }

        let framesetter = CTFramesetterCreateWithAttributedString(attributed)
        let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, attributed.length), path, nil)

        CTFrameDraw(frame, context)
    }
}

class CustomLabel: UILabel, SimpleVerticalGlyphViewProtocol {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

    override func drawText(in rect: CGRect) {
        let attributed = NSMutableAttributedString(attributedString: self.attributedText!)
        let isVertical = false // if Vertical Glyph, true.
        attributed.addAttributes([NSAttributedStringKey.verticalGlyphForm: isVertical], range: NSMakeRange(0, attributed.length))
        attributed.addAttribute(NSAttributedStringKey.font, value: UIFont(name: "Hiragino Mincho ProN", size: 27)!, range: NSMakeRange(0, attributed.length))
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineHeightMultiple = 2
        paragraphStyle.lineSpacing = 4
        attributed.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, (attributed.length)))
        drawContext(attributed, textDrawRect: rect, isVertical: isVertical)
    }
}

TableView class

import UIKit

class TableViewController: UITableViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)

    let label = cell.viewWithTag(10) as! CustomLabel
    let attributedText = Utility.sharedInstance.furigana(String: "｜銀行《ぎんこう》と｜郵便局《ゆうびんきょく》の｜間《あいだ》の｜道《みち》をまっすぐ｜行《い》くと、｜学校《がっこう》の｜前《まえ》に｜出《で》ます。")

    label.attributedText = attributedText

    return cell
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return UITableViewAutomaticDimension
    //return 70
}

this is the result:

Body:
Using CoreText, the height of the View is not automatically determined.
Calculate drawing height of CoreText and set it to height of UIView in Cell.
Make the following settings for UITableView in storyboard.

* Check Automatic of Row Height

* Check Automatic of Estimate

For programs, it is as follows.

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = UITableViewAutomaticDimension

Sample code to calculate drawing height of CoreText.
I don't know whether it is the optimum code for calculating height.
Sample code is pretty sloppy so please actually refactor it.

import UIKit

class CoreTextWithTableViewController: UITableViewController {

    var texts = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // tableView.rowHeight = UITableViewAutomaticDimension // or check Automatic of Row Height in storyboard
        // tableView.estimatedRowHeight = UITableViewAutomaticDimension // or check Automatic of Estimate in storyboard

        let text = "すでに｜世界《せかい》で最も｜先進的《せんしんてき》なモバイルオペレーティングシステムであるiOSに、iOS 11が新あらたな｜基準《きじゅん》を打ち立てます。iPhoneは今まで以上に優れたものになり、iPadはかつてないほどの｜能力《のうりょく》を手に入れます。さらにこれからはどちらのデバイスにも、ゲームやアプリケーションの｜拡張現実《かくちょうげんじつ》のための驚くような｜可能性《かのうせい》が広がります。iOS 11を｜搭載《とうさい》するiPhoneとiPadは、間違いなくこれまでで最もパワフルで、最もパーソナルで、最も賢いデバイスです。"
        let text2 = "すでに｜世界《せかい》で最も｜先進的《せんしんてき》なモバイルオペレーティングシステムであるiOSに、iOS 11が新あらたな｜基準《きじゅん》を打ち立てます。iPhoneは今まで以上に優れたものになり、iPadはかつてないほどの｜能力《のうりょく》を手に入れます。"

        for _ in 0...20 {
            texts.append(text)
            texts.append(text2)
        }

        NotificationCenter.default.addObserver(self, selector: #selector(changeDirection(notification:)), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)

    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return texts.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCellWithCoreText
        let text = texts[indexPath.row]
        cell.coreTextView.text = text
        let height = cell.coreTextView.heightOfCoreText()
        cell.heightOfCoreTextView.constant = height

        // Execute redraw
        cell.coreTextView.setNeedsDisplay()

        return cell
    }
}

extension CoreTextWithTableViewController {
    @objc func changeDirection(notification: NSNotification){
        tableView.reloadData()
    }
}

class CustomCellWithCoreText: UITableViewCell {
    @IBOutlet weak var coreTextView: CustomViewWithCoreText!
    @IBOutlet weak var heightOfCoreTextView: NSLayoutConstraint!
}

class CustomViewWithCoreText: UIView, SimpleVerticalGlyphViewProtocol {

    var text: String = ""
    lazy var attributed: NSMutableAttributedString = text.attributedStringWithRuby()
    var height = CGFloat()

    override func draw(_ rect: CGRect) {
        let textDrawRect = CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.size.width, height: height)
        drawContext(attributed, textDrawRect: textDrawRect, isVertical: false)
    }

    /// get Height of CoreText Draw Rect
    func heightOfCoreText() -> CGFloat {

        // initialize height and attributed
        height = CGFloat()
        attributed = text.attributedStringWithRuby()

        // MEMO: height = CGFloat.greatestFiniteMagnitude
        let textDrawRect = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.size.width, height: CGFloat.greatestFiniteMagnitude)
        let path = CGPath(rect: textDrawRect, transform: nil)
        let framesetter = CTFramesetterCreateWithAttributedString(attributed)
        let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, attributed.length), path, nil)
        let anyArray: [AnyObject] = CTFrameGetLines(frame) as [AnyObject]
        let lines = anyArray as! [CTLine]
        for line in lines {
            var ascent = CGFloat()
            var descent = CGFloat()
            var leading = CGFloat()
            CTLineGetTypographicBounds(line, &ascent, &descent, &leading)
            height += ceil(ascent + descent + leading)
        }
        return height
    }
}

sample image

rotate tableView

It seems that the setting value of CTParagraphStyle is not reflected in the height obtained by CTLineGetTypographicBounds.
Instead, using CTFramesetterSuggestFrameSizeWithConstraints works.

func heightOfCoreText() -> CGFloat {
    // initialize height and attributed
    height = CGFloat()
    attributed = text.attributedStringWithRuby()

    // MEMO: height = CGFloat.greatestFiniteMagnitude
    let textDrawRect = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.size.width, height: CGFloat.greatestFiniteMagnitude)
    let framesetter = CTFramesetterCreateWithAttributedString(attributed)
    let frameSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, attributed.length), nil, textDrawRect.size, nil)
    height = frameSize.height
    return height
}

minimumLineSpacing = 10.0

lineHeightMultiple = 1.5


来源: stackexchange

问:
How do I remove a duplicate from a SELECT DISTINCT over multiple columns?
I have the following select statement:

```<code>SELECT DISTINCT a.month,
                a.date
           FROM a
       ORDER BY a.bar DESC NULLS LAST;
</code>```

month is a char, date is a date. I need to use the date column because that's the thing i'm ordering the results by. I'm getting this result:

```<code>foo | bar

 x---|---20-nov-15 00:00:00
 y---|---31-oct-15 00:00:00
 y---|---30-oct-15 00:00:00
 z---|---28-sept-15 00:00:00
</code>```

I am in need of a WHERE statement that would eliminate that duplicate Y from the result, I've been looking everywhere and couldn't find a solution

答:
You would seem to want GROUP BY:

```<code>SELECT a.month, MAX(a.date)
FROM a
GROUP BY a.month;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following select statement:

SELECT DISTINCT a.month,
                a.date
           FROM a
       ORDER BY a.bar DESC NULLS LAST;

month is a char, date is a date. I need to use the date column because that's the thing i'm ordering the results by. I'm getting this result:

foo | bar

 x---|---20-nov-15 00:00:00
 y---|---31-oct-15 00:00:00
 y---|---30-oct-15 00:00:00
 z---|---28-sept-15 00:00:00

I am in need of a WHERE statement that would eliminate that duplicate Y from the result, I've been looking everywhere and couldn't find a solution

Body:
You would seem to want GROUP BY:

SELECT a.month, MAX(a.date)
FROM a
GROUP BY a.month;


问:
Getting error when run react-native run-android
```<code>A problem occurred configuring project ':app'.
   > Could not resolve all dependencies for configuration ':app:_debugApk'.
     > A problem occurred configuring project ':react-native-fbsdk'.
       > Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugPublishCopy'.
         > Could not find com.android.support:appcompat-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified
         > Could not find com.android.support:appcompat-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.react:react-native:0.46.4
         > Could not find com.android.support:support-annotations:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-annotations/27.0.1/support-annotations-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-annotations/27.0.1/support-annotations-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/support-annotations/27.0.1/support-annotations-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-core:4.29.0
         > Could not find com.android.support:support-core-utils:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-core-utils/27.0.1/support-core-utils-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-core-utils/27.0.1/support-core-utils-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/support-core-utils/27.0.1/support-core-utils-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-core:4.29.0
         > Could not find com.android.support:appcompat-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
         > Could not find com.android.support:cardview-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/cardview-v7/27.0.1/cardview-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/cardview-v7/27.0.1/cardview-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/cardview-v7/27.0.1/cardview-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
         > Could not find com.android.support:customtabs:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/customtabs/27.0.1/customtabs-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/customtabs/27.0.1/customtabs-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/customtabs/27.0.1/customtabs-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
         > Could not find com.android.support:support-v4:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-v4/27.0.1/support-v4-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-v4/27.0.1/support-v4-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/support-v4/27.0.1/support-v4-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
</code>```

compileSdkVersion 25

buildToolsVersion "25.0.0"

targetSdkVersion 25

答:
I have the same issue since this morning and as far as I can see it is a problem with the react-native-fbsdk library and android support repository.

If you go into any of the subfolders on the path where your sdk is installed (in your case) "home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support" you will probably see the "26.0.0-alpha1" as the last folder even though google (https://dl.google.com/dl/android/maven2/index.html - collapse com.android.support) clearly suggests the last folder should be "27.0.2"!

I have tried downloading the latest android_m2repository from the acquired link:
https://dl.google.com/android/repository/android_m2repository_r47.zip
but it is also missing all the following folders:
26.0.0-beta1, 26.0.0-beta2, 26.0.0, 26.0.1, 26.0.2, 26.1.0, 27.0.0, 27.0.1, 27.0.2

I managed to remove the error by editing node_modules/react-native-fbsdk/android/build.gradle

compile('com.facebook.android:facebook-android-sdk:4.28.0')

but am still not able to build and I am sure this is not the propper way to go even if you are able to build!

Body:
A problem occurred configuring project ':app'.
   > Could not resolve all dependencies for configuration ':app:_debugApk'.
     > A problem occurred configuring project ':react-native-fbsdk'.
       > Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugPublishCopy'.
         > Could not find com.android.support:appcompat-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified
         > Could not find com.android.support:appcompat-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.react:react-native:0.46.4
         > Could not find com.android.support:support-annotations:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-annotations/27.0.1/support-annotations-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-annotations/27.0.1/support-annotations-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/support-annotations/27.0.1/support-annotations-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-core:4.29.0
         > Could not find com.android.support:support-core-utils:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-core-utils/27.0.1/support-core-utils-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-core-utils/27.0.1/support-core-utils-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/support-core-utils/27.0.1/support-core-utils-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-core:4.29.0
         > Could not find com.android.support:appcompat-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
         > Could not find com.android.support:cardview-v7:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/cardview-v7/27.0.1/cardview-v7-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/cardview-v7/27.0.1/cardview-v7-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/cardview-v7/27.0.1/cardview-v7-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
         > Could not find com.android.support:customtabs:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/customtabs/27.0.1/customtabs-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/customtabs/27.0.1/customtabs-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/customtabs/27.0.1/customtabs-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
         > Could not find com.android.support:support-v4:27.0.1.
           Searched in the following locations:
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-v4/27.0.1/support-v4-27.0.1.pom
             file:/home/ubuntu/Android/Sdk/extras/android/m2repository/com/android/support/support-v4/27.0.1/support-v4-27.0.1.jar
             file:/home/ubuntu/git/mstore-pro/android/sdk-manager/com/android/support/support-v4/27.0.1/support-v4-27.0.1.jar
           Required by:
             beostore:react-native-fbsdk:unspecified > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0

compileSdkVersion 25

buildToolsVersion "25.0.0"

targetSdkVersion 25


问:
Cassandra Sync and Async, which one is faster to get back the result set?
I'm making some tests on Datastax Cassandra. The case is described as below:

Prerequisite: 1 Cassandra Server, a table with a complex primary key (username, id), the Selection query like this: "select * from table_name where username='abc'; and the result set is the set of 16 rows.

Case 1: execute the query on DevCenter and it takes 1676 ms to finish

Case 2: execute synchronously the query on Java Driver by using "session.execute(statement)" and it takes 441 ms to finish

Case 3: execute the query on Java Driver by using the asynchronous solution as introduced in https://docs.datastax.com/en/developer/java-driver/3.3/manual/async/ and it takes 1121 ms to finish

Is there someone tell me circumstances where the sync/async is more faster?

答: I would say the sync/async approach is less about being faster or slower, but more about the resource utilization on your client side. Async - no long blocking for long running queries. Sync - blocking, but can be fine for fast queries. Async approach might require another programming techniques to use (Futures, callbacks..), in some programming languages it is natively better supported than in others.</p>

ContentLicense: CC BY-SA 4.0


问:
Get the indexpath from custom button in accessoryView of a UITableViewCell
I have a UISearchController with a separate UITableViewController as its searchResultsController.

```<code>class SearchResultsViewController: UITableViewController {

    var fruits: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.tableFooterView = UIView(frame: .zero)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    }

    @objc func addFruit(_ sender: UIButton) {
        let point = tableView.convert(sender.bounds.origin, to: sender)
        let indexPath = tableView.indexPathForRow(at: point)
        print(indexPath?.row)
    }

    // MARK: - Table view data source
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return fruits.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = fruits[indexPath.row]
        cell.selectionStyle = .none

        let addButton = UIButton(type: .custom)
        addButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        addButton.setImage(UIImage(named: "add"), for: .normal)
        addButton.contentMode = .scaleAspectFit
        addButton.addTarget(self, action: #selector(addFruit(_:)), for: .touchUpInside)
        addButton.sizeToFit()
        cell.accessoryView =  addButton

        return cell
    }

}
</code>```

I need to show a custom button in cells that search results are shown. So I added a UIButton as the cells' accessoryView. And it looks and works fine.

Now I need to get the cell's indexPath when the user taps on this button.

I'm trying to get it like shown below.

```<code>@objc func addFruit(_ sender: UIButton) {
    let point = tableView.convert(sender.bounds.origin, to: sender)
    let indexPath = tableView.indexPathForRow(at: point)
}
</code>```

But it keeps returning nil for every cell.

Is there any other way to get the indexPath from a custom button tap? I added a demo project here as well.

答:
```<code> let buttonPosition =  sender.convert(CGPoint.zero, to: self.tableView)
 let currentIndexPath = self.tableView.indexPathForRow(at: buttonPosition)
</code>```

Try this it worked for me :)

Body:
I have a UISearchController with a separate UITableViewController as its searchResultsController.

class SearchResultsViewController: UITableViewController {

    var fruits: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.tableFooterView = UIView(frame: .zero)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    }

    @objc func addFruit(_ sender: UIButton) {
        let point = tableView.convert(sender.bounds.origin, to: sender)
        let indexPath = tableView.indexPathForRow(at: point)
        print(indexPath?.row)
    }

    // MARK: - Table view data source
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return fruits.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = fruits[indexPath.row]
        cell.selectionStyle = .none

        let addButton = UIButton(type: .custom)
        addButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        addButton.setImage(UIImage(named: "add"), for: .normal)
        addButton.contentMode = .scaleAspectFit
        addButton.addTarget(self, action: #selector(addFruit(_:)), for: .touchUpInside)
        addButton.sizeToFit()
        cell.accessoryView =  addButton

        return cell
    }

}

I need to show a custom button in cells that search results are shown. So I added a UIButton as the cells' accessoryView. And it looks and works fine.

Now I need to get the cell's indexPath when the user taps on this button.

I'm trying to get it like shown below.

@objc func addFruit(_ sender: UIButton) {
    let point = tableView.convert(sender.bounds.origin, to: sender)
    let indexPath = tableView.indexPathForRow(at: point)
}

But it keeps returning nil for every cell.

Is there any other way to get the indexPath from a custom button tap? I added a demo project here as well.

Body:
 let buttonPosition =  sender.convert(CGPoint.zero, to: self.tableView)
 let currentIndexPath = self.tableView.indexPathForRow(at: buttonPosition)

Try this it worked for me :)


问:
Estimating the brightness of a YUV frame
I want to estimate the rough brightness of a frame that comes in as a camera preview frame, as below. I want the method to be quite fast.

```<code>public void onPreviewFrame(final byte[] bytes, Camera camera) {
  // calculate brightness
}
</code>```

Is there a way to do it without converting to RGB? It also would be very good if there is a fast way to determine blurriness without using OpenCV.

答:
Ok, I figured it out myself:</p>

```<code>                            long sumY = 0;
                            for (int j = 0, yp = 0; j < previewHeight; j++) {
                                for (int i = 0; i < previewWidth; i++, yp++) {
                                    int y = (0xff & ((int) bytes[yp]));
                                    if (y < 0) {
                                        y = 0;
                                    }

                                    sumY += y;
                                }
                            }
                            int bp = (int)sumY/(previewWidth * previewHeight);
</code>```

Body:
I want to estimate the rough brightness of a frame that comes in as a camera preview frame, as below. I want the method to be quite fast.

public void onPreviewFrame(final byte[] bytes, Camera camera) {
  // calculate brightness
}

Is there a way to do it without converting to RGB? It also would be very good if there is a fast way to determine blurriness without using OpenCV.

Body:
Ok, I figured it out myself:

                            long sumY = 0;
                            for (int j = 0, yp = 0; j < previewHeight; j++) {
                                for (int i = 0; i < previewWidth; i++, yp++) {
                                    int y = (0xff & ((int) bytes[yp]));
                                    if (y < 0) {
                                        y = 0;
                                    }

                                    sumY += y;
                                }
                            }
                            int bp = (int)sumY/(previewWidth * previewHeight);


问:
How to select WooCommerce products by post_meta and order them
I'm using the following code to select products with the following post_meta keys: _product_new, _product_almost_new and _product_old.

My code:

```<code>add_action( 'woocommerce_product_query', 'custom_vtp_shop_order' );

function custom_vtp_shop_order($q){
    if ( ! $q->is_main_query() ) return;
    if (! is_admin() && (is_shop() || is_archive) ) {

        $q->set( 'tax_query', array(array(
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => array( 'Sold', 'Service' ),
            'operator' => 'NOT IN'
        )));

        $q->set('meta_query', array(array(
            'relation' => 'OR',
                'product_new' => array(
                    'key' => '_product_new',
                    'value' => '1',
                ),
                'product_almost_new' => array(
                    'key' => '_product_almost_new',
                    'value' => '1',
                ),
                'product_old' => array(
                    'key' => '_product_old',
                    'value' => '1',
                )
            )));

        /*THIS HAS NO EFFECT*/
        $q->set('orderby', array(array(
                'product_new' => 'DESC',
                'product_old' => 'DESC',
                'product_almost_new' => 'DESC',
            )
        ));

    }

}
</code>```

I want the products to then be displayed in the following order:

product_new

product_old

product_almost_new

I am using $q->set('orderby', array(......) but this is having no effect. My products are ALWAYS being ordered product_old, product_almost_new, product_new.

Any ideas why my 'orderby' is not working? Any help is appreciated.

答:
You did all right except one thing. You have used array in array in orderby which is not correct.
Here is how it should look like:</p>

```<code>$q->set('orderby', array(
                'product_new' => 'DESC',
                'product_almost_new' => 'DESC',
                'product_old' => 'DESC',
            )
        );
</code>```

Body:
I'm using the following code to select products with the following post_meta keys: _product_new, _product_almost_new and _product_old.

My code:

add_action( 'woocommerce_product_query', 'custom_vtp_shop_order' );

function custom_vtp_shop_order($q){
    if ( ! $q->is_main_query() ) return;
    if (! is_admin() && (is_shop() || is_archive) ) {

        $q->set( 'tax_query', array(array(
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => array( 'Sold', 'Service' ),
            'operator' => 'NOT IN'
        )));

        $q->set('meta_query', array(array(
            'relation' => 'OR',
                'product_new' => array(
                    'key' => '_product_new',
                    'value' => '1',
                ),
                'product_almost_new' => array(
                    'key' => '_product_almost_new',
                    'value' => '1',
                ),
                'product_old' => array(
                    'key' => '_product_old',
                    'value' => '1',
                )
            )));

        /*THIS HAS NO EFFECT*/
        $q->set('orderby', array(array(
                'product_new' => 'DESC',
                'product_old' => 'DESC',
                'product_almost_new' => 'DESC',
            )
        ));

    }

}

I want the products to then be displayed in the following order:

product_new

product_old

product_almost_new

I am using $q->set('orderby', array(......) but this is having no effect. My products are ALWAYS being ordered product_old, product_almost_new, product_new.

Any ideas why my 'orderby' is not working? Any help is appreciated.

Body:
You did all right except one thing. You have used array in array in orderby which is not correct.
Here is how it should look like:

$q->set('orderby', array(
                'product_new' => 'DESC',
                'product_almost_new' => 'DESC',
                'product_old' => 'DESC',
            )
        );


问:
Count successful HTTP Requests in "bzm - Parallel Controller"
How to count successful HTTP Requests in "bzm - Parallel Controller". Have tried __counter() function in "BeanShell PostProcessor" with no luck.</p>

答:
You can do this as follows:

Tick Generate parent sample in the "bzm - Parallel Controller"

Add JSR223 Sampler after the "bzm - Parallel Controller"

Put the following code into "Script" area

```<code>def successful = 0
ctx.getPreviousResult().getSubResults().each { subResult ->
    if (subResult.isSuccessful()) {
        successful++
    }
}
vars.put('successful', successful as String)
</code>```

where:

ctx - is a shorthand for JMeterContext

vars - is an instance of JMeterVariables

You will be able to refer the number of successful samplers as ${successful} or ${__V(successful)} where required.

See Apache Groovy - Why and How You Should Use It for more information on Groovy scripting in JMeter tests.

Body:
You can do this as follows:

Tick Generate parent sample in the "bzm - Parallel Controller"

Add JSR223 Sampler after the "bzm - Parallel Controller"

Put the following code into "Script" area

def successful = 0
ctx.getPreviousResult().getSubResults().each { subResult ->
    if (subResult.isSuccessful()) {
        successful++
    }
}
vars.put('successful', successful as String)

where:

ctx - is a shorthand for JMeterContext

vars - is an instance of JMeterVariables

You will be able to refer the number of successful samplers as ${successful} or ${__V(successful)} where required.

See Apache Groovy - Why and How You Should Use It for more information on Groovy scripting in JMeter tests.


问:
How to hide table rows when the value is null
I am creating a project in eclipse where I want to display values input into a form in a table. I want the table to only display the rows which have values, but cannot work out how to do this. So far I have just added multiple rows and am using display:none in order to not display them, but I do not cannot think of a way to get the th:text="${name1}" to display.

Here is an example of the way I am doing it so far:

```<code><table id="table">
    <tr id="tableRow">
      <th class="tableHeader">Name</th>
      <th class="tableHeader">Description</th>
    </tr>
    <tr id="tableRow" style="display:none">
      <td class="tableCell" th:text="${name1}"></td>
      <td class="tableCell" th:text="${description1}"></td>
    </tr>
    <tr id="tableRow" style="display:none">
      <td class="tableCell" th:text="${name2}"></td>
      <td class="tableCell" th:text="${description2}"></td>
    </tr>
    <tr id="tableRow" style="display:none">
      <td class="tableCell" th:text="${name3}"></td>
      <td class="tableCell" th:text="${description3}"></td>
    </tr>
</table>
</code>```

I am relatively new to coding and so any help would be appreciated.

答:
you need to test values before consuming it

            Name
            Description

```

Body:
I am creating a project in eclipse where I want to display values input into a form in a table. I want the table to only display the rows which have values, but cannot work out how to do this. So far I have just added multiple rows and am using display:none in order to not display them, but I do not cannot think of a way to get the th:text="${name1}" to display.

Here is an example of the way I am doing it so far:

      Name
      Description

I am relatively new to coding and so any help would be appreciated.

Body:
you need to test values before consuming it

<table id="table">
        <tr id="tableRow">
            <th class="tableHeader">Name</th>
            <th class="tableHeader">Description</th>
        </tr>
        <tr id="tableRow" th:if="${name1 != null or description1 != null}">
            <td class="tableCell" th:text="${name1}"></td>
            <td class="tableCell" th:text="${description1}"></td>
        </tr>
        <tr id="tableRow" th:if="${name2 != null or description2 != null}">
            <td class="tableCell" th:text="${name2}"></td>
            <td class="tableCell" th:text="${description2}"></td>
        </tr>
        <tr id="tableRow" th:if="${name3 != null or description3 != null}">
            <td class="tableCell" th:text="${name3}"></td>
            <td class="tableCell" th:text="${description3}"></td>
        </tr>
</table>


问:
LibGdx -simple game with different type of drops
Hope everyone knows the basic Libgdx game in this link:

https://github.com/libgdx/libgdx/wiki/A-simple-game

In the simple game,rain drops are falling randomly from the top,that is of one type.
In my case,I want to implement the same thing,as drops.The difference is that,there are four type of drops.When it collides with another object,four should show four different characteristics.

In short,I created a Drop class with its object and array and can spawn drop objects too.

```<code>   Drop drop=new Drop();
   private Array<Drop> drops=new Array<Drop>();
</code>```

But what if I want to define individual attributes for drops in this case?
I want the drop object to be categorized of four types. For example have different colors yellow,red,green and blue.Also four kind of drops should fall randomly from top.

In which way,and how I should implement such a concept?

It would be very helpful if I get some idea on this.

Edit:

I have an abstract class Drop and .I am not passing texture and rectangle in the constructor.Because graphics are not available for the project right now.I am planning to assign it in a later stage.As of now,everything I am doing it with shaperenderer.

I have create() method for three distinct colored drops in my objectFactory class where I used to create all objects:

```<code> public YellowDrop createYellow(){
    YellowDrop yellow = new YellowDrop();
    yellow.setSize(100f,100f);
    yellow.setPosition(MathUtils.random(0, 800),1280);
    return yellow;
}
public RedDrop createRed(){
    RedDrop red = new RedDrop();
    red.setSize(100f,100f);
    red.setPosition(MathUtils.random(0, 800),1280);
    return red;
}
public GreenDrop createGreen(){
    GreenDrop green = new GreenDrop();
    green.setSize(100f,100f);
    green.setPosition(MathUtils.random(0, 800),1280);
    return green;
}
</code>```

And I written createRandomDrop() code like this(For me,your code is confusing though.How can I use that colon symbol there in a method?I never used it.)

private Block createRandomDrop() {
     switch (MathUtils.random(0, 3)) {
     case 0 :
         System.out.println("000000");
         return objectFactory.createYellow();
     case 1 :
         return objectFactory.createGreen();

```<code> case 2 : return objectFactory.createRed();
 default:
     return objectFactory.createGreen();
</code>```

}
}
  Here I am confused about how to return the individual drop object.
  Even though I have written the call like this:

```<code>if(TimeUtils.nanoTime() - lastDropTime > 1000000000) {
  drops.add(createRandomDrop());
  }

private void updateBlocks(float delta) {

   Iterator<Drop> iter = drops.iterator();
      while(iter.hasNext()) {
         Drop b = iter.next();
        b.update(delta);//moving drop from top to bottom in update()
         if(b.getY()<0) iter.remove();
      }
    //  System.out.println(drops.size);
</code>```

}

At last I am drawing the shaperenderer for all array elements:

```<code>  for (Drop b : drops) {
    b.drawDebug(shapeRenderer);}
</code>```

This drawdebug() is in Drop class and I am overriding it

```<code>  public void drawDebug(ShapeRenderer shapeRenderer) {
    shapeRenderer.setColor(Color.YELLOW);
    shapeRenderer.rect(collisionRectangle.x, collisionRectangle.y,
   collisionRectangle.width,
            collisionRectangle.height);
 }
</code>```

problem is that,too many drops are getting created and overlapping.May be the switch case creates the problem.

答:
What is your problem? This is simple.

Create 4 children of Drop class. yellowDrop, greenDrop, etc... And create collide() method in Drop class which will implement same functionality for all children.

Something like this:

```<code>abstract class Drop {

     abstract Texture tex;
     abstract Rectangle rect;

     Drop(Texture tex, Rectangle rect){
         // initialize values here
     }

     void showCollideAnimation(){  // example. here you can create your own void to show different characteristics.
           tex.blabla()
     }

     void collide(){
           showCollideAnimation();
     }

     // also draw, update methods etc... Hope you got that they should do functionality same for all children
}
</code>```

And then create child that will override showCollideAnimation method.

```<code>class GreenDrop extends Drop {

        @override
        void showCollideAnimation(){
             ....     // here you pass effect for Green child
        }
}
</code>```

To chose random child you can just create function that returns Drop

```<code>Drop createRandomDrop(Rectangle rect): Drop {

            switch (MathUtils.random(0, 3)) {
                case 0 : return new YellowDrop(Texture("pathToYellowTexture"), rect) break;
                case 1 : return new GreenDrop(Texture("pathToGreenTexture"), rect) break;
                // etc.
            }

}
</code>```

Now you can fill ArrayList of Drops.

```<code>private ArrayList<Drop> drops = new ArrayList<Drop>();

in render method:

if(TimeUtils.nanoTime() - lastDropTime > 1000000000) {
      drops.add(createRandomDrop(Texture(""), Rectangle()));  // specify texture and rectangle yourself
}
</code>```

Body:
Hope everyone knows the basic Libgdx game in this link:

https://github.com/libgdx/libgdx/wiki/A-simple-game

In the simple game,rain drops are falling randomly from the top,that is of one type.
In my case,I want to implement the same thing,as drops.The difference is that,there are four type of drops.When it collides with another object,four should show four different characteristics.

In short,I created a Drop class with its object and array and can spawn drop objects too.

   Drop drop=new Drop();
   private Array<Drop> drops=new Array<Drop>();

But what if I want to define individual attributes for drops in this case?
I want the drop object to be categorized of four types. For example have different colors yellow,red,green and blue.Also four kind of drops should fall randomly from top.

In which way,and how I should implement such a concept?

It would be very helpful if I get some idea on this.

Edit:

I have an abstract class Drop and .I am not passing texture and rectangle in the constructor.Because graphics are not available for the project right now.I am planning to assign it in a later stage.As of now,everything I am doing it with shaperenderer.

I have create() method for three distinct colored drops in my objectFactory class where I used to create all objects:

 public YellowDrop createYellow(){
    YellowDrop yellow = new YellowDrop();
    yellow.setSize(100f,100f);
    yellow.setPosition(MathUtils.random(0, 800),1280);
    return yellow;
}
public RedDrop createRed(){
    RedDrop red = new RedDrop();
    red.setSize(100f,100f);
    red.setPosition(MathUtils.random(0, 800),1280);
    return red;
}
public GreenDrop createGreen(){
    GreenDrop green = new GreenDrop();
    green.setSize(100f,100f);
    green.setPosition(MathUtils.random(0, 800),1280);
    return green;
}

And I written createRandomDrop() code like this(For me,your code is confusing though.How can I use that colon symbol there in a method?I never used it.)

private Block createRandomDrop() {
     switch (MathUtils.random(0, 3)) {
     case 0 :
         System.out.println("000000");
         return objectFactory.createYellow();
     case 1 :
         return objectFactory.createGreen();

 case 2 : return objectFactory.createRed();
 default:
     return objectFactory.createGreen();

}
}
  Here I am confused about how to return the individual drop object.
  Even though I have written the call like this:

if(TimeUtils.nanoTime() - lastDropTime > 1000000000) {
  drops.add(createRandomDrop());
  }

private void updateBlocks(float delta) {

   Iterator<Drop> iter = drops.iterator();
      while(iter.hasNext()) {
         Drop b = iter.next();
        b.update(delta);//moving drop from top to bottom in update()
         if(b.getY()<0) iter.remove();
      }
    //  System.out.println(drops.size);

}

At last I am drawing the shaperenderer for all array elements:

  for (Drop b : drops) {
    b.drawDebug(shapeRenderer);}

This drawdebug() is in Drop class and I am overriding it

  public void drawDebug(ShapeRenderer shapeRenderer) {
    shapeRenderer.setColor(Color.YELLOW);
    shapeRenderer.rect(collisionRectangle.x, collisionRectangle.y,
   collisionRectangle.width,
            collisionRectangle.height);
 }

problem is that,too many drops are getting created and overlapping.May be the switch case creates the problem.

Body:
What is your problem? This is simple.

Create 4 children of Drop class. yellowDrop, greenDrop, etc... And create collide() method in Drop class which will implement same functionality for all children.

Something like this:

abstract class Drop {

     abstract Texture tex;
     abstract Rectangle rect;

     Drop(Texture tex, Rectangle rect){
         // initialize values here
     }

     void showCollideAnimation(){  // example. here you can create your own void to show different characteristics.
           tex.blabla()
     }

     void collide(){
           showCollideAnimation();
     }

     // also draw, update methods etc... Hope you got that they should do functionality same for all children
}

And then create child that will override showCollideAnimation method.

class GreenDrop extends Drop {

        @override
        void showCollideAnimation(){
             ....     // here you pass effect for Green child
        }
}

To chose random child you can just create function that returns Drop

Drop createRandomDrop(Rectangle rect): Drop {

            switch (MathUtils.random(0, 3)) {
                case 0 : return new YellowDrop(Texture("pathToYellowTexture"), rect) break;
                case 1 : return new GreenDrop(Texture("pathToGreenTexture"), rect) break;
                // etc.
            }

}

Now you can fill ArrayList of Drops.

private ArrayList<Drop> drops = new ArrayList<Drop>();

in render method:

if(TimeUtils.nanoTime() - lastDropTime > 1000000000) {
      drops.add(createRandomDrop(Texture(""), Rectangle()));  // specify texture and rectangle yourself
}


问:
displaying image reusable content with pieces
I wrote a Widget – i basically created the people Widget ( Adding Editable Content to Pages - Tutorial) and modified it to my needs.

The structure of the widget

On my show.html the heroimage is missing and everywhere else the image is displayed properly.

Does anyone have a clou, what i am missing?

app.js
project index.js

show.html

答:
The code screenshots give an incomplete picture but a few things to double check or try:

Is heroimage actually a part of your project's schema?

In show.html are you tucking data.piece into its own variable? I would think the line would be

{% set image = apos.images.first(data.piece.heroimage) %}


问:
Easyautocomplete + sweetalert2 = disappear scrollbar in IE 11/Edge
I've got the following functionality. When I click the button the sweetalert2 popup opens with the easyautocomplete list. The items are fetched by ajax while typing. When there are too much items and they don't fit in the box the scrollbar appears.

I wanted to use original easyatocomplete plugin from -> easyautocomplete.com <-

but it doesn't have scrollbar functionality.So I looked around and found modified version here:

http://gnnc.com.br/samples/easy-autocomplete/easy-autocomplete.php

The problem is when I click the scrollbar to scroll positions the scrollbar disappers and the list closes. The problem occurs only in IE (tested 11 and Edge), in FF and Chrome is OK.

BUT!! As we see in the demo on modified autocomplete page, the scrollbar works fine and doesn't dissappear even in IE after trying to scroll it with mouse. It seems like it happens only when used inside sweetalert2 popup.

Here is the code I wrote:

```<code>    function addEmployeeByName() {
        swal({
            title: 'Add employee by name',
            html: 'Select employee<input type="text" name="empList" id="empList" class="form-control"><input type="hidden" id="rcp">',
            type: '',
            confirmButtonText: 'Add employee',
            confirmButtonColor: '#00A65A',

            onOpen: function () {

                                    window.setTimeout(function () {
                                            $("input#empList").focus();
                                    }, 0);

                                    var options = {
                                        url: function(phrase) {
                                            return '/ajax/employees/get_handworkers_by_name/';
                                        },

                                        minCharNumber: 3,
                                        ajaxSettings: {
                                                        dataType: "json",
                                                        method: "POST",
                                                        data: { dataType: "json" }
                                                      },

                                        preparePostData: function(data)
                                                         { data.employeename = $("#empList").val();
                                                           return data;
                                                         },

                                        getValue: function(element) {
                                                        return '['+element.rcp+'] '+element.nazwisko+' '+element.imie;
                                                  },

                                        requestDelay: 400,

                                        list: {
                                            maxNumberOfElements: 1000,
                                            onChooseEvent: function() {
                                                sel_prac_rcp = parseInt($("#empList").getSelectedItemData().rcp);
                                                sel_prac_id = parseInt($("#empList").getSelectedItemData().id);
                                                $("#empList").blur();

                                              }
                                        }

                                    };

                                    $("#empList").easyAutocomplete(options);

            }, //end onOpen

        }).then(function(val){

        console.log(val);
    });

}
</code>```

I looked into modified easyautocomplete plugin and found this (around line 1240):

```<code>           $container.on("mousedown", function(e) {

                    if (!$wrap.is(e.target) // if the target of the click isn't the container...
                        && ($wrap.has(e.target).length === 0) // ... nor a descendant of the container
                        && (e.target !== $('html').get(0))) // nor the scrollbar
                    {
                        //console.log('slog0');
                        //console.log('slog:'+toolbarClose());
                    }

                    //console.log('slog2');
                    e.stopImmediatePropagation();
                    e.preventDefault();
                    e.stopPropagation();

                    //if (jQuery.browser.msie) {
                        e.originalEvent.keyCode = 0;
                        e.originalEvent.cancelBubble = true;
                        e.originalEvent.returnValue = false;
                    //}
                });
</code>```

However playing with this fragment didn't work.

dissapearing scrollbar issue - animated gif

答:
I also bumped into the same problem in selectize plugin:

https://selectize.github.io/selectize.js/

When clicked on scroll bar in IE, it disappears. The solution is similar. In method setup around line 1261 we have:

```<code>$dropdown_content = $('<div>').addClass(settings.dropdownContentClass).appendTo($dropdown);
</code>```

I changed it into:

```<code>$dropdown_content = $('<div onmousedown="return false" unselectable="on">').addClass(settings.dropdownContentClass).appendTo($dropdown);
</code>```

what solved the problem (hopefully not breking anything else :)

Body:
I've got the following functionality. When I click the button the sweetalert2 popup opens with the easyautocomplete list. The items are fetched by ajax while typing. When there are too much items and they don't fit in the box the scrollbar appears.

I wanted to use original easyatocomplete plugin from -> easyautocomplete.com <-

but it doesn't have scrollbar functionality.So I looked around and found modified version here:

http://gnnc.com.br/samples/easy-autocomplete/easy-autocomplete.php

The problem is when I click the scrollbar to scroll positions the scrollbar disappers and the list closes. The problem occurs only in IE (tested 11 and Edge), in FF and Chrome is OK.

BUT!! As we see in the demo on modified autocomplete page, the scrollbar works fine and doesn't dissappear even in IE after trying to scroll it with mouse. It seems like it happens only when used inside sweetalert2 popup.

Here is the code I wrote:

    function addEmployeeByName() {
        swal({
            title: 'Add employee by name',
            html: 'Select employee<input type="text" name="empList" id="empList" class="form-control"><input type="hidden" id="rcp">',
            type: '',
            confirmButtonText: 'Add employee',
            confirmButtonColor: '#00A65A',

            onOpen: function () {

                                    window.setTimeout(function () {
                                            $("input#empList").focus();
                                    }, 0);

                                    var options = {
                                        url: function(phrase) {
                                            return '/ajax/employees/get_handworkers_by_name/';
                                        },

                                        minCharNumber: 3,
                                        ajaxSettings: {
                                                        dataType: "json",
                                                        method: "POST",
                                                        data: { dataType: "json" }
                                                      },

                                        preparePostData: function(data)
                                                         { data.employeename = $("#empList").val();
                                                           return data;
                                                         },

                                        getValue: function(element) {
                                                        return '['+element.rcp+'] '+element.nazwisko+' '+element.imie;
                                                  },

                                        requestDelay: 400,

                                        list: {
                                            maxNumberOfElements: 1000,
                                            onChooseEvent: function() {
                                                sel_prac_rcp = parseInt($("#empList").getSelectedItemData().rcp);
                                                sel_prac_id = parseInt($("#empList").getSelectedItemData().id);
                                                $("#empList").blur();

                                              }
                                        }

                                    };

                                    $("#empList").easyAutocomplete(options);

            }, //end onOpen

        }).then(function(val){

        console.log(val);
    });

}

I looked into modified easyautocomplete plugin and found this (around line 1240):

           $container.on("mousedown", function(e) {

                    if (!$wrap.is(e.target) // if the target of the click isn't the container...
                        && ($wrap.has(e.target).length === 0) // ... nor a descendant of the container
                        && (e.target !== $('html').get(0))) // nor the scrollbar
                    {
                        //console.log('slog0');
                        //console.log('slog:'+toolbarClose());
                    }

                    //console.log('slog2');
                    e.stopImmediatePropagation();
                    e.preventDefault();
                    e.stopPropagation();

                    //if (jQuery.browser.msie) {
                        e.originalEvent.keyCode = 0;
                        e.originalEvent.cancelBubble = true;
                        e.originalEvent.returnValue = false;
                    //}
                });

However playing with this fragment didn't work.

dissapearing scrollbar issue - animated gif

Body:
I also bumped into the same problem in selectize plugin:

https://selectize.github.io/selectize.js/

When clicked on scroll bar in IE, it disappears. The solution is similar. In method setup around line 1261 we have:

$dropdown_content = $('<div>').addClass(settings.dropdownContentClass).appendTo($dropdown);

I changed it into:

$dropdown_content = $('<div onmousedown="return false" unselectable="on">').addClass(settings.dropdownContentClass).appendTo($dropdown);

what solved the problem (hopefully not breking anything else :)


问:
How to set proxy in config for protector
I am using protector with angular 4, when i run e2e test it failed to download some dependency from network as it blocked within my org proxy.

I tried to set proxy in protractor.conf.js, but it did not work for me.

```<code>capabilities: {
'browserName': 'chrome',
'proxy': {
  'proxyType': 'manual',
  'httpProxy': 'http://ptx.proxy.corp.sopra:8080'
}
</code>```

below error I'm getting when run ng e2e

```<code>webpack: Compiled successfully.
events.js:183
  throw er; // Unhandled 'error' event
  ^

Error: connect ETIMEDOUT 216.58.204.144:443
at Object._errnoException (util.js:1024:11)
at _exceptionWithHostPort (util.js:1046:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1182:14)
</code>```

Can someone please tell me how to use the proxy within in.

答: I did find a way around to set the proxy, I set up proxy in system environment variable with key http_proxy and ng e2e ran fine for me.

Body:
I am using protector with angular 4, when i run e2e test it failed to download some dependency from network as it blocked within my org proxy.

I tried to set proxy in protractor.conf.js, but it did not work for me.

capabilities: {
'browserName': 'chrome',
'proxy': {
  'proxyType': 'manual',
  'httpProxy': 'http://ptx.proxy.corp.sopra:8080'
}

below error I'm getting when run ng e2e

webpack: Compiled successfully.
events.js:183
  throw er; // Unhandled 'error' event
  ^

Error: connect ETIMEDOUT 216.58.204.144:443
at Object._errnoException (util.js:1024:11)
at _exceptionWithHostPort (util.js:1046:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1182:14)

Can someone please tell me how to use the proxy within in.


问:
Facebook Account Kit in Ionic/Cordova app
I try to connect Facbook Account Kit in Ionic/cordova App, main problem i faced that in facebook account kit set client/server side domain name but in ionic/cordova app the webview serve from file system("file:///android_asset/www/index.html#/app/request"). So how to do this in Ionic app.</p>

答:
You can use plugin instead of webview https://github.com/gurisko/cordova-plugin-accountkit

Steps:

Create a Facebook application from https://developers.facebook.com

Enable Accountkit; Copy required credentials

Add AccountKit plugin

cordova plugin add cordova-plugin-accountkit --save --variable APP_ID="123456789" --variable APP_NAME="myApplication" --variable CLIENT_TOKEN="abcdefghijklmnopqrstuvwxyz"

AccountKitPlugin.loginWithPhoneNumber({
    useAccessToken: true,
    defaultCountryCode: "US",
  },function(res){
    console.log(res)
  },function(err){
     console.log(err)
})```
</div>
</div>
</p>

<p>Incase of Ionic with typescript just add (window) before function</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>(<any>window).AccountKitPlugin.loginWithPhoneNumber({
    useAccessToken: true,
    defaultCountryCode: "US",
  },function(res){
    console.log(res)
  },function(err){
     console.log(err)
})</code>```

Reference: https://codesundar.com/ionic-accountkit-integration/

Body:
You can use plugin instead of webview https://github.com/gurisko/cordova-plugin-accountkit

Steps:

Create a Facebook application from https://developers.facebook.com

Enable Accountkit; Copy required credentials

Add AccountKit plugin

cordova plugin add cordova-plugin-accountkit --save --variable APP_ID="123456789" --variable APP_NAME="myApplication" --variable CLIENT_TOKEN="abcdefghijklmnopqrstuvwxyz"

AccountKitPlugin.loginWithPhoneNumber({
    useAccessToken: true,
    defaultCountryCode: "US",
  },function(res){
    console.log(res)
  },function(err){
     console.log(err)
})

Incase of Ionic with typescript just add (window) before function

(<any>window).AccountKitPlugin.loginWithPhoneNumber({
    useAccessToken: true,
    defaultCountryCode: "US",
  },function(res){
    console.log(res)
  },function(err){
     console.log(err)
})

Reference: https://codesundar.com/ionic-accountkit-integration/


问:
How to open sales orders list view by context menu button in odoo 10
I want to open sales orders list view for any customer when click on context button. For this i getting all the ids on terminal but not getting list view. So, How to open customer sales orders list(Sales). For this my code is below.

Python Code:

```<code>sale_order_count = fields.Integer(compute='_compute_sale_order_count', string='# of Sales Order')

    def _compute_sale_order_count(self):

            ir_model_data = self.env['ir.model.data']

            try:

                view_id = ir_model_data.get_object_reference('sale', 'view_order_tree')[1]

            except ValueError:

                view_id = False

            record_id = self.env['sale.order'].search([('partner_id', '=', self.ren9.id)]).ids

            print "viewssss:::", view_id, record_id

            if not record_id:

                print "Not found"

            else:

                print "return,,", record_id[0]

                return {

                    'view_type': 'tree',

                    'view_mode': 'tree',

                    'views': [(view_id, 'tree')],

                    'res_model': 'sale.order',

                    'view_id': view_id,

                    'type': 'ir.actions.act_window',

                    'res_id': record_id,

                    'target': 'new',

                }
</code>```

XML Code:

```<code> <div name="button_box" position="inside">

                        <button class="oe_stat_button" type="action" name="_compute_sale_order_count"

                                icon="fa-usd">

                            <field string="Sales" name="sale_order_count" widget="statinfo"/>

                        </button>

                    </div>
</code>```

For 4 sales orders print on terminal:

viewssss::: 506 [101, 100, 99, 98]

return,, 101

Thanks in advance,

答:
Please try the follwing

Python code:

```<code>     def _view_sale_orders(self):
        ir_model_data = self.env['ir.model.data']
        try:
           tree_id = ir_model_data.get_object_reference('sale', 'view_order_tree').id
           form_id = ir_model_data.get_object_reference('sale', 'view_order_form').id
        except ValueError:
            view_id = False

        partner_id = self.ren9.id
        return {
            'name': _('Sale Orders'),
            'type': 'ir.actions.act_window',
            'domain': [('partner_id', '=', partner_id)],
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': 'sale.order',
            'view_id': False,
            'views': [(tree_id, 'tree'),(form_id, 'form')],
            'target': 'current',
            'context': ctx,
        }
</code>```

XML Code:

```<code> <div name="button_box" position="inside">

       <button class="oe_stat_button" type="object" name="_view_sale_orders" icon="fa-usd">

        <field string="Sales" name="sale_order_count" widget="statinfo"/>

     </button>

   </div>
</code>```

Body:
I want to open sales orders list view for any customer when click on context button. For this i getting all the ids on terminal but not getting list view. So, How to open customer sales orders list(Sales). For this my code is below.

Python Code:

sale_order_count = fields.Integer(compute='_compute_sale_order_count', string='# of Sales Order')

    def _compute_sale_order_count(self):

            ir_model_data = self.env['ir.model.data']

            try:

                view_id = ir_model_data.get_object_reference('sale', 'view_order_tree')[1]

            except ValueError:

                view_id = False

            record_id = self.env['sale.order'].search([('partner_id', '=', self.ren9.id)]).ids

            print "viewssss:::", view_id, record_id

            if not record_id:

                print "Not found"

            else:

                print "return,,", record_id[0]

                return {

                    'view_type': 'tree',

                    'view_mode': 'tree',

                    'views': [(view_id, 'tree')],

                    'res_model': 'sale.order',

                    'view_id': view_id,

                    'type': 'ir.actions.act_window',

                    'res_id': record_id,

                    'target': 'new',

                }

XML Code:

                        <button class="oe_stat_button" type="action" name="_compute_sale_order_count"

                                icon="fa-usd">

                            <field string="Sales" name="sale_order_count" widget="statinfo"/>

                        </button>

For 4 sales orders print on terminal:

viewssss::: 506 [101, 100, 99, 98]

return,, 101

Thanks in advance,

Body:
Please try the follwing

Python code:

     def _view_sale_orders(self):
        ir_model_data = self.env['ir.model.data']
        try:
           tree_id = ir_model_data.get_object_reference('sale', 'view_order_tree').id
           form_id = ir_model_data.get_object_reference('sale', 'view_order_form').id
        except ValueError:
            view_id = False

        partner_id = self.ren9.id
        return {
            'name': _('Sale Orders'),
            'type': 'ir.actions.act_window',
            'domain': [('partner_id', '=', partner_id)],
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': 'sale.order',
            'view_id': False,
            'views': [(tree_id, 'tree'),(form_id, 'form')],
            'target': 'current',
            'context': ctx,
        }

XML Code:

 <div name="button_box" position="inside">

       <button class="oe_stat_button" type="object" name="_view_sale_orders" icon="fa-usd">

        <field string="Sales" name="sale_order_count" widget="statinfo"/>

     </button>

   </div>


问:
How to read inline styling of an element?
I'd like to know if it's possible to determine what inline styling has been attributed to an HTML element.  I do not need to retrieve the value, but rather just detect if it's been set inline or not.

For instance, if the HTML were:

```<code><div id="foo" style="width: 100px; height: 100px; background: green;"></div>
</code>```

How can I determine that width, height, and background have been explicitly declared, inline?

As far as I can tell, the solution can work two ways.  I can ask it if a specific attribute is set and it will tell me true or false, or it can tell me all attributes that have been set.  Like so:

```<code>var obj = document.getElementById('foo');
obj.hasInlineStyle('width');  //returns true;
obj.hasInlineStyle('border'); //returns false;

//or

obj.getInlineStyles();   //returns array with values:
                       // 'width' 'height' and 'background'
</code>```

I'm not interested in css attributes that are inherited via declarations in a stylesheet, only inline styles.  One last thing, I have no control over the HTML source.

Thanks

答: The style property of an HTML Element returns a style object which lists all the properties.  Any that have a value (other than null or empty string) have been set on the inline style attribute.</p>

OwnerDisplayName: sam

Body:
I'd like to know if it's possible to determine what inline styling has been attributed to an HTML element.  I do not need to retrieve the value, but rather just detect if it's been set inline or not.

For instance, if the HTML were:

How can I determine that width, height, and background have been explicitly declared, inline?

As far as I can tell, the solution can work two ways.  I can ask it if a specific attribute is set and it will tell me true or false, or it can tell me all attributes that have been set.  Like so:

var obj = document.getElementById('foo');
obj.hasInlineStyle('width');  //returns true;
obj.hasInlineStyle('border'); //returns false;

//or

obj.getInlineStyles();   //returns array with values:
                       // 'width' 'height' and 'background'

I'm not interested in css attributes that are inherited via declarations in a stylesheet, only inline styles.  One last thing, I have no control over the HTML source.

Thanks

OwnerDisplayName: AnthonyWJones

ContentLicense: CC BY-SA 2.5


问:
learning CSLA.NET framework
What will be a good start point for learning CSLA framework. </p>

答:
Nothing like a deadline and a user wanting to see something .... Set a target, get one of the working demos and 'rework' into what you need. Have the 2008 book (if your using 3.8x) or PDF just being release if your going with versio 4 from now Jan 2011.

If your using 3.8 with tracker app (WPF and ASP) where easy enough for me 3 years ago, and were my start (we've built complex WPF and Silverlight add for my business).

Good luck

Title: learning CSLA.NET framework


问:
Modifying program using exceptions in python
I need to make a program that initializing class objects throw an exception if the day, month, and year passed as arguments to initialize object variables do not represent a valid date. The exception may only issue an invalid date message.

I do not get much exception in Python, so I did an algorithm that only has an if and else that checks whether it is valid or not. How to transform according to what I need, ie: an exception if the day, month, and year passed as arguments to initialize object variables do not represent a valid date?

```<code>def dois(day, month, year):
    checks = "true"
    i = 0
    while checks == "true" and i == 0:
        if (year%4 == 0 and year%100!= 0) or year%400 == 0:
            leap_year = "sim"
        else:
            leap_year = "nao"

        if month < 1 or month > 12:
            checks = "false"

        if day > 31 or ((month == 4 or month == 6 or month == 9 or month == 11) and day > 30):
            checks = "false"

        if (month == 2 and leap_year == "nao" and day > 28) or ( month == 2 and leap_year == "sim" and day > 29):
            checks = "false"
        i = i + 1

    if checks == "true":
        print("Valid date")
    else:
        print("Invalid date")
</code>```

I can not use ready-made functions like time.strptime, I need to use what I have implemented

答:
The practical answer:

```<code>import datetime

try:
    datetime.date(year, month, day)
    print('Valid date')
except ValueError:
    raise ValueError('Invalid date')
</code>```

The try..except..raise is really just to satisfy the condition that "the exception may only issue an invalid date message" (whatever that means exactly). In practice you would just use the ValueError raised by date as is. I don't know what the point if this exercise is, whether converting an exception or reinventing date parsing is the idea.

Body:
I need to make a program that initializing class objects throw an exception if the day, month, and year passed as arguments to initialize object variables do not represent a valid date. The exception may only issue an invalid date message.

I do not get much exception in Python, so I did an algorithm that only has an if and else that checks whether it is valid or not. How to transform according to what I need, ie: an exception if the day, month, and year passed as arguments to initialize object variables do not represent a valid date?

def dois(day, month, year):
    checks = "true"
    i = 0
    while checks == "true" and i == 0:
        if (year%4 == 0 and year%100!= 0) or year%400 == 0:
            leap_year = "sim"
        else:
            leap_year = "nao"

        if month < 1 or month > 12:
            checks = "false"

        if day > 31 or ((month == 4 or month == 6 or month == 9 or month == 11) and day > 30):
            checks = "false"

        if (month == 2 and leap_year == "nao" and day > 28) or ( month == 2 and leap_year == "sim" and day > 29):
            checks = "false"
        i = i + 1

    if checks == "true":
        print("Valid date")
    else:
        print("Invalid date")

I can not use ready-made functions like time.strptime, I need to use what I have implemented

Body:
The practical answer:

import datetime

try:
    datetime.date(year, month, day)
    print('Valid date')
except ValueError:
    raise ValueError('Invalid date')

The try..except..raise is really just to satisfy the condition that "the exception may only issue an invalid date message" (whatever that means exactly). In practice you would just use the ValueError raised by date as is. I don't know what the point if this exercise is, whether converting an exception or reinventing date parsing is the idea.


问:
Checkbox checked not passing an actual value?
My code checks the value of 2x checkboxes to equal true/false depending on a radio field. I see the checkboxes being ticket on the web page.

However, once they are passed over a HTML POST form, they have no values and always equal false.

If I give the checkboxes a value "TRUE" then of course they have only that value.

What am I missing here?

```<code>    <script>
      $(function() {
  var MAIN= $("input[type='radio']");
  var marketingPhone = $("input[type='checkbox'][name='marketingPhone']");
  var marketingRobo = $("input[type='checkbox'][name='marketingRobo']");

    MAIN.on('change', function()
        {
        if ($(this).val() == "TRUE")  {
          marketingPhone.prop('checked',true);
          marketingRobo.prop('checked',true);
        } else {
          marketingPhone.prop('checked',false);
          marketingRobo.prop('checked',false);
        }

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

The fields are as follows:

```<code>        <input type="checkbox" name="marketingPhone" value=""/>
        <input type="checkbox" name="marketingRobo" value=""/>
</code>```

答:
You need to specify a value in the HTML. If a checkbox is checked, that value is posted. These values can be anything and are definitely not the same as the true/false that are used for the prop()-call (those just mean 'set or clear the check mark').

Example:

```<code><input type="checkbox" name="marketingPhone" value="yes"/>
<input type="checkbox" name="marketingRobo" value="absolutely"/>
</code>```

When both are checked, this is posted:

```<code>marketingPhone=yes&marketingRobo=absolutely
</code>```

When not all are checked, the corresponding name=value are omitted from the posted data.

If you really want to post a value (e.g. "true" or "false") for every checkbox all the time, then the only way to do so is by adding hidden fields (one for each checkbox) that you control yourself, setting the value of the hidden field to "true" or "false" using script. You might as well then not set the checkbox value to prevent confusion on the receiving end.

Also be aware that form fields always post strings, so either treat them as literal strings or parse them into booleans on the receiving end.

Body:
My code checks the value of 2x checkboxes to equal true/false depending on a radio field. I see the checkboxes being ticket on the web page.

However, once they are passed over a HTML POST form, they have no values and always equal false.

If I give the checkboxes a value "TRUE" then of course they have only that value.

What am I missing here?

The fields are as follows:

        <input type="checkbox" name="marketingPhone" value=""/>
        <input type="checkbox" name="marketingRobo" value=""/>

Body:
You need to specify a value in the HTML. If a checkbox is checked, that value is posted. These values can be anything and are definitely not the same as the true/false that are used for the prop()-call (those just mean 'set or clear the check mark').

Example:

<input type="checkbox" name="marketingPhone" value="yes"/>
<input type="checkbox" name="marketingRobo" value="absolutely"/>

When both are checked, this is posted:

marketingPhone=yes&marketingRobo=absolutely

When not all are checked, the corresponding name=value are omitted from the posted data.

If you really want to post a value (e.g. "true" or "false") for every checkbox all the time, then the only way to do so is by adding hidden fields (one for each checkbox) that you control yourself, setting the value of the hidden field to "true" or "false" using script. You might as well then not set the checkbox value to prevent confusion on the receiving end.

Also be aware that form fields always post strings, so either treat them as literal strings or parse them into booleans on the receiving end.