问:
How to draw a Route between CurrentLocation to SearchedLocation in MkMapView in Swift
I need current location as a source and searched location as a destination, but I got the current location but here I am unable to bring coordinates(latitude and longitude) from searched location to destination.
here my destination shows nil why?
Below is the code please help me.

```<code>import UIKit
import MapKit
import CoreLocation
class MapSampViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate, UISearchBarDelegate {

    //Privacy - Location When In Use Usage Description, Privacy - Location Always Usage Description-------these two add in info.plist

    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var mapView: MKMapView!

    var source: CLLocationCoordinate2D!
    var destination: CLLocationCoordinate2D!

    var myaddress:String!
    var mycity:String!
    var mystate:String!
    var mycountry:String!
    var mytitle:String!
    var mylongitude:String!
    var mylatitude:String!
    var locationtoSearch:String!
    let locationManager = CLLocationManager()

    var currentlocationPlacemark: CLPlacemark!

    override func viewDidLoad() {

        super.viewDidLoad()
        searchBar.delegate = self
        mapView.delegate = self
        mapView.showsScale = true
        mapView.showsPointsOfInterest = true
        mapView.showsUserLocation = true

        if CLLocationManager.locationServicesEnabled()
        {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.startUpdatingLocation()
        }
        // self.showDirection()
        }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

        locationtoSearch = self.searchBar.text
        var geocoder:CLGeocoder = CLGeocoder()
        geocoder.geocodeAddressString(locationtoSearch!, completionHandler: {(placemarks, error) -> Void in
            if((error) != nil)
            {
            print("Error", error)
            }
            else if let placemark = placemarks?[0] as? CLPlacemark {

            var coordinates:CLLocationCoordinate2D = placemark.location!.coordinate
            var pointAnnotation:MKPointAnnotation = MKPointAnnotation()
                pointAnnotation.coordinate = coordinates
                print(coordinates)
              //  pointAnnotation.title = "\(String(describing: placemark.name)),\(String(describing: placemark.locality)), \(String(describing: placemark.administrativeArea)), \(String(describing: placemark.country))"

                self.myaddress = placemark.name

                self.mycity = placemark.locality

                self.mystate = placemark.administrativeArea

                self.mycountry = placemark.country

                pointAnnotation.title = "\(self.myaddress),\(self.mycity),\(self.mystate),\(self.mycountry)"

                self.mylongitude = String(stringInterpolationSegment: placemark.location?.coordinate.longitude)

                self.mylatitude = String(stringInterpolationSegment: placemark.location?.coordinate.latitude)

                self.mapView?.addAnnotation(pointAnnotation)

                self.mapView?.centerCoordinate = coordinates

                print("coordinates \(coordinates)")
                print("The latitude \(self.mylatitude)")
                print("The longitude \(self.mylongitude)")

              self.mapView?.selectAnnotation(pointAnnotation, animated: true)
            }
        })
        self.showDirection()//i called here or in view viewDidLoad
        let annotationsToRemove = mapView.annotations.filter { $0 !== self.mapView.userLocation

        }
        mapView.removeAnnotations( annotationsToRemove )
        }

       func showDirection()
       {
        source = locationManager.location?.coordinate//17.6881° N, 83.2131° E

       // let destination = CLLocationCoordinate2DMake(24.9511, 121.2358 )//If i give like this its working

        destination = CLLocationCoordinate2DMake(Double(mylongitude)!, Double(mylongitude)!)//fatal error: unexpectedly found nil while unwrapping an Optional value

        let sourcePlacemark = MKPlacemark(coordinate: source!)
        let destinationPlacemark = MKPlacemark(coordinate: destination)
        let sourceItem = MKMapItem(placemark: sourcePlacemark)
        let destinationItem = MKMapItem(placemark: destinationPlacemark)

        let directionReq = MKDirectionsRequest()
        directionReq.source = sourceItem
        directionReq.destination = destinationItem
        directionReq.transportType = .automobile

        let directions = MKDirections(request: directionReq)
        directions.calculate(completionHandler: {(response, error) in
            if error != nil {
                print("Error getting directions")
            }
            else {
                let route = response?.routes[0]
                self.mapView.add((route?.polyline)!, level:.aboveRoads)

                let rekt = route?.polyline.boundingMapRect
                self.mapView.setRegion(MKCoordinateRegionForMapRect(rekt!), animated: true)
                }
          })
      }

    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {

        let rendrer = MKPolylineRenderer(overlay: overlay)
        rendrer.strokeColor = UIColor.blue
        rendrer.lineWidth = 3
        return rendrer
     }
}
</code>```

here i called showDirection() func in searchBarSearchButtonClicked but it is getting called before coming here why?

答:
Direction requests are executed asynchronously. This means that the rest of your app doesn't wait for the direction to be fetched.

Your showDirection function is both fetching the direction and adding it to the mapView. It would be best to separate these functionalities. You can fetch the direction, update a route variable and have an observer on it which will add the route to the map once it has been fetched.

```<code>@IBOutlet weak var mapView: MKMapView!

var route: MKRoute? {
didSet {
    mapView.add((route?.polyline)!, level:.aboveRoads) }
}
</code>```

Body:
I need current location as a source and searched location as a destination, but I got the current location but here I am unable to bring coordinates(latitude and longitude) from searched location to destination.
here my destination shows nil why?
Below is the code please help me.

import UIKit
import MapKit
import CoreLocation
class MapSampViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate, UISearchBarDelegate {

    //Privacy - Location When In Use Usage Description, Privacy - Location Always Usage Description-------these two add in info.plist

    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var mapView: MKMapView!

    var source: CLLocationCoordinate2D!
    var destination: CLLocationCoordinate2D!

    var myaddress:String!
    var mycity:String!
    var mystate:String!
    var mycountry:String!
    var mytitle:String!
    var mylongitude:String!
    var mylatitude:String!
    var locationtoSearch:String!
    let locationManager = CLLocationManager()

    var currentlocationPlacemark: CLPlacemark!

    override func viewDidLoad() {

        super.viewDidLoad()
        searchBar.delegate = self
        mapView.delegate = self
        mapView.showsScale = true
        mapView.showsPointsOfInterest = true
        mapView.showsUserLocation = true

        if CLLocationManager.locationServicesEnabled()
        {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.startUpdatingLocation()
        }
        // self.showDirection()
        }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

        locationtoSearch = self.searchBar.text
        var geocoder:CLGeocoder = CLGeocoder()
        geocoder.geocodeAddressString(locationtoSearch!, completionHandler: {(placemarks, error) -> Void in
            if((error) != nil)
            {
            print("Error", error)
            }
            else if let placemark = placemarks?[0] as? CLPlacemark {

            var coordinates:CLLocationCoordinate2D = placemark.location!.coordinate
            var pointAnnotation:MKPointAnnotation = MKPointAnnotation()
                pointAnnotation.coordinate = coordinates
                print(coordinates)
              //  pointAnnotation.title = "\(String(describing: placemark.name)),\(String(describing: placemark.locality)), \(String(describing: placemark.administrativeArea)), \(String(describing: placemark.country))"

                self.myaddress = placemark.name

                self.mycity = placemark.locality

                self.mystate = placemark.administrativeArea

                self.mycountry = placemark.country

                pointAnnotation.title = "\(self.myaddress),\(self.mycity),\(self.mystate),\(self.mycountry)"

                self.mylongitude = String(stringInterpolationSegment: placemark.location?.coordinate.longitude)

                self.mylatitude = String(stringInterpolationSegment: placemark.location?.coordinate.latitude)

                self.mapView?.addAnnotation(pointAnnotation)

                self.mapView?.centerCoordinate = coordinates

                print("coordinates \(coordinates)")
                print("The latitude \(self.mylatitude)")
                print("The longitude \(self.mylongitude)")

              self.mapView?.selectAnnotation(pointAnnotation, animated: true)
            }
        })
        self.showDirection()//i called here or in view viewDidLoad
        let annotationsToRemove = mapView.annotations.filter { $0 !== self.mapView.userLocation

        }
        mapView.removeAnnotations( annotationsToRemove )
        }

       func showDirection()
       {
        source = locationManager.location?.coordinate//17.6881° N, 83.2131° E

       // let destination = CLLocationCoordinate2DMake(24.9511, 121.2358 )//If i give like this its working

        destination = CLLocationCoordinate2DMake(Double(mylongitude)!, Double(mylongitude)!)//fatal error: unexpectedly found nil while unwrapping an Optional value

        let sourcePlacemark = MKPlacemark(coordinate: source!)
        let destinationPlacemark = MKPlacemark(coordinate: destination)
        let sourceItem = MKMapItem(placemark: sourcePlacemark)
        let destinationItem = MKMapItem(placemark: destinationPlacemark)

        let directionReq = MKDirectionsRequest()
        directionReq.source = sourceItem
        directionReq.destination = destinationItem
        directionReq.transportType = .automobile

        let directions = MKDirections(request: directionReq)
        directions.calculate(completionHandler: {(response, error) in
            if error != nil {
                print("Error getting directions")
            }
            else {
                let route = response?.routes[0]
                self.mapView.add((route?.polyline)!, level:.aboveRoads)

                let rekt = route?.polyline.boundingMapRect
                self.mapView.setRegion(MKCoordinateRegionForMapRect(rekt!), animated: true)
                }
          })
      }

    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {

        let rendrer = MKPolylineRenderer(overlay: overlay)
        rendrer.strokeColor = UIColor.blue
        rendrer.lineWidth = 3
        return rendrer
     }
}

here i called showDirection() func in searchBarSearchButtonClicked but it is getting called before coming here why?

Body:
Direction requests are executed asynchronously. This means that the rest of your app doesn't wait for the direction to be fetched.

Your showDirection function is both fetching the direction and adding it to the mapView. It would be best to separate these functionalities. You can fetch the direction, update a route variable and have an observer on it which will add the route to the map once it has been fetched.

@IBOutlet weak var mapView: MKMapView!

var route: MKRoute? {
didSet {
    mapView.add((route?.polyline)!, level:.aboveRoads) }
}


来源: stackexchange

问:
CoreData object attributes disappearing on creation of next object
I'm creating some default data and saving it in coredata on first launch but during creation something is going wrong and I can't figure out what it is. (Using sugarRecord if that matters)

These are the functions for creation:

Default dataLayout (works fine)

```<code>func createDefaultDataLayout() {
    guard let db = db else { return }
    do {
        try db.operation { (context, save) throws -> Void in
            let defaultData: TMDataLayout = try! context.create()
            defaultData.id = 999

            let spot1: TMData = (try! context.fetch(FetchRequest<TMData>().filtered(with: "id", equalTo: "1")).first)!
            spot1.spot = 1
            let spot2: TMData = (try! context.fetch(FetchRequest<TMData>().filtered(with: "id", equalTo: "6")).first)!
            spot2.spot = 2
            let spot3: TMData = (try! context.fetch(FetchRequest<TMData>().filtered(with: "id", equalTo: "8")).first)!
            spot3.spot = 3
            let spot4: TMData = (try! context.fetch(FetchRequest<TMData>().filtered(with: "id", equalTo: "19")).first)!
            spot4.spot = 4

            defaultData.data = [spot1, spot2, spot3, spot4]
            save()
        }
    } catch {
        print("Error creating default data layout")
    }
}
</code>```

Default activities, using the default dataLayout

```<code>func createDefaultActivities() {
    guard let db = db else { return }
    let defaultPredicate: NSPredicate = NSPredicate(format: "id == %@", "0")

    do {
        try db.operation { (context, save) throws -> Void in

            let defaultDataLayout = try! context.fetch(FetchRequest<TMDataLayout>().filtered(with: defaultPredicate)).first
            let defaultSettings = try! context.fetch(FetchRequest<TMSettingsLayout>().filtered(with: defaultPredicate)).first

            let chosen: TMActivity = try! context.create()
            chosen.id = 999
            chosen.title = L10n.Activity.running
            chosen.iconName = "running"
            chosen.dataLayout = defaultDataLayout
            chosen.settingsLayout = defaultSettings
            chosen.goal = try! context.fetch(FetchRequest<TMGoal>().filtered(with: "title", equalTo: L10n.Goal.Nothing.title)).first
            chosen.isPartOfWorkout = false
            print(chosen)

            let walking: TMActivity = try! context.create()
            walking.id = 1
            walking.title = L10n.Activity.walking
            walking.iconName = "walking"
            walking.dataLayout = defaultDataLayout
            walking.settingsLayout = defaultSettings
            walking.isPartOfWorkout = false
            print(chosen)

            save()
        }
    } catch {
        print("Something went wrong setting up core data (dataManager)")
    }
}
</code>```

The two prints of "chosen" give something different, the first print the object is correct and has the dataLayout and settingsLayout set, but on the second one they have disappeared. I fetch and set the goal in the same way and that does stay in the object.

Where is it going wrong?

Goal creation func for comparison

```<code>func createGoalObjects() {
    guard let db = db else { return }
    do {
        try db.operation { (context, save) throws -> Void in
            let duration: TMGoal = try! context.create()
            duration.id = 1
            duration.title = L10n.Goal.Duration.title
            duration.iconName = "duration"
            duration.amount = 0
            duration.descriptionString = L10n.Goal.Duration.amount(Int(duration.amount))

            let pace: TMGoal = try! context.create()
            pace.id = 2
            pace.title = L10n.Goal.Pace.title
            pace.iconName = "pace"
            pace.amount = 0
            pace.descriptionString = L10n.Goal.Pace.amount(Int(duration.amount))

            let distance: TMGoal = try! context.create()
            distance.id = 3
            distance.title = L10n.Goal.Distance.title
            distance.iconName = "distance"
            distance.amount = 0
            distance.descriptionString = L10n.Goal.Distance.amount(duration.amount)

            let calories: TMGoal = try! context.create()
            calories.id = 4
            calories.title = L10n.Goal.Calories.title
            calories.iconName = "calories"
            calories.amount = 0
            calories.descriptionString = L10n.Goal.Calories.amount(Int(duration.amount))

            let nothing: TMGoal = try! context.create()
            nothing.id = 5
            nothing.title = L10n.Goal.Nothing.title
            nothing.iconName = "nothing"
            nothing.amount = 0
            nothing.descriptionString = L10n.Goal.Nothing.amount

            save()
        }
    } catch {
        print("Error creating default data layout")
    }
}
</code>```

Here are the 2 prints I get:

```<code><TMActivity: 0x1c40990a0> (entity: TMActivity; id: 0x1c422d2c0 <x-coredata:///TMActivity/tA820CA64-1F5A-480D-A631-0BC3E05FFC9237> ; data: {
    dataLayout = "0xd000000000040002 <x-coredata://62477925-6CCB-472D-8C45-BD6731B59AA6/TMDataLayout/p1>";
    goal = "0xd0000000000c0006 <x-coredata://62477925-6CCB-472D-8C45-BD6731B59AA6/TMGoal/p3>";
    iconName = running;
    id = 999;
    isPartOfWorkout = 0;
    partId = 0;
    parts =     (
    );
    settingsLayout = "0xd000000000040004 <x-coredata://62477925-6CCB-472D-8C45-BD6731B59AA6/TMSettingsLayout/p1>";
    title = Hardlopen;
})
<TMActivity: 0x1c40990a0> (entity: TMActivity; id: 0x1c422d2c0 <x-coredata:///TMActivity/tA820CA64-1F5A-480D-A631-0BC3E05FFC9237> ; data: {
    dataLayout = nil;
    goal = "0xd0000000000c0006 <x-coredata://62477925-6CCB-472D-8C45-BD6731B59AA6/TMGoal/p3>";
    iconName = running;
    id = 999;
    isPartOfWorkout = 0;
    partId = 0;
    parts =     (
    );
    settingsLayout = nil;
    title = Hardlopen;
})
</code>```

答: I forgot to set my dataLayout and settingsLayout relationship to many, that fixed it</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm creating some default data and saving it in coredata on first launch but during creation something is going wrong and I can't figure out what it is. (Using sugarRecord if that matters)

These are the functions for creation:

Default dataLayout (works fine)

func createDefaultDataLayout() {
    guard let db = db else { return }
    do {
        try db.operation { (context, save) throws -> Void in
            let defaultData: TMDataLayout = try! context.create()
            defaultData.id = 999

            let spot1: TMData = (try! context.fetch(FetchRequest<TMData>().filtered(with: "id", equalTo: "1")).first)!
            spot1.spot = 1
            let spot2: TMData = (try! context.fetch(FetchRequest<TMData>().filtered(with: "id", equalTo: "6")).first)!
            spot2.spot = 2
            let spot3: TMData = (try! context.fetch(FetchRequest<TMData>().filtered(with: "id", equalTo: "8")).first)!
            spot3.spot = 3
            let spot4: TMData = (try! context.fetch(FetchRequest<TMData>().filtered(with: "id", equalTo: "19")).first)!
            spot4.spot = 4

            defaultData.data = [spot1, spot2, spot3, spot4]
            save()
        }
    } catch {
        print("Error creating default data layout")
    }
}

Default activities, using the default dataLayout

func createDefaultActivities() {
    guard let db = db else { return }
    let defaultPredicate: NSPredicate = NSPredicate(format: "id == %@", "0")

    do {
        try db.operation { (context, save) throws -> Void in

            let defaultDataLayout = try! context.fetch(FetchRequest<TMDataLayout>().filtered(with: defaultPredicate)).first
            let defaultSettings = try! context.fetch(FetchRequest<TMSettingsLayout>().filtered(with: defaultPredicate)).first

            let chosen: TMActivity = try! context.create()
            chosen.id = 999
            chosen.title = L10n.Activity.running
            chosen.iconName = "running"
            chosen.dataLayout = defaultDataLayout
            chosen.settingsLayout = defaultSettings
            chosen.goal = try! context.fetch(FetchRequest<TMGoal>().filtered(with: "title", equalTo: L10n.Goal.Nothing.title)).first
            chosen.isPartOfWorkout = false
            print(chosen)

            let walking: TMActivity = try! context.create()
            walking.id = 1
            walking.title = L10n.Activity.walking
            walking.iconName = "walking"
            walking.dataLayout = defaultDataLayout
            walking.settingsLayout = defaultSettings
            walking.isPartOfWorkout = false
            print(chosen)

            save()
        }
    } catch {
        print("Something went wrong setting up core data (dataManager)")
    }
}

The two prints of "chosen" give something different, the first print the object is correct and has the dataLayout and settingsLayout set, but on the second one they have disappeared. I fetch and set the goal in the same way and that does stay in the object.

Where is it going wrong?

Goal creation func for comparison

func createGoalObjects() {
    guard let db = db else { return }
    do {
        try db.operation { (context, save) throws -> Void in
            let duration: TMGoal = try! context.create()
            duration.id = 1
            duration.title = L10n.Goal.Duration.title
            duration.iconName = "duration"
            duration.amount = 0
            duration.descriptionString = L10n.Goal.Duration.amount(Int(duration.amount))

            let pace: TMGoal = try! context.create()
            pace.id = 2
            pace.title = L10n.Goal.Pace.title
            pace.iconName = "pace"
            pace.amount = 0
            pace.descriptionString = L10n.Goal.Pace.amount(Int(duration.amount))

            let distance: TMGoal = try! context.create()
            distance.id = 3
            distance.title = L10n.Goal.Distance.title
            distance.iconName = "distance"
            distance.amount = 0
            distance.descriptionString = L10n.Goal.Distance.amount(duration.amount)

            let calories: TMGoal = try! context.create()
            calories.id = 4
            calories.title = L10n.Goal.Calories.title
            calories.iconName = "calories"
            calories.amount = 0
            calories.descriptionString = L10n.Goal.Calories.amount(Int(duration.amount))

            let nothing: TMGoal = try! context.create()
            nothing.id = 5
            nothing.title = L10n.Goal.Nothing.title
            nothing.iconName = "nothing"
            nothing.amount = 0
            nothing.descriptionString = L10n.Goal.Nothing.amount

            save()
        }
    } catch {
        print("Error creating default data layout")
    }
}

Here are the 2 prints I get:

<TMActivity: 0x1c40990a0> (entity: TMActivity; id: 0x1c422d2c0 <x-coredata:///TMActivity/tA820CA64-1F5A-480D-A631-0BC3E05FFC9237> ; data: {
    dataLayout = "0xd000000000040002 <x-coredata://62477925-6CCB-472D-8C45-BD6731B59AA6/TMDataLayout/p1>";
    goal = "0xd0000000000c0006 <x-coredata://62477925-6CCB-472D-8C45-BD6731B59AA6/TMGoal/p3>";
    iconName = running;
    id = 999;
    isPartOfWorkout = 0;
    partId = 0;
    parts =     (
    );
    settingsLayout = "0xd000000000040004 <x-coredata://62477925-6CCB-472D-8C45-BD6731B59AA6/TMSettingsLayout/p1>";
    title = Hardlopen;
})
<TMActivity: 0x1c40990a0> (entity: TMActivity; id: 0x1c422d2c0 <x-coredata:///TMActivity/tA820CA64-1F5A-480D-A631-0BC3E05FFC9237> ; data: {
    dataLayout = nil;
    goal = "0xd0000000000c0006 <x-coredata://62477925-6CCB-472D-8C45-BD6731B59AA6/TMGoal/p3>";
    iconName = running;
    id = 999;
    isPartOfWorkout = 0;
    partId = 0;
    parts =     (
    );
    settingsLayout = nil;
    title = Hardlopen;
})


问:
Fibonacci sequence python
I am trying to understand Python, but I still don't get it. I am new to the language, and wants to understand it properly.
This is a line from a Fibonacci sequence using loops. Please explain the meaning of this code. I am trying to get the pattern by hand. I got the pattern up to 3, but after 3 I am not getting the answer.</p>

```<code>a, b = 0, 1
while b < 50:
    print(b)
    a, b = b, a + b
</code>```

答:
```<code>a= int(input("Enter the first number:"));
Enter the first number:0
b= int(input("enter the second number:"));
enter the second number:1
n= int (input("enter the number of terms:"));
enter the number of terms:10
print(a,b);
0 1
while(n>2):
      c=a+b;
      a=b;
      b=c;
      print(c);
      n=n-1;

1
2
3
5
8
13
21
34
</code>```

Title: Fibonacci sequence python

Body:
I am trying to understand Python, but I still don't get it. I am new to the language, and wants to understand it properly.
This is a line from a Fibonacci sequence using loops. Please explain the meaning of this code. I am trying to get the pattern by hand. I got the pattern up to 3, but after 3 I am not getting the answer.

a, b = 0, 1
while b < 50:
    print(b)
    a, b = b, a + b


问:
How to get occurrences of string lengths for a column of strings in postgresql
Given an input of a text/string column, I want to compute the lengths of the strings in the columns, and the counts for each length.

E.g. a column with the strings:

```<code>'Ant'
'Cat'
'Dog'
'Human'
''
NULL
'A human'
</code>```

Would give:

```<code>0 : 1
3 : 3
5 : 1
7 : 1
</code>```

NOTE: the null string hasn't been counted as a 0 character string, but ignored.

答:
length() comes to mind:

```<code>select length(col), count(*)
from t
where col is not null
group by length(col)
order by length(col);
</code>```

Body:
Given an input of a text/string column, I want to compute the lengths of the strings in the columns, and the counts for each length.

E.g. a column with the strings:

'Ant'
'Cat'
'Dog'
'Human'
''
NULL
'A human'

Would give:

0 : 1
3 : 3
5 : 1
7 : 1

NOTE: the null string hasn't been counted as a 0 character string, but ignored.

Body:
length() comes to mind:

select length(col), count(*)
from t
where col is not null
group by length(col)
order by length(col);


问:
How do I determine whether the filesystem is case-sensitive in .net?
Does .net have a way to determine whether the local filesystem is case-sensitive?</p>

答:
I invoke The Cheat:</p>

```<code>Path.DirectorySeparatorChar == '\\' ? "I'm insensitive" : "I'm probably sensitive"
</code>```

OwnerDisplayName: Matt

ContentLicense: CC BY-SA 2.5

Body:
I invoke The Cheat:

Path.DirectorySeparatorChar == '\\' ? "I'm insensitive" : "I'm probably sensitive"


问:
How do I import Zbar into my Python 3.4 script?
I am pretty new to programming, and have never used Zbar before. I am trying to write a simple script that will allow me to import Zbar and use it to decode a barcode image. I already have a script set up to decode text from images that uses Pytesseract and Tesseract OCR, but I need to be able to decode barcodes as well. I have Windows 7 32 bit, and and am using Python 3.4. I have already installed Zbar and have used it from the command line successfully to decode their barcode sample. I have tried using >pip install zbar, but I keep getting the error:

"fatal error C1083: Cannot open include file: 'zbar.h': No such file or directory
  error: command 'C:\Program Files\Microsoft Visual Studio 10.0\VC\BIN\cl.exe' failed with exit status 2"

Getting the pytesseract OCR was painless but I have wasted a lot of time on this barcode portion of it, any help or alternatives would be much appreciated.

答:
As of November 2016, there is the package pyzbar. To import Zbar for python3.4+ on Windows OS, all you need to do is launch

```<code>pip install pyzbar
</code>```

This is possible because pyzbar is a ctypes-based wrapper around the zbar library that is included as dll with the Windows Python wheels.

Body:
As of November 2016, there is the package pyzbar. To import Zbar for python3.4+ on Windows OS, all you need to do is launch

pip install pyzbar

This is possible because pyzbar is a ctypes-based wrapper around the zbar library that is included as dll with the Windows Python wheels.


问:
How to schedule a dag to run a particular time of day of a month of a year. i.e., once
I'm trying to execute a dag which needs to be run only once. So I placed the dag execution interval as '@once'. However, I'm getting the error as mentioned in this link -
https://issues.apache.org/jira/browse/AIRFLOW-1400

Now i'm trying to pass the exact date of execution as below:

```<code>default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2017,11,13),
'email': ['airflow@airflow.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(seconds=5)
}

dag = DAG(
    dag_id='dagNameTest', default_args=default_args, schedule_interval='12 09 13 11 2017',concurrency=1)
</code>```

This is throwing error as:

```<code>File "/usr/lib/python2.7/site-packages/croniter/croniter.py", line 543, in expand
expr_format))
CroniterBadCronError: [12 09 13 11 2017] is not acceptable, out of range
</code>```

Can someone help to resolve this.

Thanks,
Arjun

答: You have 2017 in the "day of week" spot. Try 12 09 13 11 *. You are trying to set a "date" in a field "schedule interval". So technically this will schedule it for once a year. You can run it this way, and when it has finished, deactivate the DAG.

Body:
I'm trying to execute a dag which needs to be run only once. So I placed the dag execution interval as '@once'. However, I'm getting the error as mentioned in this link -
https://issues.apache.org/jira/browse/AIRFLOW-1400

Now i'm trying to pass the exact date of execution as below:

default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2017,11,13),
'email': ['airflow@airflow.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(seconds=5)
}

dag = DAG(
    dag_id='dagNameTest', default_args=default_args, schedule_interval='12 09 13 11 2017',concurrency=1)

This is throwing error as:

File "/usr/lib/python2.7/site-packages/croniter/croniter.py", line 543, in expand
expr_format))
CroniterBadCronError: [12 09 13 11 2017] is not acceptable, out of range

Can someone help to resolve this.

Thanks,
Arjun


问:
Bootstrap adding hidden Margins to Columns
For some reason bootstrap is adding a hidden margin to my column classes. When I inspect on an element which is currently 'col-lg-3' it does not show any margin CSS and even if I add margin:0 to the column it still adds a margin.

Please see image below.

I have been looking around for a while, and I am quite shocked I have not been able to find an answer to this. Does anyone have any insight in whats going wrong?

enter image description here

答:
Not sure if what you're saying is margin or padding.
Margin is the space before and after the columns
Padding is the space inside the column.

If want your content to start at the very edge of the column, then you do:

```<code>.col-*-* { padding: 0 }
</code>```

Body:
Not sure if what you're saying is margin or padding.
Margin is the space before and after the columns
Padding is the space inside the column.

If want your content to start at the very edge of the column, then you do:

.col-*-* { padding: 0 }


问:
Does Java have an equivalent to C#'s Environment.GetCommandLineArgs()?
I know that I can get the command-line arguments in the "main" method, but I need to be able to get them indirectly.

Thanks for your help.

答:
You could write a wrapper to take the cli and re-format it to use -DPROP=VAL

```<code>int main(int argc, char*argv[])
{
std::vector<std::string> in (argv+1,argv+argc), out();

out.push_back("java.exe");
out.push_back("-cp");
out.push_back("my-jar.jar");
out.push_back("main.class")

for( auto it = in.begin(); it!=in.end(); ++in)
{
//process CLI args. turn "-abc","BLAH" into "-Darg.a=true","-Darg.b=true","-Darg.c=BLAH" and push to out
//Do additional processing. Maybe evn use get_opt() or Boost.ProgramOptions
}
//use exec or CreateProcess to launch java with the proper args
//or even use something like WinRun4J's methods to load the jvm.dll
//Then your program shows up as "MyExe.exe" instead of "java.exe"

//Use System.getProperty("arg.a","false") to get the value of a
}
</code>```

Of course, you could always just tell you users to invoke a bash/batch script with the proper -DA=true type arguments

Body:
You could write a wrapper to take the cli and re-format it to use -DPROP=VAL

int main(int argc, char*argv[])
{
std::vector<std::string> in (argv+1,argv+argc), out();

out.push_back("java.exe");
out.push_back("-cp");
out.push_back("my-jar.jar");
out.push_back("main.class")

for( auto it = in.begin(); it!=in.end(); ++in)
{
//process CLI args. turn "-abc","BLAH" into "-Darg.a=true","-Darg.b=true","-Darg.c=BLAH" and push to out
//Do additional processing. Maybe evn use get_opt() or Boost.ProgramOptions
}
//use exec or CreateProcess to launch java with the proper args
//or even use something like WinRun4J's methods to load the jvm.dll
//Then your program shows up as "MyExe.exe" instead of "java.exe"

//Use System.getProperty("arg.a","false") to get the value of a
}

Of course, you could always just tell you users to invoke a bash/batch script with the proper -DA=true type arguments


问:
How can I detect a speed from a gps in python?
I am using a gps chip with my raspberry pi using python for coding and I want to get the speed from the gps and convert it to mph in a loop using a 1 second loop.

How can this be accomplished with fairly precise data? I am currently using the following code:

```<code>From gps import *
import time
import threading
import math
import RPi.GPIO as GPIO ## Import GPIO library
import time ## Import 'time' library. Allows us to use 'sleep'

GPIO.setmode(GPIO.BOARD) ## Use board pin numbering
GPIO.setup(40,GPIO.OUT) ## Setup GPIO Pin 40 to OUT

class GpsController(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info
        self.running = False

    def run(self):
        self.running = True
        while self.running:
            # grab EACH set of gpsd info to clear the buffer
            self.gpsd.next()

    def stopController(self):
        self.running = False

    @property
    def fix(self):
        return self.gpsd.fix

    @property
    def utc(self):
        return self.gpsd.utc

    @property
    def satellites(self):
        return self.gpsd.satellites

mph = 15

if __name__ == '__main__':
    # create the controller
    gpsc = GpsController()
    try:
        # start controller
        gpsc.start()
        while True:
            if gpsc.fix.speed < mph :
                print "speed is under 15 mph",gpsc.fix.speed
                print mph
                GPIO.output(40,GPIO.HIGH)
                time.sleep(1)
                GPIO.output(40,GPIO.LOW)
                time.sleep(1)
                #GPIO.output(40,True)
                #time.sleep(.5)
                #GPIO.output(40,False)
                #time.sleep(.10)

            elif gpsc.fix.speed > mph :
                print "speed (m/s) ",gpsc.fix.speed
                #    GPIO.cleanup()

            else:
                print "fine"
                #GPIO.cleanup()

            #print "latitude ", gpsc.fix.laif
            #print "longitude ", gpsc.fix.longitude
            #print "time utc ", gpsc.utc, " + ", gpsc.fix.time
            #print "altitude (m)", gpsc.fix.altitude
            #print "eps ", gpsc.fix.eps
            #print "epx ", gpsc.fix.epx
            #print "epv ", gpsc.fix.epv
            #print "ept ", gpsc.gpsd.fix.ept
            #print "speed (m/s) ", gpsc.fix.speed
            #print "climb ", gpsc.fix.climb
            #print "track ", gpsc.fix.track
            #print "mode ", gpsc.fix.mode
            #print "sats ", gpsc.satellites
            time.sleep(1)

#Error
    #except:
    #   print "Unexpected error:", sys.exc_info()[0]
    #  raise

    #Ctrl C
    except KeyboardInterrupt:
        print "User cancelled"

    finally:
        print "Stopping gps controller"
        gpsc.stopController()
        #wait for the thread to finish
        gpsc.join()

    print "Done"

GPIO.cleanup()
</code>```

The current code gives me a reading but it appears to be approximately 15 mph out of sync.

答: You need to grab the GPS coordinates from your chip, convert them to cartesian coordinates, and subtract the current second from the previous second. The distance between the two points is then your distance traveled in one second. This will be noisy at low speeds so you may want to do some filtering of some kind.</p>

Body:
I am using a gps chip with my raspberry pi using python for coding and I want to get the speed from the gps and convert it to mph in a loop using a 1 second loop.

How can this be accomplished with fairly precise data? I am currently using the following code:

From gps import *
import time
import threading
import math
import RPi.GPIO as GPIO ## Import GPIO library
import time ## Import 'time' library. Allows us to use 'sleep'

GPIO.setmode(GPIO.BOARD) ## Use board pin numbering
GPIO.setup(40,GPIO.OUT) ## Setup GPIO Pin 40 to OUT

class GpsController(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info
        self.running = False

    def run(self):
        self.running = True
        while self.running:
            # grab EACH set of gpsd info to clear the buffer
            self.gpsd.next()

    def stopController(self):
        self.running = False

    @property
    def fix(self):
        return self.gpsd.fix

    @property
    def utc(self):
        return self.gpsd.utc

    @property
    def satellites(self):
        return self.gpsd.satellites

mph = 15

if __name__ == '__main__':
    # create the controller
    gpsc = GpsController()
    try:
        # start controller
        gpsc.start()
        while True:
            if gpsc.fix.speed < mph :
                print "speed is under 15 mph",gpsc.fix.speed
                print mph
                GPIO.output(40,GPIO.HIGH)
                time.sleep(1)
                GPIO.output(40,GPIO.LOW)
                time.sleep(1)
                #GPIO.output(40,True)
                #time.sleep(.5)
                #GPIO.output(40,False)
                #time.sleep(.10)

            elif gpsc.fix.speed > mph :
                print "speed (m/s) ",gpsc.fix.speed
                #    GPIO.cleanup()

            else:
                print "fine"
                #GPIO.cleanup()

            #print "latitude ", gpsc.fix.laif
            #print "longitude ", gpsc.fix.longitude
            #print "time utc ", gpsc.utc, " + ", gpsc.fix.time
            #print "altitude (m)", gpsc.fix.altitude
            #print "eps ", gpsc.fix.eps
            #print "epx ", gpsc.fix.epx
            #print "epv ", gpsc.fix.epv
            #print "ept ", gpsc.gpsd.fix.ept
            #print "speed (m/s) ", gpsc.fix.speed
            #print "climb ", gpsc.fix.climb
            #print "track ", gpsc.fix.track
            #print "mode ", gpsc.fix.mode
            #print "sats ", gpsc.satellites
            time.sleep(1)

#Error
    #except:
    #   print "Unexpected error:", sys.exc_info()[0]
    #  raise

    #Ctrl C
    except KeyboardInterrupt:
        print "User cancelled"

    finally:
        print "Stopping gps controller"
        gpsc.stopController()
        #wait for the thread to finish
        gpsc.join()

    print "Done"

GPIO.cleanup()

The current code gives me a reading but it appears to be approximately 15 mph out of sync.


问:
Create linked list relationship between nodes having same relation to other nodes in neo4j
As in this figure

is it possible to create a linked-list relationship between all (:B) nodes that share a relationship [:R] with the same (:A) node, for all (:A) nodes in the database. If order is important, then assume there is a property order in all (:B) nodes.

答:
One additional option: use APOC Procedures. The procedure apoc.nodes.link() takes in a collection of nodes and makes them into a linked list using the specified relationship type. An example of usage:

```<code>MATCH (A:A)-[:R]->(B:B)
WITH A, B
ORDER BY B.order ASC
WITH A, collect(B) as bNodes
CALL apoc.nodes.link(bNodes, 'NEXT')
</code>```

Body:
One additional option: use APOC Procedures. The procedure apoc.nodes.link() takes in a collection of nodes and makes them into a linked list using the specified relationship type. An example of usage:

MATCH (A:A)-[:R]->(B:B)
WITH A, B
ORDER BY B.order ASC
WITH A, collect(B) as bNodes
CALL apoc.nodes.link(bNodes, 'NEXT')


问:
Scrolling a ViewPager programmatically, by a small amount
I have the requirement for what is effectively two activities side by side, allowing the user to scroll from one to the other, and back. I've decided that ViewPager is probably the best way to handle this, but am open to suggestions.

When the activity loads, the left hand view is displayed. I want to indicate to the user that the other view exists, by just scrolling it a small amount to the left and back again (similar to the way it's now common to show that a sliding drawer menu exists).

I've tried a number of things but have yet failed to find a method where both the views scroll smoothly together. Another way of interpretting the requirement is saying I want to programmatically fake a user flicking the page briefly.

答: Try calling the method fakeDragBy(float)! According to the documentation you need to first call beginFakeDrag() to initiate it  and then call endFakeDrag(). This will mantain the ViewPagers default snapping behavior, so once you've revealed the other screen is there you don't have to animate the transition back, simply call endFakeDrag and the ViewPager will correctly snap back to the last screen (As long as you haven't dragged it past the half-way mark). </p>

ContentLicense: CC BY-SA 4.0


问:
Why did .NET's EnableDecompression default value change between 2.0 and 3.0?
We use .NET Web Services--both non-WCF and WCF, though the overwhelming majority is non-WCF, for legacy reasons--pretty heavily, and as I was testing something in Fiddler, I noticed that the response body size was pretty large. Then I noticed that the request headers didn't have any Accept-Encoding headers.

After doing some digging, it appears that the default value for the property HttpWebClientProtocol.EnableDecompression (from the class of which all wsdl.exe-originated WS stubs derive) changed between .NET BCL versions 2.0 and 3.0. I'm curious as to the reason (which may be WCF-related), and further as to whether there are any other [pretty] fundamental changes that are pretty quiet when you simply link against a different library.

答:
Take a look at this connect link.  The first comment from Microsoft states the following:

Please also note that as part of the
  fixed we changed the default value of
  EnableDecompression to be false by
  default. We were concerned that having
  it on by default would break existing
  customers that had implemented
  decompression on top of ASP.NET Web
  Services in v1.1.

It looks like the change was a result of a bug that they needed to fix.


问:
ASP.NET testing the retrieval of currently logged in user UserId
```<code>protected void UploadImage_Click(object sender, EventArgs e)
    {
        HttpPostedFile postedFile = ImageUploader.PostedFile;
        string fileExtension =
Path.GetExtension(Path.GetFileName(postedFile.FileName));
        if (ImageUploader.HasFile && fileExtension.ToLower() == ".jpg" ||
fileExtension.ToLower() == ".gif" || fileExtension.ToLower() == ".png")
        {

            Stream fs = postedFile.InputStream;
            BinaryReader br = new BinaryReader(fs);
            Byte[] image = br.ReadBytes((int)fs.Length);
            Guid UserId = (Guid)Membership.GetUser().ProviderUserKey;

            string cs = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                string sqlcmd = "insert into ProfileImage values(@UserId, @ImageData)";
                SqlCommand cmd = new SqlCommand(sqlcmd, con);
                cmd.Parameters.AddWithValue("@UserId", UserId);
                cmd.Parameters.AddWithValue("@ImageData", image);

                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();

                ErrorLabel.Visible = true;
                ErrorLabel.Text = "Upload Success!";
                ErrorLabel.ForeColor = System.Drawing.Color.Green;

            }

        }
        else
        {
            ErrorLabel.Visible = true;
            ErrorLabel.Text = "Upload failed: Only jpg, gif, and png allowed.";
            ErrorLabel.ForeColor = System.Drawing.Color.Red;

        }
</code>```

Above is the code I am using to upload a file to the database for a user image. I need to know how to write a unit test that can return a GUID and not a null value to ensure the code works as intended.

Essentially, I want to add the currently logged in user userid from the membership provider as well as the uploaded image to the database so it can be easily retrieved later. When I test it by modifying the database to accept something other than the uniqueidentifier and the code to insert a temp userid, the insertion works. But now I want to make sure that I can actually obtain the currently logged in userid and add that to the database.

When I test this code, it says for the error that the

```<code>Guid UserId = (Guid)Membership.GetUser().ProviderUserKey
</code>```

part is returning a null value, even if I add a user to the membership tables.
How can I properly test the retrieval of a currently logged in user userid?

答:
After more digging and researching, found this in stackoverflow. Again, not a pro, lol, and didn't even know what proper keywords to use, but I found this, and I will give it a go! This seems likes its exactly what I was looking for, a unit test way to mock up a guid for a user.

Mocking Guid.NewGuid()

Body:
protected void UploadImage_Click(object sender, EventArgs e)
    {
        HttpPostedFile postedFile = ImageUploader.PostedFile;
        string fileExtension =
Path.GetExtension(Path.GetFileName(postedFile.FileName));
        if (ImageUploader.HasFile && fileExtension.ToLower() == ".jpg" ||
fileExtension.ToLower() == ".gif" || fileExtension.ToLower() == ".png")
        {

            Stream fs = postedFile.InputStream;
            BinaryReader br = new BinaryReader(fs);
            Byte[] image = br.ReadBytes((int)fs.Length);
            Guid UserId = (Guid)Membership.GetUser().ProviderUserKey;

            string cs = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                string sqlcmd = "insert into ProfileImage values(@UserId, @ImageData)";
                SqlCommand cmd = new SqlCommand(sqlcmd, con);
                cmd.Parameters.AddWithValue("@UserId", UserId);
                cmd.Parameters.AddWithValue("@ImageData", image);

                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();

                ErrorLabel.Visible = true;
                ErrorLabel.Text = "Upload Success!";
                ErrorLabel.ForeColor = System.Drawing.Color.Green;

            }

        }
        else
        {
            ErrorLabel.Visible = true;
            ErrorLabel.Text = "Upload failed: Only jpg, gif, and png allowed.";
            ErrorLabel.ForeColor = System.Drawing.Color.Red;

        }

Above is the code I am using to upload a file to the database for a user image. I need to know how to write a unit test that can return a GUID and not a null value to ensure the code works as intended.

Essentially, I want to add the currently logged in user userid from the membership provider as well as the uploaded image to the database so it can be easily retrieved later. When I test it by modifying the database to accept something other than the uniqueidentifier and the code to insert a temp userid, the insertion works. But now I want to make sure that I can actually obtain the currently logged in userid and add that to the database.

When I test this code, it says for the error that the

Guid UserId = (Guid)Membership.GetUser().ProviderUserKey

part is returning a null value, even if I add a user to the membership tables.
How can I properly test the retrieval of a currently logged in user userid?


问:
constrained random numbers sampling using python (Monte-Carlo, Markov chains, pymc)
I am trying to sample random numbers with constraints using Python and pymc library.

Here mins and maxes are arrays of minimums and maximums for each of 22 variables. It works fine in this case.

```<code>from pymc import *
X = Uniform('X', mins, maxes)
@potential
def s(X=X):
 cons1 = X[0] < 225
 cons2 = X[0] > 405
 if cons1 or cons2:
     return -inf
 else:
     return 0.0
mc = MCMC([X, s])
mc.sample(10000)
</code>```

However when I try to add one more constraint: that sum of variables must be equal to 1000, everything breaks:

```<code>from pymc import *
X = Uniform('X', mins, maxes)
@potential
def s(X=X):
 cons1 = X[0] < 225
 cons2 = X[0] > 405
 cons3 = X.sum() >= 1000
 if cons1 or cons2 or cons3:
     return -inf
 else:
     return 0.0
mc = MCMC([X, s])
mc.sample(10000)
</code>```

Error is: 'ZeroProbability: Potential s forbids its parents' current values'

Could you please recommend some solutions to this problem?

答:
Consider sampling from just two constrained uniform random variables on the standard interval, as pictured here.

The brown area represents the constrained sampling area based on some inequalities. The diagonal line represent the sum.

Notice: In 2-space the brown area has an area (otherwise known as a probability or measure) but the diagonal line has zero area, which is to say zero probability or measure.

The same holds true for higher dimensional spaces.

Body:
I am trying to sample random numbers with constraints using Python and pymc library.

Here mins and maxes are arrays of minimums and maximums for each of 22 variables. It works fine in this case.

from pymc import *
X = Uniform('X', mins, maxes)
@potential
def s(X=X):
 cons1 = X[0] < 225
 cons2 = X[0] > 405
 if cons1 or cons2:
     return -inf
 else:
     return 0.0
mc = MCMC([X, s])
mc.sample(10000)

However when I try to add one more constraint: that sum of variables must be equal to 1000, everything breaks:

from pymc import *
X = Uniform('X', mins, maxes)
@potential
def s(X=X):
 cons1 = X[0] < 225
 cons2 = X[0] > 405
 cons3 = X.sum() >= 1000
 if cons1 or cons2 or cons3:
     return -inf
 else:
     return 0.0
mc = MCMC([X, s])
mc.sample(10000)

Error is: 'ZeroProbability: Potential s forbids its parents' current values'

Could you please recommend some solutions to this problem?


问:
how i can Explode Group_Concat in foreach
Query MySQL
here query to get the result for all users with Group_concat

```<code>$result = $con->prepare("SELECT
    results.StuID,
    subjects_d.SubjectID,
    exams.ID,
    GROUP_CONCAT(results.ExamID,',',results.Exam1,',',results.Exam2,',',results.Exam3 ORDER BY results.ExamID  ASC) AS data
FROM
    results
LEFT JOIN
    users
ON
    users.UID = results.StuID
LEFT JOIN
    subjects_d
ON
    subjects_d.SubID = results.Sub_ID
LEFT JOIN
    exams
ON
    exams.ID = results.ExamID
WHERE
    subjects_d.C_ID = 3
AND
    subjects_d.SubjectID = 4
GROUP BY results.StuID");
$result->execute(array($classid, $subjectid));
$results = $result->fetchAll();
</code>```

This is Result from mysql

PHP code

```<code><?php foreach($results as $result) { ?>
    <?php echo '```';print_r($result)?>
<?php } ?>
```

<p><strong>print_r</strong></p>

```Array
(
    [StuID] => 70
    [0] => 70
    [SubjectID] => 4
    [1] => 4
    [ID] => 1
    [2] => 1
    [data] => 1,0,0,0,2,0,0,0,3,0,0,0,4,0,0,0
    [3] => 1,0,0,0,2,0,0,0,3,0,0,0,4,0,0,0
)
```

Now how I can explode this data array in foreach loop
Thank you

答:
Explode data string with comma as delimiter in foreach loop.</p>

```<code>foreach($results as $result) {
    // explode with comma
    $data_array = explode(',',$result['data']);
 }
</code>```

Body:
Query MySQL
here query to get the result for all users with Group_concat

$result = $con->prepare("SELECT
    results.StuID,
    subjects_d.SubjectID,
    exams.ID,
    GROUP_CONCAT(results.ExamID,',',results.Exam1,',',results.Exam2,',',results.Exam3 ORDER BY results.ExamID  ASC) AS data
FROM
    results
LEFT JOIN
    users
ON
    users.UID = results.StuID
LEFT JOIN
    subjects_d
ON
    subjects_d.SubID = results.Sub_ID
LEFT JOIN
    exams
ON
    exams.ID = results.ExamID
WHERE
    subjects_d.C_ID = 3
AND
    subjects_d.SubjectID = 4
GROUP BY results.StuID");
$result->execute(array($classid, $subjectid));
$results = $result->fetchAll();

This is Result from mysql

PHP code

<?php foreach($results as $result) { ?>
    <?php echo '
';print_r($result)?>
<?php } ?>

print_r

Array
(
    [StuID] => 70
    [0] => 70
    [SubjectID] => 4
    [1] => 4
    [ID] => 1
    [2] => 1
    [data] => 1,0,0,0,2,0,0,0,3,0,0,0,4,0,0,0
    [3] => 1,0,0,0,2,0,0,0,3,0,0,0,4,0,0,0
)

Now how I can explode this data array in foreach loop
Thank you

Body:
Explode data string with comma as delimiter in foreach loop.

foreach($results as $result) {
    // explode with comma
    $data_array = explode(',',$result['data']);
 }


问:
How to activate Dataflow Shuffle service?
I am trying to use Dataflow Shuffle service in python environment, but it seems shuffle service is not working, as you can see below.

I set the SDK version above 2.1, and the region is us-central1.
I thought we can activate Dataflow Shuffle service by just adding experiments option, am I missing something?

Following is the code I tested, you can reproduce the phenomenon.

```<code>import apache_beam as beam

options = beam.options.pipeline_options.PipelineOptions()
gcloud_options = options.view_as(
    beam.options.pipeline_options.GoogleCloudOptions)
gcloud_options.job_name = 'dataflow-shuffle-test'
gcloud_options.project = 'PROJECTID'
gcloud_options.staging_location = 'gs://BUCKET/staging'
gcloud_options.temp_location = 'gs://BUCKET/temp'

# maybe this is the wrong way?
debug_options = options.view_as(beam.options.pipeline_options.DebugOptions)
debug_options.experiments = 'shuffle_mode=service'

worker_options = options.view_as(beam.options.pipeline_options.WorkerOptions)
worker_options.disk_size_gb = 20
worker_options.max_num_workers = 2

options.view_as(beam.options.pipeline_options.StandardOptions).runner = 'DataflowRunner'

def modify_data2(kvpair):
    return {'name': kvpair[0],
            'sum': sum(kvpair[1])
            }

p = beam.Pipeline(options=options)

query = 'SELECT * FROM [bigquery-public-data:usa_names.usa_1910_current]'
(p | 'read' >> beam.io.Read(beam.io.BigQuerySource(project='PROJECTID',
                                                   use_standard_sql=False,
                                                   query=query))
   | 'pair' >> beam.Map(lambda x: (x['name'], x['number']))
   | "groupby" >> beam.GroupByKey()
   | 'modify' >> beam.Map(modify_data2)
   | 'write' >> beam.io.WriteToText('gs://BUCKET/test.txt', num_shards=1)
 )

p.run()
</code>```

The job finishes successfully, without any errors. Any comment would be helpful!

EDIT

Thanks to Sergei's answer, I found my mistake. What I mistook is the experiments option. Set the experiments option as below.

```<code># set as list, instead of string.
debug_options.experiments = ['shuffle_mode=service']
</code>```

Also I made a gist to run a simple pipeline with shuffle service, the notebook can be runnable on Datalab.
https://gist.github.com/hayatoy/f6664f965a2519ec406e11235faf75b6

答:
@HayatoY, it should be enough to just specify the experiments flag (--experiments shuffle_mode=service).

The Dataflow Shuffle Service is available with the Python SDK starting with the 2.1 version in the us-central1 and europe-west1 regions.

Can you check if you see the experiments line under the "Pipeline options" pane in the Job Details page in the UI? (see my screenshot)

I just launched a simple wordcount pipeline from the command line and validated that Shuffle was used by it (the metric is 0, but that's normal because the wordcount pipeline uses very little shuffle). As long as the metric is not a "-" you have proof that the Shuffle Service was used.

python -m apache_beam.examples.wordcount \
  --project $PROJECT_ID \
  --runner DataflowRunner \
  --staging_location $BUCKET/staging \
  --temp_location $BUCKET/temp \
  --output $BUCKET/output \
  --experiments shuffle_mode=service

Body:
I am trying to use Dataflow Shuffle service in python environment, but it seems shuffle service is not working, as you can see below.

I set the SDK version above 2.1, and the region is us-central1.
I thought we can activate Dataflow Shuffle service by just adding experiments option, am I missing something?

Following is the code I tested, you can reproduce the phenomenon.

import apache_beam as beam

options = beam.options.pipeline_options.PipelineOptions()
gcloud_options = options.view_as(
    beam.options.pipeline_options.GoogleCloudOptions)
gcloud_options.job_name = 'dataflow-shuffle-test'
gcloud_options.project = 'PROJECTID'
gcloud_options.staging_location = 'gs://BUCKET/staging'
gcloud_options.temp_location = 'gs://BUCKET/temp'

# maybe this is the wrong way?
debug_options = options.view_as(beam.options.pipeline_options.DebugOptions)
debug_options.experiments = 'shuffle_mode=service'

worker_options = options.view_as(beam.options.pipeline_options.WorkerOptions)
worker_options.disk_size_gb = 20
worker_options.max_num_workers = 2

options.view_as(beam.options.pipeline_options.StandardOptions).runner = 'DataflowRunner'

def modify_data2(kvpair):
    return {'name': kvpair[0],
            'sum': sum(kvpair[1])
            }

p = beam.Pipeline(options=options)

query = 'SELECT * FROM [bigquery-public-data:usa_names.usa_1910_current]'
(p | 'read' >> beam.io.Read(beam.io.BigQuerySource(project='PROJECTID',
                                                   use_standard_sql=False,
                                                   query=query))
   | 'pair' >> beam.Map(lambda x: (x['name'], x['number']))
   | "groupby" >> beam.GroupByKey()
   | 'modify' >> beam.Map(modify_data2)
   | 'write' >> beam.io.WriteToText('gs://BUCKET/test.txt', num_shards=1)
 )

p.run()

The job finishes successfully, without any errors. Any comment would be helpful!

EDIT

Thanks to Sergei's answer, I found my mistake. What I mistook is the experiments option. Set the experiments option as below.

# set as list, instead of string.
debug_options.experiments = ['shuffle_mode=service']

Also I made a gist to run a simple pipeline with shuffle service, the notebook can be runnable on Datalab.
https://gist.github.com/hayatoy/f6664f965a2519ec406e11235faf75b6


问:
Cannot find name defined in same file; How to achieve union type of const values?
I export some string constants and try to use them for a type definition in the same file, and it doesn't work.

export const SET_DETERMINATION = 'SET_DETERMINATION';
export const SET_HIGHLIGHTING = 'SET_HIGHLIGHTING';
export const SET_TEXT = 'SET_TEXT';

export type THypoAction =
  SET_DETERMINATION
  | SET_HIGHLIGHTING
  | SET_TEXT;
```

<blockquote>
  <p>TS2304: Cannot find name 'SET_DETERMINATION'.</p>

  <p>TS2304: Cannot find name 'SET_HIGHLIGHTING'.</p>

  <p>TS2304: Cannot find name 'SET_TEXT'.</p>
</blockquote>

<p>I can fix this by defining my type using the string values themselves, i.e.</p>

<pre class="lang-js prettyprint-override"><code>export type THypoAction =
  'SET_DETERMINATION'
  | 'SET_HIGHLIGHTING'
  | 'SET_TEXT';
</code>```

But this seems more fragile than referencing the constants.

Is there any way of going about this where I achieve the following?

Declare the literal string values only once

Export the constants with their string values

Define a union type of the constants' string values

For context, I am looking to build a reducer which will accept dispatched actions that adhere to an interface like the following (only with a more specific payload)

export interface IHypoAction {
  type: THypoAction;
  payload?: any;
}
```

In modules referencing this I thus need both the constants, and their type definition for the interface.

答:
@unional I'm using ts 2.6.1 and it doesn't work. In the following code example ts cannot find the name 'SET_TOKEN', but this is fixed if I enclose it as string readonly type: 'SET_TOKEN';:

```<code>import { Action } from '@ngrx/store';

export const SIGNUP = 'SIGNUP';
export const SIGNIN = 'SIGNIN';
export const LOGOUT = 'LOGOUT';
export const SET_TOKEN = 'SET_TOKEN';

/* Some other classes here */

export class SetToken implements Action {
    readonly type: SET_TOKEN; // ts error here. ts cannot find name
    constructor(public payload: string) { }
}

export type AuthActions =
    SignUp |
    SignIn |
    LogOut |
    SetToken;
</code>```

Body:
I export some string constants and try to use them for a type definition in the same file, and it doesn't work.

export const SET_DETERMINATION = 'SET_DETERMINATION';
export const SET_HIGHLIGHTING = 'SET_HIGHLIGHTING';
export const SET_TEXT = 'SET_TEXT';

export type THypoAction =
  SET_DETERMINATION
  | SET_HIGHLIGHTING
  | SET_TEXT;

TS2304: Cannot find name 'SET_DETERMINATION'.

TS2304: Cannot find name 'SET_HIGHLIGHTING'.

TS2304: Cannot find name 'SET_TEXT'.

I can fix this by defining my type using the string values themselves, i.e.

export type THypoAction =
  'SET_DETERMINATION'
  | 'SET_HIGHLIGHTING'
  | 'SET_TEXT';

But this seems more fragile than referencing the constants.

Is there any way of going about this where I achieve the following?

Declare the literal string values only once

Export the constants with their string values

Define a union type of the constants' string values

For context, I am looking to build a reducer which will accept dispatched actions that adhere to an interface like the following (only with a more specific payload)

export interface IHypoAction {
  type: THypoAction;
  payload?: any;
}

In modules referencing this I thus need both the constants, and their type definition for the interface.

Body:
@unional I'm using ts 2.6.1 and it doesn't work. In the following code example ts cannot find the name 'SET_TOKEN', but this is fixed if I enclose it as string readonly type: 'SET_TOKEN';:

import { Action } from '@ngrx/store';

export const SIGNUP = 'SIGNUP';
export const SIGNIN = 'SIGNIN';
export const LOGOUT = 'LOGOUT';
export const SET_TOKEN = 'SET_TOKEN';

/* Some other classes here */

export class SetToken implements Action {
    readonly type: SET_TOKEN; // ts error here. ts cannot find name
    constructor(public payload: string) { }
}

export type AuthActions =
    SignUp |
    SignIn |
    LogOut |
    SetToken;


问:
Using dot memory API to take multiple snapshot on same .dmv file
I am trying to profile my specific code using dot memory api. When I call the dump() method my expectation is to take snapshot and save it to dir.

I am trying to take two snapshot here one before executing my code and after executing my code by calling dump() method.

Is it possible to create the both snapshot in the same output file as we option to do it from Stand alone dot memory?

Appreciate your suggestion. following is the code snippet

```<code>SelfAttach.Attach(new SaveSnapshotProfilingConfig
{
   ProfilingControlKind = ProfilingControlKind.Api,
   SaveDir = "D:\\SelfProfiling",
   RedistDir = "D:\\Softwares\\JetBrains.Profiler.SelfSdk.2017.2.2",
   ProfilingType = ProfilingType.Memory,
   ListFile = "D:\\snapshot_list.xml"
});

while (SelfAttach.State != SelfApiState.Active)
{
     Thread.Sleep(250);  // wait until API starts
}

if (MemoryProfiler.IsActive)
{
   MemoryProfiler.Dump();
   MyMethodTobeProfiled();
   MemoryProfiler.Dump();
}

if (MemoryProfiler.CanDetach)
   MemoryProfiler.Detach();
</code>```

答:
I guess you can use dotMemory Command Line Profiler instead of "Self profiling" API to reach your needs.

Launch dotMemory command line profiler.
Determine that profiler is already attached to your app, for that you need to analyze dotMemory CLT process output.

So, pseudo code to get what you need

```<code>dotMemory.exe attach --service-output --use-api "your_app_PID"

// then the message will be printed to output
// ##dotMemory["connected",{"pid":your_app_PID,"name":"your_app_NAME.exe"}]
wait for this message

// the rest of your code remains the same
// and you need only JetBrains.Profiler.Windows.Api.dll
// no more need JetBrains.Profiler.Windows.SelfApi.dll
if (MemoryProfiler.IsActive)
{
    MemoryProfiler.Dump();
    MyMethodTobeProfiled();
    MemoryProfiler.Dump();
}

if (MemoryProfiler.CanDetach)
   MemoryProfiler.Detach();
</code>```

Read more about dotMemory command line profiler here

Body:
I am trying to profile my specific code using dot memory api. When I call the dump() method my expectation is to take snapshot and save it to dir.

I am trying to take two snapshot here one before executing my code and after executing my code by calling dump() method.

Is it possible to create the both snapshot in the same output file as we option to do it from Stand alone dot memory?

Appreciate your suggestion. following is the code snippet

SelfAttach.Attach(new SaveSnapshotProfilingConfig
{
   ProfilingControlKind = ProfilingControlKind.Api,
   SaveDir = "D:\\SelfProfiling",
   RedistDir = "D:\\Softwares\\JetBrains.Profiler.SelfSdk.2017.2.2",
   ProfilingType = ProfilingType.Memory,
   ListFile = "D:\\snapshot_list.xml"
});

while (SelfAttach.State != SelfApiState.Active)
{
     Thread.Sleep(250);  // wait until API starts
}

if (MemoryProfiler.IsActive)
{
   MemoryProfiler.Dump();
   MyMethodTobeProfiled();
   MemoryProfiler.Dump();
}

if (MemoryProfiler.CanDetach)
   MemoryProfiler.Detach();

Body:
I guess you can use dotMemory Command Line Profiler instead of "Self profiling" API to reach your needs.

Launch dotMemory command line profiler.
Determine that profiler is already attached to your app, for that you need to analyze dotMemory CLT process output.

So, pseudo code to get what you need

dotMemory.exe attach --service-output --use-api "your_app_PID"

// then the message will be printed to output
// ##dotMemory["connected",{"pid":your_app_PID,"name":"your_app_NAME.exe"}]
wait for this message

// the rest of your code remains the same
// and you need only JetBrains.Profiler.Windows.Api.dll
// no more need JetBrains.Profiler.Windows.SelfApi.dll
if (MemoryProfiler.IsActive)
{
    MemoryProfiler.Dump();
    MyMethodTobeProfiled();
    MemoryProfiler.Dump();
}

if (MemoryProfiler.CanDetach)
   MemoryProfiler.Detach();

Read more about dotMemory command line profiler here


问:
Read data from a local JSON file with data binding in ngOnInit() results in undefined variable
I am trying to get a data from json file in the assets folder, and then assign this data to a variable that will be binded to another @Input variable of a child componenet.

Code

Based on multiple solutions on the net, I retrieve my JSON data this way:

```<code>@Injectable()
export class JSONService {

    constructor(private http: HttpClient) { }

    public fromJSON(jsonFileName: string): Observable<any[]> {
      let result: any[] = new Array();
      let pathToJson: string = "assets/" + jsonFileName + ".json";

      return this.http.get(pathToJson).map(data => {
        let result: any[] = new Array();
        // Apply some treatment on data and push it to the result array
        return result;
      });
    }
}
</code>```

I then call my service in the ngOnInit() method of the parent component:

```<code>ngOnInit() {
    this.jsonService.fromJSON("users.json").subscribe(fields => {
      this.fields= fields;
      console.log(this.fields); // Log (I): this.fields is well defined
    });
    console.log(this.fields); // Log (II): this.fields is undefined
}
</code>```

Where the variable fields is binded to a child component:

```<code><child-component [childFields] = "fields"></child-component>
</code>```

Problem

The problem that I am facing is that the asynchronous call to the fromJSON method causes this.fields to be undefined at some point of the lifecycle of the page execution (Log (II) from the code above), and this causes to send an undefined value of the this.fields variable to the child component.

How to avoid to have an undefined value of the fields variable, and make sure that the child component is always loaded with the data from the json file?

答:
Just add *ngIf to check if the data is loaded</p>

```<code><child-component *ngIf="fields" [childFields] = "fields"></child-component>
</code>```

Body:
I am trying to get a data from json file in the assets folder, and then assign this data to a variable that will be binded to another @Input variable of a child componenet.

Code

Based on multiple solutions on the net, I retrieve my JSON data this way:

@Injectable()
export class JSONService {

    constructor(private http: HttpClient) { }

    public fromJSON(jsonFileName: string): Observable<any[]> {
      let result: any[] = new Array();
      let pathToJson: string = "assets/" + jsonFileName + ".json";

      return this.http.get(pathToJson).map(data => {
        let result: any[] = new Array();
        // Apply some treatment on data and push it to the result array
        return result;
      });
    }
}

I then call my service in the ngOnInit() method of the parent component:

ngOnInit() {
    this.jsonService.fromJSON("users.json").subscribe(fields => {
      this.fields= fields;
      console.log(this.fields); // Log (I): this.fields is well defined
    });
    console.log(this.fields); // Log (II): this.fields is undefined
}

Where the variable fields is binded to a child component:

<child-component [childFields] = "fields"></child-component>

Problem

The problem that I am facing is that the asynchronous call to the fromJSON method causes this.fields to be undefined at some point of the lifecycle of the page execution (Log (II) from the code above), and this causes to send an undefined value of the this.fields variable to the child component.

How to avoid to have an undefined value of the fields variable, and make sure that the child component is always loaded with the data from the json file?

Body:
Just add *ngIf to check if the data is loaded

<child-component *ngIf="fields" [childFields] = "fields"></child-component>


问:
VBA Compare times correctly
I am using VBA to compare two times from a spreadsheet.
Im my example the actual value form the sheet is 23:00 in two cells. I use them for an if-statement, the values both come from two different arrays from the type Variant.

```<code>if dataArr(v1) = rowArr(v2) Then
</code>```

If I debug the two values it shows the two value like this

0,958333333333333 / 0,958333333333333

They seem the same but the compare in the if-statement returns false

So I subtracted the two value to see if the result is zero.

```<code>dataArr(v1) - rowArr(v2)
</code>```

In this case the result is not zero but

3,33066907387547E-16

So something is wrong with the compare or the two double values that represent the time.

The only working solution I found was to convert them to string values by

```<code>CStr(dataArr(v1)) = CStr(rowArr(v2))
</code>```

which returns true as it should be.

I don't really like this solution because it is not really how it should work. I also investigated what happens to the values before they end up in the compare but I could not find any mistake . Actually all the values in the dataArr are coming from the spreadsheet (ListObject.DataBodyRange.Value) and then certain values are copied to the rowArr out of the dataArr so it really should be the same value.

Any suggestions? Thanks!

答:
If the cells are actually formatted for time instead of a string, I would make the definition of my arrays a "Date" not a "Variant".

Then you would have all the date/time related functionality in VBA at your disposal (like DateDiff() ).

Title: VBA Compare times correctly

Body:
I am using VBA to compare two times from a spreadsheet.
Im my example the actual value form the sheet is 23:00 in two cells. I use them for an if-statement, the values both come from two different arrays from the type Variant.

if dataArr(v1) = rowArr(v2) Then

If I debug the two values it shows the two value like this

0,958333333333333 / 0,958333333333333

They seem the same but the compare in the if-statement returns false

So I subtracted the two value to see if the result is zero.

dataArr(v1) - rowArr(v2)

In this case the result is not zero but

3,33066907387547E-16

So something is wrong with the compare or the two double values that represent the time.

The only working solution I found was to convert them to string values by

CStr(dataArr(v1)) = CStr(rowArr(v2))

which returns true as it should be.

I don't really like this solution because it is not really how it should work. I also investigated what happens to the values before they end up in the compare but I could not find any mistake . Actually all the values in the dataArr are coming from the spreadsheet (ListObject.DataBodyRange.Value) and then certain values are copied to the rowArr out of the dataArr so it really should be the same value.

Any suggestions? Thanks!


问:
Check if custom font can display character
I have a custom font which is displaying the box character. The font I am using does not support all languages apparently. I want to check if the String I am about to display can be displayed by my custom font. If it cannot then I want to use the standard Android font (which I know can display the characters). I can't find a method to check if my Typeface can display a particular String though. I am sure I have seen a method around that does this somewhere. Anyone know?</p>

答:
To check whether the music symbol ♫ is being displayed in a string (if it is not being displayed on some devices), you can try measuring the string width; if width == 0 then the symbol is absent.

```<code>Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
Rect rtt = new Rect();
paint.getTextBounds( "♫", 0, 1, rtt );
    if( rtt.width() == 0 ){
}
</code>```

Body:
To check whether the music symbol ♫ is being displayed in a string (if it is not being displayed on some devices), you can try measuring the string width; if width == 0 then the symbol is absent.

Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
Rect rtt = new Rect();
paint.getTextBounds( "♫", 0, 1, rtt );
    if( rtt.width() == 0 ){
}


问:
Request.Headers["Referer"] does not exist
I have a solution with two ASP.NET Core MVC projects. One project (Client) is making a request to the other (Server) using HttpClient. When the action in Server receives the request, I want to get the URL of the thing that sent it. Every article I have read purports Request.Headers["Referer"] as the solution, but in my case Headers does not contain a "referer" key (or "referrer").

When receiving the request in Server, how should I find the URL of the Client that sent it?

答:
That is how you you get the referring url for a request.  But the referer isn't the thing that sent the request.  The referer gets set in the headers by the browser when a person clicks on a link from one website to go to another website.  When that request is made by the browser to the new website the request will typically have the Referer header which will contain the url of the prior website.

The receiving server can't get the url of the "client" making the request, remember a typical web browser client isn't at any url.  All the receiving server can get is the IP address of the client typically.

Since you have control of the client software, if you wanted you could have the client put whatever info you want in the header of the request before it's sent to the server and the server could then get that info out of the header.


问:
How to implement a mechanism for users to block abusive users using firebase with help of JSQMessagesViewController in swift 4
I have implemented one-to-one chat using "Firebase" with the help of "JSQMessagesViewController" in swift 4 and I have submitted my app to Appstore. But, app gets rejected and asking for "A mechanism for users to block abusive users".

So, how I can achieve this mechanism in swift 4. I am not able to implement it, any code/suggestions will more appreciate.

Thank you in advance.

答:
1st you would need is a flag on your user objects similar to isBlocked or you could create a new table in Firebase that holds a list of users (or Ids) that are blocked for a certain user. You could write a cloud function that filters out that information before returning to the device or just parse it on the device. Checking for your isBlocked property and just does not show them in your list of conversations.

2nd yo need an entry point for actually adding the blocked flag to a user. You could do this many ways really depends on your design. You could add a button to the navigation bar that presented the user with options like this

(Make sure to add a call to this where appropriate I would suggest in the ViewDidLoad())

```<code>func prepareNavbarButton() {
    let button = UIBarButtonItem(image: #imageLiteral(resourceName: "conversation_Options_Image"), style: .plain, target: self, action: #selector(uploadContact))
    navigationItem.rightBarButtonItem = button
}
</code>```

or on a message itself with this method

```<code>override func collectionView(collectionView: JSQMessagesCollectionView, didTapMessageBubbleAtIndexPath indexPath: NSIndexPath!) {
  super.collectionView(collectionView, didTapMessageBubbleAtIndexPath: indexPath)
  presentOptions()
}

func presentOptions() {
  let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
    actionSheet.addAction(UIAlertAction(title: "Block User", style: .default, handler: { _ in
        blockUserAction()
    }))
    actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
}

func blockUserAction() {
    //CODE TO ADD USER ID TO BLOCKED USER IN FIREBASE
}
</code>```

3rd I would provide a list of blocked users in a "Settings" like page that allows you to remove people from the list.

I would also suggest that you swap out JSQMessagesViewController with MessageKit since JSQMessagesViewController is deprecated and will not have future support. MessageKit is the replacement and has a slack channel that anyone can join. It is also written in Swift 4 so you will not need to have a bridging-header-file to have it as a part of your project. It has most of the features of JSQMessagesViewController already and more are to come.

Body:
1st you would need is a flag on your user objects similar to isBlocked or you could create a new table in Firebase that holds a list of users (or Ids) that are blocked for a certain user. You could write a cloud function that filters out that information before returning to the device or just parse it on the device. Checking for your isBlocked property and just does not show them in your list of conversations.

2nd yo need an entry point for actually adding the blocked flag to a user. You could do this many ways really depends on your design. You could add a button to the navigation bar that presented the user with options like this

(Make sure to add a call to this where appropriate I would suggest in the ViewDidLoad())

func prepareNavbarButton() {
    let button = UIBarButtonItem(image: #imageLiteral(resourceName: "conversation_Options_Image"), style: .plain, target: self, action: #selector(uploadContact))
    navigationItem.rightBarButtonItem = button
}

or on a message itself with this method

override func collectionView(collectionView: JSQMessagesCollectionView, didTapMessageBubbleAtIndexPath indexPath: NSIndexPath!) {
  super.collectionView(collectionView, didTapMessageBubbleAtIndexPath: indexPath)
  presentOptions()
}

func presentOptions() {
  let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
    actionSheet.addAction(UIAlertAction(title: "Block User", style: .default, handler: { _ in
        blockUserAction()
    }))
    actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
}

func blockUserAction() {
    //CODE TO ADD USER ID TO BLOCKED USER IN FIREBASE
}

3rd I would provide a list of blocked users in a "Settings" like page that allows you to remove people from the list.

I would also suggest that you swap out JSQMessagesViewController with MessageKit since JSQMessagesViewController is deprecated and will not have future support. MessageKit is the replacement and has a slack channel that anyone can join. It is also written in Swift 4 so you will not need to have a bridging-header-file to have it as a part of your project. It has most of the features of JSQMessagesViewController already and more are to come.


问:
J2ME SDK 3.0 WMA Console in NetBeans
Does anyone knows if NetBeans 6.9.1 has the WMA console of J2ME 3.0 SDK?

Thanks.

答: AFAIK, WMA console is available in Java ME SDK 3.0, but not in netbeans.</p>

Title: J2ME SDK 3.0 WMA Console in NetBeans


问:
Optimal way to get last posts of user's friends in Firebase
In my DB each user has friends. And I need to get 50 last posts of the user's friends. See below structure of posts of each user in Firebase DB.

So what is optimal way to do that? If a user has for example 150 friends, then my Android app should have as many listeners as friends. Is it ok to have 150 or more DB listeners in the app? Also what is the way to get all friends' posts in single query? Thanks.

```<code>root
- posts
  - {userUid}
    - {postUid}
      - text
      - dateCreated
</code>```

答:
You can have 150+ listeners but the less the better. Maybe you can just watch all posts instead of listening to every friend separtely.

To get all posts of a friend once try:

```<code>ref('posts').child(friendUid).once('value').then(function(snapshot) {
   console.log(snapshot.val());
});
</code>```

To get the last 50 posts of a friend once try:

```<code>ref('posts').child(friendUid).orderByChild("dateCreated").limitToLast(50).once('value').then(function(snapshot) {
   console.log(snapshot.val());
});
</code>```

(depending on your dateCreated property you might need to use limitToFirst instead of limitToLast. Check the Firebase Query docu for more information.)

Body:
In my DB each user has friends. And I need to get 50 last posts of the user's friends. See below structure of posts of each user in Firebase DB.

So what is optimal way to do that? If a user has for example 150 friends, then my Android app should have as many listeners as friends. Is it ok to have 150 or more DB listeners in the app? Also what is the way to get all friends' posts in single query? Thanks.

root
- posts
  - {userUid}
    - {postUid}
      - text
      - dateCreated

Body:
You can have 150+ listeners but the less the better. Maybe you can just watch all posts instead of listening to every friend separtely.

To get all posts of a friend once try:

ref('posts').child(friendUid).once('value').then(function(snapshot) {
   console.log(snapshot.val());
});

To get the last 50 posts of a friend once try:

ref('posts').child(friendUid).orderByChild("dateCreated").limitToLast(50).once('value').then(function(snapshot) {
   console.log(snapshot.val());
});

(depending on your dateCreated property you might need to use limitToFirst instead of limitToLast. Check the Firebase Query docu for more information.)


问:
VBA very easy program and struggle
so I am getting errors for some reason "next without for"
here is the code:</p>

```<code>Sub test()
Dim y As Integer
y = 0

For i = 1 To 7
    For j = 1 To 7
        If Cells(i, 1) = Cells(j, 1) Then
            y = y + 1

    Next j

        Cells(i, 2).Value = y
        y = 0
Next i

End Sub
</code>```

答:
The problem doesn't come from your For ... To ... Next but from your If condition that you forgot to close with the End If instruction.

```<code>Sub test()
    Dim y As Integer
    y = 0

    For i = 1 To 7
        For j = 1 To 7
            If Cells(i, 1) = Cells(j, 1) Then
                y = y + 1
            End If 'You forgot to end the condition
        Next j

        Cells(i, 2).Value = y
        y = 0
    Next i
End Sub
</code>```

Title: VBA very easy program and struggle

Body:
so I am getting errors for some reason "next without for"
here is the code:

Sub test()
Dim y As Integer
y = 0

For i = 1 To 7
    For j = 1 To 7
        If Cells(i, 1) = Cells(j, 1) Then
            y = y + 1

    Next j

        Cells(i, 2).Value = y
        y = 0
Next i

End Sub

Body:
The problem doesn't come from your For ... To ... Next but from your If condition that you forgot to close with the End If instruction.

Sub test()
    Dim y As Integer
    y = 0

    For i = 1 To 7
        For j = 1 To 7
            If Cells(i, 1) = Cells(j, 1) Then
                y = y + 1
            End If 'You forgot to end the condition
        Next j

        Cells(i, 2).Value = y
        y = 0
    Next i
End Sub


问:
Pandas `drop_duplicates` doesn't keep first row
I created a Dataframe that has a duplicate row like the below:

```<code>df = pd.DataFrame({"Order Date": ["January 1, 2017", "March 15, 2017", "April 20, 2017", "June 23, 2017", "December 12, 2017", None, "April 20, 2017", "April 20, 2017"],
         "Sales Person": ["John", "John", "Rick", "Mary", "Mary", "Rick", "Rick", "Rick"],
         "Items Sold": [4, -999, 1, np.nan, 7, 3, 1, 1],
         "Item Price": [4.99, 1.99, 9.99, 19.99, 0.99, 2.99, 9.99, 9.99]})
</code>```

Which looks like this in Jupyter:

If I get the duplicates it correctly shows the two rows that are duplicates.

```<code>df[df.duplicated()]
</code>```

I then call drop_duplicates to drop the second duplicate and keep the first.

```<code>df.drop_duplicates()
</code>```

However, it looks like it's removing both rows instead of keeping the first. Am I missing something in the drop_duplicates method? The docstring indicates that the keep parameter defaults to first and this still happens even if I explicitly put in that parameter.

答:
You have three duplicated row in your example ,using keep= False to see them all

```<code>df[df.duplicated(keep=False)]
Out[661]:
   Item Price  Items Sold      Order Date Sales Person
2        9.99         1.0  April 20, 2017         Rick
6        9.99         1.0  April 20, 2017         Rick
7        9.99         1.0  April 20, 2017         Rick
</code>```

Then, you do drop_duplicates will only keep the 1st one at row 3 index =2

```<code>df.drop_duplicates()
Out[659]:
   Item Price  Items Sold         Order Date Sales Person
0        4.99         4.0    January 1, 2017         John
1        1.99      -999.0     March 15, 2017         John
2        9.99         1.0     April 20, 2017         Rick
3       19.99         NaN      June 23, 2017         Mary
4        0.99         7.0  December 12, 2017         Mary
5        2.99         3.0               None         Rick
</code>```

Body:
I created a Dataframe that has a duplicate row like the below:

df = pd.DataFrame({"Order Date": ["January 1, 2017", "March 15, 2017", "April 20, 2017", "June 23, 2017", "December 12, 2017", None, "April 20, 2017", "April 20, 2017"],
         "Sales Person": ["John", "John", "Rick", "Mary", "Mary", "Rick", "Rick", "Rick"],
         "Items Sold": [4, -999, 1, np.nan, 7, 3, 1, 1],
         "Item Price": [4.99, 1.99, 9.99, 19.99, 0.99, 2.99, 9.99, 9.99]})

Which looks like this in Jupyter:

If I get the duplicates it correctly shows the two rows that are duplicates.

df[df.duplicated()]

I then call drop_duplicates to drop the second duplicate and keep the first.

df.drop_duplicates()

However, it looks like it's removing both rows instead of keeping the first. Am I missing something in the drop_duplicates method? The docstring indicates that the keep parameter defaults to first and this still happens even if I explicitly put in that parameter.

Body:
You have three duplicated row in your example ,using keep= False to see them all

df[df.duplicated(keep=False)]
Out[661]:
   Item Price  Items Sold      Order Date Sales Person
2        9.99         1.0  April 20, 2017         Rick
6        9.99         1.0  April 20, 2017         Rick
7        9.99         1.0  April 20, 2017         Rick

Then, you do drop_duplicates will only keep the 1st one at row 3 index =2

df.drop_duplicates()
Out[659]:
   Item Price  Items Sold         Order Date Sales Person
0        4.99         4.0    January 1, 2017         John
1        1.99      -999.0     March 15, 2017         John
2        9.99         1.0     April 20, 2017         Rick
3       19.99         NaN      June 23, 2017         Mary
4        0.99         7.0  December 12, 2017         Mary
5        2.99         3.0               None         Rick


问:
How to use SceneTransitionAnimation to tranform between 2 imageview have different rates
I have 2 imageView have different size wait for transition.But the displacement process is shocked at the end due to differences in size

ImageView1 have size 340*340 ,ScaleType is CENTER_CROP
ImageView2 have full screen ,ScaleType is fitXY

This 's my code

start Activity1

```<code>Intent intent=new Intent(getActivity(),Show_Picture.class);
intent.putExtra("hinhanh",caculator(position));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
       ActivityOptionsCompat optionsCompat=ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(),view,"myimage");
       startActivity(intent,optionsCompat.toBundle());
}
</code>```

get back at Activity2

```<code>public void onBackPressed() {
    super.onBackPressed();
    /*finish();
    overridePendingTransition(0,R.anim.show_picture_out);*/
    ConstraintLayout.LayoutParams layoutParams= (ConstraintLayout.LayoutParams) imageView.getLayoutParams();
    layoutParams.height=layoutParams.width;
    imageView.setLayoutParams(layoutParams);
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
</code>```

Any help will be appreciated ^^

答:
Make sure that view is indeed your ImageView and make sure that the ImageView in the second activity has the xml tag of

```<code>android:transitionName="myimage"
</code>```

Body:
I have 2 imageView have different size wait for transition.But the displacement process is shocked at the end due to differences in size

ImageView1 have size 340*340 ,ScaleType is CENTER_CROP
ImageView2 have full screen ,ScaleType is fitXY

This 's my code

start Activity1

Intent intent=new Intent(getActivity(),Show_Picture.class);
intent.putExtra("hinhanh",caculator(position));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
       ActivityOptionsCompat optionsCompat=ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(),view,"myimage");
       startActivity(intent,optionsCompat.toBundle());
}

get back at Activity2

public void onBackPressed() {
    super.onBackPressed();
    /*finish();
    overridePendingTransition(0,R.anim.show_picture_out);*/
    ConstraintLayout.LayoutParams layoutParams= (ConstraintLayout.LayoutParams) imageView.getLayoutParams();
    layoutParams.height=layoutParams.width;
    imageView.setLayoutParams(layoutParams);
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
}

Any help will be appreciated ^^

Body:
Make sure that view is indeed your ImageView and make sure that the ImageView in the second activity has the xml tag of

android:transitionName="myimage"


问:
Getting jibberish when attempting to open DOCX in a browser
Using a memory stream & the correct MIME type with Response.ContentType. Special characters are displayed instead of prompting to open a Word document. I'm using:

```<code>            using (MemoryStream ms = new MemoryStream())
        {
            doc.SaveAs(ms);

            Response.Clear();
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
            Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            ms.WriteTo(Response.OutputStream);
            Response.End();
        }
</code>```

Here's an example of the output I get now rather than a prompt to open a Word document:

答: Turns out it was not a MIME or Response.ContentType issue at all. Being an MVC application, I was attempting to open the FileResult in a modal. Copy/Paste fail, as other buttons worked this way to display content. Not a Word document!</p>

Body:
Using a memory stream & the correct MIME type with Response.ContentType. Special characters are displayed instead of prompting to open a Word document. I'm using:

            using (MemoryStream ms = new MemoryStream())
        {
            doc.SaveAs(ms);

            Response.Clear();
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
            Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            ms.WriteTo(Response.OutputStream);
            Response.End();
        }

Here's an example of the output I get now rather than a prompt to open a Word document: