问:
SwiftUI App Crashing EXC_BAD_ACCESS error when coredata list items are deleted
The following code is working all the way until the delete operation is done on list items. But this is not occurring every time the code is running. It crashes with EXC_BAD_ACCESS code of thread error:

Then I realized, this error is occurring after a certain time after delete operation if the app is kept running

This is why this error is very confusing to figure out. But it started appearing when I added DispatchQueue.main.async method to tasks in Model.swift.

The purpose of this code is to reload updated results from core data using self.fetchAll() method when there is any change happened in the list.

Another problem I noticed is the red lines appearing after deleting.

Questions:

How to update content view struct with least code when a core data list is updated? (This link has a different approach by the fetch method is called every time explicitly in code.)

How to optimize this code with less code and more stability?

Is the red line issue from the picture is part of an existing macOS bug?

macOS: 10.15.4

XCode: 11.5

Target: 10.15

Model.swift

```<code>import Foundation
import CoreData

class Model: ObservableObject {
    @Published var context: NSManagedObjectContext
    @Published var tasks: [Task] = [Task]() {
        didSet {
            DispatchQueue.main.async {
                self.fetchAll()
            }
        }
    }
    init(_ viewContext: NSManagedObjectContext) {
        context = viewContext
    }
}

// MARK: Methods

extension Model {
    func fetchAll() {
        let req = Task.fetchRequest() as NSFetchRequest<Task>
        req.sortDescriptors = [NSSortDescriptor(keyPath: \Task.name, ascending: true)]
        do {
            self.tasks = try self.context.fetch(req)
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }

    func addTask(_ text: String) {
        let name = text.trimmingCharacters(in: .whitespacesAndNewlines)
        if (name != "") {
            let task = Task(context: self.context)
            task.id = UUID()
            task.name = name
            task.creationTimestamp = Date()
            task.updatedTimestamp = Date()
            self.context.insert(task)
            self.save()
        }
    }

    func save() {
        guard self.context.hasChanges else { return }
        do {
            try self.context.save()
            print("Saved changes")
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }
}
</code>```

AppDelegate.swift

```<code>import Cocoa
import SwiftUI

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    var window: NSWindow!
    var model: Model!

    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
        return true
    }

    func applicationDidFinishLaunching(_ aNotification: Notification) {

        model = Model(persistentContainer.viewContext)
        let contentView = ContentView().environmentObject(model)

        window = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
            styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
            backing: .buffered, defer: false)
        window.center()
        window.setFrameAutosaveName("Main Window")
        window.contentView = NSHostingView(rootView: contentView)
        window.makeKeyAndOrderFront(nil)
    }

    func applicationWillTerminate(_ aNotification: Notification) { }

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentCloudKitContainer = {
        let container = NSPersistentCloudKitContainer(name: "Todo_List")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error {
                fatalError("Unresolved error \(error)")
            }
        })
        container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
        container.viewContext.undoManager = nil
        container.viewContext.shouldDeleteInaccessibleFaults = true
        container.viewContext.automaticallyMergesChangesFromParent = true
        return container
    }()

    // MARK: - Core Data Saving and Undo support

    @IBAction func saveAction(_ sender: AnyObject?) {
        let context = persistentContainer.viewContext

        if !context.commitEditing() {
            NSLog("\(NSStringFromClass(type(of: self))) unable to commit editing before saving")
        }
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let nserror = error as NSError
                NSApplication.shared.presentError(nserror)
            }
        }
    }

    func windowWillReturnUndoManager(window: NSWindow) -> UndoManager? {
        return persistentContainer.viewContext.undoManager
    }

    func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
        let context = persistentContainer.viewContext

        if !context.commitEditing() {
            NSLog("\(NSStringFromClass(type(of: self))) unable to commit editing to terminate")
            return .terminateCancel
        }

        if !context.hasChanges {
            return .terminateNow
        }

        do {
            try context.save()
        } catch {
            let nserror = error as NSError
            let result = sender.presentError(nserror)
            if (result) {
                return .terminateCancel
            }

            let question = NSLocalizedString("Could not save changes while quitting. Quit anyway?", comment: "Quit without saves error question message")
            let info = NSLocalizedString("Quitting now will lose any changes you have made since the last successful save", comment: "Quit without saves error question info");
            let quitButton = NSLocalizedString("Quit anyway", comment: "Quit anyway button title")
            let cancelButton = NSLocalizedString("Cancel", comment: "Cancel button title")
            let alert = NSAlert()
            alert.messageText = question
            alert.informativeText = info
            alert.addButton(withTitle: quitButton)
            alert.addButton(withTitle: cancelButton)

            let answer = alert.runModal()
            if answer == .alertSecondButtonReturn {
                return .terminateCancel
            }
        }
        return .terminateNow
    }
}

</code>```

ContentView.swift

```<code>import SwiftUI

struct ContentView: View {
    @EnvironmentObject var model: Model
    @State var taskName: String = ""

    var body: some View {
        VStack{
            ZStack{
                TaskList()
                    .padding(.top,31)
                VStack(spacing:0){
                    TextField("New Task", text: self.$taskName, onCommit: {
                        self.model.addTask(self.taskName)
                        self.taskName = ""
                    })
                        .padding(5)
                    Divider().offset(y:-1)
                        Spacer()
                }
                if model.tasks.isEmpty {
                    Text("Nothing To Do\nPlease add something To Do.")
                        .multilineTextAlignment(.center)
                        .font(.headline)
                        .padding(.horizontal)
                        .frame(maxWidth: .infinity, maxHeight: .infinity)
                }
            }
        }
        .frame(minWidth: 200, maxWidth: .infinity, maxHeight: .infinity)
        .onAppear{
            self.model.fetchAll()
        }
    }
}
</code>```

TaskList.swift

```<code>import SwiftUI

struct TaskList: View {
    @EnvironmentObject var model: Model

    @State var selection: Task?

    var body: some View {
        List(selection: self.$selection){
            ForEach(self.model.tasks, id: \.self) { task in
                TaskRow(task: task).tag(task)
            }
            .onDelete(perform: onDelete)
        }
    }

    private func onDelete(with indexSet: IndexSet) {
        indexSet.forEach { index in
            let task = self.model.tasks[index]
            self.model.context.delete(task)
        }
        self.model.save()
    }
}
</code>```

TaskRow.swift

```<code>struct TaskRow: View {
    @ObservedObject var task: Task
    @EnvironmentObject var model: Model
    var dateString: String {
        if let timestamp = task.updatedTimestamp {
            let formatter = DateFormatter()
            formatter.dateStyle = .long
            formatter.timeStyle = .medium
            return formatter.string(from: timestamp)
        } else {
            return "No date recorded"
        }
    }
    var body: some View {
        HStack {
            Toggle(isOn: Binding<Bool>(get: { () -> Bool in
                return self.task.checked
            }, set: { (enabled) in
                self.task.checked = enabled
                self.task.updatedTimestamp = Date()
                self.model.save()
            })){
                Text("")
            }
            VStack {
                HStack {
                    Text(task.name ?? "Unknown Task").font(.system(size: 20))
                    Spacer()
                }
                HStack {
                    Text(dateString).font(.system(size: 10)).bold()
                    Spacer()
                }
            }
        }
    }
}
</code>```

答:
Make sure Task is an Identifiable:

```<code>extension Task: Identifiable {
}
</code>```

If you dont know you should be able to do this in your ForEach:

```<code>ForEach(self.model.tasks) {task in
}
</code>```

I've actually had this issue as well. The workaround I had to do was to add a field isDeleted instead of actually deleting the record off CoreData. Then you can either clean it up later, when app is on background or terminated. or just keep the record in Coredata.

Body:
The following code is working all the way until the delete operation is done on list items. But this is not occurring every time the code is running. It crashes with EXC_BAD_ACCESS code of thread error:

Then I realized, this error is occurring after a certain time after delete operation if the app is kept running

This is why this error is very confusing to figure out. But it started appearing when I added DispatchQueue.main.async method to tasks in Model.swift.

The purpose of this code is to reload updated results from core data using self.fetchAll() method when there is any change happened in the list.

Another problem I noticed is the red lines appearing after deleting.

Questions:

How to update content view struct with least code when a core data list is updated? (This link has a different approach by the fetch method is called every time explicitly in code.)

How to optimize this code with less code and more stability?

Is the red line issue from the picture is part of an existing macOS bug?

macOS: 10.15.4

XCode: 11.5

Target: 10.15

Model.swift

import Foundation
import CoreData

class Model: ObservableObject {
    @Published var context: NSManagedObjectContext
    @Published var tasks: [Task] = [Task]() {
        didSet {
            DispatchQueue.main.async {
                self.fetchAll()
            }
        }
    }
    init(_ viewContext: NSManagedObjectContext) {
        context = viewContext
    }
}

// MARK: Methods

extension Model {
    func fetchAll() {
        let req = Task.fetchRequest() as NSFetchRequest<Task>
        req.sortDescriptors = [NSSortDescriptor(keyPath: \Task.name, ascending: true)]
        do {
            self.tasks = try self.context.fetch(req)
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }

    func addTask(_ text: String) {
        let name = text.trimmingCharacters(in: .whitespacesAndNewlines)
        if (name != "") {
            let task = Task(context: self.context)
            task.id = UUID()
            task.name = name
            task.creationTimestamp = Date()
            task.updatedTimestamp = Date()
            self.context.insert(task)
            self.save()
        }
    }

    func save() {
        guard self.context.hasChanges else { return }
        do {
            try self.context.save()
            print("Saved changes")
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }
}

AppDelegate.swift

import Cocoa
import SwiftUI

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    var window: NSWindow!
    var model: Model!

    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
        return true
    }

    func applicationDidFinishLaunching(_ aNotification: Notification) {

        model = Model(persistentContainer.viewContext)
        let contentView = ContentView().environmentObject(model)

        window = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
            styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
            backing: .buffered, defer: false)
        window.center()
        window.setFrameAutosaveName("Main Window")
        window.contentView = NSHostingView(rootView: contentView)
        window.makeKeyAndOrderFront(nil)
    }

    func applicationWillTerminate(_ aNotification: Notification) { }

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentCloudKitContainer = {
        let container = NSPersistentCloudKitContainer(name: "Todo_List")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error {
                fatalError("Unresolved error \(error)")
            }
        })
        container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
        container.viewContext.undoManager = nil
        container.viewContext.shouldDeleteInaccessibleFaults = true
        container.viewContext.automaticallyMergesChangesFromParent = true
        return container
    }()

    // MARK: - Core Data Saving and Undo support

    @IBAction func saveAction(_ sender: AnyObject?) {
        let context = persistentContainer.viewContext

        if !context.commitEditing() {
            NSLog("\(NSStringFromClass(type(of: self))) unable to commit editing before saving")
        }
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let nserror = error as NSError
                NSApplication.shared.presentError(nserror)
            }
        }
    }

    func windowWillReturnUndoManager(window: NSWindow) -> UndoManager? {
        return persistentContainer.viewContext.undoManager
    }

    func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
        let context = persistentContainer.viewContext

        if !context.commitEditing() {
            NSLog("\(NSStringFromClass(type(of: self))) unable to commit editing to terminate")
            return .terminateCancel
        }

        if !context.hasChanges {
            return .terminateNow
        }

        do {
            try context.save()
        } catch {
            let nserror = error as NSError
            let result = sender.presentError(nserror)
            if (result) {
                return .terminateCancel
            }

            let question = NSLocalizedString("Could not save changes while quitting. Quit anyway?", comment: "Quit without saves error question message")
            let info = NSLocalizedString("Quitting now will lose any changes you have made since the last successful save", comment: "Quit without saves error question info");
            let quitButton = NSLocalizedString("Quit anyway", comment: "Quit anyway button title")
            let cancelButton = NSLocalizedString("Cancel", comment: "Cancel button title")
            let alert = NSAlert()
            alert.messageText = question
            alert.informativeText = info
            alert.addButton(withTitle: quitButton)
            alert.addButton(withTitle: cancelButton)

            let answer = alert.runModal()
            if answer == .alertSecondButtonReturn {
                return .terminateCancel
            }
        }
        return .terminateNow
    }
}

ContentView.swift

import SwiftUI

struct ContentView: View {
    @EnvironmentObject var model: Model
    @State var taskName: String = ""

    var body: some View {
        VStack{
            ZStack{
                TaskList()
                    .padding(.top,31)
                VStack(spacing:0){
                    TextField("New Task", text: self.$taskName, onCommit: {
                        self.model.addTask(self.taskName)
                        self.taskName = ""
                    })
                        .padding(5)
                    Divider().offset(y:-1)
                        Spacer()
                }
                if model.tasks.isEmpty {
                    Text("Nothing To Do\nPlease add something To Do.")
                        .multilineTextAlignment(.center)
                        .font(.headline)
                        .padding(.horizontal)
                        .frame(maxWidth: .infinity, maxHeight: .infinity)
                }
            }
        }
        .frame(minWidth: 200, maxWidth: .infinity, maxHeight: .infinity)
        .onAppear{
            self.model.fetchAll()
        }
    }
}

TaskList.swift

import SwiftUI

struct TaskList: View {
    @EnvironmentObject var model: Model

    @State var selection: Task?

    var body: some View {
        List(selection: self.$selection){
            ForEach(self.model.tasks, id: \.self) { task in
                TaskRow(task: task).tag(task)
            }
            .onDelete(perform: onDelete)
        }
    }

    private func onDelete(with indexSet: IndexSet) {
        indexSet.forEach { index in
            let task = self.model.tasks[index]
            self.model.context.delete(task)
        }
        self.model.save()
    }
}

TaskRow.swift

struct TaskRow: View {
    @ObservedObject var task: Task
    @EnvironmentObject var model: Model
    var dateString: String {
        if let timestamp = task.updatedTimestamp {
            let formatter = DateFormatter()
            formatter.dateStyle = .long
            formatter.timeStyle = .medium
            return formatter.string(from: timestamp)
        } else {
            return "No date recorded"
        }
    }
    var body: some View {
        HStack {
            Toggle(isOn: Binding<Bool>(get: { () -> Bool in
                return self.task.checked
            }, set: { (enabled) in
                self.task.checked = enabled
                self.task.updatedTimestamp = Date()
                self.model.save()
            })){
                Text("")
            }
            VStack {
                HStack {
                    Text(task.name ?? "Unknown Task").font(.system(size: 20))
                    Spacer()
                }
                HStack {
                    Text(dateString).font(.system(size: 10)).bold()
                    Spacer()
                }
            }
        }
    }
}

Body:
Make sure Task is an Identifiable:

extension Task: Identifiable {
}

If you dont know you should be able to do this in your ForEach:

ForEach(self.model.tasks) {task in
}

I've actually had this issue as well. The workaround I had to do was to add a field isDeleted instead of actually deleting the record off CoreData. Then you can either clean it up later, when app is on background or terminated. or just keep the record in Coredata.


来源: stackexchange

问:
Ansible synchronize always sets changed
I need to set the contents of a dest folder to be the same as my src folder.  So I am using the synchronize module:

```<code>- name: files for /lib/user/ based on the Runtime version
  synchronize:
    src: "/data/managedFiles/lib/{{ runtime.version }}/user/"
    dest: "{{ mule_directory }}{{ mule_runtime_name }}/lib/user/"
    delete: yes
  register: result
</code>```

But this sets "changed" to 'true' in result, even when there was no change.   I need this to be only set to 'true' if there was a something changed because the next task tests for this state.

If I repeat the same synchronize task right after this one it doesn't set 'changed' to 'true'.  But that one always doesn't get set to 'true'.

Subsequent runs of the play with no change to the src ("/data/managedFiles/lib/{{ runtime.version }}/user/") always set result with 'changed'.

答:
By default, the timestamps of the files are included in the test that detects when to copy the files.  Since the files are being pulled from git, the timestamps are different on each play creating a false signal.  But not when the same synchronize is run twice in a row.  The solution is to set checksum parameter to yes so that timestamps are not checked.  But this requires also setting the recursive and archive parameters:</p>

```<code>- name: files for /lib/user/ based on the Runtime version
  synchronize:
    src: "/data/managedFiles/lib/{{ runtime.version }}/user/"
    dest: "{{ mule_directory }}{{ mule_runtime_name }}/lib/user/"
    recursive: yes
    archive: no
    checksum: yes
    delete: yes
  register: result
</code>```

ContentLicense: CC BY-SA 4.0

Title: Ansible synchronize always sets changed

Body:
I need to set the contents of a dest folder to be the same as my src folder.  So I am using the synchronize module:

- name: files for /lib/user/ based on the Runtime version
  synchronize:
    src: "/data/managedFiles/lib/{{ runtime.version }}/user/"
    dest: "{{ mule_directory }}{{ mule_runtime_name }}/lib/user/"
    delete: yes
  register: result

But this sets "changed" to 'true' in result, even when there was no change.   I need this to be only set to 'true' if there was a something changed because the next task tests for this state.

If I repeat the same synchronize task right after this one it doesn't set 'changed' to 'true'.  But that one always doesn't get set to 'true'.

Subsequent runs of the play with no change to the src ("/data/managedFiles/lib/{{ runtime.version }}/user/") always set result with 'changed'.

Body:
By default, the timestamps of the files are included in the test that detects when to copy the files.  Since the files are being pulled from git, the timestamps are different on each play creating a false signal.  But not when the same synchronize is run twice in a row.  The solution is to set checksum parameter to yes so that timestamps are not checked.  But this requires also setting the recursive and archive parameters:

- name: files for /lib/user/ based on the Runtime version
  synchronize:
    src: "/data/managedFiles/lib/{{ runtime.version }}/user/"
    dest: "{{ mule_directory }}{{ mule_runtime_name }}/lib/user/"
    recursive: yes
    archive: no
    checksum: yes
    delete: yes
  register: result


问:
Django: Run a function if certain condition is met
I have a Word model, where a user can add words and various fields, like this (shortened version):

```<code>class Word(models.Model):
    target_word = models.CharField()
    source_word = models.CharField()
    add_to_review = models.BooleanField(default=True)
    example_sentence = models.CharField()
    image = models.ImageField(upload_to='images/',blank=True)
    audio = models.FileField(upload_to='audio/',blank=True)
</code>```

I also have a Flashcard model where a user can add and study flashcards. Here I show only the relevant code:

```<code>class FlashcardManager(models.Manager):
    def create_flashcard(self, user, question, answer, deck_name):
        try:
            deck = Deck.objects.get(owner=user, name=deck_name)
        except ObjectDoesNotExist:
            deck = Deck(owner=user, name=deck_name)
            deck.save()

        self.create(owner=user, question=question, answer=answer,
                    deck=deck)
        return deck

class Flashcard(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    deck = models.ForeignKey(Deck, on_delete=models.CASCADE)
    question = models.TextField()
    answer = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    last_shown_at = models.DateTimeField(auto_now_add=True)
    next_due_date = models.DateTimeField(default=timezone.now)
    difficulty = models.FloatField(default=2.5)
    consec_correct_answers = models.IntegerField(default=0)

    objects = FlashcardManager()

    def __str__(self):
        return self.question
</code>```

When a user creates a new word, I want to give them the option of automatically creating a flashcard using the info provided. In other words, question = target_word, answer = source_word, and the deck name can either be some default value, or I can add a field to the Word model. Is there a way I can do this by using the add_to_review field of the Word model and the create_flashcard method of the FlashcardManager model? I've tried adding a function to my Word model that runs if add_to_review is true. I don't get any errors, but nothing happens.

I know one option would be to just combine the two models... but I do have my own reasons for keeping them seperate. I might still do that, but I was just wondering if what I am trying to do is possible / feasible? I'm not really sure what exactly to google, so haven't been able to find any info on this. So any advice would be great, thanks!

答:
Not sure if this is the best way, but it worked. Initially I had problems with the signal not being called, but this got fixed when I moved it to my models.py file instead of having it separate in a signals.py file. </p>

```<code>@receiver(post_save, sender=Word)
def flash_from_word(sender, created, instance, **kwargs):
    if created:
        flash_wanted = Word.objects.filter(add_to_review=True)
        instance._meta.model.objects.all()
        target_word = instance.target_word
        source_word = instance.source_word
        deck_name = instance.deck_name
        user = instance.user
        if flash_wanted:
            flash = Flashcard.objects.create(owner=user, question=target_word,answer=source_word,deck=Deck.objects.get(name=deck_name,owner=user))

post_save.connect(flash_from_word, sender=Word)
</code>```

Body:
I have a Word model, where a user can add words and various fields, like this (shortened version):

class Word(models.Model):
    target_word = models.CharField()
    source_word = models.CharField()
    add_to_review = models.BooleanField(default=True)
    example_sentence = models.CharField()
    image = models.ImageField(upload_to='images/',blank=True)
    audio = models.FileField(upload_to='audio/',blank=True)

I also have a Flashcard model where a user can add and study flashcards. Here I show only the relevant code:

class FlashcardManager(models.Manager):
    def create_flashcard(self, user, question, answer, deck_name):
        try:
            deck = Deck.objects.get(owner=user, name=deck_name)
        except ObjectDoesNotExist:
            deck = Deck(owner=user, name=deck_name)
            deck.save()

        self.create(owner=user, question=question, answer=answer,
                    deck=deck)
        return deck

class Flashcard(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    deck = models.ForeignKey(Deck, on_delete=models.CASCADE)
    question = models.TextField()
    answer = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    last_shown_at = models.DateTimeField(auto_now_add=True)
    next_due_date = models.DateTimeField(default=timezone.now)
    difficulty = models.FloatField(default=2.5)
    consec_correct_answers = models.IntegerField(default=0)

    objects = FlashcardManager()

    def __str__(self):
        return self.question

When a user creates a new word, I want to give them the option of automatically creating a flashcard using the info provided. In other words, question = target_word, answer = source_word, and the deck name can either be some default value, or I can add a field to the Word model. Is there a way I can do this by using the add_to_review field of the Word model and the create_flashcard method of the FlashcardManager model? I've tried adding a function to my Word model that runs if add_to_review is true. I don't get any errors, but nothing happens.

I know one option would be to just combine the two models... but I do have my own reasons for keeping them seperate. I might still do that, but I was just wondering if what I am trying to do is possible / feasible? I'm not really sure what exactly to google, so haven't been able to find any info on this. So any advice would be great, thanks!

Body:
Not sure if this is the best way, but it worked. Initially I had problems with the signal not being called, but this got fixed when I moved it to my models.py file instead of having it separate in a signals.py file.

@receiver(post_save, sender=Word)
def flash_from_word(sender, created, instance, **kwargs):
    if created:
        flash_wanted = Word.objects.filter(add_to_review=True)
        instance._meta.model.objects.all()
        target_word = instance.target_word
        source_word = instance.source_word
        deck_name = instance.deck_name
        user = instance.user
        if flash_wanted:
            flash = Flashcard.objects.create(owner=user, question=target_word,answer=source_word,deck=Deck.objects.get(name=deck_name,owner=user))

post_save.connect(flash_from_word, sender=Word)


问:
facing a problem Dividing the maximum length of a string using substr PHP
I'm facing a problem with dividing the maximum number by itself.
Example, the number is

```<code>6667880025043855
</code>```

which is max length is 16, so I will divide it into four digits with four breaks in every number

Example:

```<code>6667
8800
2504
3855
</code>```

So what I did is using substr and dividing it by four.

The code:

```<code>if (strlen($number) == 16) { // instaces if the max length is 16.
  echo $number1 = substr($number, 0, 4)."</br>";
   echo $number2 = substr($number, 4, 8)."</br>";
   echo $number3 = substr($number, 8, 12)."</br>";
   echo $number4 = substr($number, 12, 16)."</br>";
}
</code>```

But my output would be:

```<code>6667
88002504
25043855
3855
</code>```

Am I doing it wrong?
P.S:
I'm still in the beginner's phase.

答:
You should research the function in here: https://www.php.net/manual/en/function.substr.php
The third param is the number of characters in your substr.

It should be:

```<code>$number = '6667880025043855';

if (strlen($number) == 16) { // instaces if the max length is 16.
  echo $number1 = substr($number, 0, 4)."</br>";
   echo $number2 = substr($number, 4, 4)."</br>";
   echo $number3 = substr($number, 8, 4)."</br>";
   echo $number4 = substr($number, 12, 4)."</br>";
}
</code>```

Body:
I'm facing a problem with dividing the maximum number by itself.
Example, the number is

6667880025043855

which is max length is 16, so I will divide it into four digits with four breaks in every number

Example:

6667
8800
2504
3855

So what I did is using substr and dividing it by four.

The code:

if (strlen($number) == 16) { // instaces if the max length is 16.
  echo $number1 = substr($number, 0, 4)."
";
   echo $number2 = substr($number, 4, 8)."
";
   echo $number3 = substr($number, 8, 12)."
";
   echo $number4 = substr($number, 12, 16)."
";
}

But my output would be:

6667
88002504
25043855
3855

Am I doing it wrong?
P.S:
I'm still in the beginner's phase.

Body:
You should research the function in here: https://www.php.net/manual/en/function.substr.php
The third param is the number of characters in your substr.

It should be:

$number = '6667880025043855';

if (strlen($number) == 16) { // instaces if the max length is 16.
  echo $number1 = substr($number, 0, 4)."</br>";
   echo $number2 = substr($number, 4, 4)."</br>";
   echo $number3 = substr($number, 8, 4)."</br>";
   echo $number4 = substr($number, 12, 4)."</br>";
}


问:
Is there a way to remove comma/s in my database? Codeigniter PHP
How can I remove comma(s) from my database?

I need to remove them per data.
So I have this data

Product 1,Product 2,,,,,  - I need to remove per commas

So, I need to remove per commas. Here is my View

```<code><?php echo form_open('subjects/remove_core'); ?>

 <?php  $core_subjs = explode(',', $subjects['core_subjects']); ?>
    <?php foreach($core_subjs as $key => $subject): ?>

        <input type="hidden" name="remove_core" class="form-control" value="<?php echo $subjects['core_subjects'].'' ?>" /><br>

        <input type="text" name="coresubjs[]" class="form-control" value="<?php echo $subject ?>" /><br>
        <button type="submit" class="btn btn-success btn-sm">Save</button>

  <?php endforeach ?>
</form>
</code>```

My Controller

```<code>public function remove_core(){

    $this->subject_model->remove_core();

    redirect('subjects/edit/'.$_SESSION['editID']);
}
</code>```

My Model- So in here I am not sure if I am doing this right, as per result is not correct.

```<code>public function remove_core(){
        $data = array(
            'core_subjects' => " "
        );

        $this->db->where('id', $this->input->post('coresubjID'));
        return $this->db->update('subjects', $data);
}
</code>```

How I implode data

```<code>public function update_core(){
        $data = array(
            'core_subjects' => implode(',',$this->input->post('coresubjs[]'))
        );

        $this->db->where('id', $this->input->post('coresubjID'));
        return $this->db->update('subjects', $data);
}
</code>```

答:
In your update_core function, you need to trim the additional ','. You can do this as follow -

```<code>public function update_core(){
        $data = array(
            'core_subjects' => rtrim(implode(',', $this->input->post('coresubjs[]')), ','); // remove the extra ',' to the right
        );

        $this->db->where('id', $this->input->post('coresubjID'));
        return $this->db->update('subjects', $data);
}
</code>```

Also, remember that you don't have to remove the data every time you update. When updating it will automatically overwrite the previous value. So your remove_core method is redundant and should be removed

Body:
How can I remove comma(s) from my database?

I need to remove them per data.
So I have this data

Product 1,Product 2,,,,,  - I need to remove per commas

So, I need to remove per commas. Here is my View

<?php echo form_open('subjects/remove_core'); ?>

 <?php  $core_subjs = explode(',', $subjects['core_subjects']); ?>
    <?php foreach($core_subjs as $key => $subject): ?>

        <input type="hidden" name="remove_core" class="form-control" value="<?php echo $subjects['core_subjects'].'' ?>" />

        <input type="text" name="coresubjs[]" class="form-control" value="<?php echo $subject ?>" />

        <button type="submit" class="btn btn-success btn-sm">Save</button>

  <?php endforeach ?>
</form>

My Controller

public function remove_core(){

    $this->subject_model->remove_core();

    redirect('subjects/edit/'.$_SESSION['editID']);
}

My Model- So in here I am not sure if I am doing this right, as per result is not correct.

public function remove_core(){
        $data = array(
            'core_subjects' => " "
        );

        $this->db->where('id', $this->input->post('coresubjID'));
        return $this->db->update('subjects', $data);
}

How I implode data

public function update_core(){
        $data = array(
            'core_subjects' => implode(',',$this->input->post('coresubjs[]'))
        );

        $this->db->where('id', $this->input->post('coresubjID'));
        return $this->db->update('subjects', $data);
}

Body:
In your update_core function, you need to trim the additional ','. You can do this as follow -

public function update_core(){
        $data = array(
            'core_subjects' => rtrim(implode(',', $this->input->post('coresubjs[]')), ','); // remove the extra ',' to the right
        );

        $this->db->where('id', $this->input->post('coresubjID'));
        return $this->db->update('subjects', $data);
}

Also, remember that you don't have to remove the data every time you update. When updating it will automatically overwrite the previous value. So your remove_core method is redundant and should be removed


问:
GCC inline assembly error: asm-specifier for variable '%al' conflicts with asm clobber list
Sorry for so many questions, but I've encountered yet another cryptic error trying to compile the following inline assembly (with -fasm-blocks) which works in MSVC, but apparently not in GCC and wasn't able to deal with it:

```<code>unsigned char testData = 128;

__asm
{
    // ...
    mov al, testData
    mov ah, al // error: asm-specifier for variable '%al' conflicts with asm clobber list
    shl eax, 16
    // ...
};
</code>```

What is this clobber list and what is wrong with it?

I also tried to change optimization level, but it had no effect.

答:
This has to be some bug in gcc (maybe __asm blocks have implicit clobbering). Anyway there are many workarounds:

```<code>__asm
{
    // ...
    mov ah, testData
    mov al, ah
    shl eax, 16
    // ...
};
</code>```

or

```<code>__asm
{
    // ...
    mov al, testData
    mov ah, testData
    shl eax, 16
    // ...
};
</code>```

or

```<code>__asm
{
    // ...
    movzx eax, testData
    imul eax, 0x0101
    shl eax, 16
    // ...
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Sorry for so many questions, but I've encountered yet another cryptic error trying to compile the following inline assembly (with -fasm-blocks) which works in MSVC, but apparently not in GCC and wasn't able to deal with it:

unsigned char testData = 128;

__asm
{
    // ...
    mov al, testData
    mov ah, al // error: asm-specifier for variable '%al' conflicts with asm clobber list
    shl eax, 16
    // ...
};

What is this clobber list and what is wrong with it?

I also tried to change optimization level, but it had no effect.

Body:
This has to be some bug in gcc (maybe __asm blocks have implicit clobbering). Anyway there are many workarounds:

__asm
{
    // ...
    mov ah, testData
    mov al, ah
    shl eax, 16
    // ...
};

or

__asm
{
    // ...
    mov al, testData
    mov ah, testData
    shl eax, 16
    // ...
};

or

__asm
{
    // ...
    movzx eax, testData
    imul eax, 0x0101
    shl eax, 16
    // ...
};


问:
When page refresh my ngnix server gives 404 not found error
Problem:

I have built angular application and then I host it on a virtual machine using Nginx docker container for that I have created a ./Dockerfile like this.

```<code>FROM nginx:1.17.1-alpine
COPY ./dist/HRM-Front-end /usr/share/nginx/html
COPY ./nginx.conf /etc/nginx/
EXPOSE 3003
CMD ["nginx", "-g", "daemon off;"]
</code>```

This is my app-routing.module.ts file.

```<code>import {NgModule} from '@angular/core';
import {PreloadAllModules, RouterModule, Routes} from '@angular/router';
import {HomeMainComponent} from '../module/home/feature/home-main/home-main.component';

const routes: Routes = [
  {path: '', component: HomeMainComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes, {
      scrollPositionRestoration: 'enabled',
      preloadingStrategy: PreloadAllModules
    })],
  exports: [RouterModule]
})
export class AppRoutingModule {
}
</code>```

And then nginx.conf file like this.

on alpine, copy to /etc/nginx/nginx.conf

```<code>user                            root;
worker_processes                auto;

error_log                       /var/log/nginx/error.log warn;

events {
    worker_connections          1024;
}

http {
    include                     /etc/nginx/mime.types;
    default_type                application/octet-stream;
    sendfile                    off;
    access_log                  off;
    keepalive_timeout           3000;
    server {
        listen                  3003;
        root                    /usr/share/nginx/html;
        index                   index.html;
        server_name             localhost;
        client_max_body_size    16m;
    }
}
</code>```

After running the server I can access it in the browser successfully but when I try to refresh the page it gives me 404 Not found issue. I try to figure out what is the issue. But I was unable to do it can someone help me to solve this issue. Thank you.

答:
You can see you will have to add fallback for every route * serve index.html in htaccess
Look for nginx configuration https://angular.io/guide/deployment</p>

Body:
Problem:

I have built angular application and then I host it on a virtual machine using Nginx docker container for that I have created a ./Dockerfile like this.

FROM nginx:1.17.1-alpine
COPY ./dist/HRM-Front-end /usr/share/nginx/html
COPY ./nginx.conf /etc/nginx/
EXPOSE 3003
CMD ["nginx", "-g", "daemon off;"]

This is my app-routing.module.ts file.

import {NgModule} from '@angular/core';
import {PreloadAllModules, RouterModule, Routes} from '@angular/router';
import {HomeMainComponent} from '../module/home/feature/home-main/home-main.component';

const routes: Routes = [
  {path: '', component: HomeMainComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes, {
      scrollPositionRestoration: 'enabled',
      preloadingStrategy: PreloadAllModules
    })],
  exports: [RouterModule]
})
export class AppRoutingModule {
}

And then nginx.conf file like this.

on alpine, copy to /etc/nginx/nginx.conf

user                            root;
worker_processes                auto;

error_log                       /var/log/nginx/error.log warn;

events {
    worker_connections          1024;
}

http {
    include                     /etc/nginx/mime.types;
    default_type                application/octet-stream;
    sendfile                    off;
    access_log                  off;
    keepalive_timeout           3000;
    server {
        listen                  3003;
        root                    /usr/share/nginx/html;
        index                   index.html;
        server_name             localhost;
        client_max_body_size    16m;
    }
}

After running the server I can access it in the browser successfully but when I try to refresh the page it gives me 404 Not found issue. I try to figure out what is the issue. But I was unable to do it can someone help me to solve this issue. Thank you.


问:
Why "TypeError: express.Router is not a function"
Trying to make a login app with nodejs express.
However after I run it. it shows TypeError: express.Router is not a function.
My express is the latest version4.13.4. Can anyone help me?Here is the code.</p>

```<code>var User = require('../modules/user');
var config = require('../../config');

var secretKey = config.secretKey;

module.exports = function(app,express){
    var api = express.Router;
    api.post('/signup', function(req,res){
        var user = new User({
            name: req.body.name,
            username: req.body.username,
            password: req.body.password
        });

        user.save(function(err){
            if(err){
                res.send(err);
                return;
            }

            res.json({ message: 'user has been created'});
        })
    });

    return api;
};
</code>```

答:
```<code>const express = require('express');
const mongoose = require('mongoose');

const router = express.Router();
router.get('/', (req, res)=>{
    res.send('Course Controller');
});

module.exports = router;
</code>```

Body:
Trying to make a login app with nodejs express.
However after I run it. it shows TypeError: express.Router is not a function.
My express is the latest version4.13.4. Can anyone help me?Here is the code.

var User = require('../modules/user');
var config = require('../../config');

var secretKey = config.secretKey;

module.exports = function(app,express){
    var api = express.Router;
    api.post('/signup', function(req,res){
        var user = new User({
            name: req.body.name,
            username: req.body.username,
            password: req.body.password
        });

        user.save(function(err){
            if(err){
                res.send(err);
                return;
            }

            res.json({ message: 'user has been created'});
        })
    });

    return api;
};


问:
How do I call a static method defined in one script from another script?
I have a method defined in the file "shared.groovy" like this:

```<code>def static configure()
{
    .....
}
</code>```

And I have another script file in the same dir, where I need to call the configure() method. I'm trying it this way

```<code>shared.configure()
</code>```

but getting this exception:

```<code>FATAL: No such property: shared for class: script14095498929361009943305
groovy.lang.MissingPropertyException: No such property: shared for class: script14095498929361009943305
</code>```

Another ideas?

答: This seems fixed in Groovy 2.5.3.  Before that, one would need to import static shared.configure (in addition to import shared) and only then call shared.configure().

Body:
I have a method defined in the file "shared.groovy" like this:

def static configure()
{
    .....
}

And I have another script file in the same dir, where I need to call the configure() method. I'm trying it this way

shared.configure()

but getting this exception:

FATAL: No such property: shared for class: script14095498929361009943305
groovy.lang.MissingPropertyException: No such property: shared for class: script14095498929361009943305

Another ideas?


问:
In Android, how do I query MediaStore only for files in a specific path? Or alternatively, only display files in a certain path?
Suppose I have an Android block of code that looks something like this:

```<code>String[] proj = {MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media._ID};
int[] to = new int[] { R.id.artist_name };
Cursor musiccursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null, MediaStore.Audio.Media.ARTIST);
ListView musiclist = (ListView) findViewById(R.id.mylist);

SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.songitem, musiccursor, proj, to);
musiclist.setAdapter(mAdapter);
</code>```

But what I want, is this:

```<code>String selection = MediaStore.Audio.Media.FILE_PATH + " ilike '%audio%books%'";

String[] proj = {MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media._ID};
int[] to = new int[] { R.id.artist_name };
Cursor musiccursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, selection, null, MediaStore.Audio.Media.ARTIST);
ListView musiclist = (ListView) findViewById(R.id.mylist);

SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.songitem, musiccursor, proj, to);
musiclist.setAdapter(mAdapter);
</code>```

The only problem, of course, is that FILE_PATH is not actually a column I can use, and as far as I can tell, no such column exists.

So I'm wondering:

Is there a way to query only for music in a certain directory? If so, how?

If that's not an option, should I make a ListAdapter that filters by directory? If so, again, how would I go about in doing that?

Thanks for any advice.

答:
MediaStore.MediaColumns.DATA is what you are looking for something like 'FILE_PATH'.

So file path can be retrieved by

```<code>String filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA));
</code>```

Body:
Suppose I have an Android block of code that looks something like this:

String[] proj = {MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media._ID};
int[] to = new int[] { R.id.artist_name };
Cursor musiccursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null, MediaStore.Audio.Media.ARTIST);
ListView musiclist = (ListView) findViewById(R.id.mylist);

SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.songitem, musiccursor, proj, to);
musiclist.setAdapter(mAdapter);

But what I want, is this:

String selection = MediaStore.Audio.Media.FILE_PATH + " ilike '%audio%books%'";

String[] proj = {MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media._ID};
int[] to = new int[] { R.id.artist_name };
Cursor musiccursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, selection, null, MediaStore.Audio.Media.ARTIST);
ListView musiclist = (ListView) findViewById(R.id.mylist);

SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.songitem, musiccursor, proj, to);
musiclist.setAdapter(mAdapter);

The only problem, of course, is that FILE_PATH is not actually a column I can use, and as far as I can tell, no such column exists.

So I'm wondering:

Is there a way to query only for music in a certain directory? If so, how?

If that's not an option, should I make a ListAdapter that filters by directory? If so, again, how would I go about in doing that?

Thanks for any advice.

Body:
MediaStore.MediaColumns.DATA is what you are looking for something like 'FILE_PATH'.

So file path can be retrieved by

String filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA));


问:
Removing substring of from a list of strings
There are several countries with numbers and/or parenthesis in my list. How I  remove these?

e.g.

'Bolivia (Plurinational State of)' should be 'Bolivia',

'Switzerland17' should be 'Switzerland'.

答:
Run just:

```<code>df.Country.replace(r'\d+|\s*\([^)]*\)', '', regex=True, inplace=True)
</code>```

Assuming that the initial content of your DataFrame is:

```<code>                            Country
0  Bolivia (Plurinational State of)
1                     Switzerland17
2                    United Kingdom
</code>```

after the above replace you will have:

```<code>          Country
0         Bolivia
1     Switzerland
2  United Kingdom
</code>```

The above pattern contains:

the first alternative - a non-empty sequence of digits,

the second alternative:

an optional sequence of "white" chars,

an opening parenthesis (quoted),

a sequence of chars other than ) (between brackets no quotation is
needed),

a closing parenthesis (also quoted).

Body:
Run just:

df.Country.replace(r'\d+|\s*\([^)]*\)', '', regex=True, inplace=True)

Assuming that the initial content of your DataFrame is:

                            Country
0  Bolivia (Plurinational State of)
1                     Switzerland17
2                    United Kingdom

after the above replace you will have:

          Country
0         Bolivia
1     Switzerland
2  United Kingdom

The above pattern contains:

the first alternative - a non-empty sequence of digits,

the second alternative:

an optional sequence of "white" chars,

an opening parenthesis (quoted),

a sequence of chars other than ) (between brackets no quotation is
needed),

a closing parenthesis (also quoted).


答:
To remove the extraneous commas going into the database, you can use array_filter, trim, or preg_replace depending on your preference.

With a theoretical value for $this->input->post('coresubjs[]') of

array(
   '',
   '',
   '0',
   'A',
   'B',
   '',
   'D',
   '',
   '',
);
```

<p>Using <code>implode(',')</code> only will result in</p>

```,,0,A,B,,D,,
```

<h2>Disclaimer</h2>

<p>However please keep in mind, that any commas in the post values will not be properly accounted for and should be escaped using another means. eg: <code>1,000</code> will be exploded as <code>array("1", "000")</code>. For this reason I recommend refactoring in favor of using <code>json_encode()</code> and <code>json_decode()</code> or <code>serialize()</code> and <code>unserialize()</code>, instead of <code>implode(',')</code> and <code>explode(',')</code></p>

<p>Example: https://3v4l.org/I2ObY</p>

<hr>

<h2>array_filter</h2>

<p>Removes the "empty" values (<code>0, "", false, null</code>) from the <code>implode</code> array argument.
This will work against any input value that is empty, including the middle of the array.</p>

<pre class="lang-php prettyprint-override"><code>implode(',', array_filter($this->input->post('coresubjs[]')))
</code>```

Result

Notice that all extraneous commas and the 0 value was removed

```<code>A,B,D
</code>```

To circumvent the issue with "empty" values such as 0, false, you can use a custom callback instead.

implode(',', array_filter($this->input->post('coresubjs[]'), function($value) {
    return null !== $value && '' !== $value;
}))
```

<p><strong>Result</strong><br>
<em>Notice all extraneous commas were removed</em></p>

```0,A,B,D
```

<hr>

<h2>trim</h2>

<p>Removes only the leading and trailing commas from the <code>implode</code> value.</p>

<pre class="lang-php prettyprint-override"><code>trim(implode(',', $this->input->post('coresubjs[]')), ',')
</code>```

Result

Notice the leading and trailing commas are removed but extra comma in the middle remained.

```<code>0,A,B,,D
</code>```

preg_replace

Similar to trim, removing the leading and trailing commas from the implode value, with the addition of replacing any 2 or more commas in the middle with a single comma.

preg_replace(['/,{2,}/', '/^,+/', '/,+$/'], [',', '', ''], implode(',', $this->input->post('coresubjs[]')))
```

<p>Pattern Explanation:</p>

<ul>
<li><code>,{2,}</code> any 2 or more commas </li>
<li><code>^,+</code> begins with 1 or more comma </li>
<li><code>,+$</code> ends with 1 ore more comma</li>
</ul>

<p><strong>Result</strong><br>
<em>Notice All extraneous commas have been removed</em></p>

```0,A,B,D
```

Title: Is there a way to remove comma/s in my database? Codeigniter PHP

Body:
To remove the extraneous commas going into the database, you can use array_filter, trim, or preg_replace depending on your preference.

With a theoretical value for $this->input->post('coresubjs[]') of

array(
   '',
   '',
   '0',
   'A',
   'B',
   '',
   'D',
   '',
   '',
);

Using implode(',') only will result in

,,0,A,B,,D,,

Disclaimer

However please keep in mind, that any commas in the post values will not be properly accounted for and should be escaped using another means. eg: 1,000 will be exploded as array("1", "000"). For this reason I recommend refactoring in favor of using json_encode() and json_decode() or serialize() and unserialize(), instead of implode(',') and explode(',')

Example: https://3v4l.org/I2ObY

array_filter

Removes the "empty" values (0, "", false, null) from the implode array argument.
This will work against any input value that is empty, including the middle of the array.

implode(',', array_filter($this->input->post('coresubjs[]')))

Result

Notice that all extraneous commas and the 0 value was removed

A,B,D

To circumvent the issue with "empty" values such as 0, false, you can use a custom callback instead.

implode(',', array_filter($this->input->post('coresubjs[]'), function($value) {
    return null !== $value && '' !== $value;
}))

Result

Notice all extraneous commas were removed

0,A,B,D

trim

Removes only the leading and trailing commas from the implode value.

trim(implode(',', $this->input->post('coresubjs[]')), ',')

Result

Notice the leading and trailing commas are removed but extra comma in the middle remained.

0,A,B,,D

preg_replace

Similar to trim, removing the leading and trailing commas from the implode value, with the addition of replacing any 2 or more commas in the middle with a single comma.

preg_replace(['/,{2,}/', '/^,+/', '/,+$/'], [',', '', ''], implode(',', $this->input->post('coresubjs[]')))

Pattern Explanation:

,{2,} any 2 or more commas

^,+ begins with 1 or more comma

,+$ ends with 1 ore more comma

Result

Notice All extraneous commas have been removed

0,A,B,D


答:
You can remove string by this way:-

Remove numbers:-

```<code>import re
a = 'Switzerland17'
pattern = '[0-9]'
res = re.sub(pattern, '', a)
print(res)
</code>```

Output:-

```<code>'Switzerland'
</code>```

Remove parenthesis:-

```<code>b = 'Bolivia (Plurinational State of)'
pattern2 = '(\s*\(.*\))'
res2 = re.sub(pattern2, '', b)
print(res2)
</code>```

Output:-

```<code>'Bolivia'
</code>```

Title: Removing substring of from a list of strings

Body:
There are several countries with numbers and/or parenthesis in my list. How I  remove these?

e.g.

'Bolivia (Plurinational State of)' should be 'Bolivia',

'Switzerland17' should be 'Switzerland'.

Body:
You can remove string by this way:-

Remove numbers:-

import re
a = 'Switzerland17'
pattern = '[0-9]'
res = re.sub(pattern, '', a)
print(res)

Output:-

'Switzerland'

Remove parenthesis:-

b = 'Bolivia (Plurinational State of)'
pattern2 = '(\s*\(.*\))'
res2 = re.sub(pattern2, '', b)
print(res2)

Output:-

'Bolivia'


问:
Heroku application error unable to trace logs
I deployed my small project to heroku server. Also run the heroku ps:scale web=1 to add free dynos to run my project. but it seems there is some error I am not able to trace it. Please help.

答:
In many environments (e.g. Heroku), and as a convention, you can set the environment variable PORT to tell your web server what port to listen on.

So process.env.PORT || 3000 means: whatever is in the environment variable PORT, or 3000 if there's nothing there.

So you pass that app.listen, or to app.set(port, ...), and that makes your server be able to accept a parameter from the environment what port to listen on.

If you pass 3000 hard-coded to app.listen(), you're always listening on port 3000, which might be just for you, or not, depending on your requirements and the requirements of the environment in which you're running your server.


问:
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure when trying to build spring boot docker image
I am trying to build my docker image for my spring boot application but keep encountering this error:

```<code> :: Spring Boot ::        (v2.2.5.RELEASE)

2020-05-31 02:18:39.820  INFO 63 --- [           main] c.g.Apollo.ApolloApplicationTests        : Starting ApolloApplicationTests on 4b284b60945e with PID 63 (started by root in /build)
2020-05-31 02:18:39.838  INFO 63 --- [           main] c.g.Apollo.ApolloApplicationTests        : No active profile set, falling back to default profiles: default
2020-05-31 02:18:42.208  INFO 63 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-05-31 02:18:42.467  INFO 63 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 216ms. Found 3 JPA repository interfaces.
2020-05-31 02:18:44.902  INFO 63 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-05-31 02:18:46.575 ERROR 63 --- [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Exception during pool initialization.

com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
        at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174) ~[mysql-connector-java-8.0.20.jar:8.0.20]
        at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64) ~[mysql-connector-java-8.0.20.jar:8.0.20]
        at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836) ~[mysql-connector-java-8.0.20.jar:8.0.20]
        at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456) ~[mysql-connector-java-8.0.20.jar:8.0.20]
        at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246) ~[mysql-connector-java-8.0.20.jar:8.0.20]
        at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197) ~[mysql-connector-java-8.0.20.jar:8.0.20]
        at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-3.4.2.jar:na]
        at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:354) ~[HikariCP-3.4.2.jar:na]
        at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:202) ~[HikariCP-3.4.2.jar:na]
        at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:473) ~[HikariCP-3.4.2.jar:na]
        at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:554) ~[HikariCP-3.4.2.jar:na]
        at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-3.4.2.jar:na]
        at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-3.4.2.jar:na]
</code>```

Terminal when successfully running in intellij:

```<code> :: Spring Boot ::        (v2.2.5.RELEASE)

2020-05-31 01:04:39.322  INFO 19524 --- [  restartedMain] c.g.Apollo.ApolloApplication             : Starting ApolloApplication on asd-PC with PID 19524 (C:\Projects\Apollo\target\classes started by asd in C:\Projects\Apollo)
2020-05-31 01:04:39.324  INFO 19524 --- [  restartedMain] c.g.Apollo.ApolloApplication             : No active profile set, falling back to default profiles: default
2020-05-31 01:04:39.354  INFO 19524 --- [  restartedMain] o.s.b.devtools.restart.ChangeableUrls    : The Class-Path manifest attribute in C:\Users\asd\.m2\repository\org\glassfish\jaxb\jaxb-runtime\2.3.2\jaxb-runtime-2.3.2.jar referenced one or more files that do not exist: file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/jakarta.xml.bind-api-2.3.2.jar,file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/txw2-2.3.2.jar,file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/istack-commons-runtime-3.0.8.jar,file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/stax-ex-1.8.1.jar,file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/FastInfoset-1.2.16.jar,file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/jakarta.activation-api-1.2.1.jar
2020-05-31 01:04:39.354  INFO 19524 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-05-31 01:04:39.354  INFO 19524 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2020-05-31 01:04:39.785  INFO 19524 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-05-31 01:04:39.846  INFO 19524 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 54ms. Found 3 JPA repository interfaces.
2020-05-31 01:04:40.214  INFO 19524 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-05-31 01:04:40.220  INFO 19524 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-05-31 01:04:40.221  INFO 19524 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.31]
2020-05-31 01:04:40.293  INFO 19524 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-05-31 01:04:40.293  INFO 19524 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 939 ms
2020-05-31 01:04:40.365  INFO 19524 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-05-31 01:04:40.702  INFO 19524 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2020-05-31 01:04:40.731  INFO 19524 --- [  restartedMain] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-05-31 01:04:40.800  INFO 19524 --- [  restartedMain] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.4.12.Final
2020-05-31 01:04:40.919  INFO 19524 --- [  restartedMain] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-05-31 01:04:41.006  INFO 19524 --- [  restartedMain] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2020-05-31 01:04:41.407  INFO 19524 --- [  restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-05-31 01:04:41.413  INFO 19524 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-05-31 01:04:41.650  WARN 19524 --- [  restartedMain] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-05-31 01:04:41.717  INFO 19524 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-05-31 01:04:41.967  INFO 19524 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2020-05-31 01:04:41.995  INFO 19524 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-05-31 01:04:41.997  INFO 19524 --- [  restartedMain] c.g.Apollo.ApolloApplication             : Started ApolloApplication in 2.911 seconds (JVM running for 3.899)
</code>```

My Dockerfile:

```<code>FROM maven:3.6.3-jdk-11-slim AS MAVEN_BUILD

COPY pom.xml /build/
COPY src /build/src/
WORKDIR /build/
RUN mvn package

FROM openjdk:11-jre-alpine

WORKDIR /app
COPY --from=MAVEN_BUILD /build/target/*.war /app/app.war
ENTRYPOINT ["java", "-jar", "app.war"]
</code>```

My application.properties:

```<code>## GraphQL SPQR ##
server.port=8080
graphql.spqr.gui.enabled=true
graphql.spqr.http.endpoint=/graphql
graphql.spqr.ws.endpoint=/graphql

## Database Properties ##
spring.datasource.url=jdbc:mysql://localhost:3306/innodb
spring.datasource.username=root
spring.datasource.password=1234
</code>```

My application works when I build and run the project in Intellij but not when I try and build my docker image. I am using MySQL and have just been connecting on localhost on port 3306.

答:
The error message seems to indicate the issue is failing to connect to the database. From your settings, it appears that you are trying to connect to the DB using localhost:3306. That will not work when you are running the application in a container because docker creates its own network which is separate from you machine’s network.  So, localhost in the container does not refer to your machine.
You need to instead setup a docker network that will allow your container to access the database in a specific IP address.
Here is an article with the specifics:
 https://nickjanetakis.com/blog/docker-tip-35-connect-to-a-database-running-on-your-docker-host
Note that I have assumed from your post, that the DB is installed in your host machine. If it is not and the DB is running in its own container, the you need to create a docker network and attach both containers to that network. </p>

Body:
I am trying to build my docker image for my spring boot application but keep encountering this error:

 :: Spring Boot ::        (v2.2.5.RELEASE)

2020-05-31 02:18:39.820  INFO 63 --- [           main] c.g.Apollo.ApolloApplicationTests        : Starting ApolloApplicationTests on 4b284b60945e with PID 63 (started by root in /build)
2020-05-31 02:18:39.838  INFO 63 --- [           main] c.g.Apollo.ApolloApplicationTests        : No active profile set, falling back to default profiles: default
2020-05-31 02:18:42.208  INFO 63 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-05-31 02:18:42.467  INFO 63 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 216ms. Found 3 JPA repository interfaces.
2020-05-31 02:18:44.902  INFO 63 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-05-31 02:18:46.575 ERROR 63 --- [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Exception during pool initialization.

com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
        at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174) ~[mysql-connector-java-8.0.20.jar:8.0.20]
        at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64) ~[mysql-connector-java-8.0.20.jar:8.0.20]
        at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836) ~[mysql-connector-java-8.0.20.jar:8.0.20]
        at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456) ~[mysql-connector-java-8.0.20.jar:8.0.20]
        at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246) ~[mysql-connector-java-8.0.20.jar:8.0.20]
        at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197) ~[mysql-connector-java-8.0.20.jar:8.0.20]
        at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-3.4.2.jar:na]
        at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:354) ~[HikariCP-3.4.2.jar:na]
        at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:202) ~[HikariCP-3.4.2.jar:na]
        at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:473) ~[HikariCP-3.4.2.jar:na]
        at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:554) ~[HikariCP-3.4.2.jar:na]
        at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-3.4.2.jar:na]
        at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-3.4.2.jar:na]

Terminal when successfully running in intellij:

 :: Spring Boot ::        (v2.2.5.RELEASE)

2020-05-31 01:04:39.322  INFO 19524 --- [  restartedMain] c.g.Apollo.ApolloApplication             : Starting ApolloApplication on asd-PC with PID 19524 (C:\Projects\Apollo\target\classes started by asd in C:\Projects\Apollo)
2020-05-31 01:04:39.324  INFO 19524 --- [  restartedMain] c.g.Apollo.ApolloApplication             : No active profile set, falling back to default profiles: default
2020-05-31 01:04:39.354  INFO 19524 --- [  restartedMain] o.s.b.devtools.restart.ChangeableUrls    : The Class-Path manifest attribute in C:\Users\asd\.m2\repository\org\glassfish\jaxb\jaxb-runtime\2.3.2\jaxb-runtime-2.3.2.jar referenced one or more files that do not exist: file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/jakarta.xml.bind-api-2.3.2.jar,file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/txw2-2.3.2.jar,file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/istack-commons-runtime-3.0.8.jar,file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/stax-ex-1.8.1.jar,file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/FastInfoset-1.2.16.jar,file:/C:/Users/asd/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/jakarta.activation-api-1.2.1.jar
2020-05-31 01:04:39.354  INFO 19524 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-05-31 01:04:39.354  INFO 19524 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2020-05-31 01:04:39.785  INFO 19524 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-05-31 01:04:39.846  INFO 19524 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 54ms. Found 3 JPA repository interfaces.
2020-05-31 01:04:40.214  INFO 19524 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-05-31 01:04:40.220  INFO 19524 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-05-31 01:04:40.221  INFO 19524 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.31]
2020-05-31 01:04:40.293  INFO 19524 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-05-31 01:04:40.293  INFO 19524 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 939 ms
2020-05-31 01:04:40.365  INFO 19524 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-05-31 01:04:40.702  INFO 19524 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2020-05-31 01:04:40.731  INFO 19524 --- [  restartedMain] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-05-31 01:04:40.800  INFO 19524 --- [  restartedMain] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.4.12.Final
2020-05-31 01:04:40.919  INFO 19524 --- [  restartedMain] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-05-31 01:04:41.006  INFO 19524 --- [  restartedMain] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2020-05-31 01:04:41.407  INFO 19524 --- [  restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-05-31 01:04:41.413  INFO 19524 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-05-31 01:04:41.650  WARN 19524 --- [  restartedMain] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-05-31 01:04:41.717  INFO 19524 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-05-31 01:04:41.967  INFO 19524 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2020-05-31 01:04:41.995  INFO 19524 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-05-31 01:04:41.997  INFO 19524 --- [  restartedMain] c.g.Apollo.ApolloApplication             : Started ApolloApplication in 2.911 seconds (JVM running for 3.899)

My Dockerfile:

FROM maven:3.6.3-jdk-11-slim AS MAVEN_BUILD

COPY pom.xml /build/
COPY src /build/src/
WORKDIR /build/
RUN mvn package

FROM openjdk:11-jre-alpine

WORKDIR /app
COPY --from=MAVEN_BUILD /build/target/*.war /app/app.war
ENTRYPOINT ["java", "-jar", "app.war"]

My application.properties:

## GraphQL SPQR ##
server.port=8080
graphql.spqr.gui.enabled=true
graphql.spqr.http.endpoint=/graphql
graphql.spqr.ws.endpoint=/graphql

## Database Properties ##
spring.datasource.url=jdbc:mysql://localhost:3306/innodb
spring.datasource.username=root
spring.datasource.password=1234

My application works when I build and run the project in Intellij but not when I try and build my docker image. I am using MySQL and have just been connecting on localhost on port 3306.


问:
Is it possible to detect that your javascript code is executing because of an event?
If you don't control the invocation of your code, but would like to know if it's being executed by an event handler, is this possible?</p>

答: Javascript has event object that can help you identify the source of the event.</p>

OwnerDisplayName: daveb

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: shahkalpesh


问:
Problem in sorting using Comparator interface
I have created a ArrayList of HashMap like

```<code>ArrayList<HashMap<?,?>>  var = new ArrayList<HashMap<?,?>>();
</code>```

My HashMaps contains a String value "name" with key "name".What I want is to sort ArrayList by name so can I do this using Comparator?
Please Help Me.

答:
```<code>        ArrayList<HashMap<String,String>>  var = new ArrayList<HashMap<String,String>>();
    Collections.sort(var, new Comparator(){

        public int compare(Object o1, Object o2)
        {
            Map map1 = (Map) o1;
            Map map2 = (Map)o2;
            String name1 = (String) map1.get("name");
            String name2 = (String) map2.get("name");
            if(name1 != null){
            return name1.compareTo(name2);
            } else if(name2 != null){
            return name2.compareTo(name1);
            }else{
             return 0;
            }
        }
    });
</code>```

Here is  the answer.

Body:
I have created a ArrayList of HashMap like

ArrayList<HashMap<?,?>>  var = new ArrayList<HashMap<?,?>>();

My HashMaps contains a String value "name" with key "name".What I want is to sort ArrayList by name so can I do this using Comparator?
Please Help Me.

Body:
        ArrayList<HashMap<String,String>>  var = new ArrayList<HashMap<String,String>>();
    Collections.sort(var, new Comparator(){

        public int compare(Object o1, Object o2)
        {
            Map map1 = (Map) o1;
            Map map2 = (Map)o2;
            String name1 = (String) map1.get("name");
            String name2 = (String) map2.get("name");
            if(name1 != null){
            return name1.compareTo(name2);
            } else if(name2 != null){
            return name2.compareTo(name1);
            }else{
             return 0;
            }
        }
    });

Here is  the answer.


问:
How to transit another ejs file in Node.js
When I develop ejs file, I would like to transit to another ejs by clicking button.
But when I try to click and trnasit to quiz.ejs,nothing happend.

Are there any wrong point in ejs ?

And how to fix them?

Thanks

following is a part of my ejs file.

```<code><button onclick = "href = '/quiz'">start</button>
</code>```

And following is my Router.

```<code>router.get('/quiz',(req,res)=>{
    res.render(Views+'quiz.ejs');
});
</code>```

following is a part of my app.js

```<code>app.use('/quiz',Router);
</code>```

答:
Firstly you don't transit to any ejs file. You transit to another route which renders an ejs file.

So all you need to do is

Create a ejs file, lets say 'quiz.ejs'

Add a route to render this -

router.get('/quiz',(req,res)=>{
    res.render('quiz');
});

And then finally redirect the user to quiz route.

"href = '/quiz'>To Quiz</button>

Also note that you need  anchor tag to navigate not a button.

Body:
When I develop ejs file, I would like to transit to another ejs by clicking button.
But when I try to click and trnasit to quiz.ejs,nothing happend.

Are there any wrong point in ejs ?

And how to fix them?

Thanks

following is a part of my ejs file.

<button onclick = "href = '/quiz'">start</button>

And following is my Router.

router.get('/quiz',(req,res)=>{
    res.render(Views+'quiz.ejs');
});

following is a part of my app.js

app.use('/quiz',Router);

Body:
Firstly you don't transit to any ejs file. You transit to another route which renders an ejs file.

So all you need to do is

Create a ejs file, lets say 'quiz.ejs'

Add a route to render this -

router.get('/quiz',(req,res)=>{
    res.render('quiz');
});

And then finally redirect the user to quiz route.

<a "href = '/quiz'>To Quiz</button>

Also note that you need <a> anchor tag to navigate not a button.


Title: Scala Spark DataFrame Question:How to add new columns by matching the value in current row to somewhere from previous rows

Body:
I need help with Spark Dataframe.

The original dataframe df looks like this:

+---+---------+-------+---+------+
| id|      tim|  price|qty|qtyChg|
+---+---------+-------+---+------+
|  1|31951.509|  0.370|  1|     1|
|  2|31951.515|145.380|100|   100|
|  3|31951.519|149.370|100|   100|
|  4|31951.520|144.370|100|   100|
|  5|31951.520|149.370|300|   200|
|  6|31951.520|119.370|  5|     5|
|  7|31951.521|149.370|400|   100|
|  8|31951.522|109.370| 50|    50|
|  9|31951.522|149.370|410|    10|
| 10|31951.522|144.370|400|   300|
| 11|31951.522|149.870| 50|    50|
| 12|31951.524|149.370|610|   200|
| 13|31951.526|135.130| 22|    22|
| 14|31951.527|149.370|750|   140|
| 15|31951.528| 89.370|100|   100|
| 16|31951.528|145.870| 50|    50|
| 17|31951.528|139.370|100|   100|
| 18|31951.531|149.370|769|    19|
| 19|31951.531|144.370|410|    10|
| 20|31951.538|149.370|869|   100|
+---+---------+-------+---+------+

I am adding two columns top1price and top2priceby code

val ww = Window.partitionBy().orderBy($"tim")
val newdf = df.withColumn("sequence",sort_array(collect_set(col("price")).over(ww),asc=false))
                .withColumn("top1price",col("sequence").getItem(0))
                .withColumn("top2price",col("sequence").getItem(1)).drop("sequence")

newdf looks like this:

+---+---------+-------+---+------+---------+---------+
| id|      tim|  price|qty|qtyChg|top1price|top2price|
+---+---------+-------+---+------+---------+---------+
|  1|31951.509|  0.370|  1|     1|    0.370|     null|
|  2|31951.515|145.380|100|   100|  145.380|    0.370|
|  3|31951.519|149.370|100|   100|  149.370|  145.380|
|  4|31951.520|119.370|  5|     5|  149.370|  145.380|
|  5|31951.520|144.370|100|   100|  149.370|  145.380|
|  6|31951.520|149.370|300|   200|  149.370|  145.380|
|  7|31951.521|149.370|400|   100|  149.370|  145.380|
|  8|31951.522|109.370| 50|    50|  149.870|  149.370|
|  9|31951.522|144.370|400|   300|  149.870|  149.370|
| 10|31951.522|149.370|410|    10|  149.870|  149.370|
| 11|31951.522|149.870| 50|    50|  149.870|  149.370|
| 12|31951.524|149.370|610|   200|  149.870|  149.370|
| 13|31951.526|135.130| 22|    22|  149.870|  149.370|
| 14|31951.527|149.370|750|   140|  149.870|  149.370|
| 15|31951.528| 89.370|100|   100|  149.870|  149.370|
| 16|31951.528|139.370|100|   100|  149.870|  149.370|
| 17|31951.528|145.870| 50|    50|  149.870|  149.370|
| 18|31951.531|144.370|410|    10|  149.870|  149.370|
| 19|31951.531|149.370|769|    19|  149.870|  149.370|
| 20|31951.538|144.880|200|   200|  149.870|  149.370|
+---+---------+-------+---+------+---------+---------+

The logic behind top1price is what is the highest price so far at every moment. For example, at time 31951.520 (id = 6), the highest price by that time is 149.370 which comes from row id=6. The second-highest price by that time is 145.38 which comes from row2. I am interested in add two more columns top1priceQty and top2priceQty. The same example, in row 6, the highest price is 149.370 and its corresponding qty is 300 which also comes from row 6. The top2price is 145.380 and its top2priceQty would 100 which also comes from row2.

 |  8|31951.522|109.370| 50|    50|  149.870|  149.370|

For row8, top1price is 149.870 which comes from row 11 because row 8 to row 11 are the same moment. So by that time, 149.870 is the highest price and its corresponding top1priceQty would be 50. top2price is 149.370 which comes from row7, so is corresponding top2priceQty is 400 which also comes from row 7.

Thank you in advance!

Body:
I tried to solve this using following approach.

Please note that:

I haven't performed any performance testing, hence use this after performing some performance experiments using some variation of data as per the requirement. The below solution will affect the performance badly since there is no partitionBy clause in the windowing

Please check the output, and see whether its satisfies your requirement or not. I haven't done row by row match. But I think it should work.

Code (self-explanatory)

Load the data

val data =
      """
        |id|      tim|  price|qty|qtyChg
        | 1|31951.509|  0.370|  1|     1
        | 2|31951.515|145.380|100|   100
        | 3|31951.519|149.370|100|   100
        | 4|31951.520|144.370|100|   100
        | 5|31951.520|149.370|300|   200
        | 6|31951.520|119.370|  5|     5
        | 7|31951.521|149.370|400|   100
        | 8|31951.522|109.370| 50|    50
        | 9|31951.522|149.370|410|    10
        |10|31951.522|144.370|400|   300
        |11|31951.522|149.870| 50|    50
        |12|31951.524|149.370|610|   200
        |13|31951.526|135.130| 22|    22
        |14|31951.527|149.370|750|   140
        |15|31951.528| 89.370|100|   100
        |16|31951.528|145.870| 50|    50
        |17|31951.528|139.370|100|   100
        |18|31951.531|149.370|769|    19
        |19|31951.531|144.370|410|    10
        |20|31951.538|149.370|869|   100
      """.stripMargin

    val stringDS = data.split(System.lineSeparator())
      .map(_.split("\\|").map(_.replaceAll("""^[ \t]+|[ \t]+$""", "")).mkString(","))
      .toSeq.toDS()
    val df = spark.read
      .option("sep", ",")
      .option("inferSchema", "true")
      .option("header", "true")
      .csv(stringDS)
    df.show(false)
    df.printSchema()

Output-

+---+---------+------+---+------+
|id |tim      |price |qty|qtyChg|
+---+---------+------+---+------+
|1  |31951.509|0.37  |1  |1     |
|2  |31951.515|145.38|100|100   |
|3  |31951.519|149.37|100|100   |
|4  |31951.52 |144.37|100|100   |
|5  |31951.52 |149.37|300|200   |
|6  |31951.52 |119.37|5  |5     |
|7  |31951.521|149.37|400|100   |
|8  |31951.522|109.37|50 |50    |
|9  |31951.522|149.37|410|10    |
|10 |31951.522|144.37|400|300   |
|11 |31951.522|149.87|50 |50    |
|12 |31951.524|149.37|610|200   |
|13 |31951.526|135.13|22 |22    |
|14 |31951.527|149.37|750|140   |
|15 |31951.528|89.37 |100|100   |
|16 |31951.528|145.87|50 |50    |
|17 |31951.528|139.37|100|100   |
|18 |31951.531|149.37|769|19    |
|19 |31951.531|144.37|410|10    |
|20 |31951.538|149.37|869|100   |
+---+---------+------+---+------+

root
 |-- id: integer (nullable = true)
 |-- tim: double (nullable = true)
 |-- price: double (nullable = true)
 |-- qty: integer (nullable = true)
 |-- qtyChg: integer (nullable = true)

Fetch the highest and second highest price and related quantity

   val w = Window.orderBy("tim").rangeBetween(Window.unboundedPreceding, Window.currentRow)
    val w1 = Window.orderBy("tim")

    val processedDF = df.withColumn("maxPriceQty", max(struct(col("price"), col("qty"))).over(w))
      .withColumn("secondMaxPriceQty", lag(col("maxPriceQty"), 1).over(w1))
      .withColumn("top1price", col("maxPriceQty.price"))
      .withColumn("top1priceQty", col("maxPriceQty.qty"))
      .withColumn("top2price", col("secondMaxPriceQty.price"))
      .withColumn("top2priceQty", col("secondMaxPriceQty.qty"))
      processedDF.show(false)

Output-

+---+---------+------+---+------+-------------+-----------------+---------+------------+---------+------------+
|id |tim      |price |qty|qtyChg|maxPriceQty  |secondMaxPriceQty|top1price|top1priceQty|top2price|top2priceQty|
+---+---------+------+---+------+-------------+-----------------+---------+------------+---------+------------+
|1  |31951.509|0.37  |1  |1     |[0.37, 1]    |null             |0.37     |1           |null     |null        |
|2  |31951.515|145.38|100|100   |[145.38, 100]|[0.37, 1]        |145.38   |100         |0.37     |1           |
|3  |31951.519|149.37|100|100   |[149.37, 100]|[145.38, 100]    |149.37   |100         |145.38   |100         |
|4  |31951.52 |144.37|100|100   |[149.37, 300]|[149.37, 100]    |149.37   |300         |149.37   |100         |
|5  |31951.52 |149.37|300|200   |[149.37, 300]|[149.37, 300]    |149.37   |300         |149.37   |300         |
|6  |31951.52 |119.37|5  |5     |[149.37, 300]|[149.37, 300]    |149.37   |300         |149.37   |300         |
|7  |31951.521|149.37|400|100   |[149.37, 400]|[149.37, 300]    |149.37   |400         |149.37   |300         |
|8  |31951.522|109.37|50 |50    |[149.87, 50] |[149.37, 400]    |149.87   |50          |149.37   |400         |
|9  |31951.522|149.37|410|10    |[149.87, 50] |[149.87, 50]     |149.87   |50          |149.87   |50          |
|10 |31951.522|144.37|400|300   |[149.87, 50] |[149.87, 50]     |149.87   |50          |149.87   |50          |
|11 |31951.522|149.87|50 |50    |[149.87, 50] |[149.87, 50]     |149.87   |50          |149.87   |50          |
|12 |31951.524|149.37|610|200   |[149.87, 50] |[149.87, 50]     |149.87   |50          |149.87   |50          |
|13 |31951.526|135.13|22 |22    |[149.87, 50] |[149.87, 50]     |149.87   |50          |149.87   |50          |
|14 |31951.527|149.37|750|140   |[149.87, 50] |[149.87, 50]     |149.87   |50          |149.87   |50          |
|15 |31951.528|89.37 |100|100   |[149.87, 50] |[149.87, 50]     |149.87   |50          |149.87   |50          |
|16 |31951.528|145.87|50 |50    |[149.87, 50] |[149.87, 50]     |149.87   |50          |149.87   |50          |
|17 |31951.528|139.37|100|100   |[149.87, 50] |[149.87, 50]     |149.87   |50          |149.87   |50          |
|18 |31951.531|149.37|769|19    |[149.87, 50] |[149.87, 50]     |149.87   |50          |149.87   |50          |
|19 |31951.531|144.37|410|10    |[149.87, 50] |[149.87, 50]     |149.87   |50          |149.87   |50          |
|20 |31951.538|149.37|869|100   |[149.87, 50] |[149.87, 50]     |149.87   |50          |149.87   |50          |
+---+---------+------+---+------+-------------+-----------------+---------+------------+---------+------------+

Please observe last 4 output columns and for explanation of rowsBetween and rangeBetween follow this link


问:
Create a New Column by evaluating multiple columns
I have a data.frame dt_info that looks like the following:

```<code>date       col_1     col_2    col_3  ... col_100
d/m/y       info1     n/a      n/a   ...  n/a
d/m/y       n/a       n/a     info2  ...  n/a
d/m/y       n/a       n/a       n/a  ...  infon
</code>```

The output I'm looking for should be like this:

```<code>date       col_1     col_2    col_3  ... col_100    new_col
d/m/y       info1     n/a      n/a   ...  n/a         info1
d/m/y       n/a       n/a     info2  ...  n/a         info2
d/m/y       n/a       n/a       n/a  ...  infon       infon
</code>```

I'm using this code line

```<code>dt_info$new_col <- apply(dt_info[2],1, function(x){
ifelse(x != "n/a", x, "")})
</code>```

That kinda do what I want but I have two issues
I'm not able to go do it for each column using [1:n]
If I change Manually the [] index and run the code, the whole column got replaced.

What am I lacking in my script?
Is there another way to achieve what I'm trying to do?

答:
If the value n/a is really the NA value for R, then you may use coalesce here from the dplyr library

```<code>library(dplyr_
dt_info$new_col <- coalesce(dt_info$col_1, dt_info$col_2, ..., dt_info$col_100)
</code>```

If the n/a value be literally there, then you may first convert it to NA, and then use coalesce as above:

```<code>dt_info[dt_info == "n/a"] = NA
dt_info$new_col <- coalesce(dt_info$col_1, dt_info$col_2, ..., dt_info$col_100)
</code>```

Body:
I have a data.frame dt_info that looks like the following:

date       col_1     col_2    col_3  ... col_100
d/m/y       info1     n/a      n/a   ...  n/a
d/m/y       n/a       n/a     info2  ...  n/a
d/m/y       n/a       n/a       n/a  ...  infon

The output I'm looking for should be like this:

date       col_1     col_2    col_3  ... col_100    new_col
d/m/y       info1     n/a      n/a   ...  n/a         info1
d/m/y       n/a       n/a     info2  ...  n/a         info2
d/m/y       n/a       n/a       n/a  ...  infon       infon

I'm using this code line

dt_info$new_col <- apply(dt_info[2],1, function(x){
ifelse(x != "n/a", x, "")})

That kinda do what I want but I have two issues
I'm not able to go do it for each column using [1:n]
If I change Manually the [] index and run the code, the whole column got replaced.

What am I lacking in my script?
Is there another way to achieve what I'm trying to do?

Body:
If the value n/a is really the NA value for R, then you may use coalesce here from the dplyr library

library(dplyr_
dt_info$new_col <- coalesce(dt_info$col_1, dt_info$col_2, ..., dt_info$col_100)

If the n/a value be literally there, then you may first convert it to NA, and then use coalesce as above:

dt_info[dt_info == "n/a"] = NA
dt_info$new_col <- coalesce(dt_info$col_1, dt_info$col_2, ..., dt_info$col_100)


问:
TypeError: __init__() got multiple values for argument 'kernel_size' error occured in tensorflow 2.0
```<code>#vgg16
class  VGGBase(Model):
    def __init__(self):
        super(VGGBase,self).__init__()
        self.conv1_1 = tf.keras.layers.Conv2D(3,64, kernel_size=3,padding=1,strides=1),
        self.conv1_2 = tf.keras.layers.Conv2D(64,64, kernel_size=3, padding=1,strides=1),
        self.pool1 = tf.keras.layers.MaxPool2D(2,2),

        self.conv2_1  =  tf.keras.layers.Conv2D(64,128, kernel_size=3, padding=1,strides= 1),
        self.conv2_2 = tf.keras.layers.Conv2D(128,128, kernel_size=3,padding=1,strides= 1),
        self.pool2 = tf.keras.layers.MaxPool2D(2,2),
 def call(self,x):
        x = relu(self.conv1_1(x))
        x = relu(self.conv1_2(x))
        x = relu(self.pool1(x))

        x = relu(self.conv2_1(x))
        x = relu(self.conv2_2(x))
        x = relu(self.pool2(x))
</code>```

This is tensrflow 2.0 and got the error of got
multiple values for argument 'kernel_size"

File "/home/jake/Gits/ssd_tensorflow/model.py", line 10, in init
      self.conv1_1 = tf.keras.layers.Conv2D(3,64, kernel_size=3,padding=1,strides=1,input_shape=input_shape), TypeError:
  init() got multiple values for argument 'kernel_size'

答:
The call signature for Conv2D is long, but starts with Conv2d(filter, kernel_size, ...). You called it with two positional arguments filling in filter and kernel_size and then tried to set kernel_size=3. Since kernel_size was already filled with a positional argument, you got the error.

Kernel size should be a two element tuple. You may have meant

```<code>self.conv1_1 = tf.keras.layers.Conv2D(64, kernel_size=(3,3), padding=1, strides=1),
</code>```

As an aside, self.conv1_1 will be a 1 element tuple, which may be what you want. Otherwise, remove that ending comma.

Body:
#vgg16
class  VGGBase(Model):
    def __init__(self):
        super(VGGBase,self).__init__()
        self.conv1_1 = tf.keras.layers.Conv2D(3,64, kernel_size=3,padding=1,strides=1),
        self.conv1_2 = tf.keras.layers.Conv2D(64,64, kernel_size=3, padding=1,strides=1),
        self.pool1 = tf.keras.layers.MaxPool2D(2,2),

        self.conv2_1  =  tf.keras.layers.Conv2D(64,128, kernel_size=3, padding=1,strides= 1),
        self.conv2_2 = tf.keras.layers.Conv2D(128,128, kernel_size=3,padding=1,strides= 1),
        self.pool2 = tf.keras.layers.MaxPool2D(2,2),
 def call(self,x):
        x = relu(self.conv1_1(x))
        x = relu(self.conv1_2(x))
        x = relu(self.pool1(x))

        x = relu(self.conv2_1(x))
        x = relu(self.conv2_2(x))
        x = relu(self.pool2(x))

This is tensrflow 2.0 and got the error of got
multiple values for argument 'kernel_size"

File "/home/jake/Gits/ssd_tensorflow/model.py", line 10, in init
      self.conv1_1 = tf.keras.layers.Conv2D(3,64, kernel_size=3,padding=1,strides=1,input_shape=input_shape), TypeError:
  init() got multiple values for argument 'kernel_size'

Body:
The call signature for Conv2D is long, but starts with Conv2d(filter, kernel_size, ...). You called it with two positional arguments filling in filter and kernel_size and then tried to set kernel_size=3. Since kernel_size was already filled with a positional argument, you got the error.

Kernel size should be a two element tuple. You may have meant

self.conv1_1 = tf.keras.layers.Conv2D(64, kernel_size=(3,3), padding=1, strides=1),

As an aside, self.conv1_1 will be a 1 element tuple, which may be what you want. Otherwise, remove that ending comma.


问:
Jetpack compose ui : How to create cardview?
I want to create Cardview using jetpack compose but i am not able to find any
example.

答:
in v0.1.0-dev09 version, can be done like this, where the padding of Card sets the margin of the card, the padding of Box sets the padding inside the card.

```<code>Card(
  shape = RoundedCornerShape(8.dp),
  modifier = Modifier.padding(16.dp).fillMaxWidth()
) {
  Box(modifier = Modifier.height(200.dp).padding(16.dp)) {
    Text("This is a card view")
  }
}
</code>```

Body:
in v0.1.0-dev09 version, can be done like this, where the padding of Card sets the margin of the card, the padding of Box sets the padding inside the card.

Card(
  shape = RoundedCornerShape(8.dp),
  modifier = Modifier.padding(16.dp).fillMaxWidth()
) {
  Box(modifier = Modifier.height(200.dp).padding(16.dp)) {
    Text("This is a card view")
  }
}


问:
Linking 64-bit NASM with MinGW-64 causes "File format not recognized" error
I am trying to assemble and link a 64-bit NASM program on Windows using MinGW-64bit with the following batch command:

```<code>nasm -f win64 HelloWorld.asm && "C:\Program Files (x86)\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin\gcc.exe" HelloWorld.obj -o HelloWorld.exe
</code>```

But I get this error:

```<code>HelloWorld.obj: file not recognized: File format not recognized
collect2.exe: error: ld returned 1 exit status
</code>```

How can I fix this?

答: It turns out that, although I downloaded and installed MinGW-64, I still got a 32-bit version because I selected the i686 option upon installation.  I reinstalled with the "x86-64" option and it fixed the problem.</p>

Body:
I am trying to assemble and link a 64-bit NASM program on Windows using MinGW-64bit with the following batch command:

nasm -f win64 HelloWorld.asm && "C:\Program Files (x86)\mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32\bin\gcc.exe" HelloWorld.obj -o HelloWorld.exe

But I get this error:

HelloWorld.obj: file not recognized: File format not recognized
collect2.exe: error: ld returned 1 exit status

How can I fix this?


问:
I cannot center the text of a userdefined Button
I created a Button and I set its UIID to boutonPpal. I set the bgAlign attribute to ALIGN_CENTER in the resource Editor but the text of the Button is not centered at runtime !

So how to make the text centered ?

答: bgAlign aligns the background image of a component. Use the "Align" tab if using the latest LWUIT. If you are using 1.4 you need to actually invoke setAlign() on the component since in 1.4 alignment was not a part of the theme.</p>