问:
How do I get a dropped pin inside a MapView to save coordinates and present them as a String using SwiftUI?
I made a Form using SwiftUI, in which I have a section that allows a user to press on a button that takes them to a MapKit View. Once inside the map view, the user can press the "+" button to place a pin on a map. This takes them to the Edit View where they can enter text inside a TextField to label the pin (see screenshot below). I have been stuck here for the past few days attempting to save the pin's coordinates or even the user's input inside the TextField to return it as text (either as city, state or country) inside the Form.

Form -> Map View -> Edit View

Here are some code snippets.

1) From FormView:

```<code>
    import SwiftUI
    import MapKit

    struct FormView: View {
        @State private var selectedTitle = ""
        @State var meuf: Meuf
        @State private var meufs = [Meuf]()
        @State private var show = false
        @State private var singleIsPresented = false
        @Environment(\.presentationMode) var presentationMode
        let newMeuf : Bool
        @EnvironmentObject var meufStorage : MeufStorage
        @State private  var showMap = false

        var body: some View {
            NavigationView{
                Form{
                    //MARK: LOCATION
                    Section{
                        HStack {
                            Button(action: { self.showMap = true }) {
                                Image(systemName: "mappin.and.ellipse")
                            }
                            .sheet(isPresented: $showMap) {
                                LocationMap(showModal: self.$showMap)
                            }
                            Text("Pin your location")
                                .font(.subheadline)
                        }
                    }

                   // MARK: [ SAVE ENTRY ]
                    Section {
                        Button(action: {
                            if self.newMeuf {
                                self.saveData()
                                self.meufStorage.meufs.append(self.meuf)
                            } else {
                                for x in 0..<self.meufStorage.meufs.count {
                                    if self.meufStorage.meufs[x].id == self.meuf.id {
                                        self.meufStorage.meufs[x] = self.meuf
                                    }
                                }
                            }
                            self.presentationMode.wrappedValue.dismiss()
                        }) {
                            HStack{
                                Spacer()
                                Text("Save")
                                Spacer()
                            }
                        }.disabled(meuf.title.isEmpty)
                    }

                }.navigationBarTitle(Text(meuf.title))
            }
        }

        //Get file directory url
        func getFileDirectory() -> URL{
            let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
            return paths[0]
        }

        //Load data from file directory
        func loadData(){
            let filename = getFileDirectory().appendingPathComponent("SavedPlaces")

            do {
                let data = try Data(contentsOf: filename)
                meufs = try JSONDecoder().decode([Meuf].self, from: data)

            }catch{
                debugPrint(error)
            }
        }

        //Save data to file directory
        func saveData(){
            let filename = getFileDirectory().appendingPathComponent("SavedPlaces")
            let data = try? JSONEncoder().encode(self.meufs)
            do{
                try data?.write(to: filename, options: [.atomic , .completeFileProtection])
            }catch{
                debugPrint(error)
            }
        }

    }

    struct FormView_Previews: PreviewProvider {
        static var previews: some View {
            FormView(meuf: Meuf(), newMeuf: true)
        }
    }

</code>```

2) From LocationMap:

```<code>import SwiftUI
import MapKit

struct LocationMap: View {
    @State private var centerCoordinate = CLLocationCoordinate2D()
    @State private var locations = [CodableMKPointAnnotation]()
    @State private var selectedPlace: MKPointAnnotation?
    @State private var showingPlaceDetails = false
    @State private var showingEditScreen = false

    @Binding var showModal: Bool

    var body: some View {
        ZStack{
            MapView(centerCoordinate: $centerCoordinate, annotations: locations, selectedPlace: $selectedPlace, showingPlaceDetails: $showingPlaceDetails)
                .edgesIgnoringSafeArea(.all)
            Circle()
                .fill(Color.blue)
                .opacity(0.3)
                .frame(width: 32, height: 32)
            VStack {
                Spacer()
                HStack{
                    Spacer()
                    Button(action:{
                        let newLocation = CodableMKPointAnnotation()
                        newLocation.title = ""
                        newLocation.coordinate = self.centerCoordinate
                        self.locations.append(newLocation)

                        self.selectedPlace = newLocation
                        self.showingEditScreen = true
                    }){
                        Image(systemName: "plus")
                    }
                    .padding()
                    .background(Color.black.opacity(0.7))
                    .foregroundColor(Color.white)
                    .clipShape(Circle())
                    .shadow(radius: 0.7)
                    .padding([.trailing , .bottom])
                }
            }
            .padding()
        }.alert(isPresented: $showingPlaceDetails) {
            Alert(title: Text(selectedPlace?.title ?? "Unknown"), message: Text(selectedPlace?.subtitle ?? "Missing place information."), primaryButton: .default(Text("OK")), secondaryButton: .default(Text("Edit")) {
                self.showingEditScreen = true
                }
            )
        }
        .sheet(isPresented: $showingEditScreen, onDismiss: savedData) {
            if self.selectedPlace != nil {
                EditView(placemark: self.selectedPlace!)
            }
        }

        .onAppear(perform: loadData)

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

        func loadData() {
            let filename = getDocumentsDirectory().appendingPathComponent("Saved Places")

            do {
                let data = try Data(contentsOf: filename)
                locations = try JSONDecoder().decode([CodableMKPointAnnotation].self, from: data)
            } catch {
                print("Unable to load saved data.")
            }
        }

        func savedData() {
            do {
                let filename = getDocumentsDirectory().appendingPathComponent("SavedPlaces")
                let data = try JSONEncoder().encode(self.locations)
                try data.write(to: filename, options: [.atomicWrite, .completeFileProtection])
            } catch {
                print("Unable to save data")
            }
        }

}
struct LocationMap_Previews: PreviewProvider {
    static var previews: some View {
        LocationMap(showModal: .constant(true))
    }
}
</code>```

3) From MapView:

```<code>import MapKit
import Combine
import SwiftUI

struct MapView: UIViewRepresentable {
    @Binding var centerCoordinate: CLLocationCoordinate2D
    var annotations: [MKPointAnnotation]
    @Binding var selectedPlace: MKPointAnnotation?
    @Binding var showingPlaceDetails: Bool

    func makeUIView(context: UIViewRepresentableContext<MapView>) -> MKMapView {
        let mapView = MKMapView()
        mapView.delegate = context.coordinator
        return mapView
    }

    func updateUIView(_ uiView: MKMapView, context: UIViewRepresentableContext<MapView>) {
        if annotations.count != uiView.annotations.count{
            uiView.removeAnnotations(uiView.annotations)
            uiView.addAnnotations(annotations)
        }
    }

    ///Coordinator class for passing data
    class Coordinator: NSObject , MKMapViewDelegate{
        let parent: MapView

        init(_ parent: MapView){
            self.parent = parent
        }

        func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {
            parent.centerCoordinate = mapView.centerCoordinate
        }

        //Gets called whenever the rightCalloutAccessory is tapped
        func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
            guard let placeMark = view.annotation as? MKPointAnnotation else {return}
            parent.selectedPlace = placeMark
            parent.showingPlaceDetails = true
        }

        //Customizes the way the marker looks
        func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
            let identifier = "PlaceMark"
            var annotationview = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)

            if annotationview == nil {
                annotationview = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)

                annotationview?.canShowCallout = true

                annotationview?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
            }else {
                annotationview?.annotation = annotation
            }

            return annotationview

        }

    }

    func makeCoordinator() -> MapView.Coordinator {
        Coordinator(self)
    }
}

extension MKPointAnnotation {
    static var example: MKPointAnnotation {
        let annotation = MKPointAnnotation()
        annotation.title = "Montreal"
        annotation.subtitle = "Home of French Canadians"
        annotation.coordinate = CLLocationCoordinate2D(latitude: 45.5, longitude: -73.58)
        return annotation
    }
}

struct MapView_Previews: PreviewProvider {
    static var previews: some View {
        MapView(centerCoordinate: .constant(MKPointAnnotation.example.coordinate), annotations: [MKPointAnnotation.example], selectedPlace: .constant(MKPointAnnotation.example), showingPlaceDetails: .constant(false))
    }
}
</code>```

4) From Edit View:

```<code>import SwiftUI
import MapKit

struct EditView: View {

    @Environment(\.presentationMode) var presentationMode
    @ObservedObject var placemark: MKPointAnnotation

    var body: some View {
        NavigationView {
            Form {
                Section {
                    TextField("Place name", text: $placemark.wrappedTitle)
                    TextField("Description", text: $placemark.wrappedSubtitle)
                }

            }
            .navigationBarTitle("Edit place")
            .navigationBarItems(trailing: Button("Done") {
                self.presentationMode.wrappedValue.dismiss()
            })
        }

    }

}

struct EditView_Previews: PreviewProvider {
    static var previews: some View {
        EditView(placemark: MKPointAnnotation.example)
    }
}
</code>```

5) MKPointAnnotation Codable

```<code>import Foundation
import MapKit

class  CodableMKPointAnnotation: MKPointAnnotation , Codable {
    enum codingKeys: CodingKey {
        case title ,subtitle , longitude , latitude
    }
    override init() {
        super.init()
    }

    public required init(from decoder: Decoder) throws{
        super.init()

        let container = try decoder.container(keyedBy: codingKeys.self)
        title = try container.decode(String.self, forKey: .title)
        subtitle = try container.decode(String.self, forKey: .subtitle)

        let latitude = try container.decode(CLLocationDegrees.self, forKey: .latitude)
        let longitude = try container.decode(CLLocationDegrees.self, forKey: .longitude)
        coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: codingKeys.self)
        try container.encode(title, forKey: .title)
        try container.encode(subtitle, forKey: .subtitle)
        try container.encode(coordinate.latitude, forKey: .latitude)
        try container.encode(coordinate.longitude, forKey: .longitude)

    }
}
</code>```

6) MKPointAnnotation Object

```<code>import MapKit

extension MKPointAnnotation: ObservableObject{
    public var wrappedTitle: String{
        get{
            self.title ?? "No Title"
        }
        set{
            self.title = newValue
        }
    }

    public var wrappedSubtitle: String{
        get{
            self.subtitle ?? "No information on this location"
        }
        set{
            self.subtitle = newValue
        }
    }
}
</code>```

7) Meuf & MeufStorage:

```<code>import Foundation

struct Meuf: Identifiable, Encodable, Decodable {
    var id = UUID()
    var img = ""
    var title = ""
    var rating = 3.0
    var seen = false
    var seenDate = ""
}

class MeufStorage: ObservableObject {
    @Published var meufs = [Meuf]()
}
</code>```

8) Scene Delegate:

```<code>import UIKit
import SwiftUI

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        let meufStorage = MeufStorage()
        let contentView = MeufList().environment(\.managedObjectContext, context).environmentObject(meufStorage)

        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)

            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        }
    }

    func sceneDidEnterBackground(_ scene: UIScene) {
        (UIApplication.shared.delegate as? AppDelegate)?.saveContext()
    }

}
</code>```

答:
Hello I managed to get the solution.

Will add code only which is changed

```<code>// Made this a ObservableObject
class Meuf: Identifiable, Codable, ObservableObject {
var id = UUID()
var img = ""
var title = ""
var rating = 3.0
var seen = false
var seenDate = ""
var locations = [CodableMKPointAnnotation]() // We need this to keep the track of locations
}
</code>```

FormView

```<code>struct FormView: View {
    @State private var selectedTitle = ""

    @ObservedObject var meufObject = Meuf() // This is new will help to keep track of the added locations

    @State private var meufs = [Meuf]()
    @State private var show = false
    @State private var singleIsPresented = false
    @Environment(\.presentationMode) var presentationMode
    @EnvironmentObject var meufStorage : MeufStorage
    @State private  var showMap = false

    var body: some View {
        NavigationView{
            Form {
                List {
                    // This will list the added locations now
                    ForEach(self.meufObject.locations, id: \.self) { location in
                        LocationView(location: location)
                    }
                }

                //MARK: LOCATION
                Section{
                    HStack {
                        Button(action: { self.showMap = true }) {
                            Image(systemName: "mappin.and.ellipse")
                        }
                        .sheet(isPresented: $showMap) {
                            LocationMap(meufObject: self.meufObject, showModal: self.$showMap)
                        }
                        Text("Pin your location")
                            .font(.subheadline)
                    }
                }

                // MARK: [ SAVE ENTRY ]
                Section {
                    Button(action: {
                        // Handle save action
                    }) {
                        HStack{
                            Spacer()
                            Text("Save")
                            Spacer()
                        }
                    }
                }

            }
        }
    }

    // Rest of your code stays same .......
}

// Added this new view to render the location view
struct LocationView: View {
    var location : CodableMKPointAnnotation
    var body: some View {
        Text(location.title ?? "title" )
    }
}
</code>```

LocationMap

```<code>struct LocationMap: View {
    @ObservedObject var meufObject: Meuf // This is new will help to keep track of the added locations

    @State private var centerCoordinate = CLLocationCoordinate2D()
    @State private var locations = [CodableMKPointAnnotation]()
    @State private var selectedPlace: MKPointAnnotation?
    @State private var showingPlaceDetails = false
    @State private var showingEditScreen = false

    @Environment(\.presentationMode) var presentationMode

    @Binding var showModal: Bool

    var body: some View {
        ZStack{
            MapView(centerCoordinate: $centerCoordinate, annotations: locations, selectedPlace: $selectedPlace, showingPlaceDetails: $showingPlaceDetails)
                .edgesIgnoringSafeArea(.all)
            Circle()
                .fill(Color.blue)
                .opacity(0.3)
                .frame(width: 32, height: 32)
            VStack {
                Spacer()
                HStack{
                    Spacer()
                    Button(action:{
                        let newLocation = CodableMKPointAnnotation()
                        newLocation.title = ""
                        newLocation.coordinate = self.centerCoordinate
                        self.locations.append(newLocation)
                        self.meufObject.locations = self.locations // By doing this we will be able to pass it to main screen
                        self.selectedPlace = newLocation
                        self.showingEditScreen = true
                    }){
                        Image(systemName: "plus")
                    }
                    .padding()
                    .background(Color.black.opacity(0.7))
                    .foregroundColor(Color.white)
                    .clipShape(Circle())
                    .shadow(radius: 0.7)
                    .padding([.trailing , .bottom])
                    // Rest stays same as your implementation
                }
            }
            .padding()
        }
    }
    // Rest stays same as your implementation
}
</code>```

Body:
I made a Form using SwiftUI, in which I have a section that allows a user to press on a button that takes them to a MapKit View. Once inside the map view, the user can press the "+" button to place a pin on a map. This takes them to the Edit View where they can enter text inside a TextField to label the pin (see screenshot below). I have been stuck here for the past few days attempting to save the pin's coordinates or even the user's input inside the TextField to return it as text (either as city, state or country) inside the Form.

Form -> Map View -> Edit View

Here are some code snippets.

1) From FormView:

    import SwiftUI
    import MapKit

    struct FormView: View {
        @State private var selectedTitle = ""
        @State var meuf: Meuf
        @State private var meufs = [Meuf]()
        @State private var show = false
        @State private var singleIsPresented = false
        @Environment(\.presentationMode) var presentationMode
        let newMeuf : Bool
        @EnvironmentObject var meufStorage : MeufStorage
        @State private  var showMap = false

        var body: some View {
            NavigationView{
                Form{
                    //MARK: LOCATION
                    Section{
                        HStack {
                            Button(action: { self.showMap = true }) {
                                Image(systemName: "mappin.and.ellipse")
                            }
                            .sheet(isPresented: $showMap) {
                                LocationMap(showModal: self.$showMap)
                            }
                            Text("Pin your location")
                                .font(.subheadline)
                        }
                    }

                   // MARK: [ SAVE ENTRY ]
                    Section {
                        Button(action: {
                            if self.newMeuf {
                                self.saveData()
                                self.meufStorage.meufs.append(self.meuf)
                            } else {
                                for x in 0..<self.meufStorage.meufs.count {
                                    if self.meufStorage.meufs[x].id == self.meuf.id {
                                        self.meufStorage.meufs[x] = self.meuf
                                    }
                                }
                            }
                            self.presentationMode.wrappedValue.dismiss()
                        }) {
                            HStack{
                                Spacer()
                                Text("Save")
                                Spacer()
                            }
                        }.disabled(meuf.title.isEmpty)
                    }

                }.navigationBarTitle(Text(meuf.title))
            }
        }

        //Get file directory url
        func getFileDirectory() -> URL{
            let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
            return paths[0]
        }

        //Load data from file directory
        func loadData(){
            let filename = getFileDirectory().appendingPathComponent("SavedPlaces")

            do {
                let data = try Data(contentsOf: filename)
                meufs = try JSONDecoder().decode([Meuf].self, from: data)

            }catch{
                debugPrint(error)
            }
        }

        //Save data to file directory
        func saveData(){
            let filename = getFileDirectory().appendingPathComponent("SavedPlaces")
            let data = try? JSONEncoder().encode(self.meufs)
            do{
                try data?.write(to: filename, options: [.atomic , .completeFileProtection])
            }catch{
                debugPrint(error)
            }
        }

    }

    struct FormView_Previews: PreviewProvider {
        static var previews: some View {
            FormView(meuf: Meuf(), newMeuf: true)
        }
    }

2) From LocationMap:

import SwiftUI
import MapKit

struct LocationMap: View {
    @State private var centerCoordinate = CLLocationCoordinate2D()
    @State private var locations = [CodableMKPointAnnotation]()
    @State private var selectedPlace: MKPointAnnotation?
    @State private var showingPlaceDetails = false
    @State private var showingEditScreen = false

    @Binding var showModal: Bool

    var body: some View {
        ZStack{
            MapView(centerCoordinate: $centerCoordinate, annotations: locations, selectedPlace: $selectedPlace, showingPlaceDetails: $showingPlaceDetails)
                .edgesIgnoringSafeArea(.all)
            Circle()
                .fill(Color.blue)
                .opacity(0.3)
                .frame(width: 32, height: 32)
            VStack {
                Spacer()
                HStack{
                    Spacer()
                    Button(action:{
                        let newLocation = CodableMKPointAnnotation()
                        newLocation.title = ""
                        newLocation.coordinate = self.centerCoordinate
                        self.locations.append(newLocation)

                        self.selectedPlace = newLocation
                        self.showingEditScreen = true
                    }){
                        Image(systemName: "plus")
                    }
                    .padding()
                    .background(Color.black.opacity(0.7))
                    .foregroundColor(Color.white)
                    .clipShape(Circle())
                    .shadow(radius: 0.7)
                    .padding([.trailing , .bottom])
                }
            }
            .padding()
        }.alert(isPresented: $showingPlaceDetails) {
            Alert(title: Text(selectedPlace?.title ?? "Unknown"), message: Text(selectedPlace?.subtitle ?? "Missing place information."), primaryButton: .default(Text("OK")), secondaryButton: .default(Text("Edit")) {
                self.showingEditScreen = true
                }
            )
        }
        .sheet(isPresented: $showingEditScreen, onDismiss: savedData) {
            if self.selectedPlace != nil {
                EditView(placemark: self.selectedPlace!)
            }
        }

        .onAppear(perform: loadData)

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

        func loadData() {
            let filename = getDocumentsDirectory().appendingPathComponent("Saved Places")

            do {
                let data = try Data(contentsOf: filename)
                locations = try JSONDecoder().decode([CodableMKPointAnnotation].self, from: data)
            } catch {
                print("Unable to load saved data.")
            }
        }

        func savedData() {
            do {
                let filename = getDocumentsDirectory().appendingPathComponent("SavedPlaces")
                let data = try JSONEncoder().encode(self.locations)
                try data.write(to: filename, options: [.atomicWrite, .completeFileProtection])
            } catch {
                print("Unable to save data")
            }
        }

}
struct LocationMap_Previews: PreviewProvider {
    static var previews: some View {
        LocationMap(showModal: .constant(true))
    }
}

3) From MapView:

import MapKit
import Combine
import SwiftUI

struct MapView: UIViewRepresentable {
    @Binding var centerCoordinate: CLLocationCoordinate2D
    var annotations: [MKPointAnnotation]
    @Binding var selectedPlace: MKPointAnnotation?
    @Binding var showingPlaceDetails: Bool

    func makeUIView(context: UIViewRepresentableContext<MapView>) -> MKMapView {
        let mapView = MKMapView()
        mapView.delegate = context.coordinator
        return mapView
    }

    func updateUIView(_ uiView: MKMapView, context: UIViewRepresentableContext<MapView>) {
        if annotations.count != uiView.annotations.count{
            uiView.removeAnnotations(uiView.annotations)
            uiView.addAnnotations(annotations)
        }
    }

    ///Coordinator class for passing data
    class Coordinator: NSObject , MKMapViewDelegate{
        let parent: MapView

        init(_ parent: MapView){
            self.parent = parent
        }

        func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {
            parent.centerCoordinate = mapView.centerCoordinate
        }

        //Gets called whenever the rightCalloutAccessory is tapped
        func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
            guard let placeMark = view.annotation as? MKPointAnnotation else {return}
            parent.selectedPlace = placeMark
            parent.showingPlaceDetails = true
        }

        //Customizes the way the marker looks
        func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
            let identifier = "PlaceMark"
            var annotationview = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)

            if annotationview == nil {
                annotationview = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)

                annotationview?.canShowCallout = true

                annotationview?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
            }else {
                annotationview?.annotation = annotation
            }

            return annotationview

        }

    }

    func makeCoordinator() -> MapView.Coordinator {
        Coordinator(self)
    }
}

extension MKPointAnnotation {
    static var example: MKPointAnnotation {
        let annotation = MKPointAnnotation()
        annotation.title = "Montreal"
        annotation.subtitle = "Home of French Canadians"
        annotation.coordinate = CLLocationCoordinate2D(latitude: 45.5, longitude: -73.58)
        return annotation
    }
}

struct MapView_Previews: PreviewProvider {
    static var previews: some View {
        MapView(centerCoordinate: .constant(MKPointAnnotation.example.coordinate), annotations: [MKPointAnnotation.example], selectedPlace: .constant(MKPointAnnotation.example), showingPlaceDetails: .constant(false))
    }
}

4) From Edit View:

import SwiftUI
import MapKit

struct EditView: View {

    @Environment(\.presentationMode) var presentationMode
    @ObservedObject var placemark: MKPointAnnotation

    var body: some View {
        NavigationView {
            Form {
                Section {
                    TextField("Place name", text: $placemark.wrappedTitle)
                    TextField("Description", text: $placemark.wrappedSubtitle)
                }

            }
            .navigationBarTitle("Edit place")
            .navigationBarItems(trailing: Button("Done") {
                self.presentationMode.wrappedValue.dismiss()
            })
        }

    }

}

struct EditView_Previews: PreviewProvider {
    static var previews: some View {
        EditView(placemark: MKPointAnnotation.example)
    }
}

5) MKPointAnnotation Codable

import Foundation
import MapKit

class  CodableMKPointAnnotation: MKPointAnnotation , Codable {
    enum codingKeys: CodingKey {
        case title ,subtitle , longitude , latitude
    }
    override init() {
        super.init()
    }

    public required init(from decoder: Decoder) throws{
        super.init()

        let container = try decoder.container(keyedBy: codingKeys.self)
        title = try container.decode(String.self, forKey: .title)
        subtitle = try container.decode(String.self, forKey: .subtitle)

        let latitude = try container.decode(CLLocationDegrees.self, forKey: .latitude)
        let longitude = try container.decode(CLLocationDegrees.self, forKey: .longitude)
        coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: codingKeys.self)
        try container.encode(title, forKey: .title)
        try container.encode(subtitle, forKey: .subtitle)
        try container.encode(coordinate.latitude, forKey: .latitude)
        try container.encode(coordinate.longitude, forKey: .longitude)

    }
}

6) MKPointAnnotation Object

import MapKit

extension MKPointAnnotation: ObservableObject{
    public var wrappedTitle: String{
        get{
            self.title ?? "No Title"
        }
        set{
            self.title = newValue
        }
    }

    public var wrappedSubtitle: String{
        get{
            self.subtitle ?? "No information on this location"
        }
        set{
            self.subtitle = newValue
        }
    }
}

7) Meuf & MeufStorage:

import Foundation

struct Meuf: Identifiable, Encodable, Decodable {
    var id = UUID()
    var img = ""
    var title = ""
    var rating = 3.0
    var seen = false
    var seenDate = ""
}

class MeufStorage: ObservableObject {
    @Published var meufs = [Meuf]()
}

8) Scene Delegate:

import UIKit
import SwiftUI

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        let meufStorage = MeufStorage()
        let contentView = MeufList().environment(\.managedObjectContext, context).environmentObject(meufStorage)

        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)

            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        }
    }

    func sceneDidEnterBackground(_ scene: UIScene) {
        (UIApplication.shared.delegate as? AppDelegate)?.saveContext()
    }

}

Body:
Hello I managed to get the solution.

Will add code only which is changed

// Made this a ObservableObject
class Meuf: Identifiable, Codable, ObservableObject {
var id = UUID()
var img = ""
var title = ""
var rating = 3.0
var seen = false
var seenDate = ""
var locations = [CodableMKPointAnnotation]() // We need this to keep the track of locations
}

FormView

struct FormView: View {
    @State private var selectedTitle = ""

    @ObservedObject var meufObject = Meuf() // This is new will help to keep track of the added locations

    @State private var meufs = [Meuf]()
    @State private var show = false
    @State private var singleIsPresented = false
    @Environment(\.presentationMode) var presentationMode
    @EnvironmentObject var meufStorage : MeufStorage
    @State private  var showMap = false

    var body: some View {
        NavigationView{
            Form {
                List {
                    // This will list the added locations now
                    ForEach(self.meufObject.locations, id: \.self) { location in
                        LocationView(location: location)
                    }
                }

                //MARK: LOCATION
                Section{
                    HStack {
                        Button(action: { self.showMap = true }) {
                            Image(systemName: "mappin.and.ellipse")
                        }
                        .sheet(isPresented: $showMap) {
                            LocationMap(meufObject: self.meufObject, showModal: self.$showMap)
                        }
                        Text("Pin your location")
                            .font(.subheadline)
                    }
                }

                // MARK: [ SAVE ENTRY ]
                Section {
                    Button(action: {
                        // Handle save action
                    }) {
                        HStack{
                            Spacer()
                            Text("Save")
                            Spacer()
                        }
                    }
                }

            }
        }
    }

    // Rest of your code stays same .......
}

// Added this new view to render the location view
struct LocationView: View {
    var location : CodableMKPointAnnotation
    var body: some View {
        Text(location.title ?? "title" )
    }
}

LocationMap

struct LocationMap: View {
    @ObservedObject var meufObject: Meuf // This is new will help to keep track of the added locations

    @State private var centerCoordinate = CLLocationCoordinate2D()
    @State private var locations = [CodableMKPointAnnotation]()
    @State private var selectedPlace: MKPointAnnotation?
    @State private var showingPlaceDetails = false
    @State private var showingEditScreen = false

    @Environment(\.presentationMode) var presentationMode

    @Binding var showModal: Bool

    var body: some View {
        ZStack{
            MapView(centerCoordinate: $centerCoordinate, annotations: locations, selectedPlace: $selectedPlace, showingPlaceDetails: $showingPlaceDetails)
                .edgesIgnoringSafeArea(.all)
            Circle()
                .fill(Color.blue)
                .opacity(0.3)
                .frame(width: 32, height: 32)
            VStack {
                Spacer()
                HStack{
                    Spacer()
                    Button(action:{
                        let newLocation = CodableMKPointAnnotation()
                        newLocation.title = ""
                        newLocation.coordinate = self.centerCoordinate
                        self.locations.append(newLocation)
                        self.meufObject.locations = self.locations // By doing this we will be able to pass it to main screen
                        self.selectedPlace = newLocation
                        self.showingEditScreen = true
                    }){
                        Image(systemName: "plus")
                    }
                    .padding()
                    .background(Color.black.opacity(0.7))
                    .foregroundColor(Color.white)
                    .clipShape(Circle())
                    .shadow(radius: 0.7)
                    .padding([.trailing , .bottom])
                    // Rest stays same as your implementation
                }
            }
            .padding()
        }
    }
    // Rest stays same as your implementation
}


来源: stackexchange

问:
Is there Blazor WASM + WebAPI project template like there's `dotnet new react`?
I'd want to ask whether is there project template for webapi with web assembly blazor under one project

just like dotnet new blazorserver but with WASM instead of SignalR websocket

.NET Core 3.1

答:
I was never able to get the template working with the above answer. I logged a Github issue but the Blazor team couldn't answer why this wasn't working for me.

However, if you clone this repo, there is a sample Blazor Wasm app here. That should run and you will be able to get going straight away.

ContentLicense: CC BY-SA 4.0


问:
how do i Zoom and pan an SVG Document embed in XHTML Page using AMPLE SDK
Hello i am developing my map from raster to vector

i have managed to embed the SVG Map File into the XHTML page and i am using AMPLE SDK Library it is great works on all browsers.

but how can i use this library to zoom and pan into the map?
i am using AMPLE SDK because the Raphael Converter from SVG To Raphael not working in
good way.
RAPHAEL CONVERTER

答:
You can implement zoom and pan on SVG fragment by manipulating viewBox attribute on svg element as echo-flow suggested. However you should be using setAttribute to get the change reflected:

```<code>ample.getElementById("mysvg").setAttribute("viewBox", "500 500 1000 1000");
</code>```

or

```<code>ample.query("#mysvg").attr("viewBox", "500 500 1000 1000");
</code>```

Study the format of viewBox attribute and it will not be difficult to find out how it should be manipulated.

ContentLicense: CC BY-SA 3.0

Body:
You can implement zoom and pan on SVG fragment by manipulating viewBox attribute on svg element as echo-flow suggested. However you should be using setAttribute to get the change reflected:

ample.getElementById("mysvg").setAttribute("viewBox", "500 500 1000 1000");

or

ample.query("#mysvg").attr("viewBox", "500 500 1000 1000");

Study the format of viewBox attribute and it will not be difficult to find out how it should be manipulated.


问:
How to add mustache email template and send it
Mustache template: email.mustache

```<code>{{subject}}

Hello {{userName}}!
</code>```

The object I will send.

```<code>data class Email(
        @Email
        val emailAddress: String,
        val subject: String,
        val userName: String,
        val message: String
)
</code>```

My service:

```<code>@Service
class EmailService {

    @Autowired
    private lateinit var javaMailSender: JavaMailSender

    override fun sendEmail(email: Email): Boolean {
        val msg = SimpleMailMessage()
        msg.setTo(email.emailAddress)
        msg.setSubject(email.subject)
        msg.setText(email.message)
        try {
            javaMailSender.send(msg)
        } catch (e: Exception) {
            return false
        }
        return true
    }
}
</code>```

But how can I load my mustache template in this? I imagine I need to parse the mustache template then use that as msg.setText(parsedTemplate) -- something like that.

答:
It looks like Mustache.java can do what you need:

```<code>import com.github.mustachejava.DefaultMustacheFactory
import com.github.mustachejava.Mustache
import java.io.StringWriter

data class Email(
    val subject: String,
    val userName: String
)

fun main() {
    val scopes = mapOf(
        "email" to Email(subject = "Welcome", userName = "J_Strauton")
    )

    val writer = StringWriter()
    val mf = DefaultMustacheFactory()
    val mustache: Mustache = mf.compile("email.mustache")
    mustache.execute(writer, scopes)
    writer.flush()

    val email = writer.toString()
}
</code>```

Your email.mustache file could look like this:

```<code>{{email.subject}}

Hello {{email.userName}}!
</code>```

Body:
Mustache template: email.mustache

{{subject}}

Hello {{userName}}!

The object I will send.

data class Email(
        @Email
        val emailAddress: String,
        val subject: String,
        val userName: String,
        val message: String
)

My service:

@Service
class EmailService {

    @Autowired
    private lateinit var javaMailSender: JavaMailSender

    override fun sendEmail(email: Email): Boolean {
        val msg = SimpleMailMessage()
        msg.setTo(email.emailAddress)
        msg.setSubject(email.subject)
        msg.setText(email.message)
        try {
            javaMailSender.send(msg)
        } catch (e: Exception) {
            return false
        }
        return true
    }
}

But how can I load my mustache template in this? I imagine I need to parse the mustache template then use that as msg.setText(parsedTemplate) -- something like that.

Body:
It looks like Mustache.java can do what you need:

import com.github.mustachejava.DefaultMustacheFactory
import com.github.mustachejava.Mustache
import java.io.StringWriter

data class Email(
    val subject: String,
    val userName: String
)

fun main() {
    val scopes = mapOf(
        "email" to Email(subject = "Welcome", userName = "J_Strauton")
    )

    val writer = StringWriter()
    val mf = DefaultMustacheFactory()
    val mustache: Mustache = mf.compile("email.mustache")
    mustache.execute(writer, scopes)
    writer.flush()

    val email = writer.toString()
}

Your email.mustache file could look like this:

{{email.subject}}

Hello {{email.userName}}!


问:
Inserting a model works, but List fails on Asp.net Core 3.1 and HttpClient
//Class

```<code>public class Model
{
    public string Name { get; set; }
    public List<Item> Items { get; set; } = new List<Item>();
}

public class Item
{
    public string Description { get; set; }
}
</code>```

This is the model that I was referring to.

//Model 1

```<code>{
    "Name": "",
    "Items":[
        {
            "Description":""
        }
    ]
}
</code>```

//Model 2

```<code>{
    "Name": ""
}
</code>```

//Request

```<code>var model = new Model();
var content = JsonConvert.SerializeObject(model);

using var client = new HttpClient { "BaseAddress" = new Uri("http://localhost:80/main") };
var content = new StringContent(
    content,
    Encoding.UTF8,
    "application/json");

content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
var response = await client.PostAsync("insert", content);
</code>```

//Controller

```<code>[ApiController]
public class MainController : ControllerBase
{
    [HttpPost("insert")]
    public async Task<IActionResult> Insert([FromBody] Model model)
    {

    }
}
</code>```

If I insert a Model 1 with a list, i get a

```<code>{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
  Date: Thu, 13 Feb 2020 22:04:06 GMT
  Server: Kestrel
  Transfer-Encoding: chunked
  Content-Type: text/plain
}}
</code>```

But if I insert Model 2 w/o a list, works fine.

I did try passing the list as json string to my controller manually (post), and does the same behavior, does not accept the list, but does the model.

I did get an exception on the API

```<code>fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
      An unhandled exception has occurred while executing the request.
System.NotSupportedException: Collection was of a fixed size.
   at System.Array.System.Collections.IList.Add(Object value)
   at System.Text.Json.JsonSerializer.ApplyObjectToEnumerable(Object value, ReadStack& state, Boolean setPropertyDirectly)
   at System.Text.Json.JsonSerializer.HandleEndArray(JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& readStack)
   at System.Text.Json.JsonSerializer.ReadCore(JsonReaderState& readerState, Boolean isFinalBlock, ReadOnlySpan`1 buffer, JsonSerializerOptions options, ReadStack& readStack)
   at System.Text.Json.JsonSerializer.ReadAsync[TValue](Stream utf8Json, Type returnType, JsonSerializerOptions options, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
   at Microsoft.AspNetCore.Mvc.ModelBinding.Binders.BodyModelBinder.BindModelAsync(ModelBindingContext bindingContext)
   at Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.BindModelAsync(ActionContext actionContext, IModelBinder modelBinder, IValueProvider valueProvider, ParameterDescriptor parameter, ModelMetadata metadata, Object value)
   at Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider.<>c__DisplayClass0_0.<<CreateBinderDelegate>g__Bind|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
</code>```

It does not reach the Controller when i put a break point.

I'm on netcoreapp3.1
Newtonsoft.Json 12.0.3
Its getting referenced in a netstandard project 2.1

答:
Reference from the question "Where did IMvcBuilder AddJsonOptions go in .Net Core 3.0?
" Link

Thank you @dbc

Body:
//Class

public class Model
{
    public string Name { get; set; }
    public List<Item> Items { get; set; } = new List<Item>();
}

public class Item
{
    public string Description { get; set; }
}

This is the model that I was referring to.

//Model 1

{
    "Name": "",
    "Items":[
        {
            "Description":""
        }
    ]
}

//Model 2

{
    "Name": ""
}

//Request

var model = new Model();
var content = JsonConvert.SerializeObject(model);

using var client = new HttpClient { "BaseAddress" = new Uri("http://localhost:80/main") };
var content = new StringContent(
    content,
    Encoding.UTF8,
    "application/json");

content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
var response = await client.PostAsync("insert", content);

//Controller

[ApiController]
public class MainController : ControllerBase
{
    [HttpPost("insert")]
    public async Task<IActionResult> Insert([FromBody] Model model)
    {

    }
}

If I insert a Model 1 with a list, i get a

{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
  Date: Thu, 13 Feb 2020 22:04:06 GMT
  Server: Kestrel
  Transfer-Encoding: chunked
  Content-Type: text/plain
}}

But if I insert Model 2 w/o a list, works fine.

I did try passing the list as json string to my controller manually (post), and does the same behavior, does not accept the list, but does the model.

I did get an exception on the API

fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
      An unhandled exception has occurred while executing the request.
System.NotSupportedException: Collection was of a fixed size.
   at System.Array.System.Collections.IList.Add(Object value)
   at System.Text.Json.JsonSerializer.ApplyObjectToEnumerable(Object value, ReadStack& state, Boolean setPropertyDirectly)
   at System.Text.Json.JsonSerializer.HandleEndArray(JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& readStack)
   at System.Text.Json.JsonSerializer.ReadCore(JsonReaderState& readerState, Boolean isFinalBlock, ReadOnlySpan`1 buffer, JsonSerializerOptions options, ReadStack& readStack)
   at System.Text.Json.JsonSerializer.ReadAsync[TValue](Stream utf8Json, Type returnType, JsonSerializerOptions options, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
   at Microsoft.AspNetCore.Mvc.ModelBinding.Binders.BodyModelBinder.BindModelAsync(ModelBindingContext bindingContext)
   at Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.BindModelAsync(ActionContext actionContext, IModelBinder modelBinder, IValueProvider valueProvider, ParameterDescriptor parameter, ModelMetadata metadata, Object value)
   at Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider.<>c__DisplayClass0_0.<<CreateBinderDelegate>g__Bind|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

It does not reach the Controller when i put a break point.

I'm on netcoreapp3.1
Newtonsoft.Json 12.0.3
Its getting referenced in a netstandard project 2.1


问:
Biometric Dialog

So, I wanted to integrate Biometeric Dialog similar to that in my android app. I was following google android docs. Here's the Link to the documentation. But I think this is for fingerprint authentication only. How to get both icons in same dialog? if two things are registered on your phone? Are they using custom api for biometric?

答:
This dialog will only Appear if you are using Android 9 or higher on a device that has face ID and both faceid and fingerprints are registered

But NOT on samsung devices with android 9.

this is the code needed to display it:

```<code>val biometricPrompt = BiometricPrompt.Builder(context)
.setTitle(title)
.setSubtitle(subtitleText)
.setDescription(description)
.setNegativeButton(negativeButton, executor!!, cancelListener)
.build()

 biometricPrompt.authenticate(cancellationSignal, executor, BiometricCallback)
</code>```

Title: Biometric Dialog

Body:
This dialog will only Appear if you are using Android 9 or higher on a device that has face ID and both faceid and fingerprints are registered

But NOT on samsung devices with android 9.

this is the code needed to display it:

val biometricPrompt = BiometricPrompt.Builder(context)
.setTitle(title)
.setSubtitle(subtitleText)
.setDescription(description)
.setNegativeButton(negativeButton, executor!!, cancelListener)
.build()

 biometricPrompt.authenticate(cancellationSignal, executor, BiometricCallback)


问:
Why is adaptive threshold image smaller than the original?
I am trying to use adapativeThreshold on a live stream that will eventually be used for shape detection. Regular threshold does not show enough of what I want to see. When I use the code below, the regular threshold comes out as expected, but the adaptive thresholds for some reason are much thinner than the original and I cannot see anything in the view. It looks like something is happening, but I can't tell what. Any ideas on how I can make the adaptive threshold windows full size?

This is what I see when I run the program in each window:

```<code>#import packages
from documentscanner.pyimagesearch.transform import four_point_transform
from pyimagesearch.shapedetector import ShapeDetector
from skimage.filters import threshold_local
import numpy as np
import cv2
import imutils

def draw_Contours(screen, points):
    cv2.drawContours(screen, [points], -1, (0, 255, 0), 2)
    cv2.imshow("Outline", screen)

def nothing(x):
    #any operation
    pass

#access video camera
cap = cv2.VideoCapture(0)

cv2.namedWindow('Trackbars')
cv2.createTrackbar('min_edge', 'Trackbars', 75, 100, nothing)
cv2.createTrackbar('max_edge', 'Trackbars', 110,300, nothing)

while True:
    _, frame = cap.read()       #read video camera data

    minedge = cv2.getTrackbarPos('min_edge', 'Trackbars')
    maxedge = cv2.getTrackbarPos('max_edge', 'Trackbars')

    #convert image to gray scale
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (5, 5), 0)
    #blur = cv2.GaussianBlur(frame, (5, 5), 0)
    #edged = cv2.Canny(gray, minedge, maxedge)

    #threshhold instead of edging
    thresh = cv2.threshold(gray, 60, 255, cv2.THRESH_BINARY)[1]
    thresh2 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
                                    cv2.THRESH_BINARY, 11, 2)[1]
    thresh3 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C,\
                                    cv2.THRESH_BINARY, 11, 2)[1]

    #find contours in edges image, keeping the largest ones, and initialize the screen contour/shapedetect
    cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)
    sd = ShapeDetector()
    cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]

    #loop over contours
    for c in cnts:
        #approximate the contour points
        peri = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.02*peri, True)

        #check points in contour
        if len(approx) == 4:
            print("rectangle found: ")
            print(approx)
            draw_Contours(frame, approx)

        if len(approx) == 3:
            print("triangle found: ")
            print(approx)
            draw_Contours(frame, approx)

        if len(approx) == 2:
            print("line found: ")
            print(approx)
            draw_Contours(frame, approx)

        #show the countour(outline) of the shapes

    #show original frame and gray frame
    cv2.imshow('Frame', frame)
    #cv2.imshow('Copy', gray)
    #cv2.imshow('Edged', edged)
    cv2.imshow('Threshold', thresh)
    cv2.imshow('ThresholdGaussian', thresh2)
    cv2.imshow('ThresholdMean', thresh3)

    #detect key press and exit with escape key
    key = cv2.waitKey(1)
    if key == 27:
        break

#close the program
cap.release()
cv2.destroyAllWindows()
</code>```

答:
Instead of using

```<code>thresh2 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
                                cv2.THRESH_BINARY, 11, 2)[1]
thresh3 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C,\
                                cv2.THRESH_BINARY, 11, 2)[1]
</code>```

Use it without numpy indexing and then this error won't occur.

```<code>thresh2 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
                                cv2.THRESH_BINARY, 11, 2) # don't use [1]
thresh3 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C,\
                                cv2.THRESH_BINARY, 11, 2)
</code>```

This is because normal thresholding returns two values while adaptive thresholding returns only a single value.

Body:
I am trying to use adapativeThreshold on a live stream that will eventually be used for shape detection. Regular threshold does not show enough of what I want to see. When I use the code below, the regular threshold comes out as expected, but the adaptive thresholds for some reason are much thinner than the original and I cannot see anything in the view. It looks like something is happening, but I can't tell what. Any ideas on how I can make the adaptive threshold windows full size?

This is what I see when I run the program in each window:

#import packages
from documentscanner.pyimagesearch.transform import four_point_transform
from pyimagesearch.shapedetector import ShapeDetector
from skimage.filters import threshold_local
import numpy as np
import cv2
import imutils

def draw_Contours(screen, points):
    cv2.drawContours(screen, [points], -1, (0, 255, 0), 2)
    cv2.imshow("Outline", screen)

def nothing(x):
    #any operation
    pass

#access video camera
cap = cv2.VideoCapture(0)

cv2.namedWindow('Trackbars')
cv2.createTrackbar('min_edge', 'Trackbars', 75, 100, nothing)
cv2.createTrackbar('max_edge', 'Trackbars', 110,300, nothing)

while True:
    _, frame = cap.read()       #read video camera data

    minedge = cv2.getTrackbarPos('min_edge', 'Trackbars')
    maxedge = cv2.getTrackbarPos('max_edge', 'Trackbars')

    #convert image to gray scale
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (5, 5), 0)
    #blur = cv2.GaussianBlur(frame, (5, 5), 0)
    #edged = cv2.Canny(gray, minedge, maxedge)

    #threshhold instead of edging
    thresh = cv2.threshold(gray, 60, 255, cv2.THRESH_BINARY)[1]
    thresh2 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
                                    cv2.THRESH_BINARY, 11, 2)[1]
    thresh3 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C,\
                                    cv2.THRESH_BINARY, 11, 2)[1]

    #find contours in edges image, keeping the largest ones, and initialize the screen contour/shapedetect
    cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)
    sd = ShapeDetector()
    cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]

    #loop over contours
    for c in cnts:
        #approximate the contour points
        peri = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.02*peri, True)

        #check points in contour
        if len(approx) == 4:
            print("rectangle found: ")
            print(approx)
            draw_Contours(frame, approx)

        if len(approx) == 3:
            print("triangle found: ")
            print(approx)
            draw_Contours(frame, approx)

        if len(approx) == 2:
            print("line found: ")
            print(approx)
            draw_Contours(frame, approx)

        #show the countour(outline) of the shapes

    #show original frame and gray frame
    cv2.imshow('Frame', frame)
    #cv2.imshow('Copy', gray)
    #cv2.imshow('Edged', edged)
    cv2.imshow('Threshold', thresh)
    cv2.imshow('ThresholdGaussian', thresh2)
    cv2.imshow('ThresholdMean', thresh3)

    #detect key press and exit with escape key
    key = cv2.waitKey(1)
    if key == 27:
        break

#close the program
cap.release()
cv2.destroyAllWindows()

Body:
Instead of using

thresh2 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
                                cv2.THRESH_BINARY, 11, 2)[1]
thresh3 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C,\
                                cv2.THRESH_BINARY, 11, 2)[1]

Use it without numpy indexing and then this error won't occur.

thresh2 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
                                cv2.THRESH_BINARY, 11, 2) # don't use [1]
thresh3 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C,\
                                cv2.THRESH_BINARY, 11, 2)

This is because normal thresholding returns two values while adaptive thresholding returns only a single value.


问:
Only run JavaScript function once
When a button is clicked, I'm displaying an image (in a JS function) however the function prints the image every time the button is clicked. I want the function to run only once so that the image can only be displayed once. What do I need to add to my code to do this?</p>

```<code><button class="colour-btn colour-btn--3" onClick="showImage3()"></button>
</code>```

```<code>function showImage3() {
    var img3 = document.createElement('img')
    img3.setAttribute("src", "")
    img3.setAttribute("width", "700")
    img3.setAttribute("height", "400")
    document.body.appendChild(img3)
}
</code>```

答:
```<code>var imageAdded = false

function showImage3() {
  if (!imageAdded) {
    var img3 = document.createElement('img')
    img3.setAttribute("src", "")
    img3.setAttribute("width", "700")
    img3.setAttribute("height", "400")
    document.body.appendChild(img3)
    imageAdded = true
  }
}
</code>```

Should do it, presuming you don't mind using a global variable in your code. It's not best practice, but it is the simplest way to solve this quickly.

Title: Only run JavaScript function once

Body:
When a button is clicked, I'm displaying an image (in a JS function) however the function prints the image every time the button is clicked. I want the function to run only once so that the image can only be displayed once. What do I need to add to my code to do this?

<button class="colour-btn colour-btn--3" onClick="showImage3()"></button>

function showImage3() {
    var img3 = document.createElement('img')
    img3.setAttribute("src", "")
    img3.setAttribute("width", "700")
    img3.setAttribute("height", "400")
    document.body.appendChild(img3)
}

Body:
var imageAdded = false

function showImage3() {
  if (!imageAdded) {
    var img3 = document.createElement('img')
    img3.setAttribute("src", "")
    img3.setAttribute("width", "700")
    img3.setAttribute("height", "400")
    document.body.appendChild(img3)
    imageAdded = true
  }
}

Should do it, presuming you don't mind using a global variable in your code. It's not best practice, but it is the simplest way to solve this quickly.


问:
.Net Crystal Report printing application running on termianal service connection errors when session is disconnected
I have created a .Net application to run on an App Server that gets requests for a report and prints out the requested report.

The C# application uses Crystal Reports to load the report and subsequently print it out.

The application is run on Server which is connected to via a Remote Desktop connection under a particular user account (required for old apps). When I disconnect from the Remote Session the application starts raising exceptions such as:

Message: CrystalDecisions.Shared.CrystalReportsException: Load report failed

This type of error is never raised when the Remote Session is active. The server running the app is running Windows Server 2003, my box which creates the connection is Windows XP.

I appreciate this is fairly weird, however I cannot see any problem with the application deployment I have created.

Does anyone know what could be cause this issue?

EDIT: I bit the bullet and created the application as a windows service, obviously this doesn't take long I just wasn't convinced it would solve the problem. Anyway it doesn't!!!

I have also tried removing the multi-thread code that was calling the print function asynchronously. I did this in order to simply the app and narrow down the reason it could fail. Anyway, this didn't improve the situation either!

EDIT: The two errors I get are:

System.Runtime.InteropServices.COMException
  (0x80000201):  Invalid printer
  specified.    at
  CrystalDecisions.ReportAppServer.Controllers.PrintOutputControllerClass.ModifyPrinterName(String
  newVal)    at
  CrystalDecisions.CrystalReports.Engine.PrintOptions.set_PrinterName(String
  value)    at
  Dsa.PrintServer.Service.Service.PrintCrystalReport(Report
  report)

The printer isn't invalid, this is confirmed when 60 seconds later the time ticks and the report is printed successfully.

And

The request could not be submitted for
  background processing.    at
  CrystalDecisions.ReportAppServer.Controllers.ReportSourceClass.GetLastPageNumber(RequestContext
  pRequestContext)    at
  CrystalDecisions.ReportSource.EromReportSourceBase.GetLastPageNumber(ReportPageRequestContext
  reqContext)    --- End of inner
  exception stack trace ---    at
  CrystalDecisions.ReportAppServer.ConvertDotNetToErom.ThrowDotNetException(Exception
  e)    at
  CrystalDecisions.ReportSource.EromReportSourceBase.GetLastPageNumber(ReportPageRequestContext
  reqContext)    at
  CrystalDecisions.CrystalReports.Engine.FormatEngine.PrintToPrinter(Int32
  nCopies, Boolean collated, Int32
  startPageN, Int32 endPageN)    at
  CrystalDecisions.CrystalReports.Engine.ReportDocument.PrintToPrinter(Int32
  nCopies, Boolean collated, Int32
  startPageN, Int32 endPageN)    at
  Dsa.PrintServer.Service.Service.PrintCrystalReport(Report
  report)

EDIT:

I ran filemon to check if there were any access issue. At the point when the error occurs file mon reports

Request: OPEN | Path: C:\windows\assembly\gac_msil\system\2.0.0.0__b77a5c561934e089\ws2_32.dll | Result: NOT FOUND | Other: Attributes Error

答:
If you create a window service wrapper for your application, it means that it will continue to run regardless of users logged in.  It can also be set to start up automatically.  I think that because you are using an actual application, and not a windows service it is not actually running once you logout of a session on the server.

Here is an example on Code Project:

http://www.codeproject.com/KB/system/WindowsService.aspx

OwnerDisplayName: MrEdmundo

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: MrEdmundo


问:
Add a list of variables in a powershell script
I am sure this is obvious but for the life of me I can not find the information.  Many postings on splitting output to multiple lines, but I can't find information on using Multiple lines as input.

I often create text files with lists of variables then use $servers=GC servers.txt and use a "For each" loop to process them.  There has to be a way to just include that list in the script.

For example if I normally create a 'servers.txt' consisting of:

server1

server2

server3....

Is it possible to list those server in the script it self.  Something like (and I know this doesn't work as writen:

```<code>$servers= @(
    Server1
    Server2
    Server3
    )
</code>```

UPDATE

I know I could separate them in to quotes and add commas but that is specifically what I am trying to avoid.  If I copy a list of servers from a spread sheet with right click copy, I'd like to be able to paste it in my script without having to add commas and single quotes.  Right now I avoid this by dumping the contents in to a text file then use Get-Content to import it, but I am trying to find a way to bypass that extra step and just be able to paste it in the script then click run without having to alter the text.

答:
If you want to be able to paste the server names directly into your script without using an intermediate 2nd file, just paste the list into a multi-line string like this:</p>

```<code>$serversTxt = @"
server1
server2
server3
"@

$servers = $serversTxt -split "`n"
</code>```

Body:
I am sure this is obvious but for the life of me I can not find the information.  Many postings on splitting output to multiple lines, but I can't find information on using Multiple lines as input.

I often create text files with lists of variables then use $servers=GC servers.txt and use a "For each" loop to process them.  There has to be a way to just include that list in the script.

For example if I normally create a 'servers.txt' consisting of:

server1

server2

server3....

Is it possible to list those server in the script it self.  Something like (and I know this doesn't work as writen:

$servers= @(
    Server1
    Server2
    Server3
    )

UPDATE

I know I could separate them in to quotes and add commas but that is specifically what I am trying to avoid.  If I copy a list of servers from a spread sheet with right click copy, I'd like to be able to paste it in my script without having to add commas and single quotes.  Right now I avoid this by dumping the contents in to a text file then use Get-Content to import it, but I am trying to find a way to bypass that extra step and just be able to paste it in the script then click run without having to alter the text.

Body:
If you want to be able to paste the server names directly into your script without using an intermediate 2nd file, just paste the list into a multi-line string like this:

$serversTxt = @"
server1
server2
server3
"@

$servers = $serversTxt -split "`n"


问:
I am looking find dups
I am trying to filter out the dups writing a query in Oracle TOAD SQL. Below is the data I have:

```<code>Primary          T_ID           C_ID
2039515494      276162453       20028
2176514662      276721971       5508
2176514662      276721972       5508
</code>```

I am looking to have only

```<code> Primary          T_ID          C_ID
2176514662      276721971       5508
2176514662      276721972       5508
</code>```

答:
Using the window (analytic) variant of count could help you:

```<code>SELECT primary, t_id, c_id
FROM   (SELECT primary, t_id, c_id, COUNT(*) OVER (PARTITION BY primary, c_id) AS cnt
        FROM   mytable) t
WHERE  cnt > 1
</code>```

Title: I am looking find dups

Body:
I am trying to filter out the dups writing a query in Oracle TOAD SQL. Below is the data I have:

Primary          T_ID           C_ID
2039515494      276162453       20028
2176514662      276721971       5508
2176514662      276721972       5508

I am looking to have only

 Primary          T_ID          C_ID
2176514662      276721971       5508
2176514662      276721972       5508

Body:
Using the window (analytic) variant of count could help you:

SELECT primary, t_id, c_id
FROM   (SELECT primary, t_id, c_id, COUNT(*) OVER (PARTITION BY primary, c_id) AS cnt
        FROM   mytable) t
WHERE  cnt > 1


问:
.py to .exe file conversion issue
I'm trying to convert a simple python code (any sample code) into an executable file but on opening the application all I can see is a blank black screen.

I am using:

Python 3.7

PyInstaller 3.6

One file output

I am able to convert the file to .exe using auto-py-to-exe but I don't see any output when I try to run the application.

答:
Try doing this in order:

py -3.7 -m pip uninstall pyinstaller

py -3.7 -m pip install pyinstaller

pyinstaller --onefile test.py

Title: .py to .exe file conversion issue


问:
How to remove New line character from batch variable
Good Day All!
I have a batch script, and when I echo a variable like this

```<code>echo %variable1%
</code>```

I get out put like this

```<code>TestLine1
TestLine2
TestLine3
TestLine4
</code>```

My goal would be to modify this variable to remove all the newline characters so the output would look more like

```<code>TestLine1TestLine2TestLine3TestLine4
</code>```

Is there a simple way to do this without creating files?
Thank you for your assistance.

答:
You can use the command tr:

```<code>cleanedVariable1=$(echo $variable1 | tr -d '\n' )
echo $cleanedVariable1
</code>```

The command tr removes or translates characters. The option -d removes the given characters. In this case, we are removing all new lines from our variable and assign it to a new variable.

Body:
Good Day All!
I have a batch script, and when I echo a variable like this

echo %variable1%

I get out put like this

TestLine1
TestLine2
TestLine3
TestLine4

My goal would be to modify this variable to remove all the newline characters so the output would look more like

TestLine1TestLine2TestLine3TestLine4

Is there a simple way to do this without creating files?
Thank you for your assistance.

Body:
You can use the command tr:

cleanedVariable1=$(echo $variable1 | tr -d '\n' )
echo $cleanedVariable1

The command tr removes or translates characters. The option -d removes the given characters. In this case, we are removing all new lines from our variable and assign it to a new variable.


问:
Protractor: How to encrypt passwords passed to the UI automation scripts?
I am using protractor with typescript for my UI based automation. I want to encrypt password that is passed through a json file(using json format as testdata file) to my specs.
my site password is exposed in the Json file but somehow I want to encrypt the same.</p>

答:
sounds like it'd be easier to pass the password as an environment variable instead of storing it in a file, but if you still insist to encrypt it here you go:

Generate key (password for decryption) and save it in notes (you'll need it to decrypt your password)

```<code>let uuid = require('uuid');
let key  = uuid();
console.log(key); // 3467f7d0-190f-4319-836e-8918a778d120
</code>```

Install crypto-js

Encrypt the password:

```<code>let CryptoJS = require("crypto-js");
let encryptedPassword = CryptoJS.AES.encrypt('Pa$sword123!', key).toString();
console.log(encryptedPassword); // U2FsdGVkX18iI0gLaeQmf2z7Ev82hMynTo1c2TkCCJo=
</code>```

Save it in your json data file

```<code>{
    'username': 'test-account',
    'password': 'U2FsdGVkX18iI0gLaeQmf2z7Ev82hMynTo1c2TkCCJo='
}
</code>```

Wherever you need to use your password do this

```<code>let CryptoJS = require("crypto-js");
let decryptedPassword  = CryptoJS.AES.decrypt(json['password'], process.env.PASSWORD_KEY).toString(CryptoJS.enc.Utf8);
await login(json.username, decryptedPassword);
</code>```

Run protractor with the following command specifying the decryption key from step #1

```<code>PASSWORD_KEY=3467f7d0-190f-4319-836e-8918a778d120 protractor protractor.conf.js
</code>```

P.S.

when I said it's easier to start protractor with password as an environment variable I meant this

```<code>PASSWORD=Pa$sword123! protractor protractor.conf.js
</code>```

and then refer to password as process.env.PASSWORD

Body:
sounds like it'd be easier to pass the password as an environment variable instead of storing it in a file, but if you still insist to encrypt it here you go:

Generate key (password for decryption) and save it in notes (you'll need it to decrypt your password)

let uuid = require('uuid');
let key  = uuid();
console.log(key); // 3467f7d0-190f-4319-836e-8918a778d120

Install crypto-js

Encrypt the password:

let CryptoJS = require("crypto-js");
let encryptedPassword = CryptoJS.AES.encrypt('Pa$sword123!', key).toString();
console.log(encryptedPassword); // U2FsdGVkX18iI0gLaeQmf2z7Ev82hMynTo1c2TkCCJo=

Save it in your json data file

{
    'username': 'test-account',
    'password': 'U2FsdGVkX18iI0gLaeQmf2z7Ev82hMynTo1c2TkCCJo='
}

Wherever you need to use your password do this

let CryptoJS = require("crypto-js");
let decryptedPassword  = CryptoJS.AES.decrypt(json['password'], process.env.PASSWORD_KEY).toString(CryptoJS.enc.Utf8);
await login(json.username, decryptedPassword);

Run protractor with the following command specifying the decryption key from step #1

PASSWORD_KEY=3467f7d0-190f-4319-836e-8918a778d120 protractor protractor.conf.js

P.S.

when I said it's easier to start protractor with password as an environment variable I meant this

PASSWORD=Pa$sword123! protractor protractor.conf.js

and then refer to password as process.env.PASSWORD


问:
serialize int to vector of bytes using std::vector::reverse_iterator?
Next function works fine:

```<code>std::vector<uint8_t> serialize_bytes(uint32_t ui)
{
    return {(uint8_t*)&ui, (uint8_t*)(&ui+1)};
}
</code>```

But its result depends on endianess of machine.

I also need to serialize bytes in reverse order:

```<code>std::vector<uint8_t> serialize_bytes(uint32_t ui)
{
    std::vector<uint8_t>::reverse_iterator
        begin{(uint8_t*)(&ui+1)-1}
      , end{(uint8_t*)(&ui)-1};  //ERROR: Calling a private constructor
    return {begin, end};
}
</code>```

I know multiple other ways to do serialization. The interest of this Q is to construct reverse_iterator from pointer in manner like first snippet does.

答:
std::vector<uint8_t>::reverse_iterator can only point to elements of a std::vector<uint8_t>.

Use std::reverse_iterator<uint8_t *>:

```<code>std::vector<uint8_t> serialize_bytes(uint32_t ui)
{
    using iter_t = std::reverse_iterator<std::uint8_t *>;
    std::uint8_t *ptr = reinterpret_cast<std::uint8_t *>(&ui);
    return {iter_t(ptr + sizeof ui), iter_t(ptr)};
}
</code>```

Body:
Next function works fine:

std::vector<uint8_t> serialize_bytes(uint32_t ui)
{
    return {(uint8_t*)&ui, (uint8_t*)(&ui+1)};
}

But its result depends on endianess of machine.

I also need to serialize bytes in reverse order:

std::vector<uint8_t> serialize_bytes(uint32_t ui)
{
    std::vector<uint8_t>::reverse_iterator
        begin{(uint8_t*)(&ui+1)-1}
      , end{(uint8_t*)(&ui)-1};  //ERROR: Calling a private constructor
    return {begin, end};
}

I know multiple other ways to do serialization. The interest of this Q is to construct reverse_iterator from pointer in manner like first snippet does.

Body:
std::vector<uint8_t>::reverse_iterator can only point to elements of a std::vector<uint8_t>.

Use std::reverse_iterator<uint8_t *>:

std::vector<uint8_t> serialize_bytes(uint32_t ui)
{
    using iter_t = std::reverse_iterator<std::uint8_t *>;
    std::uint8_t *ptr = reinterpret_cast<std::uint8_t *>(&ui);
    return {iter_t(ptr + sizeof ui), iter_t(ptr)};
}


问:
Thread safe while loop
I have code like this:

```<code>while(true){
    var x = get();
    new Thread(()->parse(x)).start();
}
</code>```

It dawned upon me that this may not be thread safe as the variable x may be (?) getting re-assigned.

However my function seems to be working fine.

Is this actually safe?

答:
Variable x in your code should be effectively final, which means it can not be reassigned. See e.g. this explanation or this stackoverflow question.

But the solution in general is not thread-safe, when x is an object and its fields can be accessed from outside. In such cases all changes to fields of x should be synchronized.

Title: Thread safe while loop

Body:
I have code like this:

while(true){
    var x = get();
    new Thread(()->parse(x)).start();
}

It dawned upon me that this may not be thread safe as the variable x may be (?) getting re-assigned.

However my function seems to be working fine.

Is this actually safe?


问:
How do I connect a GitHub organization to Microsoft Teams?
When I use the GitHub Bot, it only displays GitHub repositories that I own. It does not include repositories, issues, and pull requests for an organization that I contribute to.

How do I connect a GitHub organization to Microsoft Teams so that I can list and post details of issues and pull requests I created in my organization?

答:
This feature is currently not available. The GitHub Microsoft Teams integration creators have added it to their feature backlog.

Thank you for sharing the feedback. Currently the GitHub bot don't have features to support for organization related repositories, issues and pull request that we contribute. We have added this in feature backlog and will discuss with feature team regarding prioritization. — Subhasish-MSFT


问:
In SQLAlchemy ORM, How do I get the primary key columns for use in session.query().group_by()?

Question

How do I get a list of all primary key columns of a model class and all its parents in the polymorphic hierarchy, so I can use it in a session.query().group_by?

Details

In SQLAlchemy ORM, if I'm querying a class that is part of a polymorphic hierarchy and I want to GROUP BY it's primary key, I must also GROUP BY all primary keys of its parents in the polymorphic hierarchy.

Imagine the following setup inspired by the Mapping Class Inheritance Hierarchies section of the sqlalchemy documentation:

class Employee(Base):
    __tablename__ = 'employee'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    type = Column(String(50))

    __mapper_args__ = {
        'polymorphic_identity':'employee',
        'polymorphic_on':type
    }

class Engineer(Employee):
    __tablename__ = 'engineer'
    id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
    engineer_name = Column(String(30))

    __mapper_args__ = {
        'polymorphic_identity':'engineer',
    }

class EngineeringTask(Base):
    __tablename__ = 'engineering_task'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))

    assigned_engineer_id = Column(ForeignKey(Engineer.id))
    assigned_engineer = relationship(Engineer, backref=backref("assigned_tasks", lazy="dynamic"))
```

<p>If I want to do a query like</p>

```session.query(
    Engineer,
).join(
    Engineer.assigned_tasks,
).add_columns(
    func.count(EngineeringTask.id).label('assigned_task_count'),
).group_by(Engineer.id, Employee.id)
```

Such a query, which is selecting all columns from Engineer and Employee but not aggregating them, is possible in PostgreSQL because (emphasis mine):

When GROUP BY is present (...) it is not valid for the SELECT list expressions to refer to ungrouped columns except within aggregate functions or when the ungrouped column is functionally dependent on the grouped columns, since there would otherwise be more than one possible value to return for an ungrouped column. A functional dependency exists if the grouped columns (or a subset thereof) are the primary key of the table containing the ungrouped column.

But it requires that I know / care / remember all the primary key columns of the mapped class I'm selecting and all it's parents in the polymorphic hierarchy (Engineer.id and Employee.id in this case)

How can I obtain the list of all the primary key columns of Engineer and all parents in the polymorphic hierarchy, dynamically?

答:
The best I could come up with so far is this function:

from sqlalchemy import inspect

def polymorphic_primary_keys(cls):
    mapper = inspect(cls)
    yield from (column for column in mapper.columns if column.primary_key)
    if mapper.inherits is not None:
        yield from polymorphic_primary_keys(mapper.inherits.entity)
```
<p>Use it like this:</p>
<pre class="lang-py prettyprint-override"><code>query = session.query(
    Engineer,
).join(
    Engineer.assigned_tasks,
).add_columns(
    func.count(EngineeringTask.id).label('assigned_task_count'),
).group_by(*polymorphic_primary_keys(Engineer))
</code>```

Where inspect(Engineer) returns Engineer.__mapper__ which is a Mapper containing:

Mapper.columns, an iterator/dictionary/attribute accessor of the columns of the mapped model

Mapper.inherits, which is the mapper of the parent entity, if any.

It's unsatisfying for a few reasons:

There is Mapper.primary_key which is supposed to be an iterator over the primary keys, but I can't use it since it returns the primary keys of the topmost parent, not the currently mapped entity, so I have to iterate over Mapper.columns and check primary_key attribute.

There is a Mapper.polymorphic_iterator() method and a Mapper.self_and_descendants attribute that both return an iterator containing the current mapper and the mappers of all "downstream" subclasses of the current entity. Why isn't there an equivalent iterator for the "upstream" superclasses?

But it gets the job done...

Body:
Question

How do I get a list of all primary key columns of a model class and all its parents in the polymorphic hierarchy, so I can use it in a session.query().group_by?

Details

In SQLAlchemy ORM, if I'm querying a class that is part of a polymorphic hierarchy and I want to GROUP BY it's primary key, I must also GROUP BY all primary keys of its parents in the polymorphic hierarchy.

Imagine the following setup inspired by the Mapping Class Inheritance Hierarchies section of the sqlalchemy documentation:

class Employee(Base):
    __tablename__ = 'employee'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    type = Column(String(50))

    __mapper_args__ = {
        'polymorphic_identity':'employee',
        'polymorphic_on':type
    }

class Engineer(Employee):
    __tablename__ = 'engineer'
    id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
    engineer_name = Column(String(30))

    __mapper_args__ = {
        'polymorphic_identity':'engineer',
    }

class EngineeringTask(Base):
    __tablename__ = 'engineering_task'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))

    assigned_engineer_id = Column(ForeignKey(Engineer.id))
    assigned_engineer = relationship(Engineer, backref=backref("assigned_tasks", lazy="dynamic"))

If I want to do a query like

session.query(
    Engineer,
).join(
    Engineer.assigned_tasks,
).add_columns(
    func.count(EngineeringTask.id).label('assigned_task_count'),
).group_by(Engineer.id, Employee.id)

Such a query, which is selecting all columns from Engineer and Employee but not aggregating them, is possible in PostgreSQL because (emphasis mine):

When GROUP BY is present (...) it is not valid for the SELECT list expressions to refer to ungrouped columns except within aggregate functions or when the ungrouped column is functionally dependent on the grouped columns, since there would otherwise be more than one possible value to return for an ungrouped column. A functional dependency exists if the grouped columns (or a subset thereof) are the primary key of the table containing the ungrouped column.

But it requires that I know / care / remember all the primary key columns of the mapped class I'm selecting and all it's parents in the polymorphic hierarchy (Engineer.id and Employee.id in this case)

How can I obtain the list of all the primary key columns of Engineer and all parents in the polymorphic hierarchy, dynamically?

Body:
The best I could come up with so far is this function:

from sqlalchemy import inspect

def polymorphic_primary_keys(cls):
    mapper = inspect(cls)
    yield from (column for column in mapper.columns if column.primary_key)
    if mapper.inherits is not None:
        yield from polymorphic_primary_keys(mapper.inherits.entity)

Use it like this:

query = session.query(
    Engineer,
).join(
    Engineer.assigned_tasks,
).add_columns(
    func.count(EngineeringTask.id).label('assigned_task_count'),
).group_by(*polymorphic_primary_keys(Engineer))

Where inspect(Engineer) returns Engineer.__mapper__ which is a Mapper containing:

Mapper.columns, an iterator/dictionary/attribute accessor of the columns of the mapped model

Mapper.inherits, which is the mapper of the parent entity, if any.

It's unsatisfying for a few reasons:

There is Mapper.primary_key which is supposed to be an iterator over the primary keys, but I can't use it since it returns the primary keys of the topmost parent, not the currently mapped entity, so I have to iterate over Mapper.columns and check primary_key attribute.

There is a Mapper.polymorphic_iterator() method and a Mapper.self_and_descendants attribute that both return an iterator containing the current mapper and the mappers of all "downstream" subclasses of the current entity. Why isn't there an equivalent iterator for the "upstream" superclasses?

But it gets the job done...


问:
Copying folders from a source folder to a destination folder using xcopy batch command
I have a batch file that is copying data from a source folder to a destination folder. A text file called list.txt decides which folders from the source folder will be copied to the dest folder.
The contents of the text file, list.txt, are:

```<code>F:\200208
F:\200210
F:\200214
</code>```

The batch file is:

```<code>@echo off
for /f "tokens=*" %%i in (list.txt) do (
        xcopy /s /i "%%i" "D:\username\Videos\%%i"
    )
pause
</code>```

However, when I run the batch file, I get the following error messages:

```<code>Invalid path
0 File(s) copied
Invalid path
0 File(s) copied
Invalid path
0 File(s) copied
Press any key to continue . . .
</code>```

The name of the drive in which this batch file is residing is F
and folders with name 200208, 200210 & 200214 do exist in that same drive F. Also, the dest folder exists.

Can someone point out where the issue is?

答:
The destination path in your code is resolving to "D:\username\Videos\F:\200208".  That is why you are getting an invalid path.

You just want the folder name so change %%i to %%~nxi in the destination path.

Body:
I have a batch file that is copying data from a source folder to a destination folder. A text file called list.txt decides which folders from the source folder will be copied to the dest folder.
The contents of the text file, list.txt, are:

F:\200208
F:\200210
F:\200214

The batch file is:

@echo off
for /f "tokens=*" %%i in (list.txt) do (
        xcopy /s /i "%%i" "D:\username\Videos\%%i"
    )
pause

However, when I run the batch file, I get the following error messages:

Invalid path
0 File(s) copied
Invalid path
0 File(s) copied
Invalid path
0 File(s) copied
Press any key to continue . . .

The name of the drive in which this batch file is residing is F
and folders with name 200208, 200210 & 200214 do exist in that same drive F. Also, the dest folder exists.

Can someone point out where the issue is?


答:
You can use std::reverse to help you with your task.

```<code>std::vector<uint8_t> serialize_bytes(uint32_t ui)
{
    std::vector<uint8_t> v{(uint8_t*)&ui, (uint8_t*)(&ui+1)};
    std::reverse(v.begin(), v.end());
    return v;
}
</code>```

Title: serialize int to vector of bytes using std::vector::reverse_iterator?

Body:
You can use std::reverse to help you with your task.

std::vector<uint8_t> serialize_bytes(uint32_t ui)
{
    std::vector<uint8_t> v{(uint8_t*)&ui, (uint8_t*)(&ui+1)};
    std::reverse(v.begin(), v.end());
    return v;
}


答:
You can use Element.addEventListener with the option once set to true.

According to MDN, the option once is:

A Boolean indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.

```<code><button class="colour-btn colour-btn--3"></button>
<script>
document.querySelector('button').addEventListener('click', showImage3, {once: true});
</script>
</code>```

function showImage3() {
    console.log("showImage3(); only called once");
    var img3 = document.createElement('img');
    img3.setAttribute("src", "");
    img3.setAttribute("width", "700");
    img3.setAttribute("height", "400");
    document.body.appendChild(img3);
}
document.querySelector('button').addEventListener('click', showImage3, {once: true});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="colour-btn colour-btn--3">Show Image 3</button></code>```

You can also use this utility once function that returns a function encapsulating the function passed in as its parameter and will only run it at most once.

```<code>function once(fn, context){
    if(typeof fn != "function") throw TypeError("fn is not a function");
    var ran = false, res;
    return function(){
        return ran ? res : (ran = true, res = fn.apply(context||this, Array.prototype.slice.call(arguments)));
    };
}
</code>```

function once(fn, context){
    if(typeof fn != "function") throw TypeError("fn is not a function");
    var ran = false, res;
    return function(){
        return ran ? res : (ran = true, res = fn.apply(context||this, Array.prototype.slice.call(arguments)));
    };
}
function showImage3() {
    console.log("showImage3(); only called once");
    var img3 = document.createElement('img');
    img3.setAttribute("src", "");
    img3.setAttribute("width", "700");
    img3.setAttribute("height", "400");
    document.body.appendChild(img3);
}
var showImage3Once = once(showImage3);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="colour-btn colour-btn--3" onClick="showImage3Once();">Show Image 3</button></code>```

Title: Only run JavaScript function once

Body:
You can use Element.addEventListener with the option once set to true.

According to MDN, the option once is:

A Boolean indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.

<button class="colour-btn colour-btn--3"></button>
<script>
document.querySelector('button').addEventListener('click', showImage3, {once: true});
</script>

function showImage3() {
    console.log("showImage3(); only called once");
    var img3 = document.createElement('img');
    img3.setAttribute("src", "");
    img3.setAttribute("width", "700");
    img3.setAttribute("height", "400");
    document.body.appendChild(img3);
}
document.querySelector('button').addEventListener('click', showImage3, {once: true});

<button class="colour-btn colour-btn--3">Show Image 3</button>

You can also use this utility once function that returns a function encapsulating the function passed in as its parameter and will only run it at most once.

function once(fn, context){
    if(typeof fn != "function") throw TypeError("fn is not a function");
    var ran = false, res;
    return function(){
        return ran ? res : (ran = true, res = fn.apply(context||this, Array.prototype.slice.call(arguments)));
    };
}

function once(fn, context){
    if(typeof fn != "function") throw TypeError("fn is not a function");
    var ran = false, res;
    return function(){
        return ran ? res : (ran = true, res = fn.apply(context||this, Array.prototype.slice.call(arguments)));
    };
}
function showImage3() {
    console.log("showImage3(); only called once");
    var img3 = document.createElement('img');
    img3.setAttribute("src", "");
    img3.setAttribute("width", "700");
    img3.setAttribute("height", "400");
    document.body.appendChild(img3);
}
var showImage3Once = once(showImage3);

<button class="colour-btn colour-btn--3" onClick="showImage3Once();">Show Image 3</button>


问:
How to override a form default value with parsed typoscript
I created a hook (with a function afterBuildingFinished) that take a string and parse it into typoscript.
Now I want to take that typoscript to override a form (yaml) default value with. I don't understand how to ''process'' the typoscript. Like, i'm missing the step after get the typoscript parsed.

This is a part of my code :

```<code>public function afterBuildingFinished(RenderableInterface $renderable): void {

   #some code here ...

   #My parsing code :
   $parseObj = GeneralUtility::makeInstance(TypoScriptParser::class);
   $parseObj->parse($stringToParse);
   $TSparse = $parseObj->setup; #this is use to access the parse typoscript

   #Now, what do I do after?
}
</code>```

My purpose is to prefill renderable of a form with user info via a typoscript string.

Thanks.

答:
I figured it out and needed to change a little bit my code.

Here is the new one :

```<code>public function afterBuildingFinished(RenderableInterface $renderable): void {

   #some code here ...

   #My parsing code :
   $parseObj = GeneralUtility::makeInstance(TypoScriptParser::class);
   $parseObj->parse($stringToParse);

   #This process the typoscript
   #$value stock user info for a X renderable
   $cObject =  GeneralUtility::makeInstance(ObjectManager::class)->get(ContentObjectRenderer::class);
   $value = $cObject->cObjGet($parseObj->setup);

   #Some code to set the default value of the renderable
}
</code>```

To answer my question: after parsing the code, I need to process the typoscript with cObject and then set the default value of the renderable with classic setDefaultValue() functions.

Body:
I created a hook (with a function afterBuildingFinished) that take a string and parse it into typoscript.
Now I want to take that typoscript to override a form (yaml) default value with. I don't understand how to ''process'' the typoscript. Like, i'm missing the step after get the typoscript parsed.

This is a part of my code :

public function afterBuildingFinished(RenderableInterface $renderable): void {

   #some code here ...

   #My parsing code :
   $parseObj = GeneralUtility::makeInstance(TypoScriptParser::class);
   $parseObj->parse($stringToParse);
   $TSparse = $parseObj->setup; #this is use to access the parse typoscript

   #Now, what do I do after?
}

My purpose is to prefill renderable of a form with user info via a typoscript string.

Thanks.

Body:
I figured it out and needed to change a little bit my code.

Here is the new one :

public function afterBuildingFinished(RenderableInterface $renderable): void {

   #some code here ...

   #My parsing code :
   $parseObj = GeneralUtility::makeInstance(TypoScriptParser::class);
   $parseObj->parse($stringToParse);

   #This process the typoscript
   #$value stock user info for a X renderable
   $cObject =  GeneralUtility::makeInstance(ObjectManager::class)->get(ContentObjectRenderer::class);
   $value = $cObject->cObjGet($parseObj->setup);

   #Some code to set the default value of the renderable
}

To answer my question: after parsing the code, I need to process the typoscript with cObject and then set the default value of the renderable with classic setDefaultValue() functions.