问:
Paint frame backround in tkinter GUI, bg=arg location in class and change frames size
where do I need to insert the 'bg="color"' arg to paint the backround of the top frame?

---------------------------------------------------------------------------

---------------------------------------------------------------------------

Code:

```<code>import tkinter as tk
import subprocess as sub
import multiprocessing as mp
import time
import io
import os

class GUI(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.geometry("640x478")
        self.title("Gil Shwartz GUI Project")
        # self.resizable(0, 0)
        menu = tk.Frame(self, height=250, width=10, relief="solid")
        container = tk.Frame(self, relief="flat", height=200, bg="black")

        menu.pack(side=tk.LEFT, fill="both", anchor="w")
        container.pack(side=tk.TOP, fill="both", expand=True)
        menu.grid_columnconfigure(0, weight=1)
        menu.grid_rowconfigure(0, weight=1)

        self.frames = ["Menu", "MainWelcome", "testPing", "PageOne", "UptimeCheck"]

        self.frames[0] = Menu(parent=menu, controller=self)
        self.frames[1] = MainWelcome(parent=container, controller=self)
        self.frames[2] = testPing(parent=container, controller=self)
        self.frames[3] = PageOne(parent=container, controller=self)
        self.frames[4] = UptimeCheck(parent=container, controller=self)

        self.frames[0].grid(row=0, column=0, sticky="nsew")
        self.frames[1].grid(row=0, column=0, sticky="nsew")
        self.frames[2].grid(row=0, column=0, sticky="nsew")
        self.frames[3].grid(row=0, column=0, sticky="nsew")
        self.frames[4].grid(row=0, column=0, sticky="nsew")

        self.show_frame(1)

    def show_frame(self, page_name):
        frame = self.frames[page_name]
        print(frame)
        frame.tkraise()
        frame.grid(row=0, column=0, sticky="nsew")

class Menu(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        button1 = tk.Button(self, text="Ping Test", bg="royalblue2",
                            command=lambda: controller.show_frame(2))
        button2 = tk.Button(self, text="Uptime Check", bg="dark violet",
                            command=lambda: controller.show_frame(4))
        buttun3 = tk.Button(self, text="Home", bg="pale goldenrod",
                            command=lambda : controller.show_frame(1))
        button4 = tk.Button(self, text="Quit", bg="gray40",
                            command=lambda: Menu.terminate(self))

        button1.pack(fill="both", expand=True)
        button2.pack(fill="both", expand=True)
        buttun3.pack(fill="both", expand=True)
        button4.pack(fill="both", expand=True)

        # button1.grid_columnconfigure(0, weight=1)
        # button2.grid_columnconfigure(0, weight=0)
        # button4.grid_rowconfigure(0, weight=0)

    def terminate(self):
        exit()

class MainWelcome(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        canvas = tk.Canvas(self, bg="black")
        canvas.pack(expand=True, fill="both")

        # img = Image.open(fr'c:/users/{os.getlogin()}/Desktop/gil.jpg')
        # self.photo = ImageTk.PhotoImage(img)
        # canvas.create_image((0, 0), image=photo, anchor="center")

class testPing(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent, bg="skyblue1")
        self.controller = controller

        self.output = tk.LabelFrame(self, text="Output", height=325, width=580, padx=3, pady=3)
        self.output.pack(side=tk.BOTTOM, fill="both", expand=True)
        # self.output.update()
        self.textbox = tk.Text(self, height=320, width=550, pady=3, padx=3)
        self.textbox.pack(side=tk.BOTTOM, fill="both", expand=True)

        clearFile = tk.BooleanVar()
        clearFile.set(False)
        urlLabel = tk.Label(self, text="Enter URL : ", padx=7, pady=5, bg="skyblue1")
        urlInputBox = tk.Entry(self)
        urlInputBox.grid_columnconfigure(0, weight=0)
        fileNameLabel = tk.Label(self, text="Enter Filename: ", bg="skyblue1")
        fileNameInputBox = tk.Entry(self)
        clearFileLabel = tk.Label(self, text="Clear File?", padx=5, pady=5, bg="skyblue1")
        clearFileRadioYes = tk.Radiobutton(self, text="yes", value=True, var=clearFile, bg="skyblue1",
                                           command=lambda: self.callback(clearFile.get()))
        clearFileRadioNo = tk.Radiobutton(self, text="no", value=False, var=clearFile, bg="skyblue1",
                                          command=lambda: self.callback(clearFile.get()))
        urlSubmitButton = tk.Button(self, text="Submit", width=10, height=2,
                                    command=lambda: self.pingURL(urlInputBox.get(),
                                                                 clearFile.get(), fileNameInputBox.get()))
        clearFieldsButton = tk.Button(self, text="Clear Fields", padx=5, pady=5,
                                      command=lambda: self.clear_boxes(urlInputBox, fileNameInputBox))

        urlLabel.pack(anchor="w")
        urlInputBox.pack(anchor="w", padx=10)
        fileNameLabel.pack(anchor="w", padx=7, pady=5)
        fileNameInputBox.pack(anchor="w", padx=10)
        clearFileLabel.pack(anchor="w")
        clearFileRadioYes.pack(anchor="w")
        clearFileRadioNo.pack(anchor="w")
        urlSubmitButton.pack(anchor="w", pady=1)
        clearFieldsButton.pack(anchor="w")

    @classmethod
    def clear_boxes(self, urlInputBox, fileNameInputBox):
        urlInputBox.delete(0, "end")
        fileNameInputBox.delete(0, "end")

    @classmethod
    def callback(self, clearFile):
        print(f'Clear file = {clearFile}')  # Debugging Mode - check Radio box Var.

    def pingURL(self, host, clearFile, filenameInputBox):

        print(clearFile, filenameInputBox)  # Debugging - Input Validation
        if clearFile is True and filenameInputBox == '':
            self.handler_clr_yes_fn_no(host)
        elif clearFile is False and filenameInputBox == '':
            self.handler_clr_no_fn_no(host)
        elif clearFile is True and filenameInputBox != '':
            self.handler_clr_yes_fn_yes(host, filenameInputBox)
        elif clearFile is False and filenameInputBox != '':
            self.handler_clr_no_fn_yes(host, filenameInputBox)

    def handler_clr_yes_fn_no(self, host):

        startprocs = []
        # nextprocs = []
        lastprocs = []

        proc1 = mp.Process(name="Clear + No Filename + WriteFile",
                           target=self.clr_yes_fn_no_writefile, args=(host,))
        proc2 = mp.Process(name="Clear + No Filename + PrintOutput",
                          target=self.clr_yes_fn_no_print_output, args=(host,))
        # proc3 = mp.Process(name="Clear + No Filename + Generate PrintOutput to GUI",
        #                    target=self.generate_clr_yes_fn_no_print_output_to_gui, args=(host,))
        # proc4 = mp.Process(name="Clear + No Filename + PrintOutput to GUI",
        #                    target=self.clr_yes_fn_no_print_output_to_gui, args=(host,))
        proc5 = mp.Process(name="Remove first line + Write new default file",
                           target=self.delete_default_lines)

        startprocs.append(proc1)
        startprocs.append(proc2)
        # startprocs.append(proc3)
        # startprocs.append(proc4)

        # nextprocs.append(proc1)

        lastprocs.append(proc5)

        for s in startprocs:
            s.start()

        for s2 in startprocs:
            s2.join()

        # for n in nextprocs:
        #     n.start()
        #
        # for p in nextprocs:
        #     p.join()

        for l in lastprocs:
            l.start()

    def handler_clr_no_fn_no(self, host):

        procs = []
        nextprocs = []

        proc1 = mp.Process(name="Append to default file",
                           target=self.clr_no_fn_no_writefile, args=(host,))
        proc2 = mp.Process(name="Print Output", target=self.clr_no_fn_no_printoutput, args=(host,))

        procs.append(proc1)
        procs.append(proc2)

        for proc in procs:
            proc.start()
        for proc in procs:
            proc.join()

        for p in nextprocs:
            p.start()

    def handler_clr_yes_fn_yes(self, host, filenameInputBox):

        procs = []
        nextprocs = []

        proc1 = mp.Process(name="Clear file + userFilename + Write to file",
                           target=self.clr_yes_fn_yes_writefile, args=(host, filenameInputBox,))
        proc2 = mp.Process(name="Clear file + user filename + Print output",
                           target=self.clr_yes_fn_yes_printoutput, args=(host,))
        proc3 = mp.Process(name="Remove Empty Lines from user filename",
                           target=self.delete_userfile_lines, args=(filenameInputBox,))

        procs.append(proc1)
        procs.append(proc2)
        nextprocs.append(proc3)

        for proc in procs:
            proc.start()

        for p in procs:
            p.join()

        for np in nextprocs:
            np.start()

    def handler_clr_no_fn_yes(self, host, filenameInputBox):

        procs = []
        nextprocs = []

        proc1 = mp.Process(name="Keep File + Userfilename + Append to Userfile",
                           target=self.clr_no_fn_yes_writefile, args=(host, filenameInputBox,))
        proc2 = mp.Process(name="Keep File + Userfilename + Print Output",
                           target=self.clr_no_fn_yes_printoutput, args=(host,))

        proc3 = mp.Process(name="Remove first line + Write new default file",
                           target=self.delete_userfile_lines, args=(filenameInputBox,))

        procs.append(proc1)
        procs.append(proc2)

        nextprocs.append(proc3)

        for p in procs:
            p.start()

        for p2 in procs:
            p2.join()

        for n in nextprocs:
            n.start()

    @classmethod
    def delete_default_lines(cls):

        time.sleep(2)
        print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}')
        file = fr'c:/users/{os.getlogin()}/Desktop/default-tmp.txt'
        newfile = fr'c:/users/{os.getlogin()}/Desktop/default.txt'

        with open(file, 'r') as inp, open(newfile, 'w+') as out:
            for line in inp:
                if not line.isspace():
                    out.write(line.lstrip())
                    out.write('')
            inp.close()
            out.close()
        os.remove(file)

    @classmethod
    def delete_userfile_lines(cls, filename):

        time.sleep(2)
        print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}')
        file = fr'c:/users/{os.getlogin()}/Desktop/{filename}-tmp.txt'
        newfile = fr'c:/users/{os.getlogin()}/Desktop/{filename}.txt'

        with open(file, 'r') as inp, open(newfile, 'w+') as out:
            for line in inp:
                if not line.isspace():
                    out.write(line.lstrip())
                    out.write('')
            inp.close()
            out.close()

    @classmethod
    def clr_yes_fn_no_print_output(self, host):

        print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}\n')
        with sub.Popen(["ping", "-n", "4", f'{host}'], stdout=sub.PIPE,
                       bufsize=1, universal_newlines=True, stderr=sub.STDOUT) as p:
            for line in p.stdout:
                print(line, end=' ')

    @classmethod
    def generate_clr_yes_fn_no_print_output_to_gui(self, host):
        print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}\n')

        sub.run(f"ping {host}", shell=True, capture_output=True)

    def clr_yes_fn_no_print_output_to_gui(self):
        tk.Frame.__init__(self, parent)
        self.textbox.insert(tk.END, proc.stdout.decode())

    @classmethod
    def clr_yes_fn_no_writefile(self, host):

        print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}\n')
        file = fr'c:/users/{os.getlogin()}/Desktop/default-tmp.txt'
        ping = sub.Popen(["ping", "-n", '4', f'{host}'], stdout=sub.PIPE)
        with open(file, 'w+') as output:
            data = output.read()
            for line in ping.stdout.readlines():
                data += str(line.decode())
            ping.stdout.close()
            output.seek(0)
            output.write(data.lstrip())

    @classmethod
    def clr_no_fn_no_printoutput(self, host):

        print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}\n')
        with sub.Popen(["ping", "-n", '4', f'{host}'], stdout=sub.PIPE,
                       bufsize=1, universal_newlines=True, stderr=sub.STDOUT) as p:
            for line in p.stdout:
                print(line, end=' ')

    @classmethod
    def clr_no_fn_no_writefile(self, host):

        print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}')
        print("Append to file function")

        with open(fr'c:/users/{os.getlogin()}/Desktop/default.txt', 'a') as output:
            sub.call(["ping", "-n", '4', f'{host}'], stdout=output)

    @classmethod
    def clr_yes_fn_yes_printoutput(self, host):

        with sub.Popen(["ping", "-n", '4', f'{host}'], stdout=sub.PIPE,
                       bufsize=1, universal_newlines=True, stderr=sub.STDOUT) as p:
            for line in p.stdout:
                print(line, end=' ')

    @classmethod
    def clr_yes_fn_yes_writefile(self, host, filename):

        file = fr'c:/users/{os.getlogin()}/Desktop/{filename}-tmp.txt'
        with open(file, 'w') as output:
            sub.call(["ping", "-n", '4', f'{host}'], stdout=output)

    @classmethod
    def clr_no_fn_yes_printoutput(self, host):

        with sub.Popen(["ping", "-n", '4', f'{host}'], stdout=sub.PIPE,
                       bufsize=1, universal_newlines=True, stderr=sub.STDOUT) as p:
            for line in p.stdout:
                print(line, end=' ')

    @classmethod
    def clr_no_fn_yes_writefile(self, host, filename):

        with open(fr'c:/users/{os.getlogin()}/Desktop/{filename}.txt', 'a') as output:
            sub.call(["ping", "-n", '4', f'{host}'], stdout=output)

class UptimeCheck(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        frame = tk.LabelFrame(self, text="This is page 2", bg="honeydew3", relief="flat")
        frame.pack(fill="both", expand=True)

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", bg="red")
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to page 2",
                           command=lambda: controller.show_frame(2))
        button.pack()

if __name__ == "__main__":
    app = GUI()
    app.mainloop()
</code>```

Update

following  acw1668's answer, how can i make the upper frame 3/4 of the screen instead of 1/2?

答:
Either specify it in the __init__():

```<code>tk.Frame.__init__(self, parent, bg=...)
</code>```

Or configure it separately:

```<code>tk.Frame.__init__(self, parent)
self.config(bg=...)
</code>```

Body:
where do I need to insert the 'bg="color"' arg to paint the backround of the top frame?

---------------------------------------------------------------------------

---------------------------------------------------------------------------

Code:

import tkinter as tk
import subprocess as sub
import multiprocessing as mp
import time
import io
import os

class GUI(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.geometry("640x478")
        self.title("Gil Shwartz GUI Project")
        # self.resizable(0, 0)
        menu = tk.Frame(self, height=250, width=10, relief="solid")
        container = tk.Frame(self, relief="flat", height=200, bg="black")

        menu.pack(side=tk.LEFT, fill="both", anchor="w")
        container.pack(side=tk.TOP, fill="both", expand=True)
        menu.grid_columnconfigure(0, weight=1)
        menu.grid_rowconfigure(0, weight=1)

        self.frames = ["Menu", "MainWelcome", "testPing", "PageOne", "UptimeCheck"]

        self.frames[0] = Menu(parent=menu, controller=self)
        self.frames[1] = MainWelcome(parent=container, controller=self)
        self.frames[2] = testPing(parent=container, controller=self)
        self.frames[3] = PageOne(parent=container, controller=self)
        self.frames[4] = UptimeCheck(parent=container, controller=self)

        self.frames[0].grid(row=0, column=0, sticky="nsew")
        self.frames[1].grid(row=0, column=0, sticky="nsew")
        self.frames[2].grid(row=0, column=0, sticky="nsew")
        self.frames[3].grid(row=0, column=0, sticky="nsew")
        self.frames[4].grid(row=0, column=0, sticky="nsew")

        self.show_frame(1)

    def show_frame(self, page_name):
        frame = self.frames[page_name]
        print(frame)
        frame.tkraise()
        frame.grid(row=0, column=0, sticky="nsew")

class Menu(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        button1 = tk.Button(self, text="Ping Test", bg="royalblue2",
                            command=lambda: controller.show_frame(2))
        button2 = tk.Button(self, text="Uptime Check", bg="dark violet",
                            command=lambda: controller.show_frame(4))
        buttun3 = tk.Button(self, text="Home", bg="pale goldenrod",
                            command=lambda : controller.show_frame(1))
        button4 = tk.Button(self, text="Quit", bg="gray40",
                            command=lambda: Menu.terminate(self))

        button1.pack(fill="both", expand=True)
        button2.pack(fill="both", expand=True)
        buttun3.pack(fill="both", expand=True)
        button4.pack(fill="both", expand=True)

        # button1.grid_columnconfigure(0, weight=1)
        # button2.grid_columnconfigure(0, weight=0)
        # button4.grid_rowconfigure(0, weight=0)

    def terminate(self):
        exit()

class MainWelcome(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        canvas = tk.Canvas(self, bg="black")
        canvas.pack(expand=True, fill="both")

        # img = Image.open(fr'c:/users/{os.getlogin()}/Desktop/gil.jpg')
        # self.photo = ImageTk.PhotoImage(img)
        # canvas.create_image((0, 0), image=photo, anchor="center")

class testPing(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent, bg="skyblue1")
        self.controller = controller

        self.output = tk.LabelFrame(self, text="Output", height=325, width=580, padx=3, pady=3)
        self.output.pack(side=tk.BOTTOM, fill="both", expand=True)
        # self.output.update()
        self.textbox = tk.Text(self, height=320, width=550, pady=3, padx=3)
        self.textbox.pack(side=tk.BOTTOM, fill="both", expand=True)

        clearFile = tk.BooleanVar()
        clearFile.set(False)
        urlLabel = tk.Label(self, text="Enter URL : ", padx=7, pady=5, bg="skyblue1")
        urlInputBox = tk.Entry(self)
        urlInputBox.grid_columnconfigure(0, weight=0)
        fileNameLabel = tk.Label(self, text="Enter Filename: ", bg="skyblue1")
        fileNameInputBox = tk.Entry(self)
        clearFileLabel = tk.Label(self, text="Clear File?", padx=5, pady=5, bg="skyblue1")
        clearFileRadioYes = tk.Radiobutton(self, text="yes", value=True, var=clearFile, bg="skyblue1",
                                           command=lambda: self.callback(clearFile.get()))
        clearFileRadioNo = tk.Radiobutton(self, text="no", value=False, var=clearFile, bg="skyblue1",
                                          command=lambda: self.callback(clearFile.get()))
        urlSubmitButton = tk.Button(self, text="Submit", width=10, height=2,
                                    command=lambda: self.pingURL(urlInputBox.get(),
                                                                 clearFile.get(), fileNameInputBox.get()))
        clearFieldsButton = tk.Button(self, text="Clear Fields", padx=5, pady=5,
                                      command=lambda: self.clear_boxes(urlInputBox, fileNameInputBox))

        urlLabel.pack(anchor="w")
        urlInputBox.pack(anchor="w", padx=10)
        fileNameLabel.pack(anchor="w", padx=7, pady=5)
        fileNameInputBox.pack(anchor="w", padx=10)
        clearFileLabel.pack(anchor="w")
        clearFileRadioYes.pack(anchor="w")
        clearFileRadioNo.pack(anchor="w")
        urlSubmitButton.pack(anchor="w", pady=1)
        clearFieldsButton.pack(anchor="w")

    @classmethod
    def clear_boxes(self, urlInputBox, fileNameInputBox):
        urlInputBox.delete(0, "end")
        fileNameInputBox.delete(0, "end")

    @classmethod
    def callback(self, clearFile):
        print(f'Clear file = {clearFile}')  # Debugging Mode - check Radio box Var.

    def pingURL(self, host, clearFile, filenameInputBox):

        print(clearFile, filenameInputBox)  # Debugging - Input Validation
        if clearFile is True and filenameInputBox == '':
            self.handler_clr_yes_fn_no(host)
        elif clearFile is False and filenameInputBox == '':
            self.handler_clr_no_fn_no(host)
        elif clearFile is True and filenameInputBox != '':
            self.handler_clr_yes_fn_yes(host, filenameInputBox)
        elif clearFile is False and filenameInputBox != '':
            self.handler_clr_no_fn_yes(host, filenameInputBox)

    def handler_clr_yes_fn_no(self, host):

        startprocs = []
        # nextprocs = []
        lastprocs = []

        proc1 = mp.Process(name="Clear + No Filename + WriteFile",
                           target=self.clr_yes_fn_no_writefile, args=(host,))
        proc2 = mp.Process(name="Clear + No Filename + PrintOutput",
                          target=self.clr_yes_fn_no_print_output, args=(host,))
        # proc3 = mp.Process(name="Clear + No Filename + Generate PrintOutput to GUI",
        #                    target=self.generate_clr_yes_fn_no_print_output_to_gui, args=(host,))
        # proc4 = mp.Process(name="Clear + No Filename + PrintOutput to GUI",
        #                    target=self.clr_yes_fn_no_print_output_to_gui, args=(host,))
        proc5 = mp.Process(name="Remove first line + Write new default file",
                           target=self.delete_default_lines)

        startprocs.append(proc1)
        startprocs.append(proc2)
        # startprocs.append(proc3)
        # startprocs.append(proc4)

        # nextprocs.append(proc1)

        lastprocs.append(proc5)

        for s in startprocs:
            s.start()

        for s2 in startprocs:
            s2.join()

        # for n in nextprocs:
        #     n.start()
        #
        # for p in nextprocs:
        #     p.join()

        for l in lastprocs:
            l.start()

    def handler_clr_no_fn_no(self, host):

        procs = []
        nextprocs = []

        proc1 = mp.Process(name="Append to default file",
                           target=self.clr_no_fn_no_writefile, args=(host,))
        proc2 = mp.Process(name="Print Output", target=self.clr_no_fn_no_printoutput, args=(host,))

        procs.append(proc1)
        procs.append(proc2)

        for proc in procs:
            proc.start()
        for proc in procs:
            proc.join()

        for p in nextprocs:
            p.start()

    def handler_clr_yes_fn_yes(self, host, filenameInputBox):

        procs = []
        nextprocs = []

        proc1 = mp.Process(name="Clear file + userFilename + Write to file",
                           target=self.clr_yes_fn_yes_writefile, args=(host, filenameInputBox,))
        proc2 = mp.Process(name="Clear file + user filename + Print output",
                           target=self.clr_yes_fn_yes_printoutput, args=(host,))
        proc3 = mp.Process(name="Remove Empty Lines from user filename",
                           target=self.delete_userfile_lines, args=(filenameInputBox,))

        procs.append(proc1)
        procs.append(proc2)
        nextprocs.append(proc3)

        for proc in procs:
            proc.start()

        for p in procs:
            p.join()

        for np in nextprocs:
            np.start()

    def handler_clr_no_fn_yes(self, host, filenameInputBox):

        procs = []
        nextprocs = []

        proc1 = mp.Process(name="Keep File + Userfilename + Append to Userfile",
                           target=self.clr_no_fn_yes_writefile, args=(host, filenameInputBox,))
        proc2 = mp.Process(name="Keep File + Userfilename + Print Output",
                           target=self.clr_no_fn_yes_printoutput, args=(host,))

        proc3 = mp.Process(name="Remove first line + Write new default file",
                           target=self.delete_userfile_lines, args=(filenameInputBox,))

        procs.append(proc1)
        procs.append(proc2)

        nextprocs.append(proc3)

        for p in procs:
            p.start()

        for p2 in procs:
            p2.join()

        for n in nextprocs:
            n.start()

    @classmethod
    def delete_default_lines(cls):

        time.sleep(2)
        print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}')
        file = fr'c:/users/{os.getlogin()}/Desktop/default-tmp.txt'
        newfile = fr'c:/users/{os.getlogin()}/Desktop/default.txt'

        with open(file, 'r') as inp, open(newfile, 'w+') as out:
            for line in inp:
                if not line.isspace():
                    out.write(line.lstrip())
                    out.write('')
            inp.close()
            out.close()
        os.remove(file)

    @classmethod
    def delete_userfile_lines(cls, filename):

        time.sleep(2)
        print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}')
        file = fr'c:/users/{os.getlogin()}/Desktop/{filename}-tmp.txt'
        newfile = fr'c:/users/{os.getlogin()}/Desktop/{filename}.txt'

        with open(file, 'r') as inp, open(newfile, 'w+') as out:
            for line in inp:
                if not line.isspace():
                    out.write(line.lstrip())
                    out.write('')
            inp.close()
            out.close()

    @classmethod
    def clr_yes_fn_no_print_output(self, host):

        print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}\n')
        with sub.Popen(["ping", "-n", "4", f'{host}'], stdout=sub.PIPE,
                       bufsize=1, universal_newlines=True, stderr=sub.STDOUT) as p:
            for line in p.stdout:
                print(line, end=' ')

    @classmethod
    def generate_clr_yes_fn_no_print_output_to_gui(self, host):
        print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}\n')

        sub.run(f"ping {host}", shell=True, capture_output=True)

    def clr_yes_fn_no_print_output_to_gui(self):
        tk.Frame.__init__(self, parent)
        self.textbox.insert(tk.END, proc.stdout.decode())

    @classmethod
    def clr_yes_fn_no_writefile(self, host):

        print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}\n')
        file = fr'c:/users/{os.getlogin()}/Desktop/default-tmp.txt'
        ping = sub.Popen(["ping", "-n", '4', f'{host}'], stdout=sub.PIPE)
        with open(file, 'w+') as output:
            data = output.read()
            for line in ping.stdout.readlines():
                data += str(line.decode())
            ping.stdout.close()
            output.seek(0)
            output.write(data.lstrip())

    @classmethod
    def clr_no_fn_no_printoutput(self, host):

        print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}\n')
        with sub.Popen(["ping", "-n", '4', f'{host}'], stdout=sub.PIPE,
                       bufsize=1, universal_newlines=True, stderr=sub.STDOUT) as p:
            for line in p.stdout:
                print(line, end=' ')

    @classmethod
    def clr_no_fn_no_writefile(self, host):

        print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}')
        print("Append to file function")

        with open(fr'c:/users/{os.getlogin()}/Desktop/default.txt', 'a') as output:
            sub.call(["ping", "-n", '4', f'{host}'], stdout=output)

    @classmethod
    def clr_yes_fn_yes_printoutput(self, host):

        with sub.Popen(["ping", "-n", '4', f'{host}'], stdout=sub.PIPE,
                       bufsize=1, universal_newlines=True, stderr=sub.STDOUT) as p:
            for line in p.stdout:
                print(line, end=' ')

    @classmethod
    def clr_yes_fn_yes_writefile(self, host, filename):

        file = fr'c:/users/{os.getlogin()}/Desktop/{filename}-tmp.txt'
        with open(file, 'w') as output:
            sub.call(["ping", "-n", '4', f'{host}'], stdout=output)

    @classmethod
    def clr_no_fn_yes_printoutput(self, host):

        with sub.Popen(["ping", "-n", '4', f'{host}'], stdout=sub.PIPE,
                       bufsize=1, universal_newlines=True, stderr=sub.STDOUT) as p:
            for line in p.stdout:
                print(line, end=' ')

    @classmethod
    def clr_no_fn_yes_writefile(self, host, filename):

        with open(fr'c:/users/{os.getlogin()}/Desktop/{filename}.txt', 'a') as output:
            sub.call(["ping", "-n", '4', f'{host}'], stdout=output)

class UptimeCheck(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        frame = tk.LabelFrame(self, text="This is page 2", bg="honeydew3", relief="flat")
        frame.pack(fill="both", expand=True)

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", bg="red")
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to page 2",
                           command=lambda: controller.show_frame(2))
        button.pack()

if __name__ == "__main__":
    app = GUI()
    app.mainloop()

Update

following  acw1668's answer, how can i make the upper frame 3/4 of the screen instead of 1/2?

Body:
Either specify it in the __init__():

tk.Frame.__init__(self, parent, bg=...)

Or configure it separately:

tk.Frame.__init__(self, parent)
self.config(bg=...)


来源: stackexchange

问:
Karma , Istanbul - code coverage report Unknown% ( 0/0 )
I'm getting this Coverage Summary

```<code>=============================== Coverage summary ===============================
Statements   : Unknown% ( 0/0 )
Branches     : Unknown% ( 0/0 )
Functions    : Unknown% ( 0/0 )
Lines        : Unknown% ( 0/0 )
================================================================================
</code>```

I applied the changes instructed in the Angular Documentation for code
coverage:
https://angular.io/guide/testing#enable-code-coverage-report

but I keep getting the same empty summery.

my karma.conf.js

```<code>module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, './coverage/singleWindow'),
      reports: ['html', 'lcovonly', 'text-summary'],
      fixWebpackSourcePaths: true,
      thresholds: {
        statements: 80,
        lines: 80,
        branches: 80,
        functions: 80
      }
       },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    restartOnFileChange: true,
});
}
</code>```

答:
I had the same issue with Angular 7 when running tests using ng test.

As it turns out, Angular CLI disable code coverage by default. You have to start your tests using ng test --code-coverage for it to work.

You can make it always on by adding "codeCoverage": true to the test task of your angular.json file:

```<code>{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "name-of-your-app": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "architect": {
        "build": {
          /* ... */
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "./karma.conf.js",
            "scripts": [],
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "codeCoverage": true
          }
        }
      }
    }
  }
}
</code>```

For more informations: https://angular.io/guide/testing#enable-code-coverage-reports

ContentLicense: CC BY-SA 4.0

Body:
I'm getting this Coverage Summary

=============================== Coverage summary ===============================
Statements   : Unknown% ( 0/0 )
Branches     : Unknown% ( 0/0 )
Functions    : Unknown% ( 0/0 )
Lines        : Unknown% ( 0/0 )
================================================================================

I applied the changes instructed in the Angular Documentation for code
coverage:
https://angular.io/guide/testing#enable-code-coverage-report

but I keep getting the same empty summery.

my karma.conf.js

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, './coverage/singleWindow'),
      reports: ['html', 'lcovonly', 'text-summary'],
      fixWebpackSourcePaths: true,
      thresholds: {
        statements: 80,
        lines: 80,
        branches: 80,
        functions: 80
      }
       },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    restartOnFileChange: true,
});
}

Body:
I had the same issue with Angular 7 when running tests using ng test.

As it turns out, Angular CLI disable code coverage by default. You have to start your tests using ng test --code-coverage for it to work.

You can make it always on by adding "codeCoverage": true to the test task of your angular.json file:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "name-of-your-app": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "architect": {
        "build": {
          /* ... */
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "./karma.conf.js",
            "scripts": [],
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "codeCoverage": true
          }
        }
      }
    }
  }
}

For more informations: https://angular.io/guide/testing#enable-code-coverage-reports


问:
Function to convert units based on conversion table
There is a very simple table in the database with metric unit conversions, that looks like:

| UnitFrom | UnitTo | Scale |
|    m     |   mm   |  1000 |
|    m     |   cm   |   100 |
    etc.
```

<p>I was thinking about creating a function to convert units that calculates the conversion from the table based on inputs (Unit, FromUnit, ToUnit).<br>
For example <code>Conv_Units(0.1, 'm', 'cm')</code> returns 100.</p>

<p>Is this even possible? What I came up with is following, but it does not work:</p>

<pre class="lang-sql prettyprint-override"><code>CREATE FUNCTION dbo.Conv_Units
(
    [@Unit] float
    , [@FromUnit] nvarchar(20)
    , [@ToUnit] nvarchar(20)
);
RETURNS float
AS
BEGIN

    DECLARE @ConvUnit float;
    DECLARE @Unit float;
    DECLARE @FromUnit nvarchar(20);
    DECLARE @ToUnit nvarchar(20);
    DECLARE @Scale float = (select Scale from dbo.UnitsConversion where FromUnit = @FromUnit and ToUnit = @ToUnit);

    SELECT @ConvUnit = @Unit * @Scale

    RETURN @ConvUnit

END
GO
</code>```

答:
Thanks @GSerg for the solution.

That was it:

```<code>CREATE FUNCTION dbo.Conv_Units(@Unit float, @FromUnit nvarchar(20), @ToUnit nvarchar(20))
RETURNS float
AS
BEGIN
    DECLARE @ConvUnit float;
    DECLARE @Scale float = (select Scale from dbo.UnitsConversion where FromUnit = @FromUnit and ToUnit = @ToUnit)

    SELECT @ConvUnit = @Unit * @Scale

    RETURN @ConvUnit

END
GO
</code>```

Body:
There is a very simple table in the database with metric unit conversions, that looks like:

| UnitFrom | UnitTo | Scale |
|    m     |   mm   |  1000 |
|    m     |   cm   |   100 |
    etc.

I was thinking about creating a function to convert units that calculates the conversion from the table based on inputs (Unit, FromUnit, ToUnit).

For example Conv_Units(0.1, 'm', 'cm') returns 100.

Is this even possible? What I came up with is following, but it does not work:

CREATE FUNCTION dbo.Conv_Units
(
    [@Unit] float
    , [@FromUnit] nvarchar(20)
    , [@ToUnit] nvarchar(20)
);
RETURNS float
AS
BEGIN

    DECLARE @ConvUnit float;
    DECLARE @Unit float;
    DECLARE @FromUnit nvarchar(20);
    DECLARE @ToUnit nvarchar(20);
    DECLARE @Scale float = (select Scale from dbo.UnitsConversion where FromUnit = @FromUnit and ToUnit = @ToUnit);

    SELECT @ConvUnit = @Unit * @Scale

    RETURN @ConvUnit

END
GO

Body:
Thanks @GSerg for the solution.

That was it:

CREATE FUNCTION dbo.Conv_Units(@Unit float, @FromUnit nvarchar(20), @ToUnit nvarchar(20))
RETURNS float
AS
BEGIN
    DECLARE @ConvUnit float;
    DECLARE @Scale float = (select Scale from dbo.UnitsConversion where FromUnit = @FromUnit and ToUnit = @ToUnit)

    SELECT @ConvUnit = @Unit * @Scale

    RETURN @ConvUnit

END
GO


问:
How do I grab an index from an array in a HashMap?
I've got a HashMap<Object, String[]> I just want to grab the 0 index position from the String[]. How do I do that?

Can I just do this? mMap.get(position)[0]?

答: Yes, you can do what you've indicated, provided position is a key in the map.

ContentLicense: CC BY-SA 3.0


问:
Getting the string in the middle of two other strings in Python
I need to find the string in between two other strings. How could I do this?

```<code>string = "vHELLOv"
</code>```

Finding "HELLO" which is in between of two lowercase "v"'s

Another example could be:

```<code>string = "/World/"
</code>```

Finding "World" in the middle of the two "/"s

答:
To remove punctuation, you could use the following regex expression in Python:</p>

```<code>import re
s = "/World/"
new_s = re.sub(r'\W', "", s)
</code>```

Body:
I need to find the string in between two other strings. How could I do this?

string = "vHELLOv"

Finding "HELLO" which is in between of two lowercase "v"'s

Another example could be:

string = "/World/"

Finding "World" in the middle of the two "/"s

Body:
To remove punctuation, you could use the following regex expression in Python:

import re
s = "/World/"
new_s = re.sub(r'\W', "", s)


问:
How can I fix my problem with merging channels in OpenCv in Python?
I simply imported an image.
I want to merge each BGR channel with zero arrays and then show them.
I've written my code as follows:

```<code>import cv2
import numpy as np
image = cv2.imread('./images/input.jpg')

B, G, R = cv2.split(image)

zeros = np.zeros((image.shape[:2]), dtype = 'int8')

cv2.imshow("Red", cv2.merge([zeros1, zeros1, R]))
cv2.imshow("Green", cv2.merge([zeros, G, zeros]))
cv2.imshow("Blue", cv2.merge([B, zeros, zeros]))

cv2.waitKey(500)
cv2.destroyAllWindows()
</code>```

After running this code I get the following error.

```<code>error                                     Traceback (most recent call last)
<ipython-input-13-9252d63ed763> in <module>
      7 zeros = np.zeros((image.shape[:2]), dtype = 'int8')
      8
----> 9 cv2.imshow("Red", cv2.merge([zeros1, zeros1, R]))
     10 cv2.imshow("Green", cv2.merge([zeros, G, zeros]))
     11 cv2.imshow("Blue", cv2.merge([B, zeros, zeros]))

error: OpenCV(4.1.1) C:\projects\opencv-python\opencv\modules\core\src\merge.dispatch.cpp:129: error: (-215:Assertion failed) mv[i].size == mv[0].size && mv[i].depth() == depth in function 'cv::merge'
</code>```

It seems correct to me. what is the problem and how can I Fix this?

答:
here's the error:

zeros = np.zeros((image.shape[:2]), dtype = 'int8')
```

<p>dtype should be the same as the image so <code>uint8</code>.</p>

<p>BTW I think you want to just show the image and you don't care about merging? </p>

<p>Then you can just do the convert from GRAY to BGR with a single channel:</p>

```cv2.imshow("Red", cv2.cvtColor(R, cv2.COLOR_GRAY2BGR))
cv2.imshow("Green", cv2.cvtColor(G, cv2.COLOR_GRAY2BGR))
cv2.imshow("Blue", cv2.cvtColor(B, cv2.COLOR_GRAY2BGR))
```

Body:
I simply imported an image.
I want to merge each BGR channel with zero arrays and then show them.
I've written my code as follows:

import cv2
import numpy as np
image = cv2.imread('./images/input.jpg')

B, G, R = cv2.split(image)

zeros = np.zeros((image.shape[:2]), dtype = 'int8')

cv2.imshow("Red", cv2.merge([zeros1, zeros1, R]))
cv2.imshow("Green", cv2.merge([zeros, G, zeros]))
cv2.imshow("Blue", cv2.merge([B, zeros, zeros]))

cv2.waitKey(500)
cv2.destroyAllWindows()

After running this code I get the following error.

error                                     Traceback (most recent call last)
<ipython-input-13-9252d63ed763> in <module>
      7 zeros = np.zeros((image.shape[:2]), dtype = 'int8')
      8
----> 9 cv2.imshow("Red", cv2.merge([zeros1, zeros1, R]))
     10 cv2.imshow("Green", cv2.merge([zeros, G, zeros]))
     11 cv2.imshow("Blue", cv2.merge([B, zeros, zeros]))

error: OpenCV(4.1.1) C:\projects\opencv-python\opencv\modules\core\src\merge.dispatch.cpp:129: error: (-215:Assertion failed) mv[i].size == mv[0].size && mv[i].depth() == depth in function 'cv::merge'

It seems correct to me. what is the problem and how can I Fix this?

Body:
here's the error:

zeros = np.zeros((image.shape[:2]), dtype = 'int8')

dtype should be the same as the image so uint8.

BTW I think you want to just show the image and you don't care about merging?

Then you can just do the convert from GRAY to BGR with a single channel:

cv2.imshow("Red", cv2.cvtColor(R, cv2.COLOR_GRAY2BGR))
cv2.imshow("Green", cv2.cvtColor(G, cv2.COLOR_GRAY2BGR))
cv2.imshow("Blue", cv2.cvtColor(B, cv2.COLOR_GRAY2BGR))


问:
When should I use a NoSQL database instead of a relational database? Is it okay to use both on the same site?
What are the advantages of using NoSQL databases? I've read a lot about them lately, but I'm still unsure why I would want to implement one, and under what circumstances I would want to use one.</p>

答:
Handling A Large Number Of Read Write Operations

Look towards NoSQL databases when you need to scale fast. And when do you generally need to scale fast?

When there are a large number of read-write operations on your website & when dealing with a large amount of data, NoSQL databases fit best in these scenarios. Since they have the ability to add nodes on the fly, they can handle more concurrent traffic & big amount of data with minimal latency.

Flexibility With Data Modeling

The second cue is during the initial phases of development when you are not sure about the data model, the database design, things are expected to change at a rapid pace. NoSQL databases offer us more flexibility.

Eventual Consistency Over Strong Consistency

It’s preferable to pick NoSQL databases when it’s OK for us to give up on Strong consistency and when we do not require transactions.

A good example of this is a social networking website like Twitter. When a tweet of a celebrity blows up and everyone is liking and re-tweeting it from around the world. Does it matter if the count of likes goes up or down a bit for a short while?

The celebrity would definitely not care if instead of the actual 5 million 500 likes, the system shows the like count as 5 million 250 for a short while.

When a large application is deployed on hundreds of servers spread across the globe, the geographically distributed nodes take some time to reach a global consensus.

Until they reach a consensus, the value of the entity is inconsistent. The value of the entity eventually gets consistent after a short while. This is what Eventual Consistency is.

Though the inconsistency does not mean that there is any sort of data loss. It just means that the data takes a short while to travel across the globe via the internet cables under the ocean to reach a global consensus and become consistent.

We experience this behaviour all the time. Especially on YouTube. Often you would see a video with 10 views and 15 likes. How is this even possible?

It’s not. The actual views are already more than the likes. It’s just the count of views is inconsistent and takes a short while to get updated.

Running Data Analytics

NoSQL databases also fit best for data analytics use cases, where we have to deal with an influx of massive amounts of data.


问:
Calling parent trait method from child class in Groovy
I have the following:

```<code>trait Trait {
    def Method() {
        // do stuff
    }
}
</code>```

```<code>class Class implements Trait {
    def Method() {
        // do other stuff
        super.Method()
    }
}
</code>```

This compiles but doesn't run as Groovy cannot resolve super.Method(). Calling just Method() results in a stack overflow.

Is it possible to override a Groovy method in this way?

答:
You can do this (using the naming conventions mentioned, but that wasn't the issue)</p>

```<code>trait Trait {
    def method() {
        println "yay"
    }
}

class MyClass implements Trait {
    def method() {
        // do other stuff
        println "woo"
        Trait.super.method()
    }
}

new MyClass().method()
</code>```

Body:
I have the following:

trait Trait {
    def Method() {
        // do stuff
    }
}

class Class implements Trait {
    def Method() {
        // do other stuff
        super.Method()
    }
}

This compiles but doesn't run as Groovy cannot resolve super.Method(). Calling just Method() results in a stack overflow.

Is it possible to override a Groovy method in this way?

Body:
You can do this (using the naming conventions mentioned, but that wasn't the issue)

trait Trait {
    def method() {
        println "yay"
    }
}

class MyClass implements Trait {
    def method() {
        // do other stuff
        println "woo"
        Trait.super.method()
    }
}

new MyClass().method()


问:
Music Genre Recognition
Today I was exploring this part  and have referred this link https://data-flair.training/blogs/python-project-music-genre-classification/
 While i was excuting i got a error at this part

```<code>`directory = "genres"
f= open("my.dat" ,'wb')
i=0
for folder in os.listdir(directory):
    i+=1
    if i==11 :
        break
    for file in os.listdir(directory+folder):
        (rate,sig) = wav.read(directory+folder+"/"+file)
        mfcc_feat = mfcc(sig,rate ,winlen=0.020, appendEnergy = False)
        covariance = np.cov(np.matrix.transpose(mfcc_feat))
        mean_matrix = mfcc_feat.mean(0)
        feature = (mean_matrix , covariance , i)
        pickle.dump(feature , f)
f.close()`
</code>```

Can anyone say whatb went wrong

答:
As the error says, you are providing a wrong path to read the files. Update the code which reads the file in your directory -

```<code>for file in os.listdir(directory+'/'+folder):
        (rate,sig) = wav.read(directory+'/'+folder+"/"+file)

</code>```

directory+folder (+ concatenates 2 strings) Output = genresbextract_single.mf(assuming bextract_single.mf is your folder name), which is an invalid path.

directory+'/'+'bextract_single.mf' Output = genres/bextract_single.mf, which is a valid path, and listdir will read all the files in that path.

Title: Music Genre Recognition

Body:
Today I was exploring this part  and have referred this link https://data-flair.training/blogs/python-project-music-genre-classification/
 While i was excuting i got a error at this part

`directory = "genres"
f= open("my.dat" ,'wb')
i=0
for folder in os.listdir(directory):
    i+=1
    if i==11 :
        break
    for file in os.listdir(directory+folder):
        (rate,sig) = wav.read(directory+folder+"/"+file)
        mfcc_feat = mfcc(sig,rate ,winlen=0.020, appendEnergy = False)
        covariance = np.cov(np.matrix.transpose(mfcc_feat))
        mean_matrix = mfcc_feat.mean(0)
        feature = (mean_matrix , covariance , i)
        pickle.dump(feature , f)
f.close()`

Can anyone say whatb went wrong

Body:
As the error says, you are providing a wrong path to read the files. Update the code which reads the file in your directory -

for file in os.listdir(directory+'/'+folder):
        (rate,sig) = wav.read(directory+'/'+folder+"/"+file)

directory+folder (+ concatenates 2 strings) Output = genresbextract_single.mf(assuming bextract_single.mf is your folder name), which is an invalid path.

directory+'/'+'bextract_single.mf' Output = genres/bextract_single.mf, which is a valid path, and listdir will read all the files in that path.


问:
Promise.allSettled in angular 9 and typescript 3.8.3
I'm trying to use Promise.allSettled but I keep geeting errors from TSLint

I use:

angular 9

Typescript 3.8.3

node 13.9.0

This is my tsconfig:

```<code>  {
    "compileOnSave": false,
    "compilerOptions": {
        "baseUrl": "./",
        "outDir": "./dist/out-tsc",
        "sourceMap": true,
        "declaration": false,
        "downlevelIteration": true,
        "experimentalDecorators": true,
        "module": "esnext",
        "moduleResolution": "node",
        "importHelpers": true,
        "target": "es2015",
        "typeRoots": ["node_modules/@types"],
        "lib": ["es2015", "dom"],
        "paths": {
            "@ing/*": ["src/app/features/*"]
        }
    },
    "angularCompilerOptions": {
        "fullTemplateTypeCheck": true,
        "strictInjectionParameters": true
    }
}
</code>```

This is where TSlint mark the error:

```<code> Promise.allSettled(loadingPromises).then(results=>{
      results.forEach( (status, value) =>{
        console.log(status,value);
      })
    });
</code>```

Te code runs perfectly ,The error TSlint throws  is:

TS2339: Property 'allSettled' does not exist on type 'PromiseConstructor'.

答:
The question is answered here:
https://stackoverflow.com/a/60276174/11057988

Suggested workaround:

```<code>declare interface PromiseConstructor {
    allSettled(promises: Array<Promise<any>>): Promise<Array<{status: 'fulfilled' | 'rejected', value?: any, reason?: any}>>;
}
</code>```

Body:
I'm trying to use Promise.allSettled but I keep geeting errors from TSLint

I use:

angular 9

Typescript 3.8.3

node 13.9.0

This is my tsconfig:

  {
    "compileOnSave": false,
    "compilerOptions": {
        "baseUrl": "./",
        "outDir": "./dist/out-tsc",
        "sourceMap": true,
        "declaration": false,
        "downlevelIteration": true,
        "experimentalDecorators": true,
        "module": "esnext",
        "moduleResolution": "node",
        "importHelpers": true,
        "target": "es2015",
        "typeRoots": ["node_modules/@types"],
        "lib": ["es2015", "dom"],
        "paths": {
            "@ing/*": ["src/app/features/*"]
        }
    },
    "angularCompilerOptions": {
        "fullTemplateTypeCheck": true,
        "strictInjectionParameters": true
    }
}

This is where TSlint mark the error:

 Promise.allSettled(loadingPromises).then(results=>{
      results.forEach( (status, value) =>{
        console.log(status,value);
      })
    });

Te code runs perfectly ,The error TSlint throws  is:

TS2339: Property 'allSettled' does not exist on type 'PromiseConstructor'.

Body:
The question is answered here:
https://stackoverflow.com/a/60276174/11057988

Suggested workaround:

declare interface PromiseConstructor {
    allSettled(promises: Array<Promise<any>>): Promise<Array<{status: 'fulfilled' | 'rejected', value?: any, reason?: any}>>;
}


问:
ion-nav push method not working in Ionic 4
<ion-nav> supports push as per the document here -- https://ionicframework.com/docs/api/nav

My currentPage html (current-page.page.html) has a button component -

```<code><ion-button (click)="goToNextPage()">Next Page</ion-button>
</code>```

My currentPage script file (current-page.page.ts) has following code -

```<code>import { Component, OnInit } from '@angular/core';
import { NavController, NavParams } from '@ionic/angular';
import { NextPage } from '../next-page/next-page.page';

@Component({
  selector: 'current-page',
  templateUrl: './current-page.page.html',
  styleUrls: ['./current-page.page.scss'],
})
export class CurrentPage implements OnInit {

  constructor(public navCtrl: NavController, public navParams: NavParams) { }

  goToNextPage () {
    this.navCtrl.push('NextPage');
  }

  ngOnInit() {
  }

}
</code>```

However, I get the format error as Property 'push' does not exist on type 'NavController'

Not sure how to use the push method properly. Any help will be appreciated.

答:
In Ionic4 You can use either a ionic NavController or Angular router.
If you want to use ionic NavController. You can write like this</p>

```<code>import {
  NavController,
} from '@ionic/angular';

export class TrainerMessagesPage implements OnInit, OnDestroy {
  public _conversations: Conversation[] = [];
  public conversations: Conversation[] = [];
  private _amr: Subscription;
  public unreadOnly = false;

  constructor(
    private navCtrl: NavController,  ) {
  }

  public goToPage() {
    this.navCtrl.navigateForward(YOUR-Page-URL);
  }

}
</code>```

Body:
<ion-nav> supports push as per the document here -- https://ionicframework.com/docs/api/nav

My currentPage html (current-page.page.html) has a button component -

<ion-button (click)="goToNextPage()">Next Page</ion-button>

My currentPage script file (current-page.page.ts) has following code -

import { Component, OnInit } from '@angular/core';
import { NavController, NavParams } from '@ionic/angular';
import { NextPage } from '../next-page/next-page.page';

@Component({
  selector: 'current-page',
  templateUrl: './current-page.page.html',
  styleUrls: ['./current-page.page.scss'],
})
export class CurrentPage implements OnInit {

  constructor(public navCtrl: NavController, public navParams: NavParams) { }

  goToNextPage () {
    this.navCtrl.push('NextPage');
  }

  ngOnInit() {
  }

}

However, I get the format error as Property 'push' does not exist on type 'NavController'

Not sure how to use the push method properly. Any help will be appreciated.

Body:
In Ionic4 You can use either a ionic NavController or Angular router.
If you want to use ionic NavController. You can write like this

import {
  NavController,
} from '@ionic/angular';

export class TrainerMessagesPage implements OnInit, OnDestroy {
  public _conversations: Conversation[] = [];
  public conversations: Conversation[] = [];
  private _amr: Subscription;
  public unreadOnly = false;

  constructor(
    private navCtrl: NavController,  ) {
  }

  public goToPage() {
    this.navCtrl.navigateForward(YOUR-Page-URL);
  }

}


问:
Apply Conditional Format to Multiple Columns with Script Editor
I am creating an onEdit(e) function to update my charts format, based on column A's value. I have Column A set up to format appropriately with Conditional Formatting and a Data Validation drop down menu, but how can I make the other columns adjacent to the updated cell the same format?

See code below:

```<code>function onEdit(e) {

// Get current active sheet
  var actSh = SpreadsheetApp.getActiveSpreadsheet();

  // Get the integer value of the location the change is made at
  var row = e.range.getRow();
  var col = e.range.getColumn();

  // Define the max range in columns
  var max = actSh.getLastColumn();

  // Set a range to apply the conditional rule to
  var range = actSh.getRange(row,(col+1),1,(max-1));

  if (col == 1) {
    // Get Rule for Column A
    var rule = e.newConditionalFormatRules().copy();
    var newRule = range.setConditionalFormatRules(rule);
  }
}
</code>```

Below is a screenshot of the spreadsheet I am trying to get the editor working on, for reference to what I am trying to accomplish.
See Link below.

答:
How to extend conditional formatting over new ranges

The steps are the following:

Retrieve the sheet of interest

Retrieve the conditional rules for this sheet with getConditionalFormatRules()

Loop through all the rules

Retrieve the ranges for each rule with getRanges()

Loop through the ranges to verify that the your column of interest is one of the ranges

If the rule was found to be applied to your column of interest (if(ranges[j].getColumn() == 1)) - make a copy of the corresponding rule with copy()

Assign a range of interest to the new copied rule with setRanges([range]) and finish the request with build

Add the new rule to the array of already exisitng rules with push()

After exiting all loops, update your sheet with the new set of rules with setConditionalFormatRules(rules)

Sample

```<code>function onEdit(e) {
  // Get current active sheet
  var actSh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  // Get the integer value of the location the change is made at
  var row = e.range.getRow();
  var col = e.range.getColumn();
  // Define the max range in columns
  var max = actSh.getLastColumn();
  // Set a range to apply the conditional rule to
  var range = actSh.getRange(row,(col+1),1,(max-1));
  if (col == 1) {
    var rules = actSh.getConditionalFormatRules();
    for (var i = 0; i < rules.length; i++){
      var ranges = rules[i].getRanges();
      for (var j = 0; j < ranges.length; j++){
        if (ranges[j].getColumn() == 1){
          var rule = rules[i].copy();
          rule.setRanges([range]).build();
          rules.push(rule);
          break;
        }
      }
    }
    actSh.setConditionalFormatRules(rules);
  }
}
</code>```

References

Class ConditionalFormatRule

Class ConditionalFormatRuleBuilder

Body:
I am creating an onEdit(e) function to update my charts format, based on column A's value. I have Column A set up to format appropriately with Conditional Formatting and a Data Validation drop down menu, but how can I make the other columns adjacent to the updated cell the same format?

See code below:

function onEdit(e) {

// Get current active sheet
  var actSh = SpreadsheetApp.getActiveSpreadsheet();

  // Get the integer value of the location the change is made at
  var row = e.range.getRow();
  var col = e.range.getColumn();

  // Define the max range in columns
  var max = actSh.getLastColumn();

  // Set a range to apply the conditional rule to
  var range = actSh.getRange(row,(col+1),1,(max-1));

  if (col == 1) {
    // Get Rule for Column A
    var rule = e.newConditionalFormatRules().copy();
    var newRule = range.setConditionalFormatRules(rule);
  }
}

Below is a screenshot of the spreadsheet I am trying to get the editor working on, for reference to what I am trying to accomplish.
See Link below.

Body:
How to extend conditional formatting over new ranges

The steps are the following:

Retrieve the sheet of interest

Retrieve the conditional rules for this sheet with getConditionalFormatRules()

Loop through all the rules

Retrieve the ranges for each rule with getRanges()

Loop through the ranges to verify that the your column of interest is one of the ranges

If the rule was found to be applied to your column of interest (if(ranges[j].getColumn() == 1)) - make a copy of the corresponding rule with copy()

Assign a range of interest to the new copied rule with setRanges([range]) and finish the request with build

Add the new rule to the array of already exisitng rules with push()

After exiting all loops, update your sheet with the new set of rules with setConditionalFormatRules(rules)

Sample

function onEdit(e) {
  // Get current active sheet
  var actSh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  // Get the integer value of the location the change is made at
  var row = e.range.getRow();
  var col = e.range.getColumn();
  // Define the max range in columns
  var max = actSh.getLastColumn();
  // Set a range to apply the conditional rule to
  var range = actSh.getRange(row,(col+1),1,(max-1));
  if (col == 1) {
    var rules = actSh.getConditionalFormatRules();
    for (var i = 0; i < rules.length; i++){
      var ranges = rules[i].getRanges();
      for (var j = 0; j < ranges.length; j++){
        if (ranges[j].getColumn() == 1){
          var rule = rules[i].copy();
          rule.setRanges([range]).build();
          rules.push(rule);
          break;
        }
      }
    }
    actSh.setConditionalFormatRules(rules);
  }
}

References

Class ConditionalFormatRule

Class ConditionalFormatRuleBuilder


问:
Heroku build never finish
When i deply in the building, never finish.

-----> Build

```<code>   Running build
   > project@1.0.0 build /tmp/build_4b8ee4ef59b560044f52943cad6d37e5
   > node server.js
   Templates engine started!
   Db started!
   App listening on port 8000!
</code>```

After .listen the process never finish.

Never finish build, after one hour time limit exceded.

const PORT = process.env.PORT || 8000; app.listen(PORT, () => { console.log('App listening on port ${PORT}!'); });

In heroku local is works, but when i push to heroku master, build never finish :(

https://i.stack.imgur.com/qxAaO.png

I connect with await to mongose for db.

答: In your package.json under scripts -> build you are telling it to run your project node server.js (this should only be your start script) instead of telling it to build your project.

Title: Heroku build never finish

Body:
When i deply in the building, never finish.

-----> Build

   Running build
   > project@1.0.0 build /tmp/build_4b8ee4ef59b560044f52943cad6d37e5
   > node server.js
   Templates engine started!
   Db started!
   App listening on port 8000!

After .listen the process never finish.

Never finish build, after one hour time limit exceded.

const PORT = process.env.PORT || 8000; app.listen(PORT, () => { console.log('App listening on port ${PORT}!'); });

In heroku local is works, but when i push to heroku master, build never finish :(

https://i.stack.imgur.com/qxAaO.png

I connect with await to mongose for db.


问:
I am trying to use elastic search with logstash and kibana but im unable to run a logstash file?
I have installed elastic search,logstash and kibana successfully. I have also installed jdk. Elastic search is running on port 9200 properly I am trying to run the logstash.conf file it is giving me following error
[it is giving me following error

This is the code i am trying to run

and i am trying to run code with following Two commands
1)logstash -f logstash.py
2)logstash -e 'input{stdin{}}output{stdout{}}'

答:
You are already running 1 instance of logstash.
either restart your OS (that will stop all running processes) and then execute it again.

Another option is to use the CLI command:

type in your CLI: top or ps aux | grep logstash

find the PID of the logstash

type: kill -9 <logstash-pid>

If you are running logstash as a service try running:

service logstash status - to see if it is running.

service logstash stop - to stop it and then.

service logstash start - to start it again.


问:
In a dockerfile, how to delete a directory and its contents from docker image? (windows)
I'm using the python:3.6.5-windowsservercore base image.

COPY . /app copies the build context into C:\app. This includes certain secret keys required for building the project.

After running the build, I want to delete keys folder (C:\app\keys), for this I use:

```<code>RUN powershell.exe Remove-Item -Path C:\app\keys -Force
</code>```

Note - I have also tried each of following alternatives:

```<code>RUN Remove-Item -Path C:\app\keys -Force
RUN RD /S /Q C:\app\keys
</code>```

This gives me following error:

```<code>Step 10/14 : RUN powershell.exe Remove-Item -Path C:\app\keys -Force
 ---> Running in 4e22124332b1
Remove-Item : Object reference not set to an instance of an object.
At line:1 char:1
+ Remove-Item -Path C:\app\keys -Force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Remove-Item], NullReferenceEx
   ception
    + FullyQualifiedErrorId : System.NullReferenceException,Microsoft.PowerShe
   ll.Commands.RemoveItemCommand

The command 'powershell -Command $ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; powershell.exe Remove-Item -Path C:\app\keys -Force' returned a non-zero code: 1
</code>```

What is the way to delete directory inside the image?

答:
Solution:

```<code>RUN Remove-Item -Path C:\app\keys -Force -Recurse
</code>```

There are 2 aspects to resolve this.

Based on your base image, what is your default shell? Bash or powershell? In my case it was powershell, so there is no need to mention powershell.exe at the beginning of the command.

The original command was incorrect RUN Remove-Item -Path C:\app\keys -Force because the folder had sub-folders and files. So you have to mention -Recurse

Body:
I'm using the python:3.6.5-windowsservercore base image.

COPY . /app copies the build context into C:\app. This includes certain secret keys required for building the project.

After running the build, I want to delete keys folder (C:\app\keys), for this I use:

RUN powershell.exe Remove-Item -Path C:\app\keys -Force

Note - I have also tried each of following alternatives:

RUN Remove-Item -Path C:\app\keys -Force
RUN RD /S /Q C:\app\keys

This gives me following error:

Step 10/14 : RUN powershell.exe Remove-Item -Path C:\app\keys -Force
 ---> Running in 4e22124332b1
Remove-Item : Object reference not set to an instance of an object.
At line:1 char:1
+ Remove-Item -Path C:\app\keys -Force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Remove-Item], NullReferenceEx
   ception
    + FullyQualifiedErrorId : System.NullReferenceException,Microsoft.PowerShe
   ll.Commands.RemoveItemCommand

The command 'powershell -Command $ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; powershell.exe Remove-Item -Path C:\app\keys -Force' returned a non-zero code: 1

What is the way to delete directory inside the image?

Body:
Solution:

RUN Remove-Item -Path C:\app\keys -Force -Recurse

There are 2 aspects to resolve this.

Based on your base image, what is your default shell? Bash or powershell? In my case it was powershell, so there is no need to mention powershell.exe at the beginning of the command.

The original command was incorrect RUN Remove-Item -Path C:\app\keys -Force because the folder had sub-folders and files. So you have to mention -Recurse


问:
How to find spearman's correlation in python for only specific values?
i HAVE A DATAMATRIX of five columns

```<code> 0     1     2     3     4

nan    34    23    34     11

43    34   123     4     44

45    12     4   nan     66

89    78    43   435     23

nan   89   nan   12     687

 6    232    34    4     nan

24    56    34   121     56

nan    9    nan   54     12

 24   nan    54    12    nan

 76    11   123    76     78

 43   nan    65    23     89

 68   233    34   nan     89

 65    53    nan    7     78

 34    65     12    8     12

 56    98     43    nan   43
</code>```

I also have a fvector

```<code>fvector
23

67

23

nan

nan

87

323

nan

78

32

78

112

nan

56

nan

56
</code>```

Till now i had just been able to find the correlation based upon full column

```<code>for i in datamatrix:
    coef,p=spearmanr(datamatrix[i],fvector)
    print(coef,p,"for column ",i)
</code>```

I want to achieve 2 things:

1). I want to find the spearman's correlation between fvector and each column of datamatrix but if one of the two variables or both variables are nan then i want to drop the correlation for particular pair.
for eg. 4th value in column 1 is 78 and 4th value in fvector is nan so i want to exclude the particular pair(not whole column) from the process of correlation.i don't have any idea how to work with specific variable for finding correlation.

2). if the total number of nan values in fvector and datamatrix's column are > 30% then exclude whole column from finding correlation.

Any resource or reference will be helpful

Thanks

答:
1) If you set nan_policy == "omit" the Nan will be ignored in the calculation. See scipy.stats.spearmanr.

2) You can compute the percentage of Nan in each column in this way: (df[i].isna().sum()*100)/df.shape[0]

All together:

```<code>nan_fvectr = int(vector.isna().sum())
for i in df:
    if ((df[i].isna().sum()+nan_fvectr)*100)/(df.shape[0]*2) >= 30:
        continue
    coef,p=stats.spearmanr(df[i],vector, nan_policy="omit")
    print(coef,p,"for column ",i)
</code>```

Body:
i HAVE A DATAMATRIX of five columns

 0     1     2     3     4

nan    34    23    34     11

43    34   123     4     44

45    12     4   nan     66

89    78    43   435     23

nan   89   nan   12     687

 6    232    34    4     nan

24    56    34   121     56

nan    9    nan   54     12

 24   nan    54    12    nan

 76    11   123    76     78

 43   nan    65    23     89

 68   233    34   nan     89

 65    53    nan    7     78

 34    65     12    8     12

 56    98     43    nan   43

I also have a fvector

fvector
23

67

23

nan

nan

87

323

nan

78

32

78

112

nan

56

nan

56

Till now i had just been able to find the correlation based upon full column

for i in datamatrix:
    coef,p=spearmanr(datamatrix[i],fvector)
    print(coef,p,"for column ",i)

I want to achieve 2 things:

1). I want to find the spearman's correlation between fvector and each column of datamatrix but if one of the two variables or both variables are nan then i want to drop the correlation for particular pair.
for eg. 4th value in column 1 is 78 and 4th value in fvector is nan so i want to exclude the particular pair(not whole column) from the process of correlation.i don't have any idea how to work with specific variable for finding correlation.

2). if the total number of nan values in fvector and datamatrix's column are > 30% then exclude whole column from finding correlation.

Any resource or reference will be helpful

Thanks

Body:
1) If you set nan_policy == "omit" the Nan will be ignored in the calculation. See scipy.stats.spearmanr.

2) You can compute the percentage of Nan in each column in this way: (df[i].isna().sum()*100)/df.shape[0]

All together:

nan_fvectr = int(vector.isna().sum())
for i in df:
    if ((df[i].isna().sum()+nan_fvectr)*100)/(df.shape[0]*2) >= 30:
        continue
    coef,p=stats.spearmanr(df[i],vector, nan_policy="omit")
    print(coef,p,"for column ",i)


问:
How to get value from selected icon dropdown?
I have 3 icons. i.e icon-star, icon-check, icon-info. if icon-start selected, then i want to store the value of the selected icon into database. for example:

icon-start with value="star"

icon-check with value="complete"

icon-info with value="important"

So, the value stored into database is "star" because i choose icon-star.

Where i must put the value? and how?

Here my modal:

```<code><form autocomplete="off" novalidate action="<?= base_url('app/admin/to-do-add')?>" method="POST">
    <input type="hidden" name="<?=$this->security->get_csrf_token_name();?>" value="<?=$this->security->get_csrf_hash();?>">
    <div class="btn-group dropup dropdown-icon-wrapper mr-1 mb-1" style="float:right">
        <button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" name="status">
            <i class="feather icon-star dropdown-icon"></i>
        </button>
        <div class="dropdown-menu">
            <span class="dropdown-item">
                <i class="feather icon-star" data-toggle="tooltip" data-placement="left" title="Starred" value="star"></i>
            </span>
            <span class="dropdown-item">
                <i class="feather icon-info" data-toggle="tooltip" data-placement="left" title="Important" value="important"></i>
            </span>
            <span class="dropdown-item">
                <i class="feather icon-check" data-toggle="tooltip" data-placement="left" title="Completed" value="complete"></i>
            </span>
        </div>
    </div>
    <br>
    <br>
    <div class="form-group">
        <label>To</label>
        <div class="controls">
            <select class="select2 form-control" name="to">
                <option value="<?php echo $dataLogin->MEmployee_ID;?>">-SELECT-</option>
                <?php foreach ($data1 as $row){ ?>
                <option value=" <?php echo $row->MEmployee_ID ?>">
                    <?php echo $row->EmployeeName?>
                </option>
                <?php } ?>
            </select>
        </div>
    </div>
    <div class=" modal-footer">
        <button type="submit" class="btn btn-primary"><?= $this->lang->line('add');?></button>
    </div>
</form>
</code>```

Here my controller :

```<code>public function addTask(){
    var_dump($this->input->post('status')); die(); //i tried to var_dump, the value is NULL
    $dataLogin = $this->employee_model->checkUserData($this->session->userdata('islogin'))->row();
    $data = [
        "MEmployee_ID" => $this->input->post('to'),
        "status" => $this->input->post('status') //here the value of selected icon
    ];
}
</code>```

答:
I am proposing a solution and it will work because I did it same and it worked.

(View) Take three checkbox input for   your three icons

<input type="checkbox" name="start" value="start">
   <input type="checkbox" name="complete" value="complete">
   <input type="checkbox" name="important" value="important">```

(Controller)

(Model)
define those three input default value type null

Try it I am here to help!

Body:
I have 3 icons. i.e icon-star, icon-check, icon-info. if icon-start selected, then i want to store the value of the selected icon into database. for example:

icon-start with value="star"

icon-check with value="complete"

icon-info with value="important"

So, the value stored into database is "star" because i choose icon-star.

Where i must put the value? and how?

Here my modal:

<form autocomplete="off" novalidate action="<?= base_url('app/admin/to-do-add')?>" method="POST">
    <input type="hidden" name="<?=$this->security->get_csrf_token_name();?>" value="<?=$this->security->get_csrf_hash();?>">

        <button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" name="status">

        </button>

        To

            <select class="select2 form-control" name="to">
                <option value="<?php echo $dataLogin->MEmployee_ID;?>">-SELECT-</option>
                <?php foreach ($data1 as $row){ ?>
                <option value=" <?php echo $row->MEmployee_ID ?>">
                    <?php echo $row->EmployeeName?>
                </option>
                <?php } ?>
            </select>

        <button type="submit" class="btn btn-primary"><?= $this->lang->line('add');?></button>

</form>

Here my controller :

public function addTask(){
    var_dump($this->input->post('status')); die(); //i tried to var_dump, the value is NULL
    $dataLogin = $this->employee_model->checkUserData($this->session->userdata('islogin'))->row();
    $data = [
        "MEmployee_ID" => $this->input->post('to'),
        "status" => $this->input->post('status') //here the value of selected icon
    ];
}

Body:
I am proposing a solution and it will work because I did it same and it worked.

(View) Take three checkbox input for   your three icons

<input type="checkbox" name="start" value="start">
   <input type="checkbox" name="complete" value="complete">
   <input type="checkbox" name="important" value="important">

(Controller)

(Model)
define those three input default value type null

Try it I am here to help!


问:
How to search in a JSONField for a key with spaces in Django with Postgres?
Suppose I've a JSONField namely "data" defined in one of my models.py in Django. The Contents of the field is somewhat similar to the following -

```<code>{
    "name": "John",
    "email": "johndoe@foo.bar",
    "last name": "Doe"
}
</code>```

I need to write a queries of the following form -

```<code>self.objects.filter(data__name="John")
</code>```

How do I write a similar query for the key "last name". I'm not able to proceed since that key has a space. Was thinking of getting the data and filtering it using python, But I think there would be more efficient way to get it done.

I've not real control over the data in the JSONField. So, I can't really change the name of the key.

答:
For JSON field you can use contains:</p>

```<code>self.objects.filter(data__contains={"last name": "Doe"})
</code>```

Body:
Suppose I've a JSONField namely "data" defined in one of my models.py in Django. The Contents of the field is somewhat similar to the following -

{
    "name": "John",
    "email": "johndoe@foo.bar",
    "last name": "Doe"
}

I need to write a queries of the following form -

self.objects.filter(data__name="John")

How do I write a similar query for the key "last name". I'm not able to proceed since that key has a space. Was thinking of getting the data and filtering it using python, But I think there would be more efficient way to get it done.

I've not real control over the data in the JSONField. So, I can't really change the name of the key.

Body:
For JSON field you can use contains:

self.objects.filter(data__contains={"last name": "Doe"})


问:
Woocommerce tags in search results
I'm trying to include in search results, results matching also product tags. By default it shows results matching product title / description.
Is it possible to add saerching via product tags? How can I do that?</p>

答:
Be default you can not search by product tags. You have to edit you search query backend code to achieve searching via tags as well.

This widget might be close to what you need: https://docs.woocommerce.com/document/woocommerce-product-search/widgets/product-filter-tags/

Title: Woocommerce tags in search results


问:
Optimizing my web application using Flash, Javascript and JSP
I have a web app that I am trying to speed up.  It looks like this:

```<code>+------+
|      |
|      |
+------+

+------+
|      |
|      |
+------+

+------+
|      |
|      |
+------+
</code>```

Each box is an iFrame containing a Flash SWF and some javascript.  The SWF downloads a thirdparty SWF that is used to display information.  I have found that the load time for the webapp is:

```<code>LoadTime = (4 seconds) * numberOfBoxes + (3 seconds)
</code>```

When I just imbed the 3rd party swf directly (without our swf or the javascript) the load time is:

```<code>LoadTime = (1 second) * numberOfBoxes + (2.5 seconds)
</code>```

I am trying to find where the extra 3 seconds is being used so that I can speed up our webapp.  I think that the candidates are:

Serverside processing (jsp)

Download

Javascript

Flash

Other?

Download

Below is an image of the downloads taken from firebug.  I have replaced the file names with what their type is.  None of the downloads are taking especially long after the first time.

One place of interest however is marked in red.  The red area is a 3 second gap between when My SWF is loaded and when two gif files are loaded followed by the Third Party SWF.  I think this pause is caused by processing on the client (is this true?).

Note: The red bars in the graph are not part of the diagram.  I added them to highlight the gap where nothing is occurring on the .net panel.

I think that I can conclude from this that I have a client side processing issue which implies either Flash or Javascript.  Question 1: Is this correct?

Edit: I added up the total non-concurrent download time:

When there is 1 iframes the download time is 1.87 seconds

When there is 2 iframes the download time is 2.29 seconds

When there is 5 iframes the download time is 8.57 seconds

When there is 10 iframes the download time is 10.62 seconds

When there is 21 iframes the download time is 17.20 seconds

Javascript

I used the profiler in firebug to profile the javascript.  Here are the results when there are four components on the page:

This means that the javascript is running for about .25 second/chart.  This seems reasonable to me.

Question 2: Am I reading these results correctly?

This leaves about 3.5 seconds/chart of processing for something else.

Flash

I inserted some trace statements in the AS3 code.  We are listening to an event called something like "done loading".  I put a trace in the first initialize method and in the "done loading" method.  The flash is only eating up .2 second/chart between those two trace statements.

Question 3: Is there a better way to to profile the flash?  Could it be the flash loading or something like that that is eating up the extra time?

Other

I am not sure if there are other things other than:

Serverside processing (jsp)

Download

Javascript

Flash

Question 4: Is there something that I am missing that could be eating up time?

Next Steps

I am not sure what my next step should be.  I know that something is taking about 1.5 - 3 seconds/chart but I cannot figure out what it is.  I suspect that it is something related to my swf.

Question 5: How should I find that missing time?

Update: Time Summary

I have graphed all of the times for each thing that could be taking time.

The X-axis is the number of charts that are being used.

The Y-axis is the about of time loading all of the charts takes.

The last graph is possibly the most important graph.  The blue dots is the amount of total loading time (measured using a stop watch).  The red dots are the amount of time that I have accounted for (Javascript, download time and flash time).

Update: Browser Wars

I am targeting IE and Firefox (although it is a nice bonus if other browsers work).  All of the results presented so far are with Firefox with firebug running.  Just for fun I thought I would try in other browsers.  I don't think that this brings me closer to a solution but interesting to see how much IE sucks.

Note: Before running tests for Firefox I cleared the cookies and cache.  I did not do this for IE or Chrome

Update: Flash Loading

I have been sprinkling console.log statements though my code trying to sandwich the slow code.  (The results get pushed out to the Firebug console).

One thing that I have noticed that seems suspicious to me me is that there is a 2.5 second gap between when my last javascript log gets printed and when my first flash log gets printed.

```<code>17:08:29.973 - Javascript code
Time difference: 2510 ms
17:08:32.483 - Flash- myComponent.init()
</code>```

Does flash need to setup a virtual machine for each swf?  Does it compile the actionscript on the client?

What happens between when I <embed> my swf and when the creationComplete event in my main .mxml?

答:
Just some ideas:

Can you eliminate the middle man, in this case, the third party swf?

Where is the third party swf located? If it is on a remote server, you should just have to download it once and then place it on your local server with your other files. That could eliminate download times.

Can you use something like a flash decompiler to decompile the third party swf's code and put the code directly into your swf? (this is probably against the rules)

What happens if you don't put the content in iframes, rather, just put them in divs?

Body:
I have a web app that I am trying to speed up.  It looks like this:

+------+
|      |
|      |
+------+

+------+
|      |
|      |
+------+

+------+
|      |
|      |
+------+

Each box is an iFrame containing a Flash SWF and some javascript.  The SWF downloads a thirdparty SWF that is used to display information.  I have found that the load time for the webapp is:

LoadTime = (4 seconds) * numberOfBoxes + (3 seconds)

When I just imbed the 3rd party swf directly (without our swf or the javascript) the load time is:

LoadTime = (1 second) * numberOfBoxes + (2.5 seconds)

I am trying to find where the extra 3 seconds is being used so that I can speed up our webapp.  I think that the candidates are:

Serverside processing (jsp)

Download

Javascript

Flash

Other?

Download

Below is an image of the downloads taken from firebug.  I have replaced the file names with what their type is.  None of the downloads are taking especially long after the first time.

One place of interest however is marked in red.  The red area is a 3 second gap between when My SWF is loaded and when two gif files are loaded followed by the Third Party SWF.  I think this pause is caused by processing on the client (is this true?).

Note: The red bars in the graph are not part of the diagram.  I added them to highlight the gap where nothing is occurring on the .net panel.

I think that I can conclude from this that I have a client side processing issue which implies either Flash or Javascript.  Question 1: Is this correct?

Edit: I added up the total non-concurrent download time:

When there is 1 iframes the download time is 1.87 seconds

When there is 2 iframes the download time is 2.29 seconds

When there is 5 iframes the download time is 8.57 seconds

When there is 10 iframes the download time is 10.62 seconds

When there is 21 iframes the download time is 17.20 seconds

Javascript

I used the profiler in firebug to profile the javascript.  Here are the results when there are four components on the page:

This means that the javascript is running for about .25 second/chart.  This seems reasonable to me.

Question 2: Am I reading these results correctly?

This leaves about 3.5 seconds/chart of processing for something else.

Flash

I inserted some trace statements in the AS3 code.  We are listening to an event called something like "done loading".  I put a trace in the first initialize method and in the "done loading" method.  The flash is only eating up .2 second/chart between those two trace statements.

Question 3: Is there a better way to to profile the flash?  Could it be the flash loading or something like that that is eating up the extra time?

Other

I am not sure if there are other things other than:

Serverside processing (jsp)

Download

Javascript

Flash

Question 4: Is there something that I am missing that could be eating up time?

Next Steps

I am not sure what my next step should be.  I know that something is taking about 1.5 - 3 seconds/chart but I cannot figure out what it is.  I suspect that it is something related to my swf.

Question 5: How should I find that missing time?

Update: Time Summary

I have graphed all of the times for each thing that could be taking time.

The X-axis is the number of charts that are being used.

The Y-axis is the about of time loading all of the charts takes.

The last graph is possibly the most important graph.  The blue dots is the amount of total loading time (measured using a stop watch).  The red dots are the amount of time that I have accounted for (Javascript, download time and flash time).

Update: Browser Wars

I am targeting IE and Firefox (although it is a nice bonus if other browsers work).  All of the results presented so far are with Firefox with firebug running.  Just for fun I thought I would try in other browsers.  I don't think that this brings me closer to a solution but interesting to see how much IE sucks.

Note: Before running tests for Firefox I cleared the cookies and cache.  I did not do this for IE or Chrome

Update: Flash Loading

I have been sprinkling console.log statements though my code trying to sandwich the slow code.  (The results get pushed out to the Firebug console).

One thing that I have noticed that seems suspicious to me me is that there is a 2.5 second gap between when my last javascript log gets printed and when my first flash log gets printed.

17:08:29.973 - Javascript code
Time difference: 2510 ms
17:08:32.483 - Flash- myComponent.init()

Does flash need to setup a virtual machine for each swf?  Does it compile the actionscript on the client?

What happens between when I <embed> my swf and when the creationComplete event in my main .mxml?


问:
Inno Setup: Different Serial keys with different options?
How to provide multiple serial number with multiple options in Inno Setup?

I want to write different values in Registry, based on different serial keys I provide to customers.

ex different serial keys like

```<code>sKey1 = "A1AA-B2ACF-HEJUI-UYTER"
sKey2 = "A1BB-B2ACF-HEJUI-UYTER"
sKey3 = "A1CC-B2ACF-HEJUI-UYTER"
</code>```

First 4 characters or different for different keys want to create in Registry

```<code>if (custInput.startwith ("A1AA") then
    Root: "HKLM"; Subkey: "SOFTWARE\Version\"; ValueType:string; ValueName:"Name";ValueData: "{"Lite"}";
elseif  (custInput.startwith ("A1BB") then
    Root: "HKLM"; Subkey: "SOFTWARE\Version\"; ValueType:string; ValueName:"Name";ValueData: "{"Pro"}";
elseif  (custInput.startwith ("A1CC") then
    Root: "HKLM"; Subkey: "SOFTWARE\Version\"; ValueType:string; ValueName:"Name";ValueData: "{"Online"}";
endif
</code>```

How to achieve this in Inno Setup? I used CheckSerial function below:

function CheckSerial(Serial: String): Boolean;
  begin
    Result := Serial = '{#SerialNumber}';
  end;
```

答:
Use a scripted constant to programatically decide about the value to store to the registry:

```<code>[Setup]
UserInfoPage=yes

[Registry]
Root: "HKLM"; Subkey: "SOFTWARE\Version"; ValueType: string; ValueName: "Name"; \
    ValueData: "{code:GetEdition}";
</code>```

[Code]

var
  Serials: TStrings;
  Editions: TStrings;

function CheckSerial(Serial: String): Boolean;
begin
  Result := (Serials.IndexOf(Serial) >= 0);
end;

procedure RegisterEdition(Serial: string; Edition: string);
begin
  Serials.Add(Serial);
  Editions.Add(Edition);
end;

function GetEdition(Param: string): string;
var
  Index: Integer;
begin
  Index := Serials.IndexOf(WizardForm.UserInfoSerialEdit.Text);
  if Index >= 0 then Result := Editions[Index];
end;

function InitializeSetup(): Boolean;
begin
  Serials := TStringList.Create;
  Editions := TStringList.Create;

  RegisterEdition('A1AA-B2ACF-HEJUI-UYTER', 'Lite');
  RegisterEdition('A1BB-B2ACF-HEJUI-UYTER', 'Pro');
  RegisterEdition('A1CC-B2ACF-HEJUI-UYTER', 'Online');

  Result := True;
end;
```

Body:
How to provide multiple serial number with multiple options in Inno Setup?

I want to write different values in Registry, based on different serial keys I provide to customers.

ex different serial keys like

sKey1 = "A1AA-B2ACF-HEJUI-UYTER"
sKey2 = "A1BB-B2ACF-HEJUI-UYTER"
sKey3 = "A1CC-B2ACF-HEJUI-UYTER"

First 4 characters or different for different keys want to create in Registry

if (custInput.startwith ("A1AA") then
    Root: "HKLM"; Subkey: "SOFTWARE\Version\"; ValueType:string; ValueName:"Name";ValueData: "{"Lite"}";
elseif  (custInput.startwith ("A1BB") then
    Root: "HKLM"; Subkey: "SOFTWARE\Version\"; ValueType:string; ValueName:"Name";ValueData: "{"Pro"}";
elseif  (custInput.startwith ("A1CC") then
    Root: "HKLM"; Subkey: "SOFTWARE\Version\"; ValueType:string; ValueName:"Name";ValueData: "{"Online"}";
endif

How to achieve this in Inno Setup? I used CheckSerial function below:

function CheckSerial(Serial: String): Boolean;
  begin
    Result := Serial = '{#SerialNumber}';
  end;

Body:
Use a scripted constant to programatically decide about the value to store to the registry:

[Setup]
UserInfoPage=yes

[Registry]
Root: "HKLM"; Subkey: "SOFTWARE\Version"; ValueType: string; ValueName: "Name"; \
    ValueData: "{code:GetEdition}";

[Code]

var
  Serials: TStrings;
  Editions: TStrings;

function CheckSerial(Serial: String): Boolean;
begin
  Result := (Serials.IndexOf(Serial) >= 0);
end;

procedure RegisterEdition(Serial: string; Edition: string);
begin
  Serials.Add(Serial);
  Editions.Add(Edition);
end;

function GetEdition(Param: string): string;
var
  Index: Integer;
begin
  Index := Serials.IndexOf(WizardForm.UserInfoSerialEdit.Text);
  if Index >= 0 then Result := Editions[Index];
end;

function InitializeSetup(): Boolean;
begin
  Serials := TStringList.Create;
  Editions := TStringList.Create;

  RegisterEdition('A1AA-B2ACF-HEJUI-UYTER', 'Lite');
  RegisterEdition('A1BB-B2ACF-HEJUI-UYTER', 'Pro');
  RegisterEdition('A1CC-B2ACF-HEJUI-UYTER', 'Online');

  Result := True;
end;


问:
How to keep values for nonexistent categories while subtracting dataframes?
I have 12 dataframes with cumulative values, and I want to transform them to non-cumulative one.

df1 = pd.DataFrame({
    "ADMIN": [1, 2],
    "FIN_SOURCE": ["A", "B"],
    "PROG": [150, 155],
    "FUNC": [1, 2],
    "ECON": [30, 50],
    "VALUE": [5, 10]
})

df2 = pd.DataFrame({
    "ADMIN": [1, 2, 1],
    "FIN_SOURCE": ["A", "B", "A"],
    "PROG": [150, 155, 160],
    "FUNC": [1, 2, 1],
    "ECON": [30, 50, 50],
    "VALUE": [10, 15, 50]
})
```

<p>Each dataset has columns pointing to different categories (<code>ADMIN</code>, <code>FIN_SOURCE</code>, <code>PROG</code>, <code>FUNC</code>, <code>ECON</code>), and for dataset+1 there are more unique values within each category. </p>

<p>What I tried to do: </p>

<pre class="lang-py prettyprint-override"><code>indxs = ["ADMIN", "FIN_SOURCE", "PROG", "FUNC", "ECON"]
(df2.set_index(indxs) - df1.set_index(indxs)).reset_index()

    ADMIN   FIN_SOURCE  PROG    FUNC    ECON    VALUE
0   1       A           150     1       30      5.0
1   1       A           160     1       50      NaN    #<- I want to keep it as 50 (value in df2 before sub)
2   2       B           155     2       50      5.0

</code>```

答:
Use DataFrame.sub with fill_value=0 parameter:

```<code>indxs = ["ADMIN", "FIN_SOURCE", "PROG", "FUNC", "ECON"]
df = df2.set_index(indxs).sub(df1.set_index(indxs), fill_value=0).reset_index()
print (df)
   ADMIN FIN_SOURCE  PROG  FUNC  ECON  VALUE
0      1          A   150     1    30    5.0
1      1          A   160     1    50   50.0
2      2          B   155     2    50    5.0
</code>```

Body:
I have 12 dataframes with cumulative values, and I want to transform them to non-cumulative one.

df1 = pd.DataFrame({
    "ADMIN": [1, 2],
    "FIN_SOURCE": ["A", "B"],
    "PROG": [150, 155],
    "FUNC": [1, 2],
    "ECON": [30, 50],
    "VALUE": [5, 10]
})

df2 = pd.DataFrame({
    "ADMIN": [1, 2, 1],
    "FIN_SOURCE": ["A", "B", "A"],
    "PROG": [150, 155, 160],
    "FUNC": [1, 2, 1],
    "ECON": [30, 50, 50],
    "VALUE": [10, 15, 50]
})

Each dataset has columns pointing to different categories (ADMIN, FIN_SOURCE, PROG, FUNC, ECON), and for dataset+1 there are more unique values within each category.

What I tried to do:

indxs = ["ADMIN", "FIN_SOURCE", "PROG", "FUNC", "ECON"]
(df2.set_index(indxs) - df1.set_index(indxs)).reset_index()

    ADMIN   FIN_SOURCE  PROG    FUNC    ECON    VALUE
0   1       A           150     1       30      5.0
1   1       A           160     1       50      NaN    #<- I want to keep it as 50 (value in df2 before sub)
2   2       B           155     2       50      5.0

Body:
Use DataFrame.sub with fill_value=0 parameter:

indxs = ["ADMIN", "FIN_SOURCE", "PROG", "FUNC", "ECON"]
df = df2.set_index(indxs).sub(df1.set_index(indxs), fill_value=0).reset_index()
print (df)
   ADMIN FIN_SOURCE  PROG  FUNC  ECON  VALUE
0      1          A   150     1    30    5.0
1      1          A   160     1    50   50.0
2      2          B   155     2    50    5.0


问:
Getting the string in the middle of two other strings in Python
I need to find the string in between two other strings. How could I do this?

```<code>string = "vHELLOv"
</code>```

Finding "HELLO" which is in between of two lowercase "v"'s

Another example could be:

```<code>string = "/World/"
</code>```

Finding "World" in the middle of the two "/"s

答:
"Another example could be" - Just those words made me think you are not only interested in v or / but any type of character that surrounds a string of interest. Therefor you could try a pattern like:

```<code>^(.)(.+)\1$
</code>```

Or if you want to define the possibilities:

```<code>^([\/v])(.+)\1$
</code>```

This way you would capture the first character in a capture group that you can refer to later down the line. You don't need to distinquish between v or / or any character perse. Now grab group 2 from a search result, e.g.:

```<code>import re
s = 'vHELLOv'
print(re.search(r'^(.)(.+)\1$', s).group(2))
</code>```

returns:

```<code>HELLO
</code>```

Body:
I need to find the string in between two other strings. How could I do this?

string = "vHELLOv"

Finding "HELLO" which is in between of two lowercase "v"'s

Another example could be:

string = "/World/"

Finding "World" in the middle of the two "/"s

Body:
"Another example could be" - Just those words made me think you are not only interested in v or / but any type of character that surrounds a string of interest. Therefor you could try a pattern like:

^(.)(.+)\1$

Or if you want to define the possibilities:

^([\/v])(.+)\1$

This way you would capture the first character in a capture group that you can refer to later down the line. You don't need to distinquish between v or / or any character perse. Now grab group 2 from a search result, e.g.:

import re
s = 'vHELLOv'
print(re.search(r'^(.)(.+)\1$', s).group(2))

returns:

HELLO