问:
can't get returned values in a structure in swift 3
I'm having this code:

```<code>//
//  Measurement.swift
//  BicycleSpeed

    import Foundation
    import CoreBluetooth

    // CSC Measurement
    // https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.csc_measurement.xml
    //
    //  Flags : 1 byte.  Bit 0: Wheel. Bit 1: Crank
    //  Cumulative Wheel revolutions: 4 bytes uint32
    //  Last wheel event time: 2 bytes. uint16 (1/1024s)
    //  Cumulative Crank revolutions: 2 bytes uint16
    //  Last cranck event time: 2 bytes. uint16 (1/1024s)

    struct Measurement : CustomDebugStringConvertible {

      let hasWheel:Bool
      let hasCrank:Bool
      let cumulativeWheel:UInt32
      let lastWheelEventTime:TimeInterval
      let cumulativeCrank:UInt16
      let lastCrankEventTime:TimeInterval
      let wheelSize:UInt32

      init(data:Data, wheelSize:UInt32) {

        self.wheelSize = wheelSize
        // Flags
        var flags:UInt8=0
        (data as NSData).getBytes(&flags, range: NSRange(location: 0, length: 1))

        hasWheel = ((flags & BTConstants.WheelFlagMask) > 0)
        hasCrank = ((flags & BTConstants.CrankFlagMask) > 0)

        var wheel:UInt32=0
        var wheelTime:UInt16=0
        var crank:UInt16=0
        var crankTime:UInt16=0

        var currentOffset = 1
        var length = 0

        if ( hasWheel ) {

          length = MemoryLayout<UInt32>.size
          (data as NSData).getBytes(&wheel, range: NSRange(location: currentOffset, length: length))
          currentOffset += length

          length = MemoryLayout<UInt16>.size
          (data as NSData).getBytes(&wheelTime, range: NSRange(location: currentOffset, length: length))
          currentOffset += length
        }

        if ( hasCrank ) {

          length = MemoryLayout<UInt16>.size
          (data as NSData).getBytes(&crank, range: NSRange(location: currentOffset, length: length))
          currentOffset += length

          length = MemoryLayout<UInt16>.size
          (data as NSData).getBytes(&crankTime, range: NSRange(location: currentOffset, length: length))
          currentOffset += length
        }

        cumulativeWheel     = CFSwapInt32LittleToHost(wheel)
        lastWheelEventTime  = TimeInterval( Double(CFSwapInt16LittleToHost(wheelTime))/BTConstants.TimeScale)
        cumulativeCrank     = CFSwapInt16LittleToHost(crank)
        lastCrankEventTime  = TimeInterval( Double(CFSwapInt16LittleToHost(crankTime))/BTConstants.TimeScale)

      }

      func timeIntervalForCurrentSample( _ current:TimeInterval, previous:TimeInterval ) -> TimeInterval {
        var timeDiff:TimeInterval = 0
        if( current >= previous ) {
            timeDiff = current - previous
        }
        else {
          // passed the maximum value
          timeDiff =  ( TimeInterval((Double( UINT16_MAX) / BTConstants.TimeScale)) - previous) + current
        }
        return timeDiff

      }

      func valueDiffForCurrentSample<T:UnsignedInteger>( _ current:T, previous:T , max:T) -> T {

        var diff:T = 0
        if  ( current >= previous ) {
          diff = current - previous
        }
        else {
           diff = ( max - previous ) + current
        }
        return diff
      }

      func valuesForPreviousMeasurement( _ previousSample:Measurement? ) -> ( cadenceinRPM:Double?, distanceinMeters:Double?, speedInMetersPerSecond:Double?)? {

        var distance:Double?, cadence:Double?, speed:Double?
        guard let previousSample = previousSample else {
          return nil
        }
        if ( hasWheel && previousSample.hasWheel ) {
          let wheelTimeDiff = timeIntervalForCurrentSample(lastWheelEventTime, previous: previousSample.lastWheelEventTime)
          let valueDiff = valueDiffForCurrentSample(cumulativeWheel, previous: previousSample.cumulativeWheel, max: UInt32.max)

          distance = Double( valueDiff * wheelSize) / 1000.0 // distance in meters
          if  distance != nil  &&  wheelTimeDiff > 0 {
            speed = (wheelTimeDiff == 0 ) ? 0 : distance! / wheelTimeDiff // m/s
          }
        }

        if( hasCrank && previousSample.hasCrank ) {
          let crankDiffTime = timeIntervalForCurrentSample(lastCrankEventTime, previous: previousSample.lastCrankEventTime)
          let valueDiff = Double(valueDiffForCurrentSample(cumulativeCrank, previous: previousSample.cumulativeCrank, max: UInt16.max))

          cadence = (crankDiffTime == 0) ? 0 : Double(60.0 * valueDiff / crankDiffTime) // RPM

        }
        print( "Cadence: \(String(describing: cadence)) RPM. Distance: \(String(describing: distance)) meters. Speed: \(String(describing: speed)) Km/h" )
        return ( cadenceinRPM:cadence, distanceinMeters:distance, speedInMetersPerSecond:speed)

      }

      var debugDescription:String {
        get {
            return "Wheel Revs: \(cumulativeWheel). Last wheel event time: \(lastWheelEventTime). Crank Revs: \(cumulativeCrank). Last Crank event time: \(lastCrankEventTime)"
        }
      }

        var myMeasurement = ((Measurement?) -> (cadenceinRPM: Double?, DistanceinMeters: Double?, speedinMetersPerSecond: Double?)).self

        struct dataVariables {

            static var mySpeed = myMeasurement.speedInMetersPerSecond

            static var myCadence : Double?
            static var miDistance : Double?

            static var myLastWheelEventTime : Double? = Measurement.valuesForPreviousMeasurement(lastWheelEventTime)

            static var myLastCrankEventTime : Double? = Measurement.valuesForPreviousMeasurement(lastCrankEventTime)

        }
    }

    }
</code>```

and I'm trying to assign to static variables inside the struct dataVariables the returned values cadenceinRPM,distanceinMeters,speedinMetersPerSecond

as well as lastWheelEventTime and lastCrankEventTime, so I can access them in another class, but I'm having the following errors:
on var mySpeed : Instance member'myMeasurement' cannot be used on type 'Measurement'
on var myLastWheelEventTime and var myLastCrankEventTime : Instance member 'valuesForPreviousMeasurement' cannot be used on type 'Measurement' ; did you mean to use a value of this type instead?
how can a reference to those returned values than?
Can somebody explain the error? I searched for other similar questions but I'm not getting to a solution yet
I have tried to change var myVariable to

```<code>var myMeasurement = Measurement.self
</code>```

but the errors stayed the same.

and this other code

```<code>    //
//  CadenceSensor.swift

import Foundation
import CoreBluetooth

/*
 // Bluetooth  "Cycling Speed and Cadence"
 https://developer.bluetooth.org/gatt/services/Pages/ServiceViewer.aspx?u=org.bluetooth.service.cycling_speed_and_cadence.xml

 Service Cycling Speed and Cadence. Characteristic [2A5B]  // Measurement
 Service Cycling Speed and Cadence. Characteristic [2A5C]  // Supported Features
 Service Cycling Speed and Cadence. Characteristic [2A5D]  // Sensor location
 Service Cycling Speed and Cadence. Characteristic [2A55]  // Control Point

 */

public struct BTConstants {
    static let CadenceService         = "1816"
    static let CSCMeasurementUUID     = "2a5b"
    static let CSCFeatureUUID         = "2a5c"
    static let SensorLocationUUID     = "2a5d"
    static let ControlPointUUID       = "2a55"
    static let WheelFlagMask:UInt8    = 0b01
    static let CrankFlagMask:UInt8    = 0b10
    static let DefaultWheelSize:UInt32   = UInt32(myVariables.circonferenzaRuota!)  // In millimiters. 700x30 (by default my bike's wheels) :)
    static let TimeScale              = 1024.0
}

protocol CadenceSensorDelegate {

    func errorDiscoveringSensorInformation(_ error:NSError)
    func sensorReady()
    func sensorUpdatedValues( speedInMetersPerSecond speed:Double?, cadenceInRpm cadence:Double?, distanceInMeters distance:Double? )
}

class CadenceSensor: NSObject {

    let peripheral:CBPeripheral
    var sensorDelegate:CadenceSensorDelegate?
    var measurementCharasteristic:CBCharacteristic?
    var lastMeasurement:Measurement?
    let wheelCircunference:UInt32

    init(peripheral:CBPeripheral , wheel:UInt32=BTConstants.DefaultWheelSize) {
        self.peripheral = peripheral
        wheelCircunference = wheel
    }

    func start() {
        self.peripheral.discoverServices(nil)
        self.peripheral.delegate = self
    }

    func stop() {
        if let measurementCharasteristic = measurementCharasteristic {
            peripheral.setNotifyValue(false, for: measurementCharasteristic)
        }

    }

    func handleValueData( _ data:Data ) {

        let measurement = Measurement(data: data, wheelSize: wheelCircunference)
        print("\(measurement)")

        let values = measurement.valuesForPreviousMeasurement(lastMeasurement)
        lastMeasurement = measurement

        sensorDelegate?.sensorUpdatedValues(speedInMetersPerSecond: values?.speedInMetersPerSecond, cadenceInRpm: values?.cadenceinRPM, distanceInMeters: values?.distanceinMeters)
    }
}

extension CadenceSensor : CBPeripheralDelegate {

    func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
        guard error == nil else {
            sensorDelegate?.errorDiscoveringSensorInformation(NSError(domain: CBErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey:NSLocalizedString("Error receiving measurements updates", comment:"")]))

            return
        }
        print("notification status changed for [\(characteristic.uuid)]...")
    }

    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {

        print("Updated [\(characteristic.uuid)]...")

        guard error == nil  , let data = characteristic.value  else {

            return
        }

        handleValueData(data)

    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        guard error == nil  else {
            sensorDelegate?.errorDiscoveringSensorInformation(error! as NSError)
            return
        }
        // Find the cadence service
        guard let cadenceService =  peripheral.services?.filter({ (service) -> Bool in
            return service.uuid == CBUUID(string: BTConstants.CadenceService)
        }).first else {

            sensorDelegate?.errorDiscoveringSensorInformation(NSError(domain: CBErrorDomain, code: NSNotFound, userInfo: [NSLocalizedDescriptionKey:NSLocalizedString("Cadence service not found for this peripheral", comment:"")]))
            return
        }
        // Discover the cadence service characteristics
        peripheral.discoverCharacteristics(nil, for:cadenceService )
        print("Cadence service discovered")

    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {

        guard let characteristics = service.characteristics else {
            sensorDelegate?.errorDiscoveringSensorInformation(NSError(domain: CBErrorDomain, code: NSNotFound, userInfo: [NSLocalizedDescriptionKey:NSLocalizedString("No characteristics found for the cadence service", comment:"")]))
            return

        }

        print("Received characteristics");

        // Enable notifications for the measurement characteristic
        for characteristic in characteristics {

            print("Service \(service.uuid). Characteristic [\(characteristic.uuid)]")

            if characteristic.uuid == CBUUID(string: BTConstants.CSCMeasurementUUID) {

                print("Found measurement characteristic. Subscribing...")
                peripheral.setNotifyValue(true, for: characteristic)
                measurementCharasteristic  = characteristic

            }
        }
        sensorDelegate?.sensorReady()

    }

}
</code>```

and this other code

```<code>    //
//  MainViewController.swift
//  BicycleSpeed

import UIKit
import CoreBluetooth

class MainViewController: UIViewController {

  struct Constants {

    static let ScanSegue = "ScanSegue"
    static let SensorUserDefaultsKey = "lastsensorused"
  }

  var bluetoothManager:BluetoothManager!
  var sensor:CadenceSensor?
  weak var scanViewController:ScanViewController?
  var infoViewController:InfoTableViewController?
  var accumulatedDistance:Double?

  lazy var distanceFormatter:LengthFormatter = {

    let formatter = LengthFormatter()
    formatter.numberFormatter.maximumFractionDigits = 1

    return formatter
  }()

  //@IBOutlet var labelBTStatus:UILabel!
  @IBOutlet var scanItem:UIBarButtonItem!
  @IBOutlet weak var idLabel: UILabel!

  override func viewDidLoad() {

      bluetoothManager = BluetoothManager()
      bluetoothManager.bluetoothDelegate = self
      scanItem.isEnabled = false

  }

  deinit {
    disconnectSensor()
  }

  @IBAction func unwindSegue( _ segue:UIStoryboardSegue ) {
      bluetoothManager.stopScan()
    guard let sensor = (segue as? ScanUnwindSegue)?.sensor else {
      return
    }
    print("Need to connect to sensor \(sensor.peripheral.identifier)")
    connectToSensor(sensor)

  }

  func disconnectSensor( ) {
    if sensor != nil  {
      bluetoothManager.disconnectSensor(sensor!)
      sensor = nil
    }
    accumulatedDistance = nil
  }

  func connectToSensor(_ sensor:CadenceSensor) {

    self.sensor  = sensor
    bluetoothManager.connectToSensor(sensor)
    // Save the sensor ID
    UserDefaults.standard.set(sensor.peripheral.identifier.uuidString, forKey: Constants.SensorUserDefaultsKey)
    UserDefaults.standard.synchronize()

  }
  // TODO: REconnect. Try this every X seconds
  func checkPreviousSensor() {

    guard let sensorID = UserDefaults.standard.object(forKey: Constants.SensorUserDefaultsKey)  as? String else {
      return
    }
    guard let sensor = bluetoothManager.retrieveSensorWithIdentifier(sensorID) else {
      return
    }
    self.sensor = sensor
    connectToSensor(sensor)

  }

  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let infoVC = segue.destination as? InfoTableViewController {
        infoViewController = infoVC
    }
    if segue.identifier == Constants.ScanSegue {

        // Scan segue
      bluetoothManager.startScan()
      scanViewController  = (segue.destination as? UINavigationController)?.viewControllers.first as? ScanViewController
    }

  }

}

extension MainViewController : CadenceSensorDelegate {

  func errorDiscoveringSensorInformation(_ error: NSError) {
      print("An error ocurred disconvering the sensor services/characteristics: \(error)")
  }

  func sensorReady() {
    print("Sensor ready to go...")
    accumulatedDistance = 0.0
  }

  func updateSensorInfo() {
    let name = sensor?.peripheral.name ?? ""
    let uuid = sensor?.peripheral.identifier.uuidString ?? ""

    OperationQueue.main.addOperation { () -> Void in
      self.infoViewController?.showDeviceName(name , uuid:uuid )
    }
  }

  func sensorUpdatedValues( speedInMetersPerSecond speed:Double?, cadenceInRpm cadence:Double?, distanceInMeters distance:Double? ) {

    accumulatedDistance? += distance ?? 0
    let distanceText = (accumulatedDistance != nil && accumulatedDistance! >= 1.0) ? distanceFormatter.string(fromMeters: accumulatedDistance!) : "N/A"
    let speedText = (speed != nil) ? distanceFormatter.string(fromValue: speed!*3.6, unit: .kilometer) + NSLocalizedString("/h", comment:"(km) Per hour") : "N/A"
    let cadenceText = (cadence != nil) ? String(format: "%.2f %@",  cadence!, NSLocalizedString("RPM", comment:"Revs per minute") ) : "N/A"

    OperationQueue.main.addOperation { () -> Void in

      self.infoViewController?.showMeasurementWithSpeed(speedText , cadence: cadenceText, distance: distanceText )
    }
  }

}

extension MainViewController : BluetoothManagerDelegate {

  func stateChanged(_ state: CBCentralManagerState) {
    print("State Changed: \(state)")
    var enabled = false
    var title = ""
    switch state {
    case .poweredOn:
        title = "Bluetooth ON"
        enabled = true
        // When the bluetooth changes to ON, try to reconnect to the previous sensor
        checkPreviousSensor()

    case .resetting:
        title = "Reseeting"
    case .poweredOff:
      title = "Bluetooth Off"
    case .unauthorized:
      title = "Bluetooth not authorized"
    case .unknown:
      title = "Unknown"
    case .unsupported:
      title = "Bluetooth not supported"
    }
    infoViewController?.showBluetoothStatusText( title )
    scanItem.isEnabled = enabled
  }

  func sensorConnection( _ sensor:CadenceSensor, error:NSError?) {
      print("")
    guard error == nil else {
      self.sensor = nil
      print("Error connecting to sensor: \(sensor.peripheral.identifier)")
      updateSensorInfo()
      accumulatedDistance = nil
      return
    }
    self.sensor = sensor
    self.sensor?.sensorDelegate = self
    print("Sensor connected. \(String(describing: sensor.peripheral.name)). [\(sensor.peripheral.identifier)]")
    updateSensorInfo()

    sensor.start()
  }

  func sensorDisconnected( _ sensor:CadenceSensor, error:NSError?) {
    print("Sensor disconnected")
    self.sensor = nil
  }

  func sensorDiscovered( _ sensor:CadenceSensor ) {
      scanViewController?.addSensor(sensor)
  }

}
</code>```

in MainViewController.swift, there is this func sensorUpdatedValues that converts the three values that I want, to strings and initialize the the func showMeasurementWithSpeed ins the InfoTableViewController.swift .

Could I just return the three values inside function sensorUpdateValues  instead to be able to store them into  new variables?

答:
The better way to solve this is by passing on the sensor object to the InfoTableViewController in the prepare(forSegue:) and then inside InfoTableViewControlleryou can call sensor.lastMeasurement.speedInMetersPerSecond or any other var that is inside there. Since the class is passed on by reference it will retain the data even when you transition to a new ViewController.

```<code>  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let infoVC = segue.destination as? InfoTableViewController {
    infoVC.sensor = self.sensor
}
if segue.identifier == Constants.ScanSegue {

    // Scan segue
  bluetoothManager.startScan()
  scanViewController  = (segue.destination as? UINavigationController)?.viewControllers.first as? ScanViewController
}
</code>```

}
Then of course you can do whatever you want with this data in the new VC( assign the values to labels or whatnot)

Body:
I'm having this code:

//
//  Measurement.swift
//  BicycleSpeed

    import Foundation
    import CoreBluetooth

    // CSC Measurement
    // https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.csc_measurement.xml
    //
    //  Flags : 1 byte.  Bit 0: Wheel. Bit 1: Crank
    //  Cumulative Wheel revolutions: 4 bytes uint32
    //  Last wheel event time: 2 bytes. uint16 (1/1024s)
    //  Cumulative Crank revolutions: 2 bytes uint16
    //  Last cranck event time: 2 bytes. uint16 (1/1024s)

    struct Measurement : CustomDebugStringConvertible {

      let hasWheel:Bool
      let hasCrank:Bool
      let cumulativeWheel:UInt32
      let lastWheelEventTime:TimeInterval
      let cumulativeCrank:UInt16
      let lastCrankEventTime:TimeInterval
      let wheelSize:UInt32

      init(data:Data, wheelSize:UInt32) {

        self.wheelSize = wheelSize
        // Flags
        var flags:UInt8=0
        (data as NSData).getBytes(&flags, range: NSRange(location: 0, length: 1))

        hasWheel = ((flags & BTConstants.WheelFlagMask) > 0)
        hasCrank = ((flags & BTConstants.CrankFlagMask) > 0)

        var wheel:UInt32=0
        var wheelTime:UInt16=0
        var crank:UInt16=0
        var crankTime:UInt16=0

        var currentOffset = 1
        var length = 0

        if ( hasWheel ) {

          length = MemoryLayout<UInt32>.size
          (data as NSData).getBytes(&wheel, range: NSRange(location: currentOffset, length: length))
          currentOffset += length

          length = MemoryLayout<UInt16>.size
          (data as NSData).getBytes(&wheelTime, range: NSRange(location: currentOffset, length: length))
          currentOffset += length
        }

        if ( hasCrank ) {

          length = MemoryLayout<UInt16>.size
          (data as NSData).getBytes(&crank, range: NSRange(location: currentOffset, length: length))
          currentOffset += length

          length = MemoryLayout<UInt16>.size
          (data as NSData).getBytes(&crankTime, range: NSRange(location: currentOffset, length: length))
          currentOffset += length
        }

        cumulativeWheel     = CFSwapInt32LittleToHost(wheel)
        lastWheelEventTime  = TimeInterval( Double(CFSwapInt16LittleToHost(wheelTime))/BTConstants.TimeScale)
        cumulativeCrank     = CFSwapInt16LittleToHost(crank)
        lastCrankEventTime  = TimeInterval( Double(CFSwapInt16LittleToHost(crankTime))/BTConstants.TimeScale)

      }

      func timeIntervalForCurrentSample( _ current:TimeInterval, previous:TimeInterval ) -> TimeInterval {
        var timeDiff:TimeInterval = 0
        if( current >= previous ) {
            timeDiff = current - previous
        }
        else {
          // passed the maximum value
          timeDiff =  ( TimeInterval((Double( UINT16_MAX) / BTConstants.TimeScale)) - previous) + current
        }
        return timeDiff

      }

      func valueDiffForCurrentSample<T:UnsignedInteger>( _ current:T, previous:T , max:T) -> T {

        var diff:T = 0
        if  ( current >= previous ) {
          diff = current - previous
        }
        else {
           diff = ( max - previous ) + current
        }
        return diff
      }

      func valuesForPreviousMeasurement( _ previousSample:Measurement? ) -> ( cadenceinRPM:Double?, distanceinMeters:Double?, speedInMetersPerSecond:Double?)? {

        var distance:Double?, cadence:Double?, speed:Double?
        guard let previousSample = previousSample else {
          return nil
        }
        if ( hasWheel && previousSample.hasWheel ) {
          let wheelTimeDiff = timeIntervalForCurrentSample(lastWheelEventTime, previous: previousSample.lastWheelEventTime)
          let valueDiff = valueDiffForCurrentSample(cumulativeWheel, previous: previousSample.cumulativeWheel, max: UInt32.max)

          distance = Double( valueDiff * wheelSize) / 1000.0 // distance in meters
          if  distance != nil  &&  wheelTimeDiff > 0 {
            speed = (wheelTimeDiff == 0 ) ? 0 : distance! / wheelTimeDiff // m/s
          }
        }

        if( hasCrank && previousSample.hasCrank ) {
          let crankDiffTime = timeIntervalForCurrentSample(lastCrankEventTime, previous: previousSample.lastCrankEventTime)
          let valueDiff = Double(valueDiffForCurrentSample(cumulativeCrank, previous: previousSample.cumulativeCrank, max: UInt16.max))

          cadence = (crankDiffTime == 0) ? 0 : Double(60.0 * valueDiff / crankDiffTime) // RPM

        }
        print( "Cadence: \(String(describing: cadence)) RPM. Distance: \(String(describing: distance)) meters. Speed: \(String(describing: speed)) Km/h" )
        return ( cadenceinRPM:cadence, distanceinMeters:distance, speedInMetersPerSecond:speed)

      }

      var debugDescription:String {
        get {
            return "Wheel Revs: \(cumulativeWheel). Last wheel event time: \(lastWheelEventTime). Crank Revs: \(cumulativeCrank). Last Crank event time: \(lastCrankEventTime)"
        }
      }

        var myMeasurement = ((Measurement?) -> (cadenceinRPM: Double?, DistanceinMeters: Double?, speedinMetersPerSecond: Double?)).self

        struct dataVariables {

            static var mySpeed = myMeasurement.speedInMetersPerSecond

            static var myCadence : Double?
            static var miDistance : Double?

            static var myLastWheelEventTime : Double? = Measurement.valuesForPreviousMeasurement(lastWheelEventTime)

            static var myLastCrankEventTime : Double? = Measurement.valuesForPreviousMeasurement(lastCrankEventTime)

        }
    }

    }

and I'm trying to assign to static variables inside the struct dataVariables the returned values cadenceinRPM,distanceinMeters,speedinMetersPerSecond

as well as lastWheelEventTime and lastCrankEventTime, so I can access them in another class, but I'm having the following errors:
on var mySpeed : Instance member'myMeasurement' cannot be used on type 'Measurement'
on var myLastWheelEventTime and var myLastCrankEventTime : Instance member 'valuesForPreviousMeasurement' cannot be used on type 'Measurement' ; did you mean to use a value of this type instead?
how can a reference to those returned values than?
Can somebody explain the error? I searched for other similar questions but I'm not getting to a solution yet
I have tried to change var myVariable to

var myMeasurement = Measurement.self

but the errors stayed the same.

and this other code

    //
//  CadenceSensor.swift

import Foundation
import CoreBluetooth

/*
 // Bluetooth  "Cycling Speed and Cadence"
 https://developer.bluetooth.org/gatt/services/Pages/ServiceViewer.aspx?u=org.bluetooth.service.cycling_speed_and_cadence.xml

 Service Cycling Speed and Cadence. Characteristic [2A5B]  // Measurement
 Service Cycling Speed and Cadence. Characteristic [2A5C]  // Supported Features
 Service Cycling Speed and Cadence. Characteristic [2A5D]  // Sensor location
 Service Cycling Speed and Cadence. Characteristic [2A55]  // Control Point

 */

public struct BTConstants {
    static let CadenceService         = "1816"
    static let CSCMeasurementUUID     = "2a5b"
    static let CSCFeatureUUID         = "2a5c"
    static let SensorLocationUUID     = "2a5d"
    static let ControlPointUUID       = "2a55"
    static let WheelFlagMask:UInt8    = 0b01
    static let CrankFlagMask:UInt8    = 0b10
    static let DefaultWheelSize:UInt32   = UInt32(myVariables.circonferenzaRuota!)  // In millimiters. 700x30 (by default my bike's wheels) :)
    static let TimeScale              = 1024.0
}

protocol CadenceSensorDelegate {

    func errorDiscoveringSensorInformation(_ error:NSError)
    func sensorReady()
    func sensorUpdatedValues( speedInMetersPerSecond speed:Double?, cadenceInRpm cadence:Double?, distanceInMeters distance:Double? )
}

class CadenceSensor: NSObject {

    let peripheral:CBPeripheral
    var sensorDelegate:CadenceSensorDelegate?
    var measurementCharasteristic:CBCharacteristic?
    var lastMeasurement:Measurement?
    let wheelCircunference:UInt32

    init(peripheral:CBPeripheral , wheel:UInt32=BTConstants.DefaultWheelSize) {
        self.peripheral = peripheral
        wheelCircunference = wheel
    }

    func start() {
        self.peripheral.discoverServices(nil)
        self.peripheral.delegate = self
    }

    func stop() {
        if let measurementCharasteristic = measurementCharasteristic {
            peripheral.setNotifyValue(false, for: measurementCharasteristic)
        }

    }

    func handleValueData( _ data:Data ) {

        let measurement = Measurement(data: data, wheelSize: wheelCircunference)
        print("\(measurement)")

        let values = measurement.valuesForPreviousMeasurement(lastMeasurement)
        lastMeasurement = measurement

        sensorDelegate?.sensorUpdatedValues(speedInMetersPerSecond: values?.speedInMetersPerSecond, cadenceInRpm: values?.cadenceinRPM, distanceInMeters: values?.distanceinMeters)
    }
}

extension CadenceSensor : CBPeripheralDelegate {

    func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
        guard error == nil else {
            sensorDelegate?.errorDiscoveringSensorInformation(NSError(domain: CBErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey:NSLocalizedString("Error receiving measurements updates", comment:"")]))

            return
        }
        print("notification status changed for [\(characteristic.uuid)]...")
    }

    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {

        print("Updated [\(characteristic.uuid)]...")

        guard error == nil  , let data = characteristic.value  else {

            return
        }

        handleValueData(data)

    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        guard error == nil  else {
            sensorDelegate?.errorDiscoveringSensorInformation(error! as NSError)
            return
        }
        // Find the cadence service
        guard let cadenceService =  peripheral.services?.filter({ (service) -> Bool in
            return service.uuid == CBUUID(string: BTConstants.CadenceService)
        }).first else {

            sensorDelegate?.errorDiscoveringSensorInformation(NSError(domain: CBErrorDomain, code: NSNotFound, userInfo: [NSLocalizedDescriptionKey:NSLocalizedString("Cadence service not found for this peripheral", comment:"")]))
            return
        }
        // Discover the cadence service characteristics
        peripheral.discoverCharacteristics(nil, for:cadenceService )
        print("Cadence service discovered")

    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {

        guard let characteristics = service.characteristics else {
            sensorDelegate?.errorDiscoveringSensorInformation(NSError(domain: CBErrorDomain, code: NSNotFound, userInfo: [NSLocalizedDescriptionKey:NSLocalizedString("No characteristics found for the cadence service", comment:"")]))
            return

        }

        print("Received characteristics");

        // Enable notifications for the measurement characteristic
        for characteristic in characteristics {

            print("Service \(service.uuid). Characteristic [\(characteristic.uuid)]")

            if characteristic.uuid == CBUUID(string: BTConstants.CSCMeasurementUUID) {

                print("Found measurement characteristic. Subscribing...")
                peripheral.setNotifyValue(true, for: characteristic)
                measurementCharasteristic  = characteristic

            }
        }
        sensorDelegate?.sensorReady()

    }

}

and this other code

    //
//  MainViewController.swift
//  BicycleSpeed

import UIKit
import CoreBluetooth

class MainViewController: UIViewController {

  struct Constants {

    static let ScanSegue = "ScanSegue"
    static let SensorUserDefaultsKey = "lastsensorused"
  }

  var bluetoothManager:BluetoothManager!
  var sensor:CadenceSensor?
  weak var scanViewController:ScanViewController?
  var infoViewController:InfoTableViewController?
  var accumulatedDistance:Double?

  lazy var distanceFormatter:LengthFormatter = {

    let formatter = LengthFormatter()
    formatter.numberFormatter.maximumFractionDigits = 1

    return formatter
  }()

  //@IBOutlet var labelBTStatus:UILabel!
  @IBOutlet var scanItem:UIBarButtonItem!
  @IBOutlet weak var idLabel: UILabel!

  override func viewDidLoad() {

      bluetoothManager = BluetoothManager()
      bluetoothManager.bluetoothDelegate = self
      scanItem.isEnabled = false

  }

  deinit {
    disconnectSensor()
  }

  @IBAction func unwindSegue( _ segue:UIStoryboardSegue ) {
      bluetoothManager.stopScan()
    guard let sensor = (segue as? ScanUnwindSegue)?.sensor else {
      return
    }
    print("Need to connect to sensor \(sensor.peripheral.identifier)")
    connectToSensor(sensor)

  }

  func disconnectSensor( ) {
    if sensor != nil  {
      bluetoothManager.disconnectSensor(sensor!)
      sensor = nil
    }
    accumulatedDistance = nil
  }

  func connectToSensor(_ sensor:CadenceSensor) {

    self.sensor  = sensor
    bluetoothManager.connectToSensor(sensor)
    // Save the sensor ID
    UserDefaults.standard.set(sensor.peripheral.identifier.uuidString, forKey: Constants.SensorUserDefaultsKey)
    UserDefaults.standard.synchronize()

  }
  // TODO: REconnect. Try this every X seconds
  func checkPreviousSensor() {

    guard let sensorID = UserDefaults.standard.object(forKey: Constants.SensorUserDefaultsKey)  as? String else {
      return
    }
    guard let sensor = bluetoothManager.retrieveSensorWithIdentifier(sensorID) else {
      return
    }
    self.sensor = sensor
    connectToSensor(sensor)

  }

  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let infoVC = segue.destination as? InfoTableViewController {
        infoViewController = infoVC
    }
    if segue.identifier == Constants.ScanSegue {

        // Scan segue
      bluetoothManager.startScan()
      scanViewController  = (segue.destination as? UINavigationController)?.viewControllers.first as? ScanViewController
    }

  }

}

extension MainViewController : CadenceSensorDelegate {

  func errorDiscoveringSensorInformation(_ error: NSError) {
      print("An error ocurred disconvering the sensor services/characteristics: \(error)")
  }

  func sensorReady() {
    print("Sensor ready to go...")
    accumulatedDistance = 0.0
  }

  func updateSensorInfo() {
    let name = sensor?.peripheral.name ?? ""
    let uuid = sensor?.peripheral.identifier.uuidString ?? ""

    OperationQueue.main.addOperation { () -> Void in
      self.infoViewController?.showDeviceName(name , uuid:uuid )
    }
  }

  func sensorUpdatedValues( speedInMetersPerSecond speed:Double?, cadenceInRpm cadence:Double?, distanceInMeters distance:Double? ) {

    accumulatedDistance? += distance ?? 0
    let distanceText = (accumulatedDistance != nil && accumulatedDistance! >= 1.0) ? distanceFormatter.string(fromMeters: accumulatedDistance!) : "N/A"
    let speedText = (speed != nil) ? distanceFormatter.string(fromValue: speed!*3.6, unit: .kilometer) + NSLocalizedString("/h", comment:"(km) Per hour") : "N/A"
    let cadenceText = (cadence != nil) ? String(format: "%.2f %@",  cadence!, NSLocalizedString("RPM", comment:"Revs per minute") ) : "N/A"

    OperationQueue.main.addOperation { () -> Void in

      self.infoViewController?.showMeasurementWithSpeed(speedText , cadence: cadenceText, distance: distanceText )
    }
  }

}

extension MainViewController : BluetoothManagerDelegate {

  func stateChanged(_ state: CBCentralManagerState) {
    print("State Changed: \(state)")
    var enabled = false
    var title = ""
    switch state {
    case .poweredOn:
        title = "Bluetooth ON"
        enabled = true
        // When the bluetooth changes to ON, try to reconnect to the previous sensor
        checkPreviousSensor()

    case .resetting:
        title = "Reseeting"
    case .poweredOff:
      title = "Bluetooth Off"
    case .unauthorized:
      title = "Bluetooth not authorized"
    case .unknown:
      title = "Unknown"
    case .unsupported:
      title = "Bluetooth not supported"
    }
    infoViewController?.showBluetoothStatusText( title )
    scanItem.isEnabled = enabled
  }

  func sensorConnection( _ sensor:CadenceSensor, error:NSError?) {
      print("")
    guard error == nil else {
      self.sensor = nil
      print("Error connecting to sensor: \(sensor.peripheral.identifier)")
      updateSensorInfo()
      accumulatedDistance = nil
      return
    }
    self.sensor = sensor
    self.sensor?.sensorDelegate = self
    print("Sensor connected. \(String(describing: sensor.peripheral.name)). [\(sensor.peripheral.identifier)]")
    updateSensorInfo()

    sensor.start()
  }

  func sensorDisconnected( _ sensor:CadenceSensor, error:NSError?) {
    print("Sensor disconnected")
    self.sensor = nil
  }

  func sensorDiscovered( _ sensor:CadenceSensor ) {
      scanViewController?.addSensor(sensor)
  }

}

in MainViewController.swift, there is this func sensorUpdatedValues that converts the three values that I want, to strings and initialize the the func showMeasurementWithSpeed ins the InfoTableViewController.swift .

Could I just return the three values inside function sensorUpdateValues  instead to be able to store them into  new variables?

Body:
The better way to solve this is by passing on the sensor object to the InfoTableViewController in the prepare(forSegue:) and then inside InfoTableViewControlleryou can call sensor.lastMeasurement.speedInMetersPerSecond or any other var that is inside there. Since the class is passed on by reference it will retain the data even when you transition to a new ViewController.

  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let infoVC = segue.destination as? InfoTableViewController {
    infoVC.sensor = self.sensor
}
if segue.identifier == Constants.ScanSegue {

    // Scan segue
  bluetoothManager.startScan()
  scanViewController  = (segue.destination as? UINavigationController)?.viewControllers.first as? ScanViewController
}

}
Then of course you can do whatever you want with this data in the new VC( assign the values to labels or whatnot)


来源: stackexchange

问:
Wirecloud geojson in a map
Hello i'm trylling to show an entity with geojson data in a map inside of Wirecloud. The data comes from my own instance of Orion. Here you have some screenshots where you can see the data from Orion and the configuration.

General configuration

Entity to POI configuration

Dashboard, Json editor is just to show the data

If i change the lat and long and i put it in a normal attribute with name, it works but in the geojson array it doesn't work.

Can someone tell me what i'm doing wrong.

Thanks

答:
Your coordinates are swapped in the coordinates array. Please take into account that the order of coordinates in GeoJSON is [long, lat]

thanks

ContentLicense: CC BY-SA 3.0

Title: Wirecloud geojson in a map


问:
canvas spiral rise effect with turning points
There is a spiral rise effect as showed bellow:

A demo can be found here: http://openlayers.org/en/latest/examples/dynamic-data.html

In the bottom of the demo page, an algorithm is used to implement this effect. But I can not figure out how does it work.

```<code>var t = theta + 2 * Math.PI * i / n;
var x = (R + r) * Math.cos(t) + p * Math.cos((R + r) * t / r);
var y = (R + r) * Math.sin(t) + p * Math.sin((R + r) * t / r);
</code>```

What does R, r and p means? And how to understand the formula above? Can someone explain detail for me? Any help is appreciated.

答:
I can recognize that code draws epicycloid curve (+ it's phase theta permanently changes to provide moving effect).

You can refer to R as radius of inner (here bigger) circle, p and r (equal values here) as radius of outer (here smaller) circle. Here r looks like radius of coil of toroidal spring.

The first summands correspond to the center of outer circle, the second ones - to the second-order rotation about outer circle center.

Play with these values and observe effects

Note that if you change p to make it not equal to r, you'll get epitrochoid curve (more general kind of epicycloid)

Body:
There is a spiral rise effect as showed bellow:

A demo can be found here: http://openlayers.org/en/latest/examples/dynamic-data.html

In the bottom of the demo page, an algorithm is used to implement this effect. But I can not figure out how does it work.

var t = theta + 2 * Math.PI * i / n;
var x = (R + r) * Math.cos(t) + p * Math.cos((R + r) * t / r);
var y = (R + r) * Math.sin(t) + p * Math.sin((R + r) * t / r);

What does R, r and p means? And how to understand the formula above? Can someone explain detail for me? Any help is appreciated.


问:
What are some software and techniques for extracting proper names from a text?
I have a large corpus of text-based documents (100,000+) from which I want to extract proper names (e.g. a person's name).

Could anyone recommend techniques and/or software that would be useful in accomplishing this goal. I'm not particularly interested in low-level text parsing, so much as I am in more high-level things such as recognizing and/or ranking.

答:
Something like this cannot be done reliably without some form of Natural Language Processing. A few common issues:

Names that are also common words: John Black

Multiple languages and various forms of the same word.

Names that refer to different things. Lily could be a name for a person, a place, a cat or just the flower.

NLP can use surrounding grammar constructs to tell some of these cases apart.

That said, a simple (and naive) technique that you could try would be to use the capitalisation of the words. If you see a capital starting letter in the middle of a sentence, it is usually a name of some sort.

You might be able to reasonably assume that any such word refers to the same thing within the same document. Two such words in a sequence are probably a name/surname combination etc.

If capitalisation in the documents cannot be trusted, you might be able to trust that of a proper wordlist, instead, in order to get a list of proper names for the applicable languages.

ContentLicense: CC BY-SA 2.5


问:
How to properly merge multiple collections in Laravel
I want to merge multiple collections into one. I do have a solution, which is the following:

```<code>$allItems = $collection1->merge($collection2)
                        ->merge($collection3)
                        ->merge($collection4)
                        ->merge($collection5);
</code>```

This actually does work, but I run into problems in cases where some or all of the collections contain no objects. I get an error along the lines of call to merge() on non object.

I actually tried to create an array of all of the collections, and then iterate through them, while checking their validity, but it didn't work and I feel it wasn't very elegant.

How can I elegantly iterate through this process of merging multiple collections, while taking into account that some or all of the collections might be empty or invalid? Appreciated!

答:
I had the same question, so I solved it in the following way:</p>

```<code>$clients = ClientAccount::query()->get();
$admins = AdminAccount::query()->get();

$users = collect($clients)->merge($admins)->merge($anotherCollection)->merge(...);
</code>```

Body:
I want to merge multiple collections into one. I do have a solution, which is the following:

$allItems = $collection1->merge($collection2)
                        ->merge($collection3)
                        ->merge($collection4)
                        ->merge($collection5);

This actually does work, but I run into problems in cases where some or all of the collections contain no objects. I get an error along the lines of call to merge() on non object.

I actually tried to create an array of all of the collections, and then iterate through them, while checking their validity, but it didn't work and I feel it wasn't very elegant.

How can I elegantly iterate through this process of merging multiple collections, while taking into account that some or all of the collections might be empty or invalid? Appreciated!

Body:
I had the same question, so I solved it in the following way:

$clients = ClientAccount::query()->get();
$admins = AdminAccount::query()->get();

$users = collect($clients)->merge($admins)->merge($anotherCollection)->merge(...);


问:
Directory Creation File naming
I have created a directory and created an anonymous block to create a file in it. Every time if I execute the block the file is overwritten. I need it to be created as a new file. What should I do to attain this.</p>

```<code>DECLARE
  v_name    utl_file.file_type;
  v_count   NUMBER := 0;
BEGIN
  v_name := utl_file.fopen('PLSQL_DIR', 'Task1.txt', 'W');
  utl_file.put_line(
    v_name,
    TO_CHAR(SYSDATE, 'DD/MM/YY/HH/MI')||' Data Migration Starts'
  );
  FOR i IN (SELECT * FROM sue_par_det_tb) LOOP
    utl_file.put_line(
      v_name,
      i.patient_name||', '|| i.ord_date||', '|| i.mobile_number||', '|| i.refered_by
    );
    v_count := v_count + 1;
  END LOOP;
  utl_file.put_line(
    v_name,
    v_count||' Rows generated at '||TO_CHAR(SYSDATE, 'DD/MM/YY/HH24/MI')
  );
  utl_file.fclose(v_name);
END;
/
</code>```

答:
Split your file name into name and extension and then check if the file exists and, if it does, then append a number to the name and check if that file exists and loop until you do not find a file.

Something like:

```<code>DECLARE
  v_file     utl_file.file_type;
  v_dir      VARCHAR2(30)  := 'PLSQL_DIR';
  v_filename VARCHAR2(256) := 'Task1.txt';
  v_name     VARCHAR2(256) := SUBSTR( v_filename, 1, INSTR( v_filename, '.', -1 ) - 1 );
  v_ext      VARCHAR2(256) := SUBSTR( v_filename, INSTR( v_filename, '.', -1 ) );
  v_num      INTEGER       := NULL;
  v_count    NUMBER        := 0;
BEGIN
  LOOP
    EXIT WHEN NOT FileExists( v_dir, v_filename );
    IF v_num IS NULL THEN
      v_num := 1;
    ELSE
      v_num := v_num + 1;
    END IF;
    v_filename := v_name || '.' || v_num || v_ext;
  END LOOP;
  v_name := utl_file.fopen( v_dir, v_filename, 'W' );
  -- rest of your code
END;
/
</code>```

Title: Directory Creation File naming

Body:
I have created a directory and created an anonymous block to create a file in it. Every time if I execute the block the file is overwritten. I need it to be created as a new file. What should I do to attain this.

DECLARE
  v_name    utl_file.file_type;
  v_count   NUMBER := 0;
BEGIN
  v_name := utl_file.fopen('PLSQL_DIR', 'Task1.txt', 'W');
  utl_file.put_line(
    v_name,
    TO_CHAR(SYSDATE, 'DD/MM/YY/HH/MI')||' Data Migration Starts'
  );
  FOR i IN (SELECT * FROM sue_par_det_tb) LOOP
    utl_file.put_line(
      v_name,
      i.patient_name||', '|| i.ord_date||', '|| i.mobile_number||', '|| i.refered_by
    );
    v_count := v_count + 1;
  END LOOP;
  utl_file.put_line(
    v_name,
    v_count||' Rows generated at '||TO_CHAR(SYSDATE, 'DD/MM/YY/HH24/MI')
  );
  utl_file.fclose(v_name);
END;
/

Body:
Split your file name into name and extension and then check if the file exists and, if it does, then append a number to the name and check if that file exists and loop until you do not find a file.

Something like:

DECLARE
  v_file     utl_file.file_type;
  v_dir      VARCHAR2(30)  := 'PLSQL_DIR';
  v_filename VARCHAR2(256) := 'Task1.txt';
  v_name     VARCHAR2(256) := SUBSTR( v_filename, 1, INSTR( v_filename, '.', -1 ) - 1 );
  v_ext      VARCHAR2(256) := SUBSTR( v_filename, INSTR( v_filename, '.', -1 ) );
  v_num      INTEGER       := NULL;
  v_count    NUMBER        := 0;
BEGIN
  LOOP
    EXIT WHEN NOT FileExists( v_dir, v_filename );
    IF v_num IS NULL THEN
      v_num := 1;
    ELSE
      v_num := v_num + 1;
    END IF;
    v_filename := v_name || '.' || v_num || v_ext;
  END LOOP;
  v_name := utl_file.fopen( v_dir, v_filename, 'W' );
  -- rest of your code
END;
/


问:
What's the difference between the :web and :app groups in capistrano/rails
I'm setting up different capistrano groups in a rails app that I inherited and I was wondering what the different between the :app group and the :web group was in capistrano/rails. From what I can tell, they do the same thing.

答:
Capistrano's roles help you run tasks only on certain servers (if you have multiple servers). In your case you can use capistrano-sidekiq gem and create a capistrano role (a server basically) which only runs sidekiq jobs with:

```<code>set :sidekiq_role, [:workers]
</code>```

You can read more here and here

Body:
Capistrano's roles help you run tasks only on certain servers (if you have multiple servers). In your case you can use capistrano-sidekiq gem and create a capistrano role (a server basically) which only runs sidekiq jobs with:

set :sidekiq_role, [:workers]

You can read more here and here


问:
Drawing a circle on an image
I have a program for image segmentation in WinForms Application C#, and I have an image loaded in a pictureBox. I need to draw a small circle(or an ellipse, it does not matter) on that image (inside a region of interest, and allowing it to grow outwards until it reaches the desired boundary).

And the question is how can I draw that circle anywhere on that image? (and if it`s possible to draw that circle in a different color, red for example)

Thank you.

答:
Sure take the graphic instance of the control anddraw on it . It will be reflected only when its repainted or Invalidated. Use DrawEllipse Method of Graphic Class to draw circle.

here is the code:

```<code>Graphics gf = picturebox1.CreateGraphics();
//A circle with Red Color and 2 Pixel wide line
gf.DrawEllipse(new Pen(Color.Red, 2),new Rectangle(0, 0, 200, 200));
</code>```

Invalidate it to actually draw it on the control (picturebox)

```<code>picturebox1.Invalidate();
</code>```

It will draw a circle 200 pixel in diameter

Title: Drawing a circle on an image

Body:
Sure take the graphic instance of the control anddraw on it . It will be reflected only when its repainted or Invalidated. Use DrawEllipse Method of Graphic Class to draw circle.

here is the code:

Graphics gf = picturebox1.CreateGraphics();
//A circle with Red Color and 2 Pixel wide line
gf.DrawEllipse(new Pen(Color.Red, 2),new Rectangle(0, 0, 200, 200));

Invalidate it to actually draw it on the control (picturebox)

picturebox1.Invalidate();

It will draw a circle 200 pixel in diameter


问:
Transparent rim when scaling bitmap in C#
I am trying to make platformer engine c# windows forms, so I am trying it out with super Mario tilesheet I found on the Internet. I cropped every picture I need its own tile object. When I draw it as it is It is alright. Because it is 16x16 picture I added scale factor. When I try to scale it picture gets transparent right and bottom edge.

Does anyone know the reason for it? I do scaling in the draw method. I have tried all similar results I found. Thanks in advance.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace PlatformerRunner
{
    class Tile
    {

        public int id;
        public int width;
        public int height;
        public bool solid;
        public String name;
        public Bitmap image;

        public Tile(int id, int width, int height, bool solid, String name, Bitmap image)
        {

            this.id = id;
            this.width = width;
            this.height = height;
            this.solid = solid;
            this.name = name;
            this.image = image;

        }

        internal void draw(Graphics g, int x, int y)
        {
            int s = Game.scale;
            g.DrawImage(new Bitmap(image, width * s, height * s), x * width * s, y * width * s);
        }
    }

}
</code>```

Image at scale 1

Image at scale 2

This is game structure that draws every tile. background just goes from (0,0) to (width,height)

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace PlatformerRunner
{

    enum GameStructureType
    {

        BACKGROUND,
        PLATFORM,
        BUILDING,
        PORTAL

    }

    class GameStructure
    {

        public int id;
        public int x;
        public int y;
        public int width;
        public int height;
        public Tile tile;
        public GameStructureType type;

        public GameStructure(int id, int x, int y, int width, int height, Tile tile, GameStructureType type)
        {

            this.id = id;
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
            this.tile = tile;
            this.type = type;

        }

        public void draw(Graphics g)
        {

            for (int i = x; i < x + width; i++ )
            {

                for (int j = y; j < y+height; j++)
                {

                    tile.draw(g,i,j);

                }

            }

        }

    }
}
</code>```

答:
Apparently the default resizing done by the Bitmap constructor will sample transparent pixels beyond the image boundaries, which leads to the behavior you are seeing.  To get a higher quality resize, you can use the ResizeImage method from @mpen's excellent answer on how to resize an image.  Change your Tile class to use that method to create the new image instead of the Bitmap constructor.

```<code>internal void draw(Graphics g, int x, int y)
{
    int s = Game.scale;
    Bitmap resized = (s > 1) ? ResizeImage(image, width * s, height * s) : image;
    g.DrawImage(resized, x * width * s, y * height * s);
}
</code>```

Note: if scale doesn't change often and you are going to be drawing the same image repeatedly, you might want to cache the resized image so you are not recreating it each time you call draw.

Body:
I am trying to make platformer engine c# windows forms, so I am trying it out with super Mario tilesheet I found on the Internet. I cropped every picture I need its own tile object. When I draw it as it is It is alright. Because it is 16x16 picture I added scale factor. When I try to scale it picture gets transparent right and bottom edge.

Does anyone know the reason for it? I do scaling in the draw method. I have tried all similar results I found. Thanks in advance.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace PlatformerRunner
{
    class Tile
    {

        public int id;
        public int width;
        public int height;
        public bool solid;
        public String name;
        public Bitmap image;

        public Tile(int id, int width, int height, bool solid, String name, Bitmap image)
        {

            this.id = id;
            this.width = width;
            this.height = height;
            this.solid = solid;
            this.name = name;
            this.image = image;

        }

        internal void draw(Graphics g, int x, int y)
        {
            int s = Game.scale;
            g.DrawImage(new Bitmap(image, width * s, height * s), x * width * s, y * width * s);
        }
    }

}

Image at scale 1

Image at scale 2

This is game structure that draws every tile. background just goes from (0,0) to (width,height)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace PlatformerRunner
{

    enum GameStructureType
    {

        BACKGROUND,
        PLATFORM,
        BUILDING,
        PORTAL

    }

    class GameStructure
    {

        public int id;
        public int x;
        public int y;
        public int width;
        public int height;
        public Tile tile;
        public GameStructureType type;

        public GameStructure(int id, int x, int y, int width, int height, Tile tile, GameStructureType type)
        {

            this.id = id;
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
            this.tile = tile;
            this.type = type;

        }

        public void draw(Graphics g)
        {

            for (int i = x; i < x + width; i++ )
            {

                for (int j = y; j < y+height; j++)
                {

                    tile.draw(g,i,j);

                }

            }

        }

    }
}

Body:
Apparently the default resizing done by the Bitmap constructor will sample transparent pixels beyond the image boundaries, which leads to the behavior you are seeing.  To get a higher quality resize, you can use the ResizeImage method from @mpen's excellent answer on how to resize an image.  Change your Tile class to use that method to create the new image instead of the Bitmap constructor.

internal void draw(Graphics g, int x, int y)
{
    int s = Game.scale;
    Bitmap resized = (s > 1) ? ResizeImage(image, width * s, height * s) : image;
    g.DrawImage(resized, x * width * s, y * height * s);
}

Note: if scale doesn't change often and you are going to be drawing the same image repeatedly, you might want to cache the resized image so you are not recreating it each time you call draw.


问:
Need the entire chain of Child of a particular parent record in SQL server
We want to get the total TREE structure (Down chain) of a particular record based on the ID from SQL Server.

This is my data table structure:

```<code>-----------------------------------------------------------------
CHILD_CODE      PARENT_CODE      CHILD_RANK      PARENT_RANK
-----------------------------------------------------------------
1               Null                  1          Null
2               1                     2          1
3               1                     2          1
4               1                     2          1
5               2                     3          2
6               2                     3          2
7               3                     3          2
8               5                     4          3
</code>```

Here I need to have the entire child tree for a parent. Means if I give 2 as parent input it will give me all the child below it as a tree till the end.
example... 1

input > PARENT_CODE = 2

output >

```<code>----------------------------------------------
PARENT_CODE     CHILD_CODE      CHILD_RANK
----------------------------------------------
2               5               3
2               6               3
2               8               4
----------------------------------------------
</code>```

Here we have used the CET like

```<code>; WITH rekurs AS (
   SELECT child_code, child_rank
   FROM   tbl
   WHERE  parent_code = 2
   UNION ALL
   SELECT ch.child_code, ch.child_rank
   FROM   tbl ch
   JOIN   rekurs r ON ch.parent_code = r.child_code
)
SELECT 2 AS PARENT_CODE, child_code, child_rank
FROM  CTE
</code>```

We have already added this CTE in out program but here we are working on a large number of records and we are facing some problem. In this CTE we are passing a single parent_code for which we are getting all the child of that particular code.

Here we want to get all the child of 30,000 parent_code, which is taking so much times while we are passing the parent_code to CTE one by one in a for loop from C# program. Is there any  way to resolve this issue?

答:
does the following could work for you:

```<code>; WITH rekurs AS (
   SELECT parent_code Root_code, child_code, child_rank
   FROM   RecursiveTable
   WHERE  parent_code IN (1, 2, 3)
   UNION ALL
   SELECT r.Root_code, ch.child_code, ch.child_Rank
   FROM   RecursiveTable ch
   JOIN   rekurs r ON ch.parent_code = r.child_code
)
SELECT Root_code, child_code, child_Rank
FROM   rekurs
ORDER BY Root_code
</code>```

This is the result set:

```<code>Root_code child_code child_Rank
1         2          2
1         3          2
1         4          2
1         7          3
1         5          3
1         6          3
1         8          4
2         5          3
2         6          3
2         8          4
3         7          3
</code>```

Body:
We want to get the total TREE structure (Down chain) of a particular record based on the ID from SQL Server.

This is my data table structure:

-----------------------------------------------------------------
CHILD_CODE      PARENT_CODE      CHILD_RANK      PARENT_RANK
-----------------------------------------------------------------
1               Null                  1          Null
2               1                     2          1
3               1                     2          1
4               1                     2          1
5               2                     3          2
6               2                     3          2
7               3                     3          2
8               5                     4          3

Here I need to have the entire child tree for a parent. Means if I give 2 as parent input it will give me all the child below it as a tree till the end.
example... 1

input > PARENT_CODE = 2

output >

----------------------------------------------
PARENT_CODE     CHILD_CODE      CHILD_RANK
----------------------------------------------
2               5               3
2               6               3
2               8               4
----------------------------------------------

Here we have used the CET like

; WITH rekurs AS (
   SELECT child_code, child_rank
   FROM   tbl
   WHERE  parent_code = 2
   UNION ALL
   SELECT ch.child_code, ch.child_rank
   FROM   tbl ch
   JOIN   rekurs r ON ch.parent_code = r.child_code
)
SELECT 2 AS PARENT_CODE, child_code, child_rank
FROM  CTE

We have already added this CTE in out program but here we are working on a large number of records and we are facing some problem. In this CTE we are passing a single parent_code for which we are getting all the child of that particular code.

Here we want to get all the child of 30,000 parent_code, which is taking so much times while we are passing the parent_code to CTE one by one in a for loop from C# program. Is there any  way to resolve this issue?

Body:
does the following could work for you:

; WITH rekurs AS (
   SELECT parent_code Root_code, child_code, child_rank
   FROM   RecursiveTable
   WHERE  parent_code IN (1, 2, 3)
   UNION ALL
   SELECT r.Root_code, ch.child_code, ch.child_Rank
   FROM   RecursiveTable ch
   JOIN   rekurs r ON ch.parent_code = r.child_code
)
SELECT Root_code, child_code, child_Rank
FROM   rekurs
ORDER BY Root_code

This is the result set:

Root_code child_code child_Rank
1         2          2
1         3          2
1         4          2
1         7          3
1         5          3
1         6          3
1         8          4
2         5          3
2         6          3
2         8          4
3         7          3


问:
Looking for a regular expression which does contain a set of words
I'm trying to create a regex for my Postfix header_checks file so it will match a string that does not include .com, .net or .org domain extension.

The following regex appears to work in regex101, but fails in Postfix.

```<code>/^From: .*\.(?!(com|net|org)>)/ HOLD
</code>```

All mail (including .com, .net, etc) get held in queue, and that's obviously not what I want.

I want the regex to match on strings like :

```<code>From: Example Mail <example@domain.bid>
From: Example Mail <example@domain.bid.co>
</code>```

Any ideas where I am going wrong with my regex?

答:
According to regexp_table the regular expression is matched with multi-line
mode off, which implies that ^ only matches the start of the string and not
the start of the line.

```
By default, matching is case-insensitive, and newlines are not  treated
as  special  characters. The behavior is controlled by flags, which are
toggled by appending one or more of the following characters after  the
pattern:

i (default: on)
       Toggles  the case sensitivity flag. By default, matching is case
       insensitive.

m (default: off)
       Toggle the multi-line mode flag. When this flag is on, the ^ and
       $  metacharacters match immediately after and immediately before
       a newline character, respectively, in addition  to  matching  at
       the start and end of the input string.
```

(By the way, I prefer "[.]" over "\." and would use a non capturing group for the alternatives: "(?:com|net|org)").

Body:
I'm trying to create a regex for my Postfix header_checks file so it will match a string that does not include .com, .net or .org domain extension.

The following regex appears to work in regex101, but fails in Postfix.

/^From: .*\.(?!(com|net|org)>)/ HOLD

All mail (including .com, .net, etc) get held in queue, and that's obviously not what I want.

I want the regex to match on strings like :

From: Example Mail <example@domain.bid>
From: Example Mail <example@domain.bid.co>

Any ideas where I am going wrong with my regex?

Body:
According to regexp_table the regular expression is matched with multi-line
mode off, which implies that ^ only matches the start of the string and not
the start of the line.

By default, matching is case-insensitive, and newlines are not  treated
as  special  characters. The behavior is controlled by flags, which are
toggled by appending one or more of the following characters after  the
pattern:

i (default: on)
       Toggles  the case sensitivity flag. By default, matching is case
       insensitive.

m (default: off)
       Toggle the multi-line mode flag. When this flag is on, the ^ and
       $  metacharacters match immediately after and immediately before
       a newline character, respectively, in addition  to  matching  at
       the start and end of the input string.

(By the way, I prefer "[.]" over "\." and would use a non capturing group for the alternatives: "(?:com|net|org)").


问:
How to force Kubernetes to update deployment with a pod in every node
I would like to know if there is a way to force Kubernetes, during a deploy, to use every node in the cluster.
The question is due some attempts that I have done where I noticed a situation like this:

a cluster of 3 nodes

I update a deployment with a command like: kubectl set image deployment/deployment_name my_repo:v2.1.2

Kubernetes updates the cluster

At the end I execute kubectl get pod and I notice that 2 pods have been deployed in the same node.
So after the update, the cluster has this configuration:

one node with 2 pods

one node with 1 pod

one node without any pod (totally without any workload)

答:
I tried some solutions and what is working at the moment is simply based on the change of version inside my deployment.yaml on DaemonSet controller.

I mean:

1) I have to deploy for the 1' time my application based on a pod with some containers. These pods should be deployed on every cluster node (I have 3 nodes). I have set up the deployment setting in the yaml file with the option replicas equal to 3:

```<code>apiVersion: apps/v1beta2 # for versions before 1.8.0 use apps/v1beta1
kind: Deployment
metadata:
  name: my-deployment
  labels:
    app: webpod
spec:
  replicas: 3
....
</code>```

I have set up the daemonset (or ds) in the yaml file with the option updateStrategy equal to RollingUpdate:

```<code>apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  name: my-daemonset

spec:
  updateStrategy:
    type: RollingUpdate
...
</code>```

The version used for one of my containers is 2.1 for example

2) I execute the deployment with the command: kubectl apply -f my-deployment.yaml

I execute the deployment with the command: kubectl apply -f my-daemonset.yaml

3) I get one pod for every node without problem

4) Now I want to update the deployment changing the version of the image that I use for one of my containers.  So I simply change the yaml file editing 2.1 with 2.2. Then I re-launch the command: kubectl apply -f my-deployment.yaml

So I can simply change the version of the image (2.1 -> 2.2) with this command:

```<code>kubectl set image ds/my-daemonset my-container=my-repository:v2.2
</code>```

5) Again, I obtain one pod for every node without problem

Behavior very different if instead I use the command:

```<code>kubectl set image deployment/my-deployment my-container=xxxx:v2.2
</code>```

In this case I get a wrong result where a node has 2 pod, a node 1 pod and last node without any pod...

To see how the deployment evolves, I can launch the command:

```<code>kubectl rollout status ds/my-daemonset
</code>```

getting something like that

```<code>Waiting for rollout to finish: 0 out of 3 new pods have been updated...
Waiting for rollout to finish: 0 out of 3 new pods have been updated...
Waiting for rollout to finish: 1 out of 3 new pods have been updated...
Waiting for rollout to finish: 1 out of 3 new pods have been updated...
Waiting for rollout to finish: 1 out of 3 new pods have been updated...
Waiting for rollout to finish: 2 out of 3 new pods have been updated...
Waiting for rollout to finish: 2 out of 3 new pods have been updated...
Waiting for rollout to finish: 2 out of 3 new pods have been updated...
Waiting for rollout to finish: 2 of 3 updated pods are available...
daemon set "my-daemonset" successfully rolled out
</code>```

Body:
I tried some solutions and what is working at the moment is simply based on the change of version inside my deployment.yaml on DaemonSet controller.

I mean:

1) I have to deploy for the 1' time my application based on a pod with some containers. These pods should be deployed on every cluster node (I have 3 nodes). I have set up the deployment setting in the yaml file with the option replicas equal to 3:

apiVersion: apps/v1beta2 # for versions before 1.8.0 use apps/v1beta1
kind: Deployment
metadata:
  name: my-deployment
  labels:
    app: webpod
spec:
  replicas: 3
....

I have set up the daemonset (or ds) in the yaml file with the option updateStrategy equal to RollingUpdate:

apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  name: my-daemonset

spec:
  updateStrategy:
    type: RollingUpdate
...

The version used for one of my containers is 2.1 for example

2) I execute the deployment with the command: kubectl apply -f my-deployment.yaml

I execute the deployment with the command: kubectl apply -f my-daemonset.yaml

3) I get one pod for every node without problem

4) Now I want to update the deployment changing the version of the image that I use for one of my containers.  So I simply change the yaml file editing 2.1 with 2.2. Then I re-launch the command: kubectl apply -f my-deployment.yaml

So I can simply change the version of the image (2.1 -> 2.2) with this command:

kubectl set image ds/my-daemonset my-container=my-repository:v2.2

5) Again, I obtain one pod for every node without problem

Behavior very different if instead I use the command:

kubectl set image deployment/my-deployment my-container=xxxx:v2.2

In this case I get a wrong result where a node has 2 pod, a node 1 pod and last node without any pod...

To see how the deployment evolves, I can launch the command:

kubectl rollout status ds/my-daemonset

getting something like that

Waiting for rollout to finish: 0 out of 3 new pods have been updated...
Waiting for rollout to finish: 0 out of 3 new pods have been updated...
Waiting for rollout to finish: 1 out of 3 new pods have been updated...
Waiting for rollout to finish: 1 out of 3 new pods have been updated...
Waiting for rollout to finish: 1 out of 3 new pods have been updated...
Waiting for rollout to finish: 2 out of 3 new pods have been updated...
Waiting for rollout to finish: 2 out of 3 new pods have been updated...
Waiting for rollout to finish: 2 out of 3 new pods have been updated...
Waiting for rollout to finish: 2 of 3 updated pods are available...
daemon set "my-daemonset" successfully rolled out


问:
Laravel 5 Route::when() replacement
Is there a way to provide in Laravel 5.5 what 4.2 had with:

```<code>Route::when('*-ajax', 'ajax');
</code>```

I had an option to attach a filter to all ajax routes, and since then I know that filters have been replaced with middleware, but I am getting an error that:

```<code>Attribute [when] does not exist.
</code>```

答:
You can use Request::is(). Few details in the doc

It accept multiple params as well.

[edit] You also have Request::ajax() which returns true when you perform an ajax request

Title: Laravel 5 Route::when() replacement

Body:
Is there a way to provide in Laravel 5.5 what 4.2 had with:

Route::when('*-ajax', 'ajax');

I had an option to attach a filter to all ajax routes, and since then I know that filters have been replaced with middleware, but I am getting an error that:

Attribute [when] does not exist.


问:
Send/Receive Data to server in C#
In my programe I have a need for requesting data from server and upon collecting the response, use the returned data for further processing.

I am using "system.net.webrequest" class for the same. I have few questions on this:

after I receive the data (data is of 0.5MB size in minimum) I have to process this entire data to derive some result. I was thinking to store the returned data in a "txt" file and then read the data from that file and process.

Is this a better idea? If not, can you please suggest.

I am making post request to several servers (>10 servers) and using data from them. I observed that for some reason if the server is not reachable then my programe stops throwing an exception

Server Not Reachable

A first chance exception of type 'System.Net.WebException' occurred in System.dll

How can I solve this problem? Any idea?

Appreaciate your help.

Thanks,
Rahul

答:
With regards to the exception; implement a try/catch region, and take appropriate action (perhaps logging the error and queuing it for a retry in a few moments).

I'm not entirely sure of what the first question is since we don't know what the data/system is - but some thoughts:

to reduce bandwidth, if the server supports compression, make sure you are telling it - set the accept-header accordingly (request.Accept = "gzip,deflate"; on your request, if using HttpWebRequest); or maybe  a denser serialization format if you control both ends of the pipe

make sure you are making appropriate use of things like Dictionary<,> when processing the data; I can't tell you what "appropriate" is without knowing what "processing" or "the data" means in your specific context ;p

Title: Send/Receive Data to server in C#


问:
Find out Excel column character from name of cell in first row
I have an excel sheet that looks like this;

The header names are found in first row. I would like to have a VBA function that returns the column number, given the cell name in the first row. For example, getColumnNumber("B Symbol") should return B. getColumnNumber("C Symbol") should return C.

I am using Excel 2016.

答:
This is the answer to my own question, modified from teddys'. There is a slight error in his answer.</p>

```<code>With Worksheets(1).Range("a1:z1") '
    Set c = .Find("whatever you need to find", lookin:=xlValues)
    If Not c Is Nothing Then
        firstAddress = split(c.Address,"$")(1) 'should be 1, not 0
        msgbox firstAddress
    End If
End With
</code>```

Body:
This is the answer to my own question, modified from teddys'. There is a slight error in his answer.

With Worksheets(1).Range("a1:z1") '
    Set c = .Find("whatever you need to find", lookin:=xlValues)
    If Not c Is Nothing Then
        firstAddress = split(c.Address,"$")(1) 'should be 1, not 0
        msgbox firstAddress
    End If
End With


问:
How can I insert multiple rows into database in Laravel?
Here is my code:

```<code>$num = 5;
$voucher = new Voucher;

for ( $i = $num; $i > 0; $i-- ) {

    $token = generateRandomString(5, ['number', 'uppercase']);

    $voucher->prefix = $request->prefix;
    $voucher->token = $token;
    $voucher->description = $request->description;
    $voucher->date_time = time();
    $voucher->save();
}
</code>```

Obviously my code should insert 5 rows. But surprisingly it inserts only 1 row. What's wrong and how can I fix it?

答:
This is basic example create multi array and simply put in insert function.   </p>

```<code>$num = 5;
$dataArray = array();
for ( $i = $num; $i > 0; $i-- ) {

    $token = generateRandomString(5, ['number', 'uppercase']);

    $dataArray[$i]['prefix'] = $request->prefix;
    $dataArray[$i]['token'] = $token;
    $dataArray[$i]['description'] = $request->description;
    $dataArray[$i]['date_time'] = time();

}

Voucher::insert($dataArray);
</code>```

Body:
Here is my code:

$num = 5;
$voucher = new Voucher;

for ( $i = $num; $i > 0; $i-- ) {

    $token = generateRandomString(5, ['number', 'uppercase']);

    $voucher->prefix = $request->prefix;
    $voucher->token = $token;
    $voucher->description = $request->description;
    $voucher->date_time = time();
    $voucher->save();
}

Obviously my code should insert 5 rows. But surprisingly it inserts only 1 row. What's wrong and how can I fix it?

Body:
This is basic example create multi array and simply put in insert function.

$num = 5;
$dataArray = array();
for ( $i = $num; $i > 0; $i-- ) {

    $token = generateRandomString(5, ['number', 'uppercase']);

    $dataArray[$i]['prefix'] = $request->prefix;
    $dataArray[$i]['token'] = $token;
    $dataArray[$i]['description'] = $request->description;
    $dataArray[$i]['date_time'] = time();

}

Voucher::insert($dataArray);


问:
How to convert a DBNULL to double?
im getting a value from the database. it came out an error saying "Conversion from DBNULL to Double is not Valid." anyone, pls help me?

Public Function Total() As Double
        Dim Total As Double

```<code>    Dim strConn As String
    strConn = ConfigurationManager.ConnectionStrings("***").ToString
    Dim conn As New SqlConnection(strConn)

    Dim strSql As String
    strSql = "SELECT SUM (p.Price * c.Quantity) as 'Total' " & _
    "FROM CartItem sci INNER JOIN Product p ON c.ProductID=p.ProductID " & _
    "WHERE c.CartID=@CartID "

    Dim cmd As New SqlCommand(strSql, conn)

    cmd.Parameters.AddWithValue("@CartID", CartID)

    Dim da As New SqlDataAdapter(cmd)

    Dim ds As New DataSet

    conn.Open()

    da.Fill(ds, "CartItem")

    conn.Close()

    If (ds.Tables("CartItem").Rows.Count) <> 0 Then
        **Total = ds.Tables("ShopCartItem").Rows(0)("Total")**
    Else
        Total = 0.0
    End If
    Return Total
End Function
</code>```

答:
You can't cast a DbNull to a double. You can, though, cast it to a nullable double (c# double?).

I wrote a bunch of DataRow extension methods (C#) that help a lot with this. Makes the syntax a lot tidier. Usage is simple. A C# example:

```<code>public class Hormone
{
    public int           ID               { get ; private set ; }
    public HormoneLuType Type             { get ; private set ; }
    public int           AgeStarted       { get ; private set ; }
    public int           AgeStopped       { get ; private set ; }
    public int           DurationInMonths { get ; private set ; }
    public bool          IsCurrentlyUsing { get ; private set ; }
    public DateTime?     DateLastEdited   { get ; private set ; }

    public string Name { get { return Type.ToString() } }

    public Hormone( DataRow dr )
    {
        this.ID               =                    dr.CastAsInt(              "ihormoneid" )        ;
        this.Type             = new HormoneLuType( dr.CastAsIntNullable(      "ihormluid"  ) ?? 0 ) ;
        this.AgeStarted       = (int)              dr.CastAsDecimal(          "nstartage"  )        ;
        this.AgeStopped       = (int)              dr.CastAsDecimal(          "nendage"    )        ;
        this.DurationInMonths = (int)              dr.CastAsDecimal(          "nduration"  )        ;
        this.IsCurrentlyUsing =                    dr.CastAsBool(             "lusingnow"  )        ;
        this.DateLastEdited   =                    dr.CastAsDateTimeNullable( "tedit"      )        ;

        return ;
    }
}
</code>```

Here's the extension class:

```<code>using System;
using System.Data;

namespace DataAccess.Utils
{
    public static class DataRowExtensions
    {

        #region downcast to DateTime

        public static DateTime CastAsDateTime( this DataRow row , int index )
        {
            return toDateTime( row[index] ) ;
        }
        public static DateTime CastAsDateTime( this DataRow row , string columnName )
        {
            return toDateTime( row[columnName] ) ;
        }

        public static DateTime? CastAsDateTimeNullable( this DataRow row , int index )
        {
            return toDateTimeNullable( row[index] );
        }
        public static DateTime? CastAsDateTimeNullable( this DataRow row , string columnName )
        {
            return toDateTimeNullable( row[columnName] ) ;
        }

        #region conversion helpers

        private static DateTime toDateTime( object o )
        {
            DateTime value = (DateTime)o;
            return value;
        }

        private static DateTime? toDateTimeNullable( object o )
        {
            bool  hasValue = !( o is DBNull );
            DateTime? value    = ( hasValue ? (DateTime?) o : (DateTime?) null ) ;
            return value;
        }

        #endregion

        #endregion downcast to DateTime

        #region downcast to byte[]

        public static byte[] CastAsByteArray( this DataRow row , int index )
        {
            return toByteArray( row[index] );
        }
        public static byte[] CastAsByteArray( this DataRow row , string columnName )
        {
            return toByteArray( row[columnName] );
        }

        #region conversion helpers

        private static byte[] toByteArray( object o )
        {
            bool   hasValue = !( o is DBNull );
            byte[] value    = ( hasValue ? (byte[]) o : (byte[]) null ) ;
            return value;
        }

        #endregion

        #endregion downcast to Byte[]

        #region downcast to int

        public static int CastAsInt( this DataRow row , int index )
        {
            return toInt( row[index] ) ;
        }
        public static int CastAsInt( this DataRow row , string columnName )
        {
            return toInt( row[columnName] ) ;
        }

        public static int? CastAsIntNullable( this DataRow row , int index )
        {
            return toIntNullable( row[index] );
        }
        public static int? CastAsIntNullable( this DataRow row , string columnName )
        {
            return toIntNullable( row[columnName] ) ;
        }

        #region conversion helpers

        private static int toInt( object o )
        {
            int value = (int)o;
            return value;
        }

        private static int? toIntNullable( object o )
        {
            bool hasValue = !( o is DBNull );
            int? value    = ( hasValue ? (int?) o : (int?) null ) ;
            return value;
        }

        #endregion

        #endregion downcast to int

        #region downcast to int

        public static decimal CastAsDecimal( this DataRow row , int index )
        {
            return toDecimal( row[index] ) ;
        }
        public static decimal CastAsDecimal( this DataRow row , string columnName )
        {
            return toDecimal( row[columnName] ) ;
        }

        public static decimal? CastAsDecimalNullable( this DataRow row , int index )
        {
            return toDecimalNullable( row[index] );
        }
        public static decimal? CastAsDecimalNullable( this DataRow row , string columnName )
        {
            return toDecimalNullable( row[columnName] ) ;
        }

        #region conversion helpers

        private static decimal toDecimal( object o )
        {
            decimal value = (decimal)o;
            return value;
        }

        private static decimal? toDecimalNullable( object o )
        {
            bool     hasValue = !( o is DBNull );
            decimal? value    = ( hasValue ? (decimal?) o : (decimal?) null ) ;
            return value;
        }

        #endregion

        #endregion downcast to int

        #region downcast to bool

        public static bool CastAsBool( this DataRow row , int index )
        {
            return toBool( row[index] ) ;
        }
        public static bool CastAsBool( this DataRow row , string columnName )
        {
            return toBool( row[columnName] ) ;
        }

        public static bool? CastAsBoolNullable( this DataRow row , int index )
        {
            return toBoolNullable( row[index] );
        }
        public static bool? CastAsBoolNullable( this DataRow row , string columnName )
        {
            return toBoolNullable( row[columnName] ) ;
        }

        #region conversion helpers

        private static bool toBool( object o )
        {
            bool value = (bool)o;
            return value;
        }

        private static bool? toBoolNullable( object o )
        {
            bool  hasValue = !( o is DBNull );
            bool? value    = ( hasValue ? (bool?) o : (bool?) null ) ;
            return value;
        }

        #endregion

        #endregion downcast to bool

        #region downcast to string

        public static string CastAsString( this DataRow row , int index )
        {
            return toString( row[index] );
        }
        public static string CastAsString( this DataRow row , string columnName )
        {
            return toString( row[columnName] );
        }

        #region conversion helpers

        private static string toString( object o )
        {
            bool   hasValue = !( o is DBNull );
            string value    = ( hasValue ? (string) o : (string) null ) ;
            return value;
        }

        #endregion

        #endregion downcast to string

    }
}
</code>```

Hope this helps!

Title: How to convert a DBNULL to double?

Body:
im getting a value from the database. it came out an error saying "Conversion from DBNULL to Double is not Valid." anyone, pls help me?

Public Function Total() As Double
        Dim Total As Double

    Dim strConn As String
    strConn = ConfigurationManager.ConnectionStrings("***").ToString
    Dim conn As New SqlConnection(strConn)

    Dim strSql As String
    strSql = "SELECT SUM (p.Price * c.Quantity) as 'Total' " & _
    "FROM CartItem sci INNER JOIN Product p ON c.ProductID=p.ProductID " & _
    "WHERE c.CartID=@CartID "

    Dim cmd As New SqlCommand(strSql, conn)

    cmd.Parameters.AddWithValue("@CartID", CartID)

    Dim da As New SqlDataAdapter(cmd)

    Dim ds As New DataSet

    conn.Open()

    da.Fill(ds, "CartItem")

    conn.Close()

    If (ds.Tables("CartItem").Rows.Count) <> 0 Then
        **Total = ds.Tables("ShopCartItem").Rows(0)("Total")**
    Else
        Total = 0.0
    End If
    Return Total
End Function

Body:
You can't cast a DbNull to a double. You can, though, cast it to a nullable double (c# double?).

I wrote a bunch of DataRow extension methods (C#) that help a lot with this. Makes the syntax a lot tidier. Usage is simple. A C# example:

public class Hormone
{
    public int           ID               { get ; private set ; }
    public HormoneLuType Type             { get ; private set ; }
    public int           AgeStarted       { get ; private set ; }
    public int           AgeStopped       { get ; private set ; }
    public int           DurationInMonths { get ; private set ; }
    public bool          IsCurrentlyUsing { get ; private set ; }
    public DateTime?     DateLastEdited   { get ; private set ; }

    public string Name { get { return Type.ToString() } }

    public Hormone( DataRow dr )
    {
        this.ID               =                    dr.CastAsInt(              "ihormoneid" )        ;
        this.Type             = new HormoneLuType( dr.CastAsIntNullable(      "ihormluid"  ) ?? 0 ) ;
        this.AgeStarted       = (int)              dr.CastAsDecimal(          "nstartage"  )        ;
        this.AgeStopped       = (int)              dr.CastAsDecimal(          "nendage"    )        ;
        this.DurationInMonths = (int)              dr.CastAsDecimal(          "nduration"  )        ;
        this.IsCurrentlyUsing =                    dr.CastAsBool(             "lusingnow"  )        ;
        this.DateLastEdited   =                    dr.CastAsDateTimeNullable( "tedit"      )        ;

        return ;
    }
}

Here's the extension class:

using System;
using System.Data;

namespace DataAccess.Utils
{
    public static class DataRowExtensions
    {

        #region downcast to DateTime

        public static DateTime CastAsDateTime( this DataRow row , int index )
        {
            return toDateTime( row[index] ) ;
        }
        public static DateTime CastAsDateTime( this DataRow row , string columnName )
        {
            return toDateTime( row[columnName] ) ;
        }

        public static DateTime? CastAsDateTimeNullable( this DataRow row , int index )
        {
            return toDateTimeNullable( row[index] );
        }
        public static DateTime? CastAsDateTimeNullable( this DataRow row , string columnName )
        {
            return toDateTimeNullable( row[columnName] ) ;
        }

        #region conversion helpers

        private static DateTime toDateTime( object o )
        {
            DateTime value = (DateTime)o;
            return value;
        }

        private static DateTime? toDateTimeNullable( object o )
        {
            bool  hasValue = !( o is DBNull );
            DateTime? value    = ( hasValue ? (DateTime?) o : (DateTime?) null ) ;
            return value;
        }

        #endregion

        #endregion downcast to DateTime

        #region downcast to byte[]

        public static byte[] CastAsByteArray( this DataRow row , int index )
        {
            return toByteArray( row[index] );
        }
        public static byte[] CastAsByteArray( this DataRow row , string columnName )
        {
            return toByteArray( row[columnName] );
        }

        #region conversion helpers

        private static byte[] toByteArray( object o )
        {
            bool   hasValue = !( o is DBNull );
            byte[] value    = ( hasValue ? (byte[]) o : (byte[]) null ) ;
            return value;
        }

        #endregion

        #endregion downcast to Byte[]

        #region downcast to int

        public static int CastAsInt( this DataRow row , int index )
        {
            return toInt( row[index] ) ;
        }
        public static int CastAsInt( this DataRow row , string columnName )
        {
            return toInt( row[columnName] ) ;
        }

        public static int? CastAsIntNullable( this DataRow row , int index )
        {
            return toIntNullable( row[index] );
        }
        public static int? CastAsIntNullable( this DataRow row , string columnName )
        {
            return toIntNullable( row[columnName] ) ;
        }

        #region conversion helpers

        private static int toInt( object o )
        {
            int value = (int)o;
            return value;
        }

        private static int? toIntNullable( object o )
        {
            bool hasValue = !( o is DBNull );
            int? value    = ( hasValue ? (int?) o : (int?) null ) ;
            return value;
        }

        #endregion

        #endregion downcast to int

        #region downcast to int

        public static decimal CastAsDecimal( this DataRow row , int index )
        {
            return toDecimal( row[index] ) ;
        }
        public static decimal CastAsDecimal( this DataRow row , string columnName )
        {
            return toDecimal( row[columnName] ) ;
        }

        public static decimal? CastAsDecimalNullable( this DataRow row , int index )
        {
            return toDecimalNullable( row[index] );
        }
        public static decimal? CastAsDecimalNullable( this DataRow row , string columnName )
        {
            return toDecimalNullable( row[columnName] ) ;
        }

        #region conversion helpers

        private static decimal toDecimal( object o )
        {
            decimal value = (decimal)o;
            return value;
        }

        private static decimal? toDecimalNullable( object o )
        {
            bool     hasValue = !( o is DBNull );
            decimal? value    = ( hasValue ? (decimal?) o : (decimal?) null ) ;
            return value;
        }

        #endregion

        #endregion downcast to int

        #region downcast to bool

        public static bool CastAsBool( this DataRow row , int index )
        {
            return toBool( row[index] ) ;
        }
        public static bool CastAsBool( this DataRow row , string columnName )
        {
            return toBool( row[columnName] ) ;
        }

        public static bool? CastAsBoolNullable( this DataRow row , int index )
        {
            return toBoolNullable( row[index] );
        }
        public static bool? CastAsBoolNullable( this DataRow row , string columnName )
        {
            return toBoolNullable( row[columnName] ) ;
        }

        #region conversion helpers

        private static bool toBool( object o )
        {
            bool value = (bool)o;
            return value;
        }

        private static bool? toBoolNullable( object o )
        {
            bool  hasValue = !( o is DBNull );
            bool? value    = ( hasValue ? (bool?) o : (bool?) null ) ;
            return value;
        }

        #endregion

        #endregion downcast to bool

        #region downcast to string

        public static string CastAsString( this DataRow row , int index )
        {
            return toString( row[index] );
        }
        public static string CastAsString( this DataRow row , string columnName )
        {
            return toString( row[columnName] );
        }

        #region conversion helpers

        private static string toString( object o )
        {
            bool   hasValue = !( o is DBNull );
            string value    = ( hasValue ? (string) o : (string) null ) ;
            return value;
        }

        #endregion

        #endregion downcast to string

    }
}

Hope this helps!