问:
Select specific values from the same column and display in different columns
I am trying to display two values from the same table in a sql query. The table holds 2 keys which have these values.

Currently, I made this

```<code>SELECT p.post_title, t.name, pm.meta_value AS address, pm.meta_value AS id
FROM `wp_posts` p
  LEFT JOIN wp_term_relationships trr ON p.ID = trr.object_id
  LEFT JOIN wp_term_taxonomy tax ON trr.term_taxonomy_id = tax.term_taxonomy_id
  LEFT JOIN wp_terms t ON tax.term_taxonomy_id = t.term_id
  LEFT JOIN wp_postmeta pm ON p.ID = pm.post_id
WHERE
  p.post_type = 'network-type' AND t.slug = 'atm' AND
  pm.meta_key IN ('network_address', 'network_branch_atm_id')
</code>```

But this shows

```<code>| post_title | name | address   | id        |
---------------------------------------------
| Post name  | bla  | 12        | 12        |
| Post name  | bla  | address 1 | address 1 |
</code>```

The postmeta table has values like this

```<code>| meta_id | post_id | meta_key              | meta_value |
----------------------------------------------------------
| 1212    | 323     | network_address       | address 1  |
| 1212    | 323     | network_branch_atm_id | 12         |
</code>```

I tried using CASE but got errors (user not allowed to execute).

What should I change to get

```<code>| post_title | name | address   | id        |
---------------------------------------------
| Post name  | bla  | address 1 | 12        |
</code>```

答:
Aggregate on the post title name, and then pivot out the address and id.  The difficulty you are having (and which I also find with the wm_postmeta table) is that information is stored as keys and values.  It can require some massaging to extract data the way you want it from the Wordpress schema.

```<code>SELECT
    p.post_title,
    t.name,
    MAX(CASE WHEN pm.meta_key = 'network_address'       THEN pm.meta_value END) AS address,
    MAX(CASE WHEN pm.meta_key = 'network_branch_atm_id' THEN pm.meta_value END) AS id
FROM wp_posts p
LEFT JOIN wp_term_relationships trr
    ON p.ID = trr.object_id
LEFT JOIN wp_term_taxonomy tax
    ON trr.term_taxonomy_id = tax.term_taxonomy_id
LEFT JOIN wp_terms t
    ON tax.term_taxonomy_id = t.term_id
LEFT JOIN wp_postmeta pm
    ON p.ID = pm.post_id
WHERE
    p.post_type = 'network-type' AND
    t.slug = 'atm' AND
    pm.meta_key IN ('network_address', 'network_branch_atm_id')
GROUP BY
    p.post_title,
    t.name;
</code>```

Body:
I am trying to display two values from the same table in a sql query. The table holds 2 keys which have these values.

Currently, I made this

SELECT p.post_title, t.name, pm.meta_value AS address, pm.meta_value AS id
FROM `wp_posts` p
  LEFT JOIN wp_term_relationships trr ON p.ID = trr.object_id
  LEFT JOIN wp_term_taxonomy tax ON trr.term_taxonomy_id = tax.term_taxonomy_id
  LEFT JOIN wp_terms t ON tax.term_taxonomy_id = t.term_id
  LEFT JOIN wp_postmeta pm ON p.ID = pm.post_id
WHERE
  p.post_type = 'network-type' AND t.slug = 'atm' AND
  pm.meta_key IN ('network_address', 'network_branch_atm_id')

But this shows

| post_title | name | address   | id        |
---------------------------------------------
| Post name  | bla  | 12        | 12        |
| Post name  | bla  | address 1 | address 1 |

The postmeta table has values like this

| meta_id | post_id | meta_key              | meta_value |
----------------------------------------------------------
| 1212    | 323     | network_address       | address 1  |
| 1212    | 323     | network_branch_atm_id | 12         |

I tried using CASE but got errors (user not allowed to execute).

What should I change to get

| post_title | name | address   | id        |
---------------------------------------------
| Post name  | bla  | address 1 | 12        |

Body:
Aggregate on the post title name, and then pivot out the address and id.  The difficulty you are having (and which I also find with the wm_postmeta table) is that information is stored as keys and values.  It can require some massaging to extract data the way you want it from the Wordpress schema.

SELECT
    p.post_title,
    t.name,
    MAX(CASE WHEN pm.meta_key = 'network_address'       THEN pm.meta_value END) AS address,
    MAX(CASE WHEN pm.meta_key = 'network_branch_atm_id' THEN pm.meta_value END) AS id
FROM wp_posts p
LEFT JOIN wp_term_relationships trr
    ON p.ID = trr.object_id
LEFT JOIN wp_term_taxonomy tax
    ON trr.term_taxonomy_id = tax.term_taxonomy_id
LEFT JOIN wp_terms t
    ON tax.term_taxonomy_id = t.term_id
LEFT JOIN wp_postmeta pm
    ON p.ID = pm.post_id
WHERE
    p.post_type = 'network-type' AND
    t.slug = 'atm' AND
    pm.meta_key IN ('network_address', 'network_branch_atm_id')
GROUP BY
    p.post_title,
    t.name;


来源: stackexchange

问:
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?

答:
Finally Solved .. it was easier than thought.. as I was understanding the three values I'm interested in were passed some how to the infoTableViewController I wanted to get rid of. And they were passed, already converted to String with the function sensorUpdatedValues inside MainView controller

```<code>  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 )
    }
  }
</code>```

so I traced down the function inside my InfospeedoViewController ( as xCode was asking for it because it was present in InfoTableViewController and rerouting to InfoSpeedoViewController made it necessary) and inside that function's body I made the connection of the values to the labels.

```<code> func showMeasurementWithSpeed( _ speed:String, cadence:String, distance:String  ) {

          speedDisplayLabel.text = speed
          cadenceDisplayLabel.text = cadence
          distanceDisplayLabel.text = distance

//        showDetailText(speed, atSection: Constants.MeasurementsSection, row:Constants.SpeedRow)
//        showDetailText(cadence, atSection: Constants.MeasurementsSection, row:Constants.CadenceRow)
//        showDetailText(distance, atSection: Constants.MeasurementsSection, row:Constants.DistanceRow)

    }
</code>```

the commented out parts were the old InfoTableViewController indication to fill the cells..
Many thanks for your help. I learned a few things and consolidated others. I guess we went the hard way trying to catch this values in the wrong place, but I guess that just because I had all the project's file printed that I could trace the data flow easier. Not fully understanding the code because of my low knowledge of swift made it a bit more difficoult, but I had this feeling the this solution was logic as often the simple way is the best way, an often one just can't see it.
thanks again
I have two more values I want to get. A new adventure begins ..should I post another question or continue this one?

ContentLicense: CC BY-SA 3.0

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:
Finally Solved .. it was easier than thought.. as I was understanding the three values I'm interested in were passed some how to the infoTableViewController I wanted to get rid of. And they were passed, already converted to String with the function sensorUpdatedValues inside MainView controller

  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 )
    }
  }

so I traced down the function inside my InfospeedoViewController ( as xCode was asking for it because it was present in InfoTableViewController and rerouting to InfoSpeedoViewController made it necessary) and inside that function's body I made the connection of the values to the labels.

 func showMeasurementWithSpeed( _ speed:String, cadence:String, distance:String  ) {

          speedDisplayLabel.text = speed
          cadenceDisplayLabel.text = cadence
          distanceDisplayLabel.text = distance

//        showDetailText(speed, atSection: Constants.MeasurementsSection, row:Constants.SpeedRow)
//        showDetailText(cadence, atSection: Constants.MeasurementsSection, row:Constants.CadenceRow)
//        showDetailText(distance, atSection: Constants.MeasurementsSection, row:Constants.DistanceRow)

    }

the commented out parts were the old InfoTableViewController indication to fill the cells..
Many thanks for your help. I learned a few things and consolidated others. I guess we went the hard way trying to catch this values in the wrong place, but I guess that just because I had all the project's file printed that I could trace the data flow easier. Not fully understanding the code because of my low knowledge of swift made it a bit more difficoult, but I had this feeling the this solution was logic as often the simple way is the best way, an often one just can't see it.
thanks again
I have two more values I want to get. A new adventure begins ..should I post another question or continue this one?


问:
Why are the result of preg_match not displayed?
I can't see the results of preg_match by regex! Where is the problem?

```<code>preg_match('@^(?:http://)?([^/]+)@i',"'".$urls['url']."'", $matches);
    $host = $matches[1];
    preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "from: <p id='long'>{$matches[0]}\n</p>";
}
</code>```

Output:

```<code>from:
</code>```

答:
Why don't you use parse_url() ?

and change "'".$urls['url']."'" to $urls['url']

ContentLicense: CC BY-SA 2.5

Body:
I can't see the results of preg_match by regex! Where is the problem?

preg_match('@^(?:http://)?([^/]+)@i',"'".$urls['url']."'", $matches);
    $host = $matches[1];
    preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "from:
{$matches[0]}\n
";
}

Output:

from:


问:
keyevent in jQuery not working
I've got an HTML element that I want to fill with specific content after someone presses "1" on the keyboard.
I use an external .js file which contains the following code:

```<code>$(document).ready(function() {
    $("#myid").html("Hello, 0111");
    $("#myid2").html("Lorem Ipsum");

    $(document).keyup(function (pressed_key) {
        if (pressed_key.key === "1") {
            $("#myid").html("Button pressed");

            setTimeout(￼function () {
                $("#myid").html("Button not pressed");
            }, 1000);
        }
    }

});
</code>```

My HTML body looks like this:

```<code><body>
    <div id="myid">0129</div>
    <div id="myid2"></div>
    <script src="js/libs/jquery/jquery.min.js"></script>
    <script src="js/script.js"></script>
</body>
</code>```

The code is not working, it outputs the content of the HTML document.

However, if I comment out the .keyup function, the rest of the JavaScript code works and changes the HTML content accordingly.

Any ideas?

答:
you need to pass event to the keyup handler not the value of the character which was typed.

```<code>$(document).ready(function() {
  $("#myid").html("Hello, 0111");
  $("#myid2").html("Lorem Ipsum");

  $(document).keyup(function(event) {
    if (String.fromCharCode(event.which) === "1") {
      $("#myid").html("Button pressed");

      setTimeout(function(){
        $("#myid").html("Button not pressed");
      }, 1000);
    }
  });
});
</code>```

0129

```

Title: keyevent in jQuery not working

Body:
I've got an HTML element that I want to fill with specific content after someone presses "1" on the keyboard.
I use an external .js file which contains the following code:

$(document).ready(function() {
    $("#myid").html("Hello, 0111");
    $("#myid2").html("Lorem Ipsum");

    $(document).keyup(function (pressed_key) {
        if (pressed_key.key === "1") {
            $("#myid").html("Button pressed");

            setTimeout(￼function () {
                $("#myid").html("Button not pressed");
            }, 1000);
        }
    }

});

My HTML body looks like this:

0129

The code is not working, it outputs the content of the HTML document.

However, if I comment out the .keyup function, the rest of the JavaScript code works and changes the HTML content accordingly.

Any ideas?

Body:
you need to pass event to the keyup handler not the value of the character which was typed.

$(document).ready(function() {
  $("#myid").html("Hello, 0111");
  $("#myid2").html("Lorem Ipsum");

  $(document).keyup(function(event) {
    if (String.fromCharCode(event.which) === "1") {
      $("#myid").html("Button pressed");

      setTimeout(function(){
        $("#myid").html("Button not pressed");
      }, 1000);
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myid">0129</div>
<div id="myid2"></div>


问:
scalatest using contains allElementsOf with ArrayBuffers
I have been working with some XML data and have been trying to write a test that tries to match that the direct children of two xml trees have all the same nodes of type bar.

I started off using a simple test to ensure that both data structures match.

The assertion matching them as strings works:

```<code>result.toString should be(expected.toString)
</code>```

but the assertion matching each individual element fails:

```<code>result should contain allElementsOf expected
</code>```

which I found on this answer here

because these simpler assertion did not work:

```<code>result should be(expected)
result should contain(expected(1))
</code>```

The test sets up the XML using before block in the test class:

```<code>  var foo: Elem = _

  before {
   foo = <foo>
     <bar type="greet" style="pleasent" target="anyone">hi</bar>
     <bar type="count">1</bar>
     <bar type="color">yellow</bar>
     <baz>
      <bar type="bad">Bad</bar>
    </baz>
  </foo>
}
</code>```

This is the code of the test:

```<code>it should "allow use of map and filter" in {
  import scala.collection.mutable.ArrayBuffer

  val expected = ArrayBuffer(
    (
      "bar",
      Map(
        "type" -> "greet",
        "style" -> "pleasent",
        "target" -> "anyone"
      ),
      "hi"
    ),
    (
      "bar",
      Map("type" -> "count"),
      "1"
    ),
    (
      "bar",
      Map("type" -> "color"),
      "yellow"
    )
  )

  val result = foo.child.map(x => {
    x match {
      case <bar>{text}</bar> => (x.label, x.attributes.asAttrMap, text)
      case <baz>_</baz> => (x.label, Map[String,String](), "")
      case _ => ("", Map[String,String](), "")
    }
  })
  .filter(x => {
    x match {
      case ("bar", _, _) => true
      case _ => false
    }
  })

  result.toString should be(expected.toString) // works
 // result should contain allElementsOf expected // fails
</code>```

}

答:
The type of elements in the collections you are comparing are different:

result contains elements of type (String, Map[String, String], Object)

expected contains elements of type (String, Map[String, String], String)

They might have the same toString representation, but that doesn't mean they are equal. The type of result is probably not what you expected from this pattern match:

```<code>x match {
  case <bar>{text}</bar> => (x.label, x.attributes.asAttrMap, text)
  case <baz>_</baz> => (x.label, Map[String,String](), "")
  case _ => ("", Map[String,String](), "")
}
</code>```

Here text is of type xml.Node. If you want to extract the contents of the node you can use text.text which also makes the test pass.

Aside: Recently there was a PR merged to Scala to issue a warning when the Object type is inferred (scala/scala#6178), because it's usually a programmer error.

Body:
I have been working with some XML data and have been trying to write a test that tries to match that the direct children of two xml trees have all the same nodes of type bar.

I started off using a simple test to ensure that both data structures match.

The assertion matching them as strings works:

result.toString should be(expected.toString)

but the assertion matching each individual element fails:

result should contain allElementsOf expected

which I found on this answer here

because these simpler assertion did not work:

result should be(expected)
result should contain(expected(1))

The test sets up the XML using before block in the test class:

  var foo: Elem = _

  before {
   foo = <foo>
     <bar type="greet" style="pleasent" target="anyone">hi</bar>
     <bar type="count">1</bar>
     <bar type="color">yellow</bar>
     <baz>
      <bar type="bad">Bad</bar>
    </baz>
  </foo>
}

This is the code of the test:

it should "allow use of map and filter" in {
  import scala.collection.mutable.ArrayBuffer

  val expected = ArrayBuffer(
    (
      "bar",
      Map(
        "type" -> "greet",
        "style" -> "pleasent",
        "target" -> "anyone"
      ),
      "hi"
    ),
    (
      "bar",
      Map("type" -> "count"),
      "1"
    ),
    (
      "bar",
      Map("type" -> "color"),
      "yellow"
    )
  )

  val result = foo.child.map(x => {
    x match {
      case <bar>{text}</bar> => (x.label, x.attributes.asAttrMap, text)
      case <baz>_</baz> => (x.label, Map[String,String](), "")
      case _ => ("", Map[String,String](), "")
    }
  })
  .filter(x => {
    x match {
      case ("bar", _, _) => true
      case _ => false
    }
  })

  result.toString should be(expected.toString) // works
 // result should contain allElementsOf expected // fails

}

Body:
The type of elements in the collections you are comparing are different:

result contains elements of type (String, Map[String, String], Object)

expected contains elements of type (String, Map[String, String], String)

They might have the same toString representation, but that doesn't mean they are equal. The type of result is probably not what you expected from this pattern match:

x match {
  case <bar>{text}</bar> => (x.label, x.attributes.asAttrMap, text)
  case <baz>_</baz> => (x.label, Map[String,String](), "")
  case _ => ("", Map[String,String](), "")
}

Here text is of type xml.Node. If you want to extract the contents of the node you can use text.text which also makes the test pass.

Aside: Recently there was a PR merged to Scala to issue a warning when the Object type is inferred (scala/scala#6178), because it's usually a programmer error.


问:
Close dropdown when second is opened / document.click blocked by click Angular 5
I am trying to create a directive for a drop-down, as long as I am working with single one it works like a charm. I can spot click outside dropdown using following code:

```<code>@HostListener('document:click', ['$event'])
  onDocumentClick(event: any): void {
    console.log("document click");
    // close
}
@HostListener('click')
  onClick(): void {
    console.log('click on ');
    // toggle
  }
</code>```

The problem occurs when there are 2 dropdowns created. I would like close first drop-down when second is opened, however when I click on the second dropdown, only "click" event is getting triggered and "document.click" is not getting executed. I would expect that both events should occur unless I explicitly use preventDefault on click but apparently this happens automatically.

What should be correct approach in Angular 5 to close first drop-down when second is opened?

答:
How about creating a directive that you can use everywhere ? </p>

```<code>@Directive( {
    selector : '[clicked-outside]' ,
    host     : {
        '(document:click)' : 'onClick($event)',
        '(document:touch)' : 'onClick($event)',
        '(document:touchstart)' : 'onClick($event)'
    }
} )
export class ClickedOutsideDirective {
    @Input( 'clicked-outside' ) callback : Function;

    constructor ( private _el : ElementRef ) {
    }

    private onClick ( event : any ) {
        if ( this.clickedOutside( event ) ) {
            if ( this.callback ) {
                this.callback();
            }
        }
    }

    private clickedOutside ( event : any ) {
        let clickedTarget = event.target;
        let host          = this._el.nativeElement;
        do {
            if ( clickedTarget === host ) {
                return false;
            }
            clickedTarget = clickedTarget.parentNode;
        } while ( clickedTarget );
        return true;
    }
}
</code>```

<p>and you can use it like this : </p>

```<code>@Component({
   selector:'your-dropdown',
   template:`
       <div class="your-dropdown-top-most-wrapper" [clicked-outside]="onClickOutSide"></div>

   `
})
export class YouDropdownComponent{

   public onClickOutSide = ()=>{

        this.closeMyDropdown()// this is your function that closes the dropdown
   }
}
</code>```

Body:
I am trying to create a directive for a drop-down, as long as I am working with single one it works like a charm. I can spot click outside dropdown using following code:

@HostListener('document:click', ['$event'])
  onDocumentClick(event: any): void {
    console.log("document click");
    // close
}
@HostListener('click')
  onClick(): void {
    console.log('click on ');
    // toggle
  }

The problem occurs when there are 2 dropdowns created. I would like close first drop-down when second is opened, however when I click on the second dropdown, only "click" event is getting triggered and "document.click" is not getting executed. I would expect that both events should occur unless I explicitly use preventDefault on click but apparently this happens automatically.

What should be correct approach in Angular 5 to close first drop-down when second is opened?

Body:
How about creating a directive that you can use everywhere ?

@Directive( {
    selector : '[clicked-outside]' ,
    host     : {
        '(document:click)' : 'onClick($event)',
        '(document:touch)' : 'onClick($event)',
        '(document:touchstart)' : 'onClick($event)'
    }
} )
export class ClickedOutsideDirective {
    @Input( 'clicked-outside' ) callback : Function;

    constructor ( private _el : ElementRef ) {
    }

    private onClick ( event : any ) {
        if ( this.clickedOutside( event ) ) {
            if ( this.callback ) {
                this.callback();
            }
        }
    }

    private clickedOutside ( event : any ) {
        let clickedTarget = event.target;
        let host          = this._el.nativeElement;
        do {
            if ( clickedTarget === host ) {
                return false;
            }
            clickedTarget = clickedTarget.parentNode;
        } while ( clickedTarget );
        return true;
    }
}

and you can use it like this :

@Component({
   selector:'your-dropdown',
   template:`
       <div class="your-dropdown-top-most-wrapper" [clicked-outside]="onClickOutSide"></div>

   `
})
export class YouDropdownComponent{

   public onClickOutSide = ()=>{

        this.closeMyDropdown()// this is your function that closes the dropdown
   }
}


问:
Different activity title in different intent actions
I have one activity and three intet filters, each with different label set on, (AndroidManifiest.xml below)

```<code>    <activity android:name=".activities.RecordActivity">
        <intent-filter>
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="com.keitai.enigma.OPEN_RECORD" />
        </intent-filter>
        <intent-filter android:label="@string/newRecord">
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="com.keitai.enigma.NEW_RECORD" />
        </intent-filter>
        <intent-filter android:label="@string/editRecord">
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="com.keitai.enigma.EDIT_RECORD" />
        </intent-filter>
    </activity>
</code>```

But activity title is not changing to label set in intent filter :( Activity always contains application label.

What I'm donig wrong?

答:
You use intents usually to pass information between activities, apps or services (just few examples).
My understanding is, that you want to change your title of one activity depending on e.g. if a button is pressed.
Therefore you need to set simply in your activity

 this.setTitle("YOUR ACTIVITY NAME");

In case you want this to happen after a button click, put it into the listener of the corresponding button.

Body:
I have one activity and three intet filters, each with different label set on, (AndroidManifiest.xml below)

    <activity android:name=".activities.RecordActivity">
        <intent-filter>
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="com.keitai.enigma.OPEN_RECORD" />
        </intent-filter>
        <intent-filter android:label="@string/newRecord">
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="com.keitai.enigma.NEW_RECORD" />
        </intent-filter>
        <intent-filter android:label="@string/editRecord">
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="com.keitai.enigma.EDIT_RECORD" />
        </intent-filter>
    </activity>

But activity title is not changing to label set in intent filter :( Activity always contains application label.

What I'm donig wrong?


问:
Find out who logged in as me, using su
On linux one can (if he has sudo rights) log in, and take control of another users account/username, doing sudo su - username

But is there a way to find out who logged in like this, and used my account?

答: /var/log/auth.log contains the  logging information for sudo attempts in ubuntu

Title: Find out who logged in as me, using su


问:
How to solve "ptrace operation not permitted" when trying to attach GDB to a process?
I'm trying to attach to a program with GDB but it returns:

Attaching to process 29139

Could not attach to process.  If your uid matches the uid of the target
process, check the setting of /proc/sys/kernel/yama/ptrace_scope, or try
again as the root user.  For more details, see /etc/sysctl.d/10-ptrace.conf

ptrace: Operation not permitted.

gdb-debugger returns:

Failed to attach to process, please check privileges and try again.

strace returns:

attach: ptrace(PTRACE_ATTACH, ...): Operation not permitted

I changed "kernel.yama.ptrace_scope" 1 to 0 and /proc/sys/kernel/yama/ptrace_scope 1 to 0 and tried set environment LD_PRELOAD=./ptrace.so with this:

```<code>#include <stdio.h>
int ptrace(int i, int j, int k, int l) {
    printf(" ptrace(%i, %i, %i, %i), returning -1\n", i, j, k, l);
    return 0;
}
</code>```

But it still returns the same error. How can I attach it to debuggers?

答:
I have faced the same problem and try a lot of solution but finally, I have found the solution, but really I don't know what the problem was. First I modified the ptrace_conf value and login into Ubuntu as a root but the problem still appears. But the most strange thing that happened is the gdb showed me a message that says:

Could not attach to process.  If your uid matches the uid of the target process, check the setting of /proc/sys/kernel/yama/ptrace_scope, or try again as the root user.

For more details, see /etc/sysctl.d/10-ptrace.conf
warning: process 3767 is already traced by process 3755 ptrace: Operation not permitted.

With ps command terminal, the process 3755 was not listed.

I found the process 3755 in /proc/$pid but I don't understand what was it!!

Finally, I deleted the target file (foo.c) that I try to attach it vid gdb and tracer c program using PTRACE_ATTACH syscall, and in the other folder, I created another c program and compiled it.

the problem is solved and I was enabled to attach to another process either by gdb or ptrace_attach syscall.

(gdb) attach 4416

Attaching to process 4416

and I send a lot of signals to process 4416.  I tested it with both gdb and ptrace, both of them run correctly.

really I don't know the problem what was, but I think it is not a bug in Ubuntu as a lot of sites have referred to it, such https://askubuntu.com/questions/143561/why-wont-strace-gdb-attach-to-a-process-even-though-im-root

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to attach to a program with GDB but it returns:

Attaching to process 29139

Could not attach to process.  If your uid matches the uid of the target
process, check the setting of /proc/sys/kernel/yama/ptrace_scope, or try
again as the root user.  For more details, see /etc/sysctl.d/10-ptrace.conf

ptrace: Operation not permitted.

gdb-debugger returns:

Failed to attach to process, please check privileges and try again.

strace returns:

attach: ptrace(PTRACE_ATTACH, ...): Operation not permitted

I changed "kernel.yama.ptrace_scope" 1 to 0 and /proc/sys/kernel/yama/ptrace_scope 1 to 0 and tried set environment LD_PRELOAD=./ptrace.so with this:

#include <stdio.h>
int ptrace(int i, int j, int k, int l) {
    printf(" ptrace(%i, %i, %i, %i), returning -1\n", i, j, k, l);
    return 0;
}

But it still returns the same error. How can I attach it to debuggers?


问:
How to parse a CSV file in an ASP.NET website?
In my website, I have many CSV files that I need to parse and insert their data into my MySQL database.

How can I parse the CSV in my website programmatically?

答:
Got the Answer:

I have successfully done the parsing of my CSV file using the below code:

```<code>_nNrRowsProccessed = 0;

    string connectionString = @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq="+ConfigurationManager.AppSettings["csvFolder"]+";";

    OdbcConnection conn = new OdbcConnection(connectionString);

    try
    {
        conn.Open();

        string strFileName = ConfigurationManager.AppSettings["csvFileName"];
        string strSQL = "Select * from " + strFileName;

        OdbcCommand cmd = new OdbcCommand();
        cmd.Connection = conn;
        cmd.CommandText = strSQL;
        cmd.CommandType = CommandType.Text;

        OdbcDataReader reader = cmd.ExecuteReader();
        string strLine = null;

        MasterCalendar_DB.OpenMySQLConnection();

        while (reader.Read())
        {
            // insert data into mastercalendar
            strLine = reader[0].ToString();
            string[] arLine = strLine.Split(';');

            string strAgencyPropertyID = arLine[0];
            DateTime dt = DateTime.Parse(arLine[1]);
            Int64 nDate = (Int64)Util.ConvertToUnixTimestamp(dt);
            String strAvailability = (arLine[2]);

            _nNrRowsProccessed++;
            MasterCalendar_DB.Insert(strAgencyPropertyID, nDate, strAvailability);
        }
    }
    finally
    {
        conn.Close();
        MasterCalendar_DB.CloseMySQLConnection();
    }
</code>```

Also you need to add the following code under Configurations tag into your web.config file:

<appSettings>
   <add key="csvFileName" value="<file_name>.csv" />
   <add key="csvFolder" value="<filePath>"/>
   </appSettings>

Hope this helps someone :)

Body:
Got the Answer:

I have successfully done the parsing of my CSV file using the below code:

_nNrRowsProccessed = 0;

    string connectionString = @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq="+ConfigurationManager.AppSettings["csvFolder"]+";";

    OdbcConnection conn = new OdbcConnection(connectionString);

    try
    {
        conn.Open();

        string strFileName = ConfigurationManager.AppSettings["csvFileName"];
        string strSQL = "Select * from " + strFileName;

        OdbcCommand cmd = new OdbcCommand();
        cmd.Connection = conn;
        cmd.CommandText = strSQL;
        cmd.CommandType = CommandType.Text;

        OdbcDataReader reader = cmd.ExecuteReader();
        string strLine = null;

        MasterCalendar_DB.OpenMySQLConnection();

        while (reader.Read())
        {
            // insert data into mastercalendar
            strLine = reader[0].ToString();
            string[] arLine = strLine.Split(';');

            string strAgencyPropertyID = arLine[0];
            DateTime dt = DateTime.Parse(arLine[1]);
            Int64 nDate = (Int64)Util.ConvertToUnixTimestamp(dt);
            String strAvailability = (arLine[2]);

            _nNrRowsProccessed++;
            MasterCalendar_DB.Insert(strAgencyPropertyID, nDate, strAvailability);
        }
    }
    finally
    {
        conn.Close();
        MasterCalendar_DB.CloseMySQLConnection();
    }

Also you need to add the following code under Configurations tag into your web.config file:

<appSettings>
   <add key="csvFileName" value="<file_name>.csv" />
   <add key="csvFolder" value="<filePath>"/>
   </appSettings>

Hope this helps someone :)


问:
Angular How do you know when Authentication Status changed?
Im currently working on a webapp with a login. But I have a problem with the Logout Button. The Logout Button is only supposed to show when you are logged in and vanish when you logout.

Thats my Button (menu-items.component):

```<code><ul class="list-group">
  <li *ngIf="isLoggedIn" (click)="onLogout()">Logout</li>
</ul>
</code>```

Code (menu-items.component):

```<code>import { Component, OnInit } from '@angular/core';
import { HttpService } from '../../http.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-menu-items',
  templateUrl: './menu-items.component.html',
  styleUrls: ['./menu-items.component.css']
})
export class MenuItemsComponent implements OnInit {
  isLoggedIn: boolean = false;
  constructor(private httpService: HttpService) {

  }

  ngOnInit() {

  }
  onSignout(){
    this.isLoggedIn = false;
    localStorage.removeItem('currentUser');
  }
}
</code>```

Basically when I login I want "isLoggedIn" to be "true".

Login Part (login.component):

```<code> onSignin(){

    const username = this.loginForm.get('username').value;
    const password = this.loginForm.get('password').value;

    this.httpServie.sendDataLogin("grant_type=password&username=" + username + "&password=" + password)
      .subscribe(
        data => {
         this.token = JSON.parse(data["_body"]).access_token
         this.username = JSON.parse(data["_body"]).userName
         localStorage.setItem('currentUser', JSON.stringify({username: this.username, token: this.token}))

        },
        err => {
          if (err.error instanceof Error) {

            this.ServerErrorMsg = err.error.message;
          } else {

            const returnArray = [];
            this.ServerErrorMsg = JSON.parse(err._body).error_description + "\n";
          }
        }
      );
  }
</code>```

The Login Part is working! Im sending my data to my API and in return im getting my Token.

But the thing is how do I tell my isLoggedIn boolean that im logged in now? I think I need an observable or something to listen to with subscribe, right?
Im new to Angular and I dont really understand observables. Could anyone help me, please?

答:
I believe you forgot to update your isLoggedIn variable after successfully logging in. </p>

<p>Try this </p>

```<code>subscribe(
    data => {
     this.token = JSON.parse(data["_body"]).access_token
     this.username = JSON.parse(data["_body"]).userName
     localStorage.setItem('currentUser', JSON.stringify({username: this.username, token: this.token}))
this.isLoggedIn=true;
}
</code>```

Body:
Im currently working on a webapp with a login. But I have a problem with the Logout Button. The Logout Button is only supposed to show when you are logged in and vanish when you logout.

Thats my Button (menu-items.component):

Logout

Code (menu-items.component):

import { Component, OnInit } from '@angular/core';
import { HttpService } from '../../http.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-menu-items',
  templateUrl: './menu-items.component.html',
  styleUrls: ['./menu-items.component.css']
})
export class MenuItemsComponent implements OnInit {
  isLoggedIn: boolean = false;
  constructor(private httpService: HttpService) {

  }

  ngOnInit() {

  }
  onSignout(){
    this.isLoggedIn = false;
    localStorage.removeItem('currentUser');
  }
}

Basically when I login I want "isLoggedIn" to be "true".

Login Part (login.component):

 onSignin(){

    const username = this.loginForm.get('username').value;
    const password = this.loginForm.get('password').value;

    this.httpServie.sendDataLogin("grant_type=password&username=" + username + "&password=" + password)
      .subscribe(
        data => {
         this.token = JSON.parse(data["_body"]).access_token
         this.username = JSON.parse(data["_body"]).userName
         localStorage.setItem('currentUser', JSON.stringify({username: this.username, token: this.token}))

        },
        err => {
          if (err.error instanceof Error) {

            this.ServerErrorMsg = err.error.message;
          } else {

            const returnArray = [];
            this.ServerErrorMsg = JSON.parse(err._body).error_description + "\n";
          }
        }
      );
  }

The Login Part is working! Im sending my data to my API and in return im getting my Token.

But the thing is how do I tell my isLoggedIn boolean that im logged in now? I think I need an observable or something to listen to with subscribe, right?
Im new to Angular and I dont really understand observables. Could anyone help me, please?

Body:
I believe you forgot to update your isLoggedIn variable after successfully logging in.

Try this

subscribe(
    data => {
     this.token = JSON.parse(data["_body"]).access_token
     this.username = JSON.parse(data["_body"]).userName
     localStorage.setItem('currentUser', JSON.stringify({username: this.username, token: this.token}))
this.isLoggedIn=true;
}


问:
How do I use single quotes as part of a string in SQL
I have a where clause that uses a string,

```<code>Where
    pm.Alias = 'Toys'R'Us France'
</code>```

However part of the string uses single quotation marks, 'R'

How do i wrap up the whole string to pass through into my Where clause

I cannot use:

```<code>Where
    pm.Alias = 'Toys''R''Us France'
</code>```

As i need the whole string encased, as i will use this in Excel to pass this as a paramter into my query

答:
You might try using extra quotes after and before the existing quotes.
In this case add quote before and after 'R', and the query will be like below.</p>

```<code>Where
    pm.Alias = 'Toys''R''Us France'
</code>```

Body:
I have a where clause that uses a string,

Where
    pm.Alias = 'Toys'R'Us France'

However part of the string uses single quotation marks, 'R'

How do i wrap up the whole string to pass through into my Where clause

I cannot use:

Where
    pm.Alias = 'Toys''R''Us France'

As i need the whole string encased, as i will use this in Excel to pass this as a paramter into my query

Body:
You might try using extra quotes after and before the existing quotes.
In this case add quote before and after 'R', and the query will be like below.

Where
    pm.Alias = 'Toys''R''Us France'


问:
How to query data inserted from HBase using Phoenix
I am using HBase-1.1 and Phoenix-4.7. I created a table in HBase and inserted a sample value and trying to query based on the inserted value from Phoenix.

I used the following query in HBase to create and insert table data

```<code>create 'T1', {NAME => 'F1', IS_MOB => true}
put 'MOBPHOENIXTEST', '1', 'F1:value', 'Initial Value'
</code>```

And created a Phoenix table to view the HBase data as follows

```<code>CREATE TABLE t1 ( pk VARCHAR PRIMARY KEY, f1."value" VARCHAR )
</code>```

also tried with this create query

```<code>CREATE TABLE t1 ( pk VARCHAR PRIMARY KEY, value VARCHAR )
</code>```

But I couldn't able to see the row inserted in HBase when running the following select query

select * from t1;

Note: I don't want to create a Phoenix view for HBase table 'T1'. Because I can also insert data to HBase from Phoenix. When I create a view, I can able to see the data from Phoenix but I couldn't able to insert a row using this view.

答:
Because of some datatype incompatibility between Hbase and Phoenix, it is not possible to view the data which is already present in the Hbase table that was inserted using the Hbase shell.

However, instead of creating a view in Phoenix, you can create a table with the same name of the existing Hbase table. This will allow you to insert data into the table which can be retrieved by using Phoenix as well as Hbase.

Please note that only the data which was stored in the VARCHAR format from Phoenix can be retrieved as is in Hbase. You might get non-readable data or data with some hexadecimal values when you try to retrieve data of other datatypes.

Body:
I am using HBase-1.1 and Phoenix-4.7. I created a table in HBase and inserted a sample value and trying to query based on the inserted value from Phoenix.

I used the following query in HBase to create and insert table data

create 'T1', {NAME => 'F1', IS_MOB => true}
put 'MOBPHOENIXTEST', '1', 'F1:value', 'Initial Value'

And created a Phoenix table to view the HBase data as follows

CREATE TABLE t1 ( pk VARCHAR PRIMARY KEY, f1."value" VARCHAR )

also tried with this create query

CREATE TABLE t1 ( pk VARCHAR PRIMARY KEY, value VARCHAR )

But I couldn't able to see the row inserted in HBase when running the following select query

select * from t1;

Note: I don't want to create a Phoenix view for HBase table 'T1'. Because I can also insert data to HBase from Phoenix. When I create a view, I can able to see the data from Phoenix but I couldn't able to insert a row using this view.


问:
Jekyll export SASS vars to Javascript vars
I have a project (UI Kit just like Bootstrap) build with Jekyll and Jekyll-Assets and I'm trying to understand if it is possible to create either a Jekyll plugin or a Jekyll-Assets plugin in order to dumb all SASS vars from a _variables.scss file into an object var in a Javascript file. The idea would be to convert:

```<code>// _variables.scss
$white: #FFF;
$black: #000;
$red: #FF0;
</code>```

into

```<code>// _variables.js
(function(){

    window.appVars = {
       white: '#FFF',
       black: '#000',
       red: '#FF0'
    }

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

Worth mentioning that this converted javascript file will later be imported into other javascript files through the Jekyll-Assets build process:

```<code>// app.js
//= include _variables.js
console.log (window.appVars);
</code>```

答:
You don't need a plugin to do this.
The simplest way is to pass jekyll variables to sass and js files.

Jekyll variables

Here, I use configuration variables from _config.yml, but you can also use variables from a _data file.

```<code># _config.yml
custom_vars:
  text_color: red
  background_color: '#ddd'
</code>```

Sass files

In standard jekyll setup there is a bootstrap file assets/main.css that imports everything it needs.
It seems that you cannot @import sass files containing a front matter and variables, so, you have to grab your variables in your boostrap file before @import statment.

```<code>// assets/main.css
{%- for var in site.custom_vars %}
${{ var[0] }}: {{ var [1] }};
{%- endfor %}
@import "whatever";
</code>```

Js files

Instruct jekyll to process you file by adding a front matter :

```<code>---
---
// assets/script.js
(function(){
    window.appVars = {
        {%- for var in site.custom_vars %}
          {{ var[0] }}: '{{ var [1] }}'
          {%- unless forloop.last %},{% endunless %}
        {%- endfor %}
    }
})();
</code>```

Body:
I have a project (UI Kit just like Bootstrap) build with Jekyll and Jekyll-Assets and I'm trying to understand if it is possible to create either a Jekyll plugin or a Jekyll-Assets plugin in order to dumb all SASS vars from a _variables.scss file into an object var in a Javascript file. The idea would be to convert:

// _variables.scss
$white: #FFF;
$black: #000;
$red: #FF0;

into

// _variables.js
(function(){

    window.appVars = {
       white: '#FFF',
       black: '#000',
       red: '#FF0'
    }

})();

Worth mentioning that this converted javascript file will later be imported into other javascript files through the Jekyll-Assets build process:

// app.js
//= include _variables.js
console.log (window.appVars);

Body:
You don't need a plugin to do this.
The simplest way is to pass jekyll variables to sass and js files.

Jekyll variables

Here, I use configuration variables from _config.yml, but you can also use variables from a _data file.

# _config.yml
custom_vars:
  text_color: red
  background_color: '#ddd'

Sass files

In standard jekyll setup there is a bootstrap file assets/main.css that imports everything it needs.
It seems that you cannot @import sass files containing a front matter and variables, so, you have to grab your variables in your boostrap file before @import statment.

// assets/main.css
{%- for var in site.custom_vars %}
${{ var[0] }}: {{ var [1] }};
{%- endfor %}
@import "whatever";

Js files

Instruct jekyll to process you file by adding a front matter :

---
---
// assets/script.js
(function(){
    window.appVars = {
        {%- for var in site.custom_vars %}
          {{ var[0] }}: '{{ var [1] }}'
          {%- unless forloop.last %},{% endunless %}
        {%- endfor %}
    }
})();


问:
Getting ActionBarOverylayLayout in layout but missing all components
I am newbi so please be patient :)

Why I can't see components on the layout?

I opened an existing project all compiles and looks ok. I opend one of the layouts and I see some components at the component tree, but at the designer I see android...ActionBarOverylayLayout.

how can I see the components ?
my gradle.build :

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 24

    defaultConfig {
        applicationId "com.adafruit.bluefruit.le.connect"
        minSdkVersion 19
        targetSdkVersion 24
        versionCode 17
        versionName "2.2.1"
    }

    useLibrary 'org.apache.http.legacy'     // TODO: remove Apache library and use HttpURLConnection (Apache is deprecated since Android 6.0)

    aaptOptions {
        noCompress "zip"
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

repositories {
    maven {
        url "https://repo.eclipse.org/content/repositories/paho-releases/"
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'no.nordicsemi.android:dfu:1.0.4'
    compile(group: 'org.eclipse.paho', name: 'org.eclipse.paho.android.service', version: '1.0.2') {
        exclude module: 'support-v4'
    }
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.larswerkman:HoloColorPicker:1.4'
    compile 'com.android.support:design:24.2.1'

    compile 'com.google.android.gms:play-services-analytics:9.6.1'
    compile 'com.google.android.gms:play-services-location:9.6.1'
    compile 'com.google.android.gms:play-services-vision:9.6.1'
}
</code>```

the layout xml :

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/default_background"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.adafruit.bluefruit.le.connect.app.UartActivity">

    <LinearLayout
        android:id="@+id/sendLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#cccccc"
            android:orientation="horizontal">

            <EditText
                android:id="@+id/sendEditText"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:inputType="textNoSuggestions|textVisiblePassword"
                android:scrollbarAlwaysDrawVerticalTrack="true"
                android:scrollbars="vertical"
                android:singleLine="false" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="onClickSend"
                android:text="@string/uart_send" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end"
            android:layout_marginTop="4dp"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/sentBytesTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/uart_sentbytes_format"
                android:textColor="@drawable/default_infotextcolor" />

            <TextView
                android:id="@+id/receivedBytesTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="20dp"
                android:text="@string/uart_receivedbytes_format"
                android:textColor="@drawable/default_infotextcolor" />

        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/sendLayout"
        android:layout_alignParentTop="true"
        android:orientation="vertical">
        <!--
          android:layout_below="@id/headerLayout"
          android:layout_marginTop="10dp"
          !-->
        <ListView
            android:id="@+id/bufferListView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="#cccccc" />

        <EditText
            android:id="@+id/bufferTextView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="#cccccc"
            android:cursorVisible="false"
            android:gravity="top"
            android:scrollbarFadeDuration="0"
            android:textColorHighlight="#ffffff" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                style="?android:attr/borderlessButtonStyle"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="onClickCopy"
                android:text="@string/uart_copy"
                android:textColor="@drawable/default_textcolor" />

            <Button
                style="?android:attr/borderlessButtonStyle"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="onClickShare"
                android:text="@string/uart_share"
                android:textColor="@drawable/default_textcolor" />

            <Button
                style="?android:attr/borderlessButtonStyle"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="onClickClear"
                android:text="@string/uart_clear"
                android:textColor="@drawable/default_textcolor" />

        </LinearLayout>
    </LinearLayout>

</RelativeLayout>
</code>```

答:
Your xml file is working fine you can see the attatched image.

The problem is you are picking wrong theme check app theme above screen preview section.Change theme from there and select "AppTheme"

Body:
I am newbi so please be patient :)

Why I can't see components on the layout?

I opened an existing project all compiles and looks ok. I opend one of the layouts and I see some components at the component tree, but at the designer I see android...ActionBarOverylayLayout.

how can I see the components ?
my gradle.build :

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24

    defaultConfig {
        applicationId "com.adafruit.bluefruit.le.connect"
        minSdkVersion 19
        targetSdkVersion 24
        versionCode 17
        versionName "2.2.1"
    }

    useLibrary 'org.apache.http.legacy'     // TODO: remove Apache library and use HttpURLConnection (Apache is deprecated since Android 6.0)

    aaptOptions {
        noCompress "zip"
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

repositories {
    maven {
        url "https://repo.eclipse.org/content/repositories/paho-releases/"
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'no.nordicsemi.android:dfu:1.0.4'
    compile(group: 'org.eclipse.paho', name: 'org.eclipse.paho.android.service', version: '1.0.2') {
        exclude module: 'support-v4'
    }
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.larswerkman:HoloColorPicker:1.4'
    compile 'com.android.support:design:24.2.1'

    compile 'com.google.android.gms:play-services-analytics:9.6.1'
    compile 'com.google.android.gms:play-services-location:9.6.1'
    compile 'com.google.android.gms:play-services-vision:9.6.1'
}

the layout xml :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/default_background"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.adafruit.bluefruit.le.connect.app.UartActivity">

    <LinearLayout
        android:id="@+id/sendLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#cccccc"
            android:orientation="horizontal">

            <EditText
                android:id="@+id/sendEditText"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:inputType="textNoSuggestions|textVisiblePassword"
                android:scrollbarAlwaysDrawVerticalTrack="true"
                android:scrollbars="vertical"
                android:singleLine="false" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="onClickSend"
                android:text="@string/uart_send" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end"
            android:layout_marginTop="4dp"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/sentBytesTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/uart_sentbytes_format"
                android:textColor="@drawable/default_infotextcolor" />

            <TextView
                android:id="@+id/receivedBytesTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="20dp"
                android:text="@string/uart_receivedbytes_format"
                android:textColor="@drawable/default_infotextcolor" />

        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/sendLayout"
        android:layout_alignParentTop="true"
        android:orientation="vertical">

        <ListView
            android:id="@+id/bufferListView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="#cccccc" />

        <EditText
            android:id="@+id/bufferTextView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="#cccccc"
            android:cursorVisible="false"
            android:gravity="top"
            android:scrollbarFadeDuration="0"
            android:textColorHighlight="#ffffff" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                style="?android:attr/borderlessButtonStyle"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="onClickCopy"
                android:text="@string/uart_copy"
                android:textColor="@drawable/default_textcolor" />

            <Button
                style="?android:attr/borderlessButtonStyle"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="onClickShare"
                android:text="@string/uart_share"
                android:textColor="@drawable/default_textcolor" />

            <Button
                style="?android:attr/borderlessButtonStyle"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="onClickClear"
                android:text="@string/uart_clear"
                android:textColor="@drawable/default_textcolor" />

        </LinearLayout>
    </LinearLayout>

</RelativeLayout>


问:
Hadoop YARN SLS (Scheduler Load Simulator)
I run the simulator with following command:

```<code>bin/slsrun.sh --input-rumen = <sample-data/2jobs2min-rumen-jh.json>
</code>```

and it gave the following error:

```<code>-su: syntax error near unexpected token `newline'
</code>```

Note: PWD is $HADOOP_ROOT/share/hadoop/tools/sls

答: It comes with your Hadoop distribution. The script is located in the tools directory: $HADOOP_HOME/share/hadoop/tools/sls/bin/slsrun.sh. A description of its usage is available at https://hadoop.apache.org/docs/r2.4.1/hadoop-sls/SchedulerLoadSimulator.html. I successfully followed the steps on my Hadoop 2.8.0 installation.

Body:
I run the simulator with following command:

bin/slsrun.sh --input-rumen = <sample-data/2jobs2min-rumen-jh.json>

and it gave the following error:

-su: syntax error near unexpected token `newline'

Note: PWD is $HADOOP_ROOT/share/hadoop/tools/sls