问:
Charts update chart in realtime - data recorded on one VC and charted in another
I have a tabbed app that starts recording on one tab, and plots the mic levels on another tab.

In the first VC, I'm gathering mic levels and storing them in an array in the model. I'm using another method in the model to update the data, and I'm calling it in the second VC in order to update the view.

What I want to do is update the chart in the second view controller from the first view controller (where the logic for storing data in the model is)

Model:

Chart.swift

```<code>import Charts

class Chart {
    static let sharedInstance = Chart()
    var lineChartView: LineChartView!

    func setChartValues() {
        let entries = (0..<GraphData.sharedInstance.array.count).map { (i) -> ChartDataEntry in
            let val = GraphData.sharedInstance.array[i]
            print(ChartDataEntry(x: Double(i), y: val))
            return ChartDataEntry(x: Double(i), y: val)
        }
        let set1 = LineChartDataSet(values: entries, label: "DataSet 1")
        let data = LineChartData(dataSet: set1)
        lineChartView.data = data
    }
}
</code>```

GraphData.swift

```<code>class GraphData {
    static let sharedInstance = GraphData()
    var array = [Double]()
}
</code>```

View Controllers:

First VC: (complete code per comment)

import UIKit
import AVFoundation

```<code>class SoundController: UIViewController, AVAudioRecorderDelegate {

    var recordingSession: AVAudioSession!
    var audioRecorder: AVAudioRecorder!
    var timer = Timer()
    @IBOutlet weak var errorLbl: UILabel!
    @IBOutlet weak var recordBtn: UIButton!

    @IBAction func recordButton(_ sender: UIButton) {
        if audioRecorder == nil {
            startRecording()
        } else {
            finishRecording(success: true)
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(false)
        errorLbl.text = ""
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        recordPermission()
    }

    func recordPermission() {
        recordingSession = AVAudioSession.sharedInstance()
        do {
            try recordingSession.setCategory(.playAndRecord, mode: .default)
            try recordingSession.setActive(true)
            recordingSession.requestRecordPermission() {  allowed in
                DispatchQueue.main.async {
                    if allowed {
                        print("recording allowed")
                    } else {
                        self.errorLbl.text = "Recording Permission was Denied. Please open settings and allow Cry It Out to access the microphone."
                    }
                }
            }
        } catch {
            self.errorLbl.text = "Recording Permission was Denied. Please open settings and allow the app to access the microphone."
        }
    }

    func getDocumentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return paths[0]
    }

    func startRecording() {
        if recordBtn.titleLabel?.text == "Tap to Re-record" {
            //reset values array
            GraphData.sharedInstance.array = []
        }
        let audioFilename = getDocumentsDirectory().appendingPathComponent("baby.m4a")

        let settings = [
            AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
            AVSampleRateKey: 12000,
            AVNumberOfChannelsKey: 1,
            AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
        ]

        do {
            audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
            audioRecorder.delegate = self
            audioRecorder.isMeteringEnabled = true
            runTimer()
            audioRecorder.record()
            runTimer()
            recordBtn.setTitle("Tap to Stop", for: .normal)
        } catch {
            finishRecording(success: false)
        }
    }

    func levelTimerCallback() -> Float {
        if audioRecorder != nil {
            audioRecorder.updateMeters()
            //If we are beyond a threshold value (-15)
            if audioRecorder.averagePower(forChannel: 0) > -15 {
                return audioRecorder.averagePower(forChannel: 0)
            }
        }
        return 0
    }

    func finishRecording(success: Bool) {
        //stop recording and reset recorder to nil for other checks
        audioRecorder.stop()
        audioRecorder = nil

        if success {
            recordBtn.setTitle("Tap to Re-record", for: .normal)
            if timer.isValid {
                timer.invalidate()
            }
        } else {
            //Recording Failed
            recordBtn.setTitle("Tap to Record", for: .normal)
            //disable timer if running (might be running or might not)
            if timer.isValid {
                timer.invalidate()
            }
        }
    }

    func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
        if !flag {
            finishRecording(success: false)
        }
    }

    //MARK: Timers

    @objc func updateTimer() {
        if levelTimerCallback() != 0 {
            let date = Date()
            let calendar = Calendar.current
            let month = calendar.component(.month, from: date)
            let day = calendar.component(.day, from: date)
            let hour = calendar.component(.hour, from: date)
            let minutes = calendar.component(.minute, from: date)
            let seconds = calendar.component(.second, from: date)
            let prettyDate = "\(month)/\(day) \(hour):\(minutes) and \(seconds) seconds"
            print(prettyDate)
            GraphData.sharedInstance.array.append(Double(levelTimerCallback()))
            //does this run the method? It should
            GraphController.sharedInstance.lineChartView?.data = Chart.sharedInstance.setChartValues()

        }
    }

    func runTimer() {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self,   selector: (#selector(SoundController.updateTimer)), userInfo: nil, repeats: true)
    }

    func stopTimer() {
        timer.invalidate()
    }

}
</code>```

Second VC:

```<code>import UIKit
import Charts

class GraphController: UIViewController {
    static let sharedInstance = GraphController()
    @IBOutlet weak var lineChartView: LineChartView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        self.lineChartView.data = Chart.sharedInstance.setChartValues()
    }

}
</code>```

答:
Try this solution without lambda functions. You don't need use static values.

1. Prepare your GraphController to have a function to receive data

```<code>class GraphController: UIViewController {

    ...

    func dataReceived ( gData : GraphData ) {
        DispatchQueue.main.async {
            // Update your chart with gData
        }
    }

}
</code>```

2. Get the reference of GraphController and use the function of step 1 to make your updates.

Please, get the reference of your GraphController from tab and use this reference to call a function to make your chart updates. I don't know exactely your situation, but if you have problems to make it, please look this: https://stackoverflow.com/a/39499751/5140756

```<code>class SoundController: UIViewController, AVAudioRecorderDelegate {

    var graphController : GraphController?

    ...

    override func viewDidLoad() {
        super.viewDidLoad()
        ...
        // get graph controller reference from tabbar.
        self.graphController = self.tabBarController.viewControllers![INDEX_OF_VIEW_CONTROLLER] as! GraphController
    }

    // finally on your function call the function's graph controller receive data
    @objc func updateTimer() {
        if levelTimerCallback() != 0 {
            let date = Date()
            let calendar = Calendar.current
            let month = calendar.component(.month, from: date)
            let day = calendar.component(.day, from: date)
            let hour = calendar.component(.hour, from: date)
            let minutes = calendar.component(.minute, from: date)
            let seconds = calendar.component(.second, from: date)
            let prettyDate = "\(month)/\(day) \(hour):\(minutes) and \(seconds) seconds"
            print(prettyDate)
            GraphData.sharedInstance.array.append(Double(levelTimerCallback()))
            //does this run the method? It should
            //GraphController.sharedInstance.lineChartView?.data = Chart.sharedInstance.setChartValues()

             if graphController != nil {
                 self.graphController!.dataReceived( gData: GraphData.sharedInstance )
             }

        }
    }

}
</code>```

Please, look the code, and make some changes that you need, I tried automate the max that I can.

Body:
I have a tabbed app that starts recording on one tab, and plots the mic levels on another tab.

In the first VC, I'm gathering mic levels and storing them in an array in the model. I'm using another method in the model to update the data, and I'm calling it in the second VC in order to update the view.

What I want to do is update the chart in the second view controller from the first view controller (where the logic for storing data in the model is)

Model:

Chart.swift

import Charts

class Chart {
    static let sharedInstance = Chart()
    var lineChartView: LineChartView!

    func setChartValues() {
        let entries = (0..<GraphData.sharedInstance.array.count).map { (i) -> ChartDataEntry in
            let val = GraphData.sharedInstance.array[i]
            print(ChartDataEntry(x: Double(i), y: val))
            return ChartDataEntry(x: Double(i), y: val)
        }
        let set1 = LineChartDataSet(values: entries, label: "DataSet 1")
        let data = LineChartData(dataSet: set1)
        lineChartView.data = data
    }
}

GraphData.swift

class GraphData {
    static let sharedInstance = GraphData()
    var array = [Double]()
}

View Controllers:

First VC: (complete code per comment)

import UIKit
import AVFoundation

class SoundController: UIViewController, AVAudioRecorderDelegate {

    var recordingSession: AVAudioSession!
    var audioRecorder: AVAudioRecorder!
    var timer = Timer()
    @IBOutlet weak var errorLbl: UILabel!
    @IBOutlet weak var recordBtn: UIButton!

    @IBAction func recordButton(_ sender: UIButton) {
        if audioRecorder == nil {
            startRecording()
        } else {
            finishRecording(success: true)
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(false)
        errorLbl.text = ""
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        recordPermission()
    }

    func recordPermission() {
        recordingSession = AVAudioSession.sharedInstance()
        do {
            try recordingSession.setCategory(.playAndRecord, mode: .default)
            try recordingSession.setActive(true)
            recordingSession.requestRecordPermission() {  allowed in
                DispatchQueue.main.async {
                    if allowed {
                        print("recording allowed")
                    } else {
                        self.errorLbl.text = "Recording Permission was Denied. Please open settings and allow Cry It Out to access the microphone."
                    }
                }
            }
        } catch {
            self.errorLbl.text = "Recording Permission was Denied. Please open settings and allow the app to access the microphone."
        }
    }

    func getDocumentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return paths[0]
    }

    func startRecording() {
        if recordBtn.titleLabel?.text == "Tap to Re-record" {
            //reset values array
            GraphData.sharedInstance.array = []
        }
        let audioFilename = getDocumentsDirectory().appendingPathComponent("baby.m4a")

        let settings = [
            AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
            AVSampleRateKey: 12000,
            AVNumberOfChannelsKey: 1,
            AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
        ]

        do {
            audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
            audioRecorder.delegate = self
            audioRecorder.isMeteringEnabled = true
            runTimer()
            audioRecorder.record()
            runTimer()
            recordBtn.setTitle("Tap to Stop", for: .normal)
        } catch {
            finishRecording(success: false)
        }
    }

    func levelTimerCallback() -> Float {
        if audioRecorder != nil {
            audioRecorder.updateMeters()
            //If we are beyond a threshold value (-15)
            if audioRecorder.averagePower(forChannel: 0) > -15 {
                return audioRecorder.averagePower(forChannel: 0)
            }
        }
        return 0
    }

    func finishRecording(success: Bool) {
        //stop recording and reset recorder to nil for other checks
        audioRecorder.stop()
        audioRecorder = nil

        if success {
            recordBtn.setTitle("Tap to Re-record", for: .normal)
            if timer.isValid {
                timer.invalidate()
            }
        } else {
            //Recording Failed
            recordBtn.setTitle("Tap to Record", for: .normal)
            //disable timer if running (might be running or might not)
            if timer.isValid {
                timer.invalidate()
            }
        }
    }

    func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
        if !flag {
            finishRecording(success: false)
        }
    }

    //MARK: Timers

    @objc func updateTimer() {
        if levelTimerCallback() != 0 {
            let date = Date()
            let calendar = Calendar.current
            let month = calendar.component(.month, from: date)
            let day = calendar.component(.day, from: date)
            let hour = calendar.component(.hour, from: date)
            let minutes = calendar.component(.minute, from: date)
            let seconds = calendar.component(.second, from: date)
            let prettyDate = "\(month)/\(day) \(hour):\(minutes) and \(seconds) seconds"
            print(prettyDate)
            GraphData.sharedInstance.array.append(Double(levelTimerCallback()))
            //does this run the method? It should
            GraphController.sharedInstance.lineChartView?.data = Chart.sharedInstance.setChartValues()

        }
    }

    func runTimer() {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self,   selector: (#selector(SoundController.updateTimer)), userInfo: nil, repeats: true)
    }

    func stopTimer() {
        timer.invalidate()
    }

}

Second VC:

import UIKit
import Charts

class GraphController: UIViewController {
    static let sharedInstance = GraphController()
    @IBOutlet weak var lineChartView: LineChartView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        self.lineChartView.data = Chart.sharedInstance.setChartValues()
    }

}

Body:
Try this solution without lambda functions. You don't need use static values.

1. Prepare your GraphController to have a function to receive data

class GraphController: UIViewController {

    ...

    func dataReceived ( gData : GraphData ) {
        DispatchQueue.main.async {
            // Update your chart with gData
        }
    }

}

2. Get the reference of GraphController and use the function of step 1 to make your updates.

Please, get the reference of your GraphController from tab and use this reference to call a function to make your chart updates. I don't know exactely your situation, but if you have problems to make it, please look this: https://stackoverflow.com/a/39499751/5140756

class SoundController: UIViewController, AVAudioRecorderDelegate {

    var graphController : GraphController?

    ...

    override func viewDidLoad() {
        super.viewDidLoad()
        ...
        // get graph controller reference from tabbar.
        self.graphController = self.tabBarController.viewControllers![INDEX_OF_VIEW_CONTROLLER] as! GraphController
    }

    // finally on your function call the function's graph controller receive data
    @objc func updateTimer() {
        if levelTimerCallback() != 0 {
            let date = Date()
            let calendar = Calendar.current
            let month = calendar.component(.month, from: date)
            let day = calendar.component(.day, from: date)
            let hour = calendar.component(.hour, from: date)
            let minutes = calendar.component(.minute, from: date)
            let seconds = calendar.component(.second, from: date)
            let prettyDate = "\(month)/\(day) \(hour):\(minutes) and \(seconds) seconds"
            print(prettyDate)
            GraphData.sharedInstance.array.append(Double(levelTimerCallback()))
            //does this run the method? It should
            //GraphController.sharedInstance.lineChartView?.data = Chart.sharedInstance.setChartValues()

             if graphController != nil {
                 self.graphController!.dataReceived( gData: GraphData.sharedInstance )
             }

        }
    }

}

Please, look the code, and make some changes that you need, I tried automate the max that I can.


来源: stackexchange

问:
max length for user password field with "algorithm: auto"?
Symfony 4.3 deprecated the bcrypt algorithm, see UPGRADE-4.3.md:

Configuring encoders using argon2i or bcrypt as algorithm has been deprecated, use auto instead.

So I changed security.yaml to:

```<code>encoders:
    App\Entity\User:
        algorithm: auto
</code>```

The problem is that, after changing to auto, the hashed string is longer:

'INSERT INTO users (..., password, ...) VALUES (...)' with params
  [...,
  "$argon2id$v=19$m=65536,t=6,p=1$d2RhZjVuaWJsSnE0TW5haA$ycOn7EHjPOoBTSa6SHDOBWL2AvwfPNjAstlSTEMmPpU",
  ...]:

SQLSTATE[22001]: String data, right truncated: 1406 Data too long for
  column 'password' at row 1

This string is 97 characters long, while my password column was 64. I don't find any documentation about the maximum possible length with the "auto" attribute, is it 97? Or it can be more?

答:
As said by @Cerad in comments, the auto mode will likely always produce passwords that are supported by the password_hash() built-in PHP function (depending on the platform).

 Therefore you can safely rely on the hint given by the password_hash() documentation:

PASSWORD_DEFAULT - [...] Note that this constant is designed to change over time as new and stronger algorithms are added to PHP. For that reason, the length of the result from using this identifier can change over time. Therefore, it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice).

ContentLicense: CC BY-SA 4.0

Body:
Symfony 4.3 deprecated the bcrypt algorithm, see UPGRADE-4.3.md:

Configuring encoders using argon2i or bcrypt as algorithm has been deprecated, use auto instead.

So I changed security.yaml to:

encoders:
    App\Entity\User:
        algorithm: auto

The problem is that, after changing to auto, the hashed string is longer:

'INSERT INTO users (..., password, ...) VALUES (...)' with params
  [...,
  "$argon2id$v=19$m=65536,t=6,p=1$d2RhZjVuaWJsSnE0TW5haA$ycOn7EHjPOoBTSa6SHDOBWL2AvwfPNjAstlSTEMmPpU",
  ...]:

SQLSTATE[22001]: String data, right truncated: 1406 Data too long for
  column 'password' at row 1

This string is 97 characters long, while my password column was 64. I don't find any documentation about the maximum possible length with the "auto" attribute, is it 97? Or it can be more?


问:
Section header height differs when set manually
I'm trying to change the height of a particular section header inside a table view. I tested with code below just to understand how tableView(_:heightForHeaderInSection:) works.

```<code>override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    print("DEBUG : ", section, tableView.sectionHeaderHeight)
    return tableView.sectionHeaderHeight
}
</code>```

Debug print below shows that the method is called multiple times, but that the header height is always 18.0 (which is default).

```<code>DEBUG :  4 18.0
DEBUG :  4 18.0
DEBUG :  0 18.0
DEBUG :  0 18.0
DEBUG :  1 18.0
DEBUG :  1 18.0
DEBUG :  2 18.0
...
DEBUG :  3 18.0
</code>```

Now, as soon as I use 18.0 as fix value for return (for testing purpose), the vertical extend of the table view is visually compressed, id est the sections are closer together, and the entire UI looks therefore different. It seems that the space between the sections is reduced, since the header of the first section is (vertically) only half visible.

```<code>override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    print("DEBUG : ", section, tableView.sectionHeaderHeight)
    return 18.0
}
</code>```

How is that possible?

Possibly a bug?

--- UPDATE --- (13.06.2019)

My question was based on the intention to hide a section (2) including header. I realized that tableView.sectionHeaderHeight was the wrong property to use. I should have used super.tableView(tableView, heightForHeaderInSection: section).

The code below works as desired:

```<code>override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    if (section == 2) && myCondition {
        return CGFloat.leastNonzeroMagnitude
    }
    return super.tableView(tableView, heightForHeaderInSection: section)
}
</code>```

Nevertheless, I don't know where the 18.0 (see above) comes from since I don't use .xib files.

BTW super.tableView(tableView, heightForHeaderInSection: section) always returns -1. I believe this makes iOS decide on its own which heigth to choose. The manually set 18.0 (for testing) made the header shrink since the iOS chosen automatic value for the header height is higher.

I didn't find a property to print this value (must be around 30.0 - a wild guess, nothing more).

答:
As per your code,

```<code>override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return tableView.sectionHeaderHeight
}
</code>```

You're returning sectionHeaderHeight as the header height that actually means UITableViewAutomaticDimension.

open var sectionHeaderHeight: CGFloat // default is
  UITableViewAutomaticDimension

As per Apple,

This nonnegative value is used only if the delegate doesn’t implement
  the tableView:heightForHeaderInSection: method.

The value you're getting when using print("DEBUG : ", section, tableView.sectionHeaderHeight), i.e. 18.0 is the height of the custom headerView in the .xib.

Still you're getting the proper UI because iOS automatically calculates the header height internally at runtime.

This is the reason your header shrinks when you are passing 18.0 as the header height manually.

In case you want to use separate header height for each section, you need to pass that manually in tableView(_:heightForHeaderInSection:) method, i.e.

```<code>override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    switch section {
    case 0:
        return 50.0
    case 1:
        return 30.0
    default:
        return tableView.sectionHeaderHeight
    }
}
</code>```

You can add more cases to the above switch statement as per your requirement. Let me know in case you still have any confusion left regarding this.

Body:
I'm trying to change the height of a particular section header inside a table view. I tested with code below just to understand how tableView(_:heightForHeaderInSection:) works.

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    print("DEBUG : ", section, tableView.sectionHeaderHeight)
    return tableView.sectionHeaderHeight
}

Debug print below shows that the method is called multiple times, but that the header height is always 18.0 (which is default).

DEBUG :  4 18.0
DEBUG :  4 18.0
DEBUG :  0 18.0
DEBUG :  0 18.0
DEBUG :  1 18.0
DEBUG :  1 18.0
DEBUG :  2 18.0
...
DEBUG :  3 18.0

Now, as soon as I use 18.0 as fix value for return (for testing purpose), the vertical extend of the table view is visually compressed, id est the sections are closer together, and the entire UI looks therefore different. It seems that the space between the sections is reduced, since the header of the first section is (vertically) only half visible.

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    print("DEBUG : ", section, tableView.sectionHeaderHeight)
    return 18.0
}

How is that possible?

Possibly a bug?

--- UPDATE --- (13.06.2019)

My question was based on the intention to hide a section (2) including header. I realized that tableView.sectionHeaderHeight was the wrong property to use. I should have used super.tableView(tableView, heightForHeaderInSection: section).

The code below works as desired:

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    if (section == 2) && myCondition {
        return CGFloat.leastNonzeroMagnitude
    }
    return super.tableView(tableView, heightForHeaderInSection: section)
}

Nevertheless, I don't know where the 18.0 (see above) comes from since I don't use .xib files.

BTW super.tableView(tableView, heightForHeaderInSection: section) always returns -1. I believe this makes iOS decide on its own which heigth to choose. The manually set 18.0 (for testing) made the header shrink since the iOS chosen automatic value for the header height is higher.

I didn't find a property to print this value (must be around 30.0 - a wild guess, nothing more).

Body:
As per your code,

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return tableView.sectionHeaderHeight
}

You're returning sectionHeaderHeight as the header height that actually means UITableViewAutomaticDimension.

open var sectionHeaderHeight: CGFloat // default is
  UITableViewAutomaticDimension

As per Apple,

This nonnegative value is used only if the delegate doesn’t implement
  the tableView:heightForHeaderInSection: method.

The value you're getting when using print("DEBUG : ", section, tableView.sectionHeaderHeight), i.e. 18.0 is the height of the custom headerView in the .xib.

Still you're getting the proper UI because iOS automatically calculates the header height internally at runtime.

This is the reason your header shrinks when you are passing 18.0 as the header height manually.

In case you want to use separate header height for each section, you need to pass that manually in tableView(_:heightForHeaderInSection:) method, i.e.

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    switch section {
    case 0:
        return 50.0
    case 1:
        return 30.0
    default:
        return tableView.sectionHeaderHeight
    }
}

You can add more cases to the above switch statement as per your requirement. Let me know in case you still have any confusion left regarding this.


问:
order by clause not working in Cassandra query
I have created a table layer using following code:

```<code>CREATE TABLE layer (
    layer_name text,
    layer_position text,
    PRIMARY KEY (layer_name, layer_position)
) WITH CLUSTERING ORDER BY (layer_position DESC)
</code>```

I use the below query to fetch data from the layer table in descending order(layer):

```<code>$select = new Cassandra\SimpleStatement(<<<EOD
                        select * from layer ORDER BY layer_position DESC
EOD
                      );

$result = $session->execute($select);
</code>```

But this query is not working.  Please can anyone help me?

答: You can use order by clause in cassandra by creating materilaized view table.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have created a table layer using following code:

CREATE TABLE layer (
    layer_name text,
    layer_position text,
    PRIMARY KEY (layer_name, layer_position)
) WITH CLUSTERING ORDER BY (layer_position DESC)

I use the below query to fetch data from the layer table in descending order(layer):

$select = new Cassandra\SimpleStatement(<<<EOD
                        select * from layer ORDER BY layer_position DESC
EOD
                      );

$result = $session->execute($select);

But this query is not working.  Please can anyone help me?


问:
Watson Assistant: Problem with extracting value for pattern entity
I am trying to get the value for the first group match of a pattern entity from the json response of Watson Assistant. The pattern is a simple regex to recognize sequences of numbers: ([0-9]+)

The json response looks like this:

```<code>    "entity": "ID",
    "location": [
      18,
      23
    ],
    "value": "id",
    "confidence": 1.0,
    "groups": [
      {
        "group": "group_0",
        "location": [
          18,
          23
        ]
      }
    ]
  },
  {
    "entity": "sys-number",
    "location": [
      18,
      23
    ],
    "value": "12345",
    "confidence": 1.0,
    "metadata": {
      "numeric_value": 12345.0
    }
  }
]
</code>```

So, the group is matched alright, but the field "value" is populated with the String literal from the entity config. I would expected to find the actual value there (which is the one the value field of the next entity, sys-number).

How do I need to change the config so that the value is included as-is in the value field (or somewhere else) and so that I don't have to extract the entity from the text string using the location values? Is it possible at all?
Thanks a lot

Cheers,
Martin

答: To access value of pattern based entity, you can either use <? @entity_name.literal ?> or <? @entity_name.groups[0] ?> - if there are more groups captured. You can find more info in the doc: https://cloud.ibm.com/docs/services/assistant?topic=assistant-entities

Body:
I am trying to get the value for the first group match of a pattern entity from the json response of Watson Assistant. The pattern is a simple regex to recognize sequences of numbers: ([0-9]+)

The json response looks like this:

    "entity": "ID",
    "location": [
      18,
      23
    ],
    "value": "id",
    "confidence": 1.0,
    "groups": [
      {
        "group": "group_0",
        "location": [
          18,
          23
        ]
      }
    ]
  },
  {
    "entity": "sys-number",
    "location": [
      18,
      23
    ],
    "value": "12345",
    "confidence": 1.0,
    "metadata": {
      "numeric_value": 12345.0
    }
  }
]

So, the group is matched alright, but the field "value" is populated with the String literal from the entity config. I would expected to find the actual value there (which is the one the value field of the next entity, sys-number).

How do I need to change the config so that the value is included as-is in the value field (or somewhere else) and so that I don't have to extract the entity from the text string using the location values? Is it possible at all?
Thanks a lot

Cheers,
Martin


问:
How to override global ValidationPipe in controller?
I use a global ValidationPipe with { transform: true, whitelist: true } options. However, in a particular controller request I want to reuse the same class but with different validations, applying the validation groups technique of class-validator. Therefore it is necessary that I override the pipe's options to apply new options.

This is on NestJS 6.2.4. I have tried applying a new pipe at the @Query(new ValidationPipe({groups: ['res']})), but the global pipe is still applied. I have applied the same logic with @UsePipes() but again the global pipe is applied.

Also, I have tried applying the always: false property along with the groups, to avoid validating the property at all times, but since this is the default behavior, it doesn't help much.

```<code>@IsNumberString({ groups: ['res'] })
resId: number;
</code>```

答:
In this case, what I would recommend is to add the ValidationPipe at the method level within your controller, instead of at the controller level.

Something like this:

@Controller('users')
export class UsersController {

    constructor(
        private readonly usersService: UsersService
    ) {
    }

    @Post()
    @UsePipes(new ValidationPipe({
        forbidUnknownValues: true,
        transform: true
    }))
    async create(@Body() createUserDtoReq: CreateUserRequestDto): Promise<UserResponseDto> {
        return await this.usersService.create(createUserDtoReq);
    }
}
```

Others might add other suggestions though.

Body:
I use a global ValidationPipe with { transform: true, whitelist: true } options. However, in a particular controller request I want to reuse the same class but with different validations, applying the validation groups technique of class-validator. Therefore it is necessary that I override the pipe's options to apply new options.

This is on NestJS 6.2.4. I have tried applying a new pipe at the @Query(new ValidationPipe({groups: ['res']})), but the global pipe is still applied. I have applied the same logic with @UsePipes() but again the global pipe is applied.

Also, I have tried applying the always: false property along with the groups, to avoid validating the property at all times, but since this is the default behavior, it doesn't help much.

@IsNumberString({ groups: ['res'] })
resId: number;

Body:
In this case, what I would recommend is to add the ValidationPipe at the method level within your controller, instead of at the controller level.

Something like this:

@Controller('users')
export class UsersController {

    constructor(
        private readonly usersService: UsersService
    ) {
    }

    @Post()
    @UsePipes(new ValidationPipe({
        forbidUnknownValues: true,
        transform: true
    }))
    async create(@Body() createUserDtoReq: CreateUserRequestDto): Promise<UserResponseDto> {
        return await this.usersService.create(createUserDtoReq);
    }
}

Others might add other suggestions though.


问:
Any way to visualize the transform origin point in CSS?
I'm trying to make an object move along an arc, for which I need to set the transform-origin point away from the object itself and then rotate it. So instead of blindly moving the transform-origin point using different lengths and then finally achieving the desired result through trial and error, is there a way to make the point visible to make the process easier?

答:
Here is a solution I use to visualize transform-origin. Try to change transform-origin value on a DIV element. You will see a semitransparent point adjusted. The drawback of this method is that you have to set position: relative to a parent element.

div {
  position: relative;
  margin: 100px;
  width: 40px;
  height: 30px;
  background: #ccc;
  transform-origin: bottom left;
  animation: rotate 1s linear infinite;
}

span {
  position: absolute;
  width: 100%;
  height: 100%;
  transform: scale(0.001);
  transform-origin: inherit;
}

span::after {
  content: '';
  display: block;
  width: 10px;
  height: 10px;
  border-radius: 100%;
  background: rgba(255,128,128,0.75);
  transform: scale(1000);
}

@keyframes rotate {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <span></span>
</div></code>```

transform-origin is necessary for scale and rotation transformations only. The meaning of it for scale is a point where an object is growing from (for scale-in) or a point where an object should be shrinked to (for scale-out). So, at first I shrink a SPAN to almost zero size, then I grow a semitransparent element (SPAN::AFTER) from this point.

https://codepen.io/vbarbarosh/pen/eaQLeJ

Body:
Here is a solution I use to visualize transform-origin. Try to change transform-origin value on a DIV element. You will see a semitransparent point adjusted. The drawback of this method is that you have to set position: relative to a parent element.

div {
  position: relative;
  margin: 100px;
  width: 40px;
  height: 30px;
  background: #ccc;
  transform-origin: bottom left;
  animation: rotate 1s linear infinite;
}

span {
  position: absolute;
  width: 100%;
  height: 100%;
  transform: scale(0.001);
  transform-origin: inherit;
}

span::after {
  content: '';
  display: block;
  width: 10px;
  height: 10px;
  border-radius: 100%;
  background: rgba(255,128,128,0.75);
  transform: scale(1000);
}

@keyframes rotate {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

<div>
  <span></span>
</div>

transform-origin is necessary for scale and rotation transformations only. The meaning of it for scale is a point where an object is growing from (for scale-in) or a point where an object should be shrinked to (for scale-out). So, at first I shrink a SPAN to almost zero size, then I grow a semitransparent element (SPAN::AFTER) from this point.

https://codepen.io/vbarbarosh/pen/eaQLeJ


问:
Angular ng-if="" with multiple arguments
I am trying to get started on angular development. And after reviewing the documentation some questions persist. How do i best write a ng-if with multiple arguments corresponding to

if( a && b) or if( a || b )

答:
Just to clarify, be aware bracket placement is important!

These can be added to any HTML tags... span, div, table, p, tr, td etc.

AngularJS

```<code>ng-if="check1 && !check2" -- AND NOT
ng-if="check1 || check2" -- OR
ng-if="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets
</code>```

Angular2+

```<code>*ngIf="check1 && !check2" -- AND NOT
*ngIf="check1 || check2" -- OR
*ngIf="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets
</code>```

It's best practice not to do calculations directly within ngIfs, so assign the variables within your component, and do any logic there.

```<code>boolean check1 = Your conditional check here...
...
</code>```

Body:
Just to clarify, be aware bracket placement is important!

These can be added to any HTML tags... span, div, table, p, tr, td etc.

AngularJS

ng-if="check1 && !check2" -- AND NOT
ng-if="check1 || check2" -- OR
ng-if="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets

Angular2+

*ngIf="check1 && !check2" -- AND NOT
*ngIf="check1 || check2" -- OR
*ngIf="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets

It's best practice not to do calculations directly within ngIfs, so assign the variables within your component, and do any logic there.

boolean check1 = Your conditional check here...
...


问:
Leaflet: adjust popup to picture size
I'm trying to include pictures in my leaflet popups, but the popup-size doesn't adjust to the picture size. I found a solution to this on github:

https://github.com/Leaflet/Leaflet/issues/724

While that solution fixes the size of the popup, the result is shifted and the popup doesn't show up centered over the icon/marker... Any way to change that?

```<code>.leaflet-popup-content {
     width:auto !important;
}
</code>```

Also the other proposed solution (setting the maxWidth on the popup) doesn't help in my case. The popup width keeps on being the default width of 300px...

```<code>function pop_Fotos(feature, layer) {
     var popupContent = '<img style="max-height:500px;max-width:500px;" src="...");
     layer.bindPopup(popupContent, {maxWidth: 500, closeOnClick: true});
}
</code>```

答:
None of the before added answers worked for me, but I came upon a quite simple solution (the link of which I can no longer find). Just wrap your image in a div:

```<code>    <div class='ppcont'><img src='yourimg.jpg' /></div>
</code>```

And add a simple css rule that corresponds to the image width:

```<code>    .ppcont{width:100px;}
</code>```

Now the popup should load correctly and it solves the need for updates or closing/opening again.

Title: Leaflet: adjust popup to picture size

Body:
I'm trying to include pictures in my leaflet popups, but the popup-size doesn't adjust to the picture size. I found a solution to this on github:

https://github.com/Leaflet/Leaflet/issues/724

While that solution fixes the size of the popup, the result is shifted and the popup doesn't show up centered over the icon/marker... Any way to change that?

.leaflet-popup-content {
     width:auto !important;
}

Also the other proposed solution (setting the maxWidth on the popup) doesn't help in my case. The popup width keeps on being the default width of 300px...

function pop_Fotos(feature, layer) {
     var popupContent = '<img style="max-height:500px;max-width:500px;" src="...");
     layer.bindPopup(popupContent, {maxWidth: 500, closeOnClick: true});
}

Body:
None of the before added answers worked for me, but I came upon a quite simple solution (the link of which I can no longer find). Just wrap your image in a div:

    <div class='ppcont'><img src='yourimg.jpg' /></div>

And add a simple css rule that corresponds to the image width:

    .ppcont{width:100px;}

Now the popup should load correctly and it solves the need for updates or closing/opening again.


问:
Immer reducer does not work with Typescript
I have a problem with reducer created by immer.js in TypeScript.

I don't understand the following:

When I use an object literal {} in initial state immutability works fine but once

```<code>const byId = (state = {}, action) =>
    produce(state, draft => {
        switch (action.type) {
            case RECEIVE_PRODUCTS:
               ...
)
        }
    })
</code>```

I change literal to instance of object immutability stop works

```<code>const byId = (state = new SomeObject(), action) =>
    produce(state, draft => {
        switch (action.type) {
            case RECEIVE_PRODUCTS:
               ...
)
        }
    })
</code>```

Can you someone idea why?

Thanks..

答:
I have created parent object

```<code>export class Immerable {
  public [immerable] = true;
}
</code>```

and all classes which I need to use within produce function has this parent. Thanks.

Body:
I have a problem with reducer created by immer.js in TypeScript.

I don't understand the following:

When I use an object literal {} in initial state immutability works fine but once

const byId = (state = {}, action) =>
    produce(state, draft => {
        switch (action.type) {
            case RECEIVE_PRODUCTS:
               ...
)
        }
    })

I change literal to instance of object immutability stop works

const byId = (state = new SomeObject(), action) =>
    produce(state, draft => {
        switch (action.type) {
            case RECEIVE_PRODUCTS:
               ...
)
        }
    })

Can you someone idea why?

Thanks..

Body:
I have created parent object

export class Immerable {
  public [immerable] = true;
}

and all classes which I need to use within produce function has this parent. Thanks.


问:
How to show a progress dialog while waiting for share intent to pop up
I noticed on older devices that once you do a standard share intent (fb, twitter, email, etc) there is a few second delay until the actual share dialog is popped up.  I was wondering how you would be able to have a progress dialog pop up while you are waiting for this share dialog to show up?

Here is my code:

```<code> private void share(String subject,String body) {
        Intent share = new Intent(Intent.ACTION_SEND);
        share.setType("text/plain");
        share.putExtra(android.content.Intent.EXTRA_SUBJECT, title);
        share.putExtra(android.content.Intent.EXTRA_TEXT, body);
        startActivity(Intent.createChooser(share, "Share via"));
    }
</code>```

答:
You Can try this code:</p>

```<code>void share(String link) {
    final ProgressDialog ringProgressDialog = ProgressDialog.show(this, "", getString(R.string.please_wait), true);
    ringProgressDialog.setCancelable(false);
    new Thread(new Runnable() {
        public void run() {
            try {
            // your share method for sharing link or image or anything
                shareTextUrl(link);
            } catch (Exception e) {
            }
            ringProgressDialog.dismiss();
        }
    }).start();
    ringProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface dialog) {

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

Body:
I noticed on older devices that once you do a standard share intent (fb, twitter, email, etc) there is a few second delay until the actual share dialog is popped up.  I was wondering how you would be able to have a progress dialog pop up while you are waiting for this share dialog to show up?

Here is my code:

 private void share(String subject,String body) {
        Intent share = new Intent(Intent.ACTION_SEND);
        share.setType("text/plain");
        share.putExtra(android.content.Intent.EXTRA_SUBJECT, title);
        share.putExtra(android.content.Intent.EXTRA_TEXT, body);
        startActivity(Intent.createChooser(share, "Share via"));
    }

Body:
You Can try this code:

void share(String link) {
    final ProgressDialog ringProgressDialog = ProgressDialog.show(this, "", getString(R.string.please_wait), true);
    ringProgressDialog.setCancelable(false);
    new Thread(new Runnable() {
        public void run() {
            try {
            // your share method for sharing link or image or anything
                shareTextUrl(link);
            } catch (Exception e) {
            }
            ringProgressDialog.dismiss();
        }
    }).start();
    ringProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface dialog) {

        }
    });
}


问:
How do I reinterpret_cast between any two types?
I would like to re-declare the type of a given variable, but unfortunately reinterpret_cast<> does not help here. This line:

```<code>reinterpret_cast<std::vector<double>>(std::string("Hello"));
</code>```

results in the following compiler error:

```<code>invalid cast from type 'std::string {aka std::basic_string<char>}' to type 'std::vector<double>'
</code>```

Is there a different, clean approach?

Notes:

I know that reinterpret_cast<> is not a proper conversion. I really do only want to re-declare the type here. Some code around this line will make sure it is only performed when appropriate

Why actually does this line above not work?

I am aware of this option, which I think is too messy: *reinterpret_cast(&OldType)

Edit/Some context: This line will be part of a templated function, with:

```<code>reinterpret_cast<T>(std::string())
</code>```

For T == std::string this is completely fine, but unfortunately the compiler will also try to instantiate (but at runtime never use) it for T == std::vector<>. And this is C++11, so there is no static_if.

答:
You want to construct a container from a string literal.

Use a different constructor overload, e.g.

```<code>template< class InputIt >
basic_string( InputIt first, InputIt last, const Allocator& alloc = Allocator());
</code>```

Which is compatible with

```<code>template< class InputIt >
vector( InputIt first, InputIt last, const Allocator& alloc = Allocator() );
</code>```

Thusly

```<code>char hello[] = "Hello";
T{ std::begin(hello), std::end(hello) }
</code>```

See it live

Body:
I would like to re-declare the type of a given variable, but unfortunately reinterpret_cast<> does not help here. This line:

reinterpret_cast<std::vector<double>>(std::string("Hello"));

results in the following compiler error:

invalid cast from type 'std::string {aka std::basic_string<char>}' to type 'std::vector<double>'

Is there a different, clean approach?

Notes:

I know that reinterpret_cast<> is not a proper conversion. I really do only want to re-declare the type here. Some code around this line will make sure it is only performed when appropriate

Why actually does this line above not work?

I am aware of this option, which I think is too messy: *reinterpret_cast(&OldType)

Edit/Some context: This line will be part of a templated function, with:

reinterpret_cast<T>(std::string())

For T == std::string this is completely fine, but unfortunately the compiler will also try to instantiate (but at runtime never use) it for T == std::vector<>. And this is C++11, so there is no static_if.

Body:
You want to construct a container from a string literal.

Use a different constructor overload, e.g.

template< class InputIt >
basic_string( InputIt first, InputIt last, const Allocator& alloc = Allocator());

Which is compatible with

template< class InputIt >
vector( InputIt first, InputIt last, const Allocator& alloc = Allocator() );

Thusly

char hello[] = "Hello";
T{ std::begin(hello), std::end(hello) }

See it live


问:
undefined reference when including a local header file in android NDK
I construct a simple android application which uses ndk with JNI.
The application has onw .cpp(debugTest.cpp) file that is used to link java and c++ with jni and another .c(javaEssentials.c) file with it's header(javaEssentials.h).
When I include in the .cpp file the .c file(#include "javaEssentials.c") no error is reported when compiling.
When I include in the .cpp file the header the compiler reports error of undefined reference of the functions the .c file has.It is real strange problem and I can't understand why is this happening.
As usual I have an include declaration of the header file in the .c file.

My android.mk is:

```<code># build file written to describe the C and C++ source files to the Android NDK

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := debugTest
LOCAL_SRC_FILES := debugTest.cpp

include $(BUILD_SHARED_LIBRARY)
</code>```

Any ideas why this is happening ?

答: You should to #include the .h files, not .c or .cpp.</p>

Body:
I construct a simple android application which uses ndk with JNI.
The application has onw .cpp(debugTest.cpp) file that is used to link java and c++ with jni and another .c(javaEssentials.c) file with it's header(javaEssentials.h).
When I include in the .cpp file the .c file(#include "javaEssentials.c") no error is reported when compiling.
When I include in the .cpp file the header the compiler reports error of undefined reference of the functions the .c file has.It is real strange problem and I can't understand why is this happening.
As usual I have an include declaration of the header file in the .c file.

My android.mk is:

# build file written to describe the C and C++ source files to the Android NDK

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := debugTest
LOCAL_SRC_FILES := debugTest.cpp

include $(BUILD_SHARED_LIBRARY)

Any ideas why this is happening ?


问:
Swift: conformance to the Protocol with Generic method with "where" clause
Summary:

I'd like to create a Class<T> which would have a corresponding ClassDelegate protocol with func<T> in it.

Goal:

To reuse a single object and behavior with multiple object classes. Receive a delegate callback with already a specialized class, without the need to cast the object to a specific class to work with it.

Sample Code:

A protocol with a generic method:

```<code>protocol GenericTableControllerDelegate: AnyObject {
    func controller<T>(controller: GenericTableController<T>, didSelect value: T)
}
</code>```

A generic base UITableViewController subclass:

```<code>open class GenericTableController<DataType>: UITableViewController {
    weak var delegate: GenericTableControllerDelegate?
    var data = [DataType]()

    open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let item = data[indexPath.row]
        delegate?.controller(controller: self, didSelect: item)
    }
}
</code>```

A specialized version of the GenericTableController:

```<code>final class SpecializedTableController: GenericTableController<NSObject> {}
</code>```

Client of the SpecializedTableController - achieves the result, but requires type-casting to be able to access the specialized data type:

```<code>final class ClientOfTableController: UIViewController, GenericTableControllerDelegate {
    // Works OK
    func controller<T>(controller: GenericTableController<T>, didSelect value: T) {
        if let value = value as? NSObject {
            // Requires unwrapping and casting
        }
    }
}
</code>```

Client of the SpecializedTableController, with "where" requirement - the only problem that it doesn't compile

```<code>final class AnotherClientOfTableController: UIViewController, GenericTableControllerDelegate {
    // Works OK
    func controller<T>(controller: GenericTableController<T>, didSelect value: T) where T: NSObject {
        // `value` is String
    }
}
</code>```

Type 'AnotherClientOfTableController' does not conform to protocol
  'GenericTableControllerDelegate' Do you want to add protocol stubs?

Is there a way to have a protocol with a generic method and being able to have a concrete (specialized) type in that method implementation?

Are there close alternatives achieving satisfying similar requirement (having a generic class but being able to handle a concrete type in the delegate callback)?

答:
On of the possible ways to resolve this situation is to use callbacks instead of delegation. By passing not a closure but a instance method it looks almost identical to the delegation pattern:

```<code>open class GenericTableController2<DataType>: UITableViewController {
    var onSelect: ((DataType) -> Void)?
    var data = [DataType]()

    open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let item = data[indexPath.row]
        onSelect?(item)
    }
}

final class CallbackExample: GenericTableController2<NSObject> {
}

final class CallBackClient: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let vc = CallbackExample()
        vc.onSelect = handleSelection
    }

    func handleSelection(_ object: NSObject) {

    }
}
</code>```

As a benefit, the code is pretty straightforward and doesn't involve any advanced workarounds for Swift's type system which often has some issues when dealing with generics and protocols.

Body:
Summary:

I'd like to create a Class<T> which would have a corresponding ClassDelegate protocol with func<T> in it.

Goal:

To reuse a single object and behavior with multiple object classes. Receive a delegate callback with already a specialized class, without the need to cast the object to a specific class to work with it.

Sample Code:

A protocol with a generic method:

protocol GenericTableControllerDelegate: AnyObject {
    func controller<T>(controller: GenericTableController<T>, didSelect value: T)
}

A generic base UITableViewController subclass:

open class GenericTableController<DataType>: UITableViewController {
    weak var delegate: GenericTableControllerDelegate?
    var data = [DataType]()

    open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let item = data[indexPath.row]
        delegate?.controller(controller: self, didSelect: item)
    }
}

A specialized version of the GenericTableController:

final class SpecializedTableController: GenericTableController<NSObject> {}

Client of the SpecializedTableController - achieves the result, but requires type-casting to be able to access the specialized data type:

final class ClientOfTableController: UIViewController, GenericTableControllerDelegate {
    // Works OK
    func controller<T>(controller: GenericTableController<T>, didSelect value: T) {
        if let value = value as? NSObject {
            // Requires unwrapping and casting
        }
    }
}

Client of the SpecializedTableController, with "where" requirement - the only problem that it doesn't compile

final class AnotherClientOfTableController: UIViewController, GenericTableControllerDelegate {
    // Works OK
    func controller<T>(controller: GenericTableController<T>, didSelect value: T) where T: NSObject {
        // `value` is String
    }
}

Type 'AnotherClientOfTableController' does not conform to protocol
  'GenericTableControllerDelegate' Do you want to add protocol stubs?

Is there a way to have a protocol with a generic method and being able to have a concrete (specialized) type in that method implementation?

Are there close alternatives achieving satisfying similar requirement (having a generic class but being able to handle a concrete type in the delegate callback)?

Body:
On of the possible ways to resolve this situation is to use callbacks instead of delegation. By passing not a closure but a instance method it looks almost identical to the delegation pattern:

open class GenericTableController2<DataType>: UITableViewController {
    var onSelect: ((DataType) -> Void)?
    var data = [DataType]()

    open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let item = data[indexPath.row]
        onSelect?(item)
    }
}

final class CallbackExample: GenericTableController2<NSObject> {
}

final class CallBackClient: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let vc = CallbackExample()
        vc.onSelect = handleSelection
    }

    func handleSelection(_ object: NSObject) {

    }
}

As a benefit, the code is pretty straightforward and doesn't involve any advanced workarounds for Swift's type system which often has some issues when dealing with generics and protocols.


问:
Delete rows from multiple tables due to data from one table
I have multiple tables that I need to delete rows from and they are all contingent on data from one table. For instance, I have a Users Table and in the Users Table the Users have a UserId. I am trying to get rid of all the data that is in relation to that one user in all the other tables.

For instance, there is a Members Table and in the Members table, there is a Foreign Key relationship to the Users table so it's tied by the UserId. The Members table can have multiple members associated with the UserId (A User can be members to more than one thing so it's a one to many relationship). Then there is also a Permissions table and in the Permissions table it has a foreign key relationship to the Members table. And in that table the Members can have multiple permissions (A Member can have permissions to more than one thing is that's a one to many relationship).

What I am needing to do is delete all the rows in the Permissions table that are in relation to the all the MemberId's that are in relation to the UserId from the User's Table (i.e. - Bob has a UserId of 7 and in the Members Table he is a Member of 3 things so he has 3 MemberId's associated to his name and in the Permissions Table those 3 MemberIds also have 3 Permissions associated to those 3 MemberIds. I am needing to delete all 9 Permission rows according to those 3 MemberIds, then delete all the 3 Member rows according to the 1 UserId, and then delete the one UserId according to a UserName).

I've tried to Inner Join multiple tables and also connect them with Unions but I am having difficulty of tying all those tables down to that one UserId and carrying that data through the flow of logic.

User has a UserId of 7

User is is associated with 3 MemberId's

The MemberId is associated with multiple PermissionId's

So I need to delete all those PermissionId's (I did a WHERE statement just on the User's MemberId's), all 3 instances of the MemberId's, and the User.

答:
If you are aware of UserID that you want to delete from different table, then this is easy to handle from table Users and Members. You need to use a Sub Query when you will delete records from Permissions table. But if there are relation (PK/FK) established between tables, you need to maintain some sequence as below-

Important Note: Delete is a risky operation unless you have proper Backup. So please try to execute scripts on test data first.

At first you have to delete records from Permission table with following script-

```<code>DELETE FROM Permissions
WHERE MemberID IN
(
    SELECT MemberID FROM Members
    WHERE UserID = 7
)
</code>```

In second step, you have to delete records from Members table as below-

```<code>DELEET FROM Member WHERE UserID = 7
</code>```

In third step, you have to delete users from Users table as below-

```<code>DELETE from Users WHERE UserID = 7
</code>```

Body:
If you are aware of UserID that you want to delete from different table, then this is easy to handle from table Users and Members. You need to use a Sub Query when you will delete records from Permissions table. But if there are relation (PK/FK) established between tables, you need to maintain some sequence as below-

Important Note: Delete is a risky operation unless you have proper Backup. So please try to execute scripts on test data first.

At first you have to delete records from Permission table with following script-

DELETE FROM Permissions
WHERE MemberID IN
(
    SELECT MemberID FROM Members
    WHERE UserID = 7
)

In second step, you have to delete records from Members table as below-

DELEET FROM Member WHERE UserID = 7

In third step, you have to delete users from Users table as below-

DELETE from Users WHERE UserID = 7


问:
How to finish current component while navigating to next component in react native
Hi I am trying to navigate to next component using navigate function. I am using react-navigation for the navigation among multiple components.

Suppose I have index.android.js and DashboardScreen.js component. I am trying to navigate to DashboardScreen.js component from index component.

It is navigating but index component always retain in component stack. when I press back then it opens index.android.js which should not be. Does anyone know how to manage this in react-native. In Android, finish() works for this.

```<code>navigate("DashboardScreen");
</code>```

When I am navigating from SplashScreen to EnableNotification then SplashScreen should be destroyed, if I am navigating from EnableNotification to CreateMessage then EnableNotification should be destroyed and if I am navigating from CreateMessage to DashboardScreen then CreateMessage should be destroyed. As of now no component is being destroyed.

index.android.js

```<code>class SplashScreen extends Component {
  render() {
    if (__DEV__) {
      console.disableYellowBox = true;
    }

    const { navigate } = this.props.navigation;

    AsyncStorage.getItem("@ProductTour:key").then(value => {
      console.log(value);
      if (value) {
        navigate("DashboardScreen");
      }
    });

    return (
     ....
    );
  }
}

const App = StackNavigator(
  {
    Splash: {
      screen: SplashScreen,
      navigationOptions: {
        header: {
          visible: false
        }
      }
    },
    EnableNotification: {
      screen: EnableNotificationScreen,
      navigationOptions: {
        header: {
          visible: false
        }
      }
    },
    CreateMessage: {
      screen: CreateMessageScreen,
      navigationOptions: {
        header: {
          visible: false
        }
      }
    },
    DashboardScreen: {
      screen: DashboardScreen,
      navigationOptions: {
        header: {
          visible: false
        }
      }
    }
  },
  {
    initialRouteName: "Splash"
  }
);
</code>```

答:
Just use 'replace' in place of 'navigate'

```<code>this.props.navigation.replace('Your Next Component Name')
</code>```

Body:
Hi I am trying to navigate to next component using navigate function. I am using react-navigation for the navigation among multiple components.

Suppose I have index.android.js and DashboardScreen.js component. I am trying to navigate to DashboardScreen.js component from index component.

It is navigating but index component always retain in component stack. when I press back then it opens index.android.js which should not be. Does anyone know how to manage this in react-native. In Android, finish() works for this.

navigate("DashboardScreen");

When I am navigating from SplashScreen to EnableNotification then SplashScreen should be destroyed, if I am navigating from EnableNotification to CreateMessage then EnableNotification should be destroyed and if I am navigating from CreateMessage to DashboardScreen then CreateMessage should be destroyed. As of now no component is being destroyed.

index.android.js

class SplashScreen extends Component {
  render() {
    if (__DEV__) {
      console.disableYellowBox = true;
    }

    const { navigate } = this.props.navigation;

    AsyncStorage.getItem("@ProductTour:key").then(value => {
      console.log(value);
      if (value) {
        navigate("DashboardScreen");
      }
    });

    return (
     ....
    );
  }
}

const App = StackNavigator(
  {
    Splash: {
      screen: SplashScreen,
      navigationOptions: {
        header: {
          visible: false
        }
      }
    },
    EnableNotification: {
      screen: EnableNotificationScreen,
      navigationOptions: {
        header: {
          visible: false
        }
      }
    },
    CreateMessage: {
      screen: CreateMessageScreen,
      navigationOptions: {
        header: {
          visible: false
        }
      }
    },
    DashboardScreen: {
      screen: DashboardScreen,
      navigationOptions: {
        header: {
          visible: false
        }
      }
    }
  },
  {
    initialRouteName: "Splash"
  }
);

Body:
Just use 'replace' in place of 'navigate'

this.props.navigation.replace('Your Next Component Name')


问:
Not In operator eliminates NULL values rows in a table
I would like to retrieve all rows with values except 1,2,3,4,5 in my COLUMNA in TABLEA .

```<code>SELECT * FROM TABLEA WHERE COLUMNA NOT IN (1,2,3,4,5)
</code>```

But this eliminates the rows with NULL values in COLUMNA too.

I don't want to eliminate NULL values rows and would like to include those rows in the resultset.

Alternatively, I can try below query for the same

```<code>SELECT * FROM TABLEA WHERE COLUMNA NOT IN (1,2,3,4,5) OR COLUMNA  IS NULL.
</code>```

But I would like to know, why is it necessary to add this OR condition?

答:
Try the following:

SELECT * FROM TABLEA WHERE ISNULL(COLUMNA,0) NOT IN (1,2,3,4,5)

Body:
I would like to retrieve all rows with values except 1,2,3,4,5 in my COLUMNA in TABLEA .

SELECT * FROM TABLEA WHERE COLUMNA NOT IN (1,2,3,4,5)

But this eliminates the rows with NULL values in COLUMNA too.

I don't want to eliminate NULL values rows and would like to include those rows in the resultset.

Alternatively, I can try below query for the same

SELECT * FROM TABLEA WHERE COLUMNA NOT IN (1,2,3,4,5) OR COLUMNA  IS NULL.

But I would like to know, why is it necessary to add this OR condition?


问:
Avoid automatic servlet mapping for a Servlet created as a @Bean in Spring Boot
I have a servlet to which I need to supply dependencies via autowiring (it's a class from an external library, I cannot change its code). I try to register it as a bean and later register it using programmatic registration (ServletContextInitializer). Here is what I have:

```<code>@Configuration
public class MyConfiguration {
    @Bean
    public MyServlet myServlet() {
        return new MyServlet();
    }
}
</code>```

Also, SpringMVC-related autoconfiguration creates a usual DispatcherServlet and maps it at /.

When I try to start the application, I get the following:

Caused by: java.lang.IllegalStateException: Multiple servlets map to path /: dispatcherServlet[mapped:JAVAX_API:null],myServlet[mapped:JAVAX_API:null]

So it looks like Spring Boot (or Spring itself?) automatically maps the servlet at the default /. I would like to avoid the mapping at all as I just need to create the servlet instance; I will register it myself later.

Can this be done?

答:
you should use a ServletRegistrationBean then you can provide an extra mapping

```<code>@Bean
public MyServlet myServlet() {
    return new MyServlet();
}

@Bean
public ServletRegistrationBean myServletRegistration(MyServlet myServlet) {
    ServletRegistrationBean registration = new ServletRegistrationBean(myServlet,
            "/myservlet/*");
    registration.setLoadOnStartup(1);
    return registration;
}

</code>```

Body:
I have a servlet to which I need to supply dependencies via autowiring (it's a class from an external library, I cannot change its code). I try to register it as a bean and later register it using programmatic registration (ServletContextInitializer). Here is what I have:

@Configuration
public class MyConfiguration {
    @Bean
    public MyServlet myServlet() {
        return new MyServlet();
    }
}

Also, SpringMVC-related autoconfiguration creates a usual DispatcherServlet and maps it at /.

When I try to start the application, I get the following:

Caused by: java.lang.IllegalStateException: Multiple servlets map to path /: dispatcherServlet[mapped:JAVAX_API:null],myServlet[mapped:JAVAX_API:null]

So it looks like Spring Boot (or Spring itself?) automatically maps the servlet at the default /. I would like to avoid the mapping at all as I just need to create the servlet instance; I will register it myself later.

Can this be done?

Body:
you should use a ServletRegistrationBean then you can provide an extra mapping

@Bean
public MyServlet myServlet() {
    return new MyServlet();
}

@Bean
public ServletRegistrationBean myServletRegistration(MyServlet myServlet) {
    ServletRegistrationBean registration = new ServletRegistrationBean(myServlet,
            "/myservlet/*");
    registration.setLoadOnStartup(1);
    return registration;
}


问:
Get User-Agent and Timezone in mixins
I am creating a mixin for a model on 'create' hook. I want to access the user-agent and user timezone information.

I tried using LoopBackContext as well. But it is not much of a help as I couldn't find object containing these information.

```<code>var loopBackContext = require('loopback-context');

module.exports = function Request(Model, options) {
  Model.observe('access', function event(ctx, next) {
   var httpContext = loopBackContext.getCurrentContext();
    //access user-agent and timezone
    next();
  });
};
</code>```

答:
Please note that loopback-context does not work very reliably, we recommend to pass context via options object as explained in https://loopback.io/doc/en/lb3/Using-current-context.html.

The ctx argument passed to operation hooks like access is yet another type of a context object, see the docs on Operation hooks.

To access additional request headers, you should also override Model's createOptionsFromRemotingContext method, see https://loopback.io/doc/en/lb3/Using-current-context.html#override-createoptionsfromremotingcontext-in-your-model

module.exports = function Request(Model, options) {
  Model.createOptionsFromRemotingContext = function(ctx) {
    const base = this.base.createOptionsFromRemotingContext(ctx);
    return {
      ...base,
      userAgent: req.headers['user-agent'],
      // etc.
    };
  });

  Model.observe('access', function event(ctx, next) {
    const options = ctx.options || {};
    // options contains data created by Model.createOptionsFromRemotingContext
    // but only when invoked via REST API.
    // when called from JavaScript (e.g. from unit-tests), options are exactly
    // as provided by the caller (often undefined).
    const userAgent = ctx.options && ctx.options.userAgent;
    // access user-agent and timezone
    next();
  });
};
```

Title: Get User-Agent and Timezone in mixins

Body:
I am creating a mixin for a model on 'create' hook. I want to access the user-agent and user timezone information.

I tried using LoopBackContext as well. But it is not much of a help as I couldn't find object containing these information.

var loopBackContext = require('loopback-context');

module.exports = function Request(Model, options) {
  Model.observe('access', function event(ctx, next) {
   var httpContext = loopBackContext.getCurrentContext();
    //access user-agent and timezone
    next();
  });
};


问:
mongoose - array of subdocument are not saved in parent document
I'm trying to push subdocuments into a parent document using push() method.
After that, I want to save the parent document calling save() method on it. But the result is an empty array.

I've also tried to call parent.markModified('children') before saving the parent doc, but it makes no difference.

Below is my Schemas and the code that should save the subdocuments :

Schema :

const profileSessionSchema = mongoose.Schema({
    firstName: { type: String, trim:true},
...
   realisations : [realisationSchema],
 });
ProfileSession = mongoose.model('ProfileSession',profileSessionSchema);

const realisationSchema = mongoose.Schema({
   profileId :{ type: mongoose.Schema.Types.ObjectId, ref: 'ProfileSession'},
   ...
   type : { type: String, enum:conf.wallTypes, required:true, default:'classic'},
});
Realisation = mongoose.model('Realisation', realisationSchema);

```

<pre class="lang-js prettyprint-override"><code>ProfileSession.create(profileData,function(err,profile){
   for(j=0;j<realisations.length;j++){  // realisations array is not empty
     var r = Realisation(realisations[j])
     r.save(function(a,real){
        profile.realisations.push(real)
     })
   }

   profile.markModified('realisations')
   profile.save()
})
</code>```

The profile document is indeed created in DB, but without the realisations subdocuments. I've found plenty of subjects about this, and it appears that the method markModified should solve the issue. But it does not in my case and I can't understand why...

Thank you for you help.
Cheers

答:
callback won't wait its non-blocking so it will immediately execute profile.save  before push anything into array, you should try to save it inside the callback or you should use async/await. I am posting both solution where we will save profile inside of callback and using async/await. I would prefer you using async/await. see both solution below :

within callback:

ProfileSession.create(profileData, function(err, profile) {
  for (j = 0; j < realisations.length; j++) { // realisations array is not empty
    var r = Realisation(realisations[j])
    r.save(function(a, real) {
      profile.realisations.push(real)
      profile.markModified('realisations')
      profile.save()
    })
  }

})```
</div>
</div>
</p>

<p><strong>with async/await :</strong></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>async function foo() {
  let newProfileData = await new ProfileSession(profileData)
  let profile = newProfileData.save();
  for (let j = 0; j < realisations.length; j++) { // realisations array is not empty
    let r = new Realisation(realisations[j])
    let real = await r.save();
    profile.realisations.push(real);
    profile.markModified('realisations')
    profile.save()
  }
}
foo()</code>```

Body:
I'm trying to push subdocuments into a parent document using push() method.
After that, I want to save the parent document calling save() method on it. But the result is an empty array.

I've also tried to call parent.markModified('children') before saving the parent doc, but it makes no difference.

Below is my Schemas and the code that should save the subdocuments :

Schema :

const profileSessionSchema = mongoose.Schema({
    firstName: { type: String, trim:true},
...
   realisations : [realisationSchema],
 });
ProfileSession = mongoose.model('ProfileSession',profileSessionSchema);

const realisationSchema = mongoose.Schema({
   profileId :{ type: mongoose.Schema.Types.ObjectId, ref: 'ProfileSession'},
   ...
   type : { type: String, enum:conf.wallTypes, required:true, default:'classic'},
});
Realisation = mongoose.model('Realisation', realisationSchema);

ProfileSession.create(profileData,function(err,profile){
   for(j=0;j<realisations.length;j++){  // realisations array is not empty
     var r = Realisation(realisations[j])
     r.save(function(a,real){
        profile.realisations.push(real)
     })
   }

   profile.markModified('realisations')
   profile.save()
})

The profile document is indeed created in DB, but without the realisations subdocuments. I've found plenty of subjects about this, and it appears that the method markModified should solve the issue. But it does not in my case and I can't understand why...

Thank you for you help.
Cheers

Body:
callback won't wait its non-blocking so it will immediately execute profile.save  before push anything into array, you should try to save it inside the callback or you should use async/await. I am posting both solution where we will save profile inside of callback and using async/await. I would prefer you using async/await. see both solution below :

within callback:

ProfileSession.create(profileData, function(err, profile) {
  for (j = 0; j < realisations.length; j++) { // realisations array is not empty
    var r = Realisation(realisations[j])
    r.save(function(a, real) {
      profile.realisations.push(real)
      profile.markModified('realisations')
      profile.save()
    })
  }

})

with async/await :

async function foo() {
  let newProfileData = await new ProfileSession(profileData)
  let profile = newProfileData.save();
  for (let j = 0; j < realisations.length; j++) { // realisations array is not empty
    let r = new Realisation(realisations[j])
    let real = await r.save();
    profile.realisations.push(real);
    profile.markModified('realisations')
    profile.save()
  }
}
foo()


问:
how to identify query statement has a subquery in it?
Developing an C# project for SQL Training and giving different exercises based on training on each topic. One of the exercise is to write a query using Sub-Query.  which needs to be evaluated whether the user has used/implemented Sub query in the Query Statment.

Q: Write a sql query to show the SalesOrderID,LineTotal,average LineTotal from the Sales.SalesOrderDetail table using Sub query

```<code>Select SalesOrderID,LineTotal [LineTotal],
(Select AVG(LineTotal) from Sales.SalesOrderDetail) as [AverageLineTotal]
from Sales.SalesOrderDetail
</code>```

[AverageLineTotal] is an sub query.

Can we identify it by any means?? like execution plan Or SP to identify it has an sub query in the statement

Is there any way to identify it through execution Plans??

答:
Parsing ad-hoc scripts is inherently complex due to the plethora T-SQL constructs and options. That being said, a robust method for targeted use cases is parsing scripts with the Microsoft.SqlServer.TransactSql.ScriptDom.

Below is an example PowerShell script that uses the script DOM assembly from the official Microsoft Dacfx NuGet package, downloading and extracting it if needed.

```<code># Add TSqlScript DOM assembly reference, downloading and extracting to the specified location if needed
$scriptDomAssemblyPath = "C:\Temp\Microsoft.SqlServer.TransactSql.ScriptDom.dll"
$scriptDomNuGetUrl = "https://www.nuget.org/api/v2/package/Microsoft.SqlServer.DacFx.x64/150.4384.2"
if(![System.IO.File]::Exists($scriptDomAssemblyPath)) {
    $response = Invoke-WebRequest -Uri $scriptDomNuGetUrl
    if ($response.StatusCode -ne 200) {
        throw "Unable to download Microsoft.SqlServer.TransactSql.ScriptDom NuGet package: $response.StatusCode : $response.StatusDescription"
    }
    $tempZipFilePath = "$([System.IO.Path]::GetTempPath())/$([System.IO.Path]::GetRandomFileName()).zip"
    [System.IO.File]::WriteAllBytes($tempZipFilePath, $response.Content)
    $response.BaseResponse.Dispose()
    $tempUnzipFolderPath = "$([System.IO.Path]::GetTempPath())/$([System.IO.Path]::GetRandomFileName())"
    Expand-Archive -Path $tempZipFilePath -DestinationPath $tempUnzipFolderPath
    $tempZipFilePath | Remove-Item
    Move-Item "$tempUnzipFolderPath\lib\net46\Microsoft.SqlServer.TransactSql.ScriptDom.dll" "$scriptDomAssemblyPath"
    $tempUnzipFolderPath | Remove-Item -Recurse
}
Add-Type -Path $scriptDomAssemblyPath

# script to be parsed
$scriptText = @"
Select SalesOrderID,LineTotal [LineTotal],
(Select AVG(LineTotal) from Sales.SalesOrderDetail) as [AverageLineTotal]
from Sales.SalesOrderDetail
"@

#parse script
$parser = New-Object Microsoft.SqlServer.TransactSql.ScriptDom.TSql150Parser($true)
$parseErrors = New-Object System.Collections.Generic.List[Microsoft.SqlServer.TransactSql.ScriptDom.ParseError]
$scriptReader = New-Object System.IO.StringReader($scriptText)
$script = $parser.Parse($scriptReader, [ref]$parseErrors)
if($parseErrors.Count -gt 0) {
    throw "$($parseErrors.Count) parsing errors"
}

# sanity check for expected SELECT query
if(($script.Batches.Count -ne 1) -or ($script.Batches[0].Statements.Count -ne 1) -or ($script.Batches[0].Statements[0].QueryExpression -eq $null)) {
    throw "script with single SELECT statement expected"
}

# find scalar subquery expression in select list
$subQueryFound = $false
foreach($selectElement in $script.Batches[0].Statements[0].QueryExpression.SelectElements) {
    if($selectElement.Expression.ToString() -eq "Microsoft.SqlServer.TransactSql.ScriptDom.ScalarSubquery") {
        $subQueryFound = $true
        break
    }
}

# show if subquery was used
if($subQueryFound) {
    Write-Host "A subquery is used"
}
else {
    Write-Host "A subquery is not used"
}
</code>```

Body:
Developing an C# project for SQL Training and giving different exercises based on training on each topic. One of the exercise is to write a query using Sub-Query.  which needs to be evaluated whether the user has used/implemented Sub query in the Query Statment.

Q: Write a sql query to show the SalesOrderID,LineTotal,average LineTotal from the Sales.SalesOrderDetail table using Sub query

Select SalesOrderID,LineTotal [LineTotal],
(Select AVG(LineTotal) from Sales.SalesOrderDetail) as [AverageLineTotal]
from Sales.SalesOrderDetail

[AverageLineTotal] is an sub query.

Can we identify it by any means?? like execution plan Or SP to identify it has an sub query in the statement

Is there any way to identify it through execution Plans??

Body:
Parsing ad-hoc scripts is inherently complex due to the plethora T-SQL constructs and options. That being said, a robust method for targeted use cases is parsing scripts with the Microsoft.SqlServer.TransactSql.ScriptDom.

Below is an example PowerShell script that uses the script DOM assembly from the official Microsoft Dacfx NuGet package, downloading and extracting it if needed.

# Add TSqlScript DOM assembly reference, downloading and extracting to the specified location if needed
$scriptDomAssemblyPath = "C:\Temp\Microsoft.SqlServer.TransactSql.ScriptDom.dll"
$scriptDomNuGetUrl = "https://www.nuget.org/api/v2/package/Microsoft.SqlServer.DacFx.x64/150.4384.2"
if(![System.IO.File]::Exists($scriptDomAssemblyPath)) {
    $response = Invoke-WebRequest -Uri $scriptDomNuGetUrl
    if ($response.StatusCode -ne 200) {
        throw "Unable to download Microsoft.SqlServer.TransactSql.ScriptDom NuGet package: $response.StatusCode : $response.StatusDescription"
    }
    $tempZipFilePath = "$([System.IO.Path]::GetTempPath())/$([System.IO.Path]::GetRandomFileName()).zip"
    [System.IO.File]::WriteAllBytes($tempZipFilePath, $response.Content)
    $response.BaseResponse.Dispose()
    $tempUnzipFolderPath = "$([System.IO.Path]::GetTempPath())/$([System.IO.Path]::GetRandomFileName())"
    Expand-Archive -Path $tempZipFilePath -DestinationPath $tempUnzipFolderPath
    $tempZipFilePath | Remove-Item
    Move-Item "$tempUnzipFolderPath\lib\net46\Microsoft.SqlServer.TransactSql.ScriptDom.dll" "$scriptDomAssemblyPath"
    $tempUnzipFolderPath | Remove-Item -Recurse
}
Add-Type -Path $scriptDomAssemblyPath

# script to be parsed
$scriptText = @"
Select SalesOrderID,LineTotal [LineTotal],
(Select AVG(LineTotal) from Sales.SalesOrderDetail) as [AverageLineTotal]
from Sales.SalesOrderDetail
"@

#parse script
$parser = New-Object Microsoft.SqlServer.TransactSql.ScriptDom.TSql150Parser($true)
$parseErrors = New-Object System.Collections.Generic.List[Microsoft.SqlServer.TransactSql.ScriptDom.ParseError]
$scriptReader = New-Object System.IO.StringReader($scriptText)
$script = $parser.Parse($scriptReader, [ref]$parseErrors)
if($parseErrors.Count -gt 0) {
    throw "$($parseErrors.Count) parsing errors"
}

# sanity check for expected SELECT query
if(($script.Batches.Count -ne 1) -or ($script.Batches[0].Statements.Count -ne 1) -or ($script.Batches[0].Statements[0].QueryExpression -eq $null)) {
    throw "script with single SELECT statement expected"
}

# find scalar subquery expression in select list
$subQueryFound = $false
foreach($selectElement in $script.Batches[0].Statements[0].QueryExpression.SelectElements) {
    if($selectElement.Expression.ToString() -eq "Microsoft.SqlServer.TransactSql.ScriptDom.ScalarSubquery") {
        $subQueryFound = $true
        break
    }
}

# show if subquery was used
if($subQueryFound) {
    Write-Host "A subquery is used"
}
else {
    Write-Host "A subquery is not used"
}


问:
Use transaction in node-oracledb
I need to execute 3 different update statements in a transaction. I am using node-oracle package. Is there an example which shows how transactions are to be done?</p>

答:
There are examples in the node-oracledb GitHub repo.  The examples have been updated to use Node.js 8's async/await style, making it easier to understand and get correct (but don't forget to use await).  Also read the manual.

The example you want is insert1.js which shows 3 statements forming a transaction.  The first two statements don't commit but the last uses autoCommit (which saves the cost of an explicit commit()):

```<code>result = await connection.execute(
  `INSERT INTO test VALUES (:id, :nm)`,
  { id : {val: 1 }, nm : {val: 'Chris'} });

result = await connection.execute(
  `INSERT INTO test VALUES (:id, :nm)`,
  [2, 'Alison']);

result = await connection.execute(
  `UPDATE test SET name = :nm`,
  ['Bambi'],
  { autoCommit: true });  // commit once for all DML in the script
</code>```

Title: Use transaction in node-oracledb

Body:
There are examples in the node-oracledb GitHub repo.  The examples have been updated to use Node.js 8's async/await style, making it easier to understand and get correct (but don't forget to use await).  Also read the manual.

The example you want is insert1.js which shows 3 statements forming a transaction.  The first two statements don't commit but the last uses autoCommit (which saves the cost of an explicit commit()):

result = await connection.execute(
  `INSERT INTO test VALUES (:id, :nm)`,
  { id : {val: 1 }, nm : {val: 'Chris'} });

result = await connection.execute(
  `INSERT INTO test VALUES (:id, :nm)`,
  [2, 'Alison']);

result = await connection.execute(
  `UPDATE test SET name = :nm`,
  ['Bambi'],
  { autoCommit: true });  // commit once for all DML in the script


问:
HTML unordered list sucks in IE7
I've created a HTML ordered list which looks fine in FF, but pretty awful in IE.
My specific problems with the way IE displays the list are:

List markers are missing

Vertical spacing between list items is very uneven

It seems the superscripts are the cause of (2), but I'm not sure how I can fix this problem (without removing the superscripts).

EDIT: I gave up on my single-list dreams and split the list into 3 separate lists. I've removed the link from the text above to avoid confusing future readers.

Thanks,
Don

答:
If it's the list at the bottom of the page, you've got a bunch of whitespace inside your list tags.  I don't know if that's causing the problem, but you might want to try eliminating it and see if that helps.  The superscripts may also be throwing things off.  Try giving the list itself a line height of 2em (or more) and see if that evens things out.

EDIT: you might also want to play with the left padding/margin on the list items and increase it to see if that brings the list markers back.  I've had to do this with list-based menus to get my menu items to show up in the proper alignment.

OwnerDisplayName: Don

ContentLicense: CC BY-SA 2.5

Title: HTML unordered list sucks in IE7

LastEditorDisplayName: Don

OwnerDisplayName: tvanfosson

LastEditorDisplayName: tvanfosson


问:
WPF/C#: 'Slide to Unlock' feature from iPhone
I just want to ask for your opinion on how to achieve the 'Slide to Unlock' feature from iPhone using Windows Presentation Foundation.

I already came across to this article: iPhone slide to unlock progress bar (part 1), and wondering if you can give me some other resources for a good head start. Thank you.

答:
WPF slider has got one "-" and it is value ,
 always when you move it, value is for example in decimal 1,122213174 so one "-".
But another way to create slider is in Windows forms.

Create trackBar1 ,and maximum = 100 points.
This is for Windows forms application:
On trackBar1_mouse_up:

```<code>if(trackBar1.Value < 100)
  {
    //Animation - slide back dynamicaly.

   for(int i=0;i<=trackBar1.Value;i++){
      int secondVal=trackBar1.Value-i;
      trackBar1.Value=secondVal;
      System.Threading.Thread.Sleep(15);
   }
 }
 if(trackBar1.Value==100)
 {
    //sets enabled to false, then after load cannot move it.
    trackBar1.Enabled=false;
    MessageBox.Show("Done!");
 }
</code>```

And this for WPF Slider: (on PreviewMouseUp)

```<code>  if (Convert.ToInt16(slider1.Value) < 99)
        {
            //Animation - slide back dynamicaly.

            for (int i = 0; i < Convert.ToInt16(slider1.Value); i++)
            {
                int secondVal = Convert.ToInt32(slider1.Value) - i;
                slider1.Value = secondVal;
                System.Threading.Thread.Sleep(10);
                if (secondVal < 2)
                {
                    slider1.Value = 0;
                }
            }
        }
        if (Convert.ToInt16(slider1.Value) > 99)
        {
            //sets enabled to false, then after load cannot move it.
            slider1.IsEnabled = false;
            slider1.Value = 100;
            MessageBox.Show("Done!");
        }
</code>```

Good luck! I hope it helps, try it with slider, but I think application will crash.

Body:
WPF slider has got one "-" and it is value ,
 always when you move it, value is for example in decimal 1,122213174 so one "-".
But another way to create slider is in Windows forms.

Create trackBar1 ,and maximum = 100 points.
This is for Windows forms application:
On trackBar1_mouse_up:

if(trackBar1.Value < 100)
  {
    //Animation - slide back dynamicaly.

   for(int i=0;i<=trackBar1.Value;i++){
      int secondVal=trackBar1.Value-i;
      trackBar1.Value=secondVal;
      System.Threading.Thread.Sleep(15);
   }
 }
 if(trackBar1.Value==100)
 {
    //sets enabled to false, then after load cannot move it.
    trackBar1.Enabled=false;
    MessageBox.Show("Done!");
 }

And this for WPF Slider: (on PreviewMouseUp)

  if (Convert.ToInt16(slider1.Value) < 99)
        {
            //Animation - slide back dynamicaly.

            for (int i = 0; i < Convert.ToInt16(slider1.Value); i++)
            {
                int secondVal = Convert.ToInt32(slider1.Value) - i;
                slider1.Value = secondVal;
                System.Threading.Thread.Sleep(10);
                if (secondVal < 2)
                {
                    slider1.Value = 0;
                }
            }
        }
        if (Convert.ToInt16(slider1.Value) > 99)
        {
            //sets enabled to false, then after load cannot move it.
            slider1.IsEnabled = false;
            slider1.Value = 100;
            MessageBox.Show("Done!");
        }

Good luck! I hope it helps, try it with slider, but I think application will crash.


问:
How to compare two arrays using tensorflow?
I need to compare two arrays and get either true or false,not elementwise result. My code is

```<code>X = tf.constant([0.05, 0.10], dtype=tf.float32, shape=[1, 2])
y = tf.constant([0.01, 0.99], dtype=tf.float32, shape=[1, 2])

equality = tf.equal(X, y)
</code>```

prints [False, False]

my requirement is to get true or false, not an array.

答:
Assuming that you want to return False if any of your values are not equal then you can use the reduce_all operation:

equality = tf.math.reduce_all(tf.equal(X, y))
```

Body:
I need to compare two arrays and get either true or false,not elementwise result. My code is

X = tf.constant([0.05, 0.10], dtype=tf.float32, shape=[1, 2])
y = tf.constant([0.01, 0.99], dtype=tf.float32, shape=[1, 2])

equality = tf.equal(X, y)

prints [False, False]

my requirement is to get true or false, not an array.


问:
How to silent print html content(Receipts)
I am developing a POS system in PHP CodeIgniter, in which i need to print receipts from every transaction. I am able to generate dynamic receipts as per the products selected and able to print them also using iframes.

My issue is that I need to print those receipts silently(Without prompting anything on screen). I tried --kisok-printing also in chrome browser, While using Kiosk it opens the print dialog then automatically print the content with the default printer and the print dialog gets closed.

I even does not need the print dialoge to be shown and print without showing any effect on screen.

Please suggest me a way for the same.

答:
I've sold the same issue using https://github.com/mike42/escpos-php for POS printer (it works great with EPSON TM-T20 only pure php:

```<code><?php
/* Call this file 'hello-world.php' */
require __DIR__ . '/vendor/autoload.php';
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\Printer;
$connector = new FilePrintConnector("php://stdout");
$printer = new Printer($connector);
$printer -> text("Hello World!\n");
$printer -> cut();
$printer -> close();
</code>```

for none POS Printer (if it appear one day you need it) I suggest you try this blog https://www.neodynamic.com/articles/Print-HTML-from-PHP-to-client-printer-without-print-dialog-silently/ notice that I never try it before.
I hope this will help you.

Body:
I've sold the same issue using https://github.com/mike42/escpos-php for POS printer (it works great with EPSON TM-T20 only pure php:

<?php
/* Call this file 'hello-world.php' */
require __DIR__ . '/vendor/autoload.php';
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\Printer;
$connector = new FilePrintConnector("php://stdout");
$printer = new Printer($connector);
$printer -> text("Hello World!\n");
$printer -> cut();
$printer -> close();

for none POS Printer (if it appear one day you need it) I suggest you try this blog https://www.neodynamic.com/articles/Print-HTML-from-PHP-to-client-printer-without-print-dialog-silently/ notice that I never try it before.
I hope this will help you.