text:
Q: Line numbers and Syntax Highlighting don't work on different tabs I am trying to resolve the issue in which line numbers don't work properly in multiple tabs. The issue is that when I create a new tab, the line numbers for the other tabs don't work, but the line numbers for the current tab does. Same goes for syntax highlighting.
I think the issue is in using the same variables when creating a new tab, but I have no idea how to resolve this issue and I am not sure if this is truly the problem. I was also thinking about redefining the text box, and the bindings associated with it everytime a tab is clicked.
Below is my code:
import tkinter as tk
import tkinter.filedialog
import traceback
import tkinter.ttk as ttk

from pygments import lex
from pygments.lexers import PythonLexer

import sys
import os

class TextLineNumbers(tk.Canvas):
    def __init__(self, *args, **kwargs):
        tk.Canvas.__init__(self, *args, **kwargs)
        self.textwidget = None

    def attach(self, text_widget):
        self.textwidget = text_widget

    def redraw(self, *args):
        '''redraw line numbers'''
        self.delete("all")

        i = self.textwidget.index("@0,0")
        while True:
            dline= self.textwidget.dlineinfo(i)
            if dline is None: break
            y = dline[1]
            linenum = str(i).split(".")[0]
            self.create_text(5,y,anchor="nw", text=linenum, font=("Courier", 9))
            i = self.textwidget.index("%s+1line" % i)

class CustomText(tk.Text):
    def __init__(self, *args, **kwargs):
        tk.Text.__init__(self, *args, **kwargs)

        self.tk.eval('''
            proc widget_proxy {widget widget_command args} {

                # call the real tk widget command with the real args
                set result [uplevel [linsert $args 0 $widget_command]]

                # generate the event for certain types of commands
                if {([lindex $args 0] in {insert replace delete}) ||
                    ([lrange $args 0 2] == {mark set insert}) ||
                    ([lrange $args 0 1] == {xview moveto}) ||
                    ([lrange $args 0 1] == {xview scroll}) ||
                    ([lrange $args 0 1] == {yview moveto}) ||
                    ([lrange $args 0 1] == {yview scroll})} {

                    event generate  $widget <<Change>> -when tail
                }

                # return the result from the real widget command
                return $result
            }
            ''')
        self.tk.eval('''
            rename {widget} _{widget}
            interp alias {{}} ::{widget} {{}} widget_proxy {widget} _{widget}
        '''.format(widget=str(self)))

        self.comment = False

class Arshi(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.fileName = "Untitled Document"
        self.content = ""
        self.previousContent = ""
        self.language = "Python"
        self.row = "0"
        self.column = "0"
        self.startCol = 0

        self.notebook = ttk.Notebook(self)

        self.menubar()
        self.bottomLabel()
        self.createtext()

    def deafultHighlight(self, argument):
        self.content = self.text.get("1.0", tk.END)
        self.lines = self.content.split("\n")

        if (self.previousContent != self.content):
            self.text.mark_set("range_start", self.row + ".0")
            data = self.text.get(self.row + ".0", self.row + "." + str(len(self.lines[int(self.row) - 1])))

            for token, content in lex(data, PythonLexer()):
                self.text.mark_set("range_end", "range_start + %dc" % len(content))
                self.text.tag_add(str(token), "range_start", "range_end")
                self.text.mark_set("range_start", "range_end")

        self.previousContent = self.text.get("1.0", tk.END)

    def highlight(self, argument):
        self.content = self.text.get("1.0", tk.END)

        if (self.previousContent != self.content):
            self.text.mark_set("range_start", "1.0")
            data = self.text.get("1.0", self.text.index(tk.INSERT))

            for token, content in lex(data, PythonLexer()):
                self.text.mark_set("range_end", "range_start + %dc" % len(content))
                self.text.tag_add(str(token), "range_start", "range_end")
                self.text.mark_set("range_start", "range_end")

        self.previousContent = self.text.get("1.0", tk.END)

    def keypress(self, argument):
        self.updateBottomLabel()
        self.deafultHighlight("argument")

    def configureTags(self, text):
        text.tag_configure("Token.Keyword", foreground="#CC7A00")
        text.tag_configure("Token.Keyword.Constant", foreground="#CC7A00")
        text.tag_configure("Token.Keyword.Declaration", foreground="#CC7A00")
        text.tag_configure("Token.Keyword.Namespace", foreground="#CC7A00")
        text.tag_configure("Token.Keyword.Pseudo", foreground="#CC7A00")
        text.tag_configure("Token.Keyword.Reserved", foreground="#CC7A00")
        text.tag_configure("Token.Keyword.Type", foreground="#CC7A00")

        text.tag_configure("Token.Name.Class", foreground="#003D99")
        text.tag_configure("Token.Name.Exception", foreground="#003D99")
        text.tag_configure("Token.Name.Function", foreground="#003D99")

        text.tag_configure("Token.Operator.Word", foreground="#CC7A00")

        text.tag_configure("Token.Comment", foreground="#B80000")

        text.tag_configure("Token.Literal.String", foreground="#248F24")

    def createtext(self):
        self.notebook.pack(fill=tk.BOTH, expand=True)

        self.tab1 = ttk.Frame(self.notebook)
        self.text = CustomText(self.tab1, bd=0, font=("Courier", 9))

        self.configureTags(self.text)

        self.vsb = tk.Scrollbar(self.tab1, orient=tk.VERTICAL)
        self.text.configure(yscrollcommand=self.vsb.set)
        self.vsb.configure(command=self.text.yview)

        self.linenumbers = TextLineNumbers(self.tab1, width=55)
        self.linenumbers.attach(self.text)

        self.vsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.linenumbers.pack(side="left", fill="y")
        self.text.pack(side="right", fill="both", expand=True)

        self.notebook.add(self.tab1, text=self.fileName)

        self.text.bind("<<Change>>", self._on_change)
        self.text.bind("<Configure>", self._on_change)
        self.text.bind("<KeyRelease>", self.keypress)
        self.text.bind("<Button-1>", self.keypress)

    def addtab(self):
        self.newTab = ttk.Frame(self.notebook)
        self.text = CustomText(self.newTab, bd=0, font=("Courier", 9))

        self.configureTags(self.text)

        self.vsb = tk.Scrollbar(self.newTab, orient=tk.VERTICAL)
        self.text.configure(yscrollcommand=self.vsb.set)
        self.vsb.configure(command=self.text.yview)

        self.linenumbers = TextLineNumbers(self.newTab, width=55)
        self.linenumbers.attach(self.text)

        self.vsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.linenumbers.pack(side="left", fill="y")
        self.text.pack(side="right", fill="both", expand=True)

        self.notebook.add(self.newTab, text="Untitled Document")

        self.text.bind("<<Change>>", self._on_change)
        self.text.bind("<Configure>", self._on_change)
        self.text.bind("<KeyRelease>", self.keypress)
        self.text.bind("<Button-1>", self.keypress)

    def removetab(self):
        numberOfTabs = self.notebook.index("end")

        if numberOfTabs > 1:
            tabIndex = self.notebook.index(self.notebook.select())
            self.notebook.forget(tabIndex)

    def run(self):
        pass

    def menubar(self):
        self.menu = tk.Menu(self)
        self.master.config(menu=self.menu)

        self.fileMenu = tk.Menu(self.menu, font=("Courier", 9))
        self.fileMenu.add_command(label="New             Ctrl+N", command=self.newFile)
        self.fileMenu.add_command(label="Open            Ctrl+O", command=self.openFile)
        self.fileMenu.add_command(label="Save            Ctrl+S", command=self.saveFile)
        self.fileMenu.add_command(label="Save As         Ctrl+Shift+S", command=self.saveAsFile)
        self.fileMenu.add_separator()
        self.fileMenu.add_command(label="New Window", command=self.addtab)
        self.fileMenu.add_command(label="Close Window", command=self.removetab)
        self.fileMenu.add_separator()
        self.fileMenu.add_command(label="Exit            Alt+F4", command=self.close)
        self.menu.add_cascade(label="File", menu=self.fileMenu)

        self.runMenu = tk.Menu(self.menu, font=("Courier", 9))
        self.runMenu.add_command(label="Run", command=self.run)
        self.menu.add_cascade(label="Run", menu=self.runMenu)

    def bottomLabel(self):
        self.positionAndLanguage = tk.Label(self, text=" Ln: 1, Col: 0, Lang: Plain", anchor=tk.W, bg="#E7E7E7", font=("Courier New", 8))
        self.positionAndLanguage.pack(fill=tk.X, side=tk.BOTTOM)

    def updateBottomLabel(self):
        self.row = self.text.index(tk.INSERT).split(".")[0]
        self.column = self.text.index(tk.INSERT).split(".")[1]
        self.positionAndLanguage["text"] = " Ln: {0}, Col: {1}, Lang: {2}".format(self.row, self.column, self.language)

    def newFile(self):
        self.fileName = "Untitled"
        self.previousContent = ""
        self.text.delete(0.0, tk.END)

    def openFile(self):
        try:
            self.fileName = tk.filedialog.askopenfilename() #Asks user to open file
            with open(self.fileName, 'r') as file:
                self.content = file.read() #Reads content typed
            self.text.delete(0.0, tk.END)
            self.text.insert(0.0, self.content)
            self.highlight(self)
        except IOError as e:
            print("Error reading file.")
        except:
            print("Unexpected error occured.")

    def deleteContent(self, file):
        file.seek(0)
        file.truncate()

    def saveFile(self):
        self.content = self.text.get(0.0, tk.END)

        try:
            with open(self.fileName, 'w') as file:
                self.deleteContent(file)
                file.write(self.content)
        except IOError as e:
            print("Error reading file.")
        except:
            print("Unexpected error occured.")

    def saveAsFile(self):
        self.content = self.text.get(0.0, tk.END)

        try:
            self.fileName = tk.filedialog.asksaveasfilename()
            if self.fileName != None:
                with open(self.fileName, 'w') as file:
                    file.write(self.content)
        except IOError as e:
            print("Error reading file.")
        except:
            print("Unexcepted error occured.")

    def close(self):
        try:
            os._exit(0)
        except:
            print(sys.exc_info()[0])

    def _on_change(self, event):
        self.linenumbers.redraw()

if __name__ == "__main__":
    root = tk.Tk()
    root.title("Arshi")
    root.geometry("1024x600")
    window = Arshi(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

A: Yes, as you observed, the issue is because you are always changing the linenumbers to the linenumber of the latest tab, so for old tabs , even if the _on_change() is called, it would call redraw only on the new line number, not on the old ones.
I believe the correct way to go forward for your application would be to have another level of abstraction, where Tab is a complete object by itself, and each tab should be a different object and should keep store the linenumber/text in itself.
Example -
import tkinter as tk
import tkinter.ttk as ttk

class TextLineNumbers(tk.Canvas):
    def __init__(self, *args, **kwargs):
        tk.Canvas.__init__(self, *args, **kwargs)
        self.textwidget = None

    def attach(self, text_widget):
        self.textwidget = text_widget

    def redraw(self, *args):
        '''redraw line numbers'''
        self.delete("all")

        i = self.textwidget.index("@0,0")
        while True:
            dline= self.textwidget.dlineinfo(i)
            if dline is None: break
            y = dline[1]
            linenum = str(i).split(".")[0]
            self.create_text(5,y,anchor="nw", text=linenum, font=("Courier", 9))
            i = self.textwidget.index("%s+1line" % i)

class CustomText(tk.Text):
    def __init__(self, *args, **kwargs):
        tk.Text.__init__(self, *args, **kwargs)

        self.tk.eval('''
            proc widget_proxy {widget widget_command args} {

                # call the real tk widget command with the real args
                set result [uplevel [linsert $args 0 $widget_command]]

                # generate the event for certain types of commands
                if {([lindex $args 0] in {insert replace delete}) ||
                    ([lrange $args 0 2] == {mark set insert}) ||
                    ([lrange $args 0 1] == {xview moveto}) ||
                    ([lrange $args 0 1] == {xview scroll}) ||
                    ([lrange $args 0 1] == {yview moveto}) ||
                    ([lrange $args 0 1] == {yview scroll})} {

                    event generate  $widget <<Change>> -when tail
                }

                # return the result from the real widget command
                return $result
            }
            ''')
        self.tk.eval('''
            rename {widget} _{widget}
            interp alias {{}} ::{widget} {{}} widget_proxy {widget} _{widget}
        '''.format(widget=str(self)))

        self.comment = False

class Tab:
    def __init__(self, parent, filename):
        self.parent = parent
        self.filename = filename
        self.tab1 = ttk.Frame(parent)
        self.text = CustomText(self.tab1, bd=0, font=("Courier", 9))

        self.vsb = tk.Scrollbar(self.tab1, orient=tk.VERTICAL)
        self.text.configure(yscrollcommand=self.vsb.set)
        self.vsb.configure(command=self.text.yview)

        self.linenumbers = TextLineNumbers(self.tab1, width=55)
        self.linenumbers.attach(self.text)

        self.vsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.linenumbers.pack(side="left", fill="y")
        self.text.pack(side="right", fill="both", expand=True)

        parent.add(self.tab1, text=filename)

        self.text.bind("<<Change>>", self._on_change)
        self.text.bind("<Configure>", self._on_change)

    def _on_change(self, event):
        self.linenumbers.redraw()

class Window(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.fileName = "Untitled Document"
        self.content = ""
        self.previousContent = ""
        self.language = "Python"
        self.row = "0"
        self.column = "0"
        self.startCol = 0

        self.notebook = ttk.Notebook(self)
        self.tabs = []
        self.menubar()
        self.createtext()

    def createtext(self):
        self.notebook.pack(fill=tk.BOTH, expand=True)
        t = Tab(self.notebook, self.fileName)
        self.tabs.append(t)

    def addtab(self):
        t = Tab(self.notebook, self.fileName)
        self.tabs.append(t)

    def removetab(self):
        numberOfTabs = self.notebook.index("end")

        if numberOfTabs > 1:
            tabIndex = self.notebook.index(self.notebook.select())
            self.notebook.forget(tabIndex)
            del self.tabs[tabIndex]

    def menubar(self):
        self.menu = tk.Menu(self)
        self.master.config(menu=self.menu)

        self.fileMenu = tk.Menu(self.menu, font=("Courier", 9))
        self.fileMenu.add_command(label="New Window", command=self.addtab)
        self.fileMenu.add_command(label="Close Window", command=self.removetab)
        self.menu.add_cascade(label="File", menu=self.fileMenu)

if __name__ == "__main__":
    root = tk.Tk()
    root.title("Window")
    root.geometry("1024x600")
    window = Window(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

I created a new class Tab and copied code from previous methods like createtext into it, and now when creating a new tab, we just need to instantiate object of Tab class.

Partially working code , for your case -
import tkinter as tk
import tkinter.filedialog
import traceback
import tkinter.ttk as ttk

from pygments import lex
from pygments.lexers import PythonLexer

import sys
import os

class TextLineNumbers(tk.Canvas):
    def __init__(self, *args, **kwargs):
        tk.Canvas.__init__(self, *args, **kwargs)
        self.textwidget = None

    def attach(self, text_widget):
        self.textwidget = text_widget

    def redraw(self, *args):
        '''redraw line numbers'''
        self.delete("all")

        i = self.textwidget.index("@0,0")
        while True:
            dline= self.textwidget.dlineinfo(i)
            if dline is None: break
            y = dline[1]
            linenum = str(i).split(".")[0]
            self.create_text(5,y,anchor="nw", text=linenum, font=("Courier", 9))
            i = self.textwidget.index("%s+1line" % i)

class CustomText(tk.Text):
    def __init__(self, *args, **kwargs):
        tk.Text.__init__(self, *args, **kwargs)

        self.tk.eval('''
            proc widget_proxy {widget widget_command args} {

                # call the real tk widget command with the real args
                set result [uplevel [linsert $args 0 $widget_command]]

                # generate the event for certain types of commands
                if {([lindex $args 0] in {insert replace delete}) ||
                    ([lrange $args 0 2] == {mark set insert}) ||
                    ([lrange $args 0 1] == {xview moveto}) ||
                    ([lrange $args 0 1] == {xview scroll}) ||
                    ([lrange $args 0 1] == {yview moveto}) ||
                    ([lrange $args 0 1] == {yview scroll})} {

                    event generate  $widget <<Change>> -when tail
                }

                # return the result from the real widget command
                return $result
            }
            ''')
        self.tk.eval('''
            rename {widget} _{widget}
            interp alias {{}} ::{widget} {{}} widget_proxy {widget} _{widget}
        '''.format(widget=str(self)))

        self.comment = False

class Tab:
    def __init__(self, parent, filename, parentwindow):
        self.fileName = "Untitled Document"
        self.content = ""
        self.previousContent = ""
        self.parentwindow = parentwindow
        self.language = "Python"
        self.parent = parent
        self.filename = filename
        self.tab1 = ttk.Frame(parent)
        self.text = CustomText(self.tab1, bd=0, font=("Courier", 9))

        self.vsb = tk.Scrollbar(self.tab1, orient=tk.VERTICAL)
        self.text.configure(yscrollcommand=self.vsb.set)
        self.vsb.configure(command=self.text.yview)

        self.linenumbers = TextLineNumbers(self.tab1, width=55)
        self.linenumbers.attach(self.text)

        self.vsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.linenumbers.pack(side="left", fill="y")
        self.text.pack(side="right", fill="both", expand=True)

        parent.add(self.tab1, text=filename)
        self.bottomLabel()

        self.text.bind("<<Change>>", self._on_change)
        self.text.bind("<Configure>", self._on_change)
        self.text.bind("<KeyRelease>", self.keypress)
        self.text.bind("<Button-1>", self.keypress)

    def deafultHighlight(self, argument):
        self.content = self.text.get("1.0", tk.END)
        self.lines = self.content.split("\n")

        if (self.previousContent != self.content):
            self.text.mark_set("range_start", self.row + ".0")
            data = self.text.get(self.row + ".0", self.row + "." + str(len(self.lines[int(self.row) - 1])))

            for token, content in lex(data, PythonLexer()):
                self.text.mark_set("range_end", "range_start + %dc" % len(content))
                self.text.tag_add(str(token), "range_start", "range_end")
                self.text.mark_set("range_start", "range_end")

        self.previousContent = self.text.get("1.0", tk.END)

    def highlight(self, argument):
        self.content = self.text.get("1.0", tk.END)

        if (self.previousContent != self.content):
            self.text.mark_set("range_start", "1.0")
            data = self.text.get("1.0", self.text.index(tk.INSERT))

            for token, content in lex(data, PythonLexer()):
                self.text.mark_set("range_end", "range_start + %dc" % len(content))
                self.text.tag_add(str(token), "range_start", "range_end")
                self.text.mark_set("range_start", "range_end")

        self.previousContent = self.text.get("1.0", tk.END)

    def keypress(self, argument):
        self.updateBottomLabel()
        self.deafultHighlight("argument")

    def _on_change(self, event):
        self.linenumbers.redraw()

    def bottomLabel(self):
        self.positionAndLanguage = tk.Label(self.parentwindow, text=" Ln: 1, Col: 0, Lang: Plain", anchor=tk.W, bg="#E7E7E7", font=("Courier New", 8))
        self.positionAndLanguage.pack(fill=tk.X, side=tk.BOTTOM)

    def updateBottomLabel(self):
        self.row = self.text.index(tk.INSERT).split(".")[0]
        self.column = self.text.index(tk.INSERT).split(".")[1]
        self.positionAndLanguage["text"] = " Ln: {0}, Col: {1}, Lang: {2}".format(self.row, self.column, self.language)

class Arshi(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.fileName = "Untitled Document"
        self.content = ""
        self.previousContent = ""
        self.language = "Python"
        self.row = "0"
        self.column = "0"
        self.startCol = 0
        self.tabs = []
        self.notebook = ttk.Notebook(self)

        self.menubar()
        #self.bottomLabel()
        self.createtext()

    def deafultHighlight(self, argument):
        self.content = self.text.get("1.0", tk.END)
        self.lines = self.content.split("\n")

        if (self.previousContent != self.content):
            self.text.mark_set("range_start", self.row + ".0")
            data = self.text.get(self.row + ".0", self.row + "." + str(len(self.lines[int(self.row) - 1])))

            for token, content in lex(data, PythonLexer()):
                self.text.mark_set("range_end", "range_start + %dc" % len(content))
                self.text.tag_add(str(token), "range_start", "range_end")
                self.text.mark_set("range_start", "range_end")

        self.previousContent = self.text.get("1.0", tk.END)

    def highlight(self, argument):
        self.content = self.text.get("1.0", tk.END)

        if (self.previousContent != self.content):
            self.text.mark_set("range_start", "1.0")
            data = self.text.get("1.0", self.text.index(tk.INSERT))

            for token, content in lex(data, PythonLexer()):
                self.text.mark_set("range_end", "range_start + %dc" % len(content))
                self.text.tag_add(str(token), "range_start", "range_end")
                self.text.mark_set("range_start", "range_end")

        self.previousContent = self.text.get("1.0", tk.END)

    def keypress(self, argument):
        self.updateBottomLabel()
        self.deafultHighlight("argument")

    def configureTags(self, text):
        text.tag_configure("Token.Keyword", foreground="#CC7A00")
        text.tag_configure("Token.Keyword.Constant", foreground="#CC7A00")
        text.tag_configure("Token.Keyword.Declaration", foreground="#CC7A00")
        text.tag_configure("Token.Keyword.Namespace", foreground="#CC7A00")
        text.tag_configure("Token.Keyword.Pseudo", foreground="#CC7A00")
        text.tag_configure("Token.Keyword.Reserved", foreground="#CC7A00")
        text.tag_configure("Token.Keyword.Type", foreground="#CC7A00")

        text.tag_configure("Token.Name.Class", foreground="#003D99")
        text.tag_configure("Token.Name.Exception", foreground="#003D99")
        text.tag_configure("Token.Name.Function", foreground="#003D99")

        text.tag_configure("Token.Operator.Word", foreground="#CC7A00")

        text.tag_configure("Token.Comment", foreground="#B80000")

        text.tag_configure("Token.Literal.String", foreground="#248F24")

    def createtext(self):
        self.notebook.pack(fill=tk.BOTH, expand=True)
        t = Tab(self.notebook, self.fileName, self)
        self.tabs.append(t)

    def addtab(self):
        t = Tab(self.notebook, self.fileName, self)
        self.tabs.append(t)

    def removetab(self):
        numberOfTabs = self.notebook.index("end")

        if numberOfTabs > 1:
            tabIndex = self.notebook.index(self.notebook.select())
            self.notebook.forget(tabIndex)

    def run(self):
        pass

    def menubar(self):
        self.menu = tk.Menu(self)
        self.master.config(menu=self.menu)

        self.fileMenu = tk.Menu(self.menu, font=("Courier", 9))
        self.fileMenu.add_command(label="New             Ctrl+N", command=self.newFile)
        self.fileMenu.add_command(label="Open            Ctrl+O", command=self.openFile)
        self.fileMenu.add_command(label="Save            Ctrl+S", command=self.saveFile)
        self.fileMenu.add_command(label="Save As         Ctrl+Shift+S", command=self.saveAsFile)
        self.fileMenu.add_separator()
        self.fileMenu.add_command(label="New Window", command=self.addtab)
        self.fileMenu.add_command(label="Close Window", command=self.removetab)
        self.fileMenu.add_separator()
        self.fileMenu.add_command(label="Exit            Alt+F4", command=self.close)
        self.menu.add_cascade(label="File", menu=self.fileMenu)

        self.runMenu = tk.Menu(self.menu, font=("Courier", 9))
        self.runMenu.add_command(label="Run", command=self.run)
        self.menu.add_cascade(label="Run", menu=self.runMenu)

    def bottomLabel(self):
        self.positionAndLanguage = tk.Label(self, text=" Ln: 1, Col: 0, Lang: Plain", anchor=tk.W, bg="#E7E7E7", font=("Courier New", 8))
        self.positionAndLanguage.pack(fill=tk.X, side=tk.BOTTOM)

    def updateBottomLabel(self):
        self.row = self.text.index(tk.INSERT).split(".")[0]
        self.column = self.text.index(tk.INSERT).split(".")[1]
        self.positionAndLanguage["text"] = " Ln: {0}, Col: {1}, Lang: {2}".format(self.row, self.column, self.language)

    def newFile(self):
        self.addtab()

    def openFile(self):
        try:
            self.fileName = tk.filedialog.askopenfilename() #Asks user to open file
            with open(self.fileName, 'r') as file:
                self.content = file.read() #Reads content typed
            self.text.delete(0.0, tk.END)
            self.text.insert(0.0, self.content)
            self.highlight(self)
        except IOError as e:
            print("Error reading file.")
        except:
            print("Unexpected error occured.")

    def deleteContent(self, file):
        file.seek(0)
        file.truncate()

    def saveFile(self):
        self.content = self.text.get(0.0, tk.END)

        try:
            with open(self.fileName, 'w') as file:
                self.deleteContent(file)
                file.write(self.content)
        except IOError as e:
            print("Error reading file.")
        except:
            print("Unexpected error occured.")

    def saveAsFile(self):
        self.content = self.text.get(0.0, tk.END)

        try:
            self.fileName = tk.filedialog.asksaveasfilename()
            if self.fileName != None:
                with open(self.fileName, 'w') as file:
                    file.write(self.content)
        except IOError as e:
            print("Error reading file.")
        except:
            print("Unexcepted error occured.")

    def close(self):
        try:
            os._exit(0)
        except:
            print(sys.exc_info()[0])

    def _on_change(self, event):
        self.linenumbers.redraw()

if __name__ == "__main__":
    root = tk.Tk()
    root.title("Arshi")
    root.geometry("1024x600")
    window = Arshi(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

Currently, open() would not work , and the bottom labels come up duplicated for each tab, you should think about how to work those out. The bottom label one can move out of Tab class back to Arshi , and then have some communication between Tab class and Arshi when tabs are changed to change the bottom label accordingly.
Also, open should open a new tab, so you can easily work on that. I would also advice you to understand the complete code and then use it in your code , rather than just copy-paste.


text:
Q: How can I add custom dimensions to a custom report in google analytics I just set up some custom dimensions in google analytics e.g. one dimension is for facebook login status another for twitter and so on. Now i want make an custom report for the social login status of my visitors.
My tracking works. I checked it with the google analytics debugger.
How can I add custom dimensions to custom reports in google analytics?

A: Just select the custom dimension you'd like to see from the list of dimensions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I copy all fields of one table to another, wider table in SQL Server 2005 Express? I know my title isn't exactly worded well, so let me clarify.  I'm using SQL Server 2005 Express.
I have a table that basically stores a "template," if you will.  Using a car as an example, the fields would be something like:
TemplateID
Color
Make
Model

Now, I have another table that represents an "instance" of the template.  It contains all the fields of the template table plus some fields that are unique to an instance:
InstanceID
VIN
SerialNumber
Color
Make
Model

I am writing a stored procedure to insert a new row into the "Instance" table.  This stored procedure will take input parameters for "VIN" and "SerialNumber," but I want it to copy "Color", "Make", and "Model" from the appropriate "Template."  The template is located by the "TemplateID," which is already known.
I am looking for advice on how to write this stored procedure.  It would be simple if it weren't for the fact that these tables contain 100+ fields (I didn't design them but I'm stuck using them.)  I would like to do something like:
INSERT INTO Instance(VIN, SerialNumber, "EverythingElse")
VALUES (@VIN, @SerialNumber, SELECT * FROM Template WHERE TemplateID = 1)

In other words, I only want to supply (through parameters) those fields not stored in the "Template" and copy everything else from the template.  Is anything like this possible without hand coding for every field?

A: Then you can use dynamic SQL like this...
DECLARE
    @Fields nvarchar(Max),
    @SQL nvarchar(Max);

SELECT
    @Fields = COALESCE(@Fields + ',', '') + column_name
FROM
    information_schema.columns
WHERE
    table_schema = 'dbo' AND
    table_name = 'Instance' AND
    column_name <> 'PrimaryKeyID' --here you exclude columns
ORDER BY
    ordinal_position;

SET @SQL = 'INSERT INTO dbo.Instance'
    + ' ('
    + @Fields
    + ') SELECT '
    + ' ('
    + @Fields
    + ') FROM Template;'

EXECUTE sp_executesql @SQL;

A: Just do a INSERT INTO and use a SELECT statement instead of a values statement.
INSERT INTO Instance(VIN, SerialNumber, a, b, c)
SELECT @VIN, @SerialNumber, a, b, c FROM Template WHERE TemplateID = 1;

You really don't want to use *. You can have SQL Server Managemnt Studio script a SELECT statement for you and it will generate the field names so you don't have to type them.


text:
Q: How to remove a matplotlib collection The Python program below plots a random set of 3 points and circles around them according to the eps slider value.
When changing the slider value, the circles change.
Also, if two circles touch each other, a segment connecting their centers is  drawn.
My problem is: how to remove such segment if the eps decreases so there is no intersection anymore?
In resume, how to remove the line collection from the plot?
MWE
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
from matplotlib import collections  as mc

# create circles
circles = []
def create_circles(N):
    for i in range(N):
        circles.append(plt.Circle(pts[i], min_distance/10, ec="b", fill=False))
        ax.add_patch(circles[i])

# create edges
def create_edges(eps):
    edges = []
    tmp = np.where(distance_matrix < 2 * eps)
    edges_ij = zip(tmp[0], tmp[1])
    for e in edges_ij:
        if e[0] < e[1]:
            edges.append([pts[e[0]], pts[e[1]]])
    lc = mc.LineCollection(edges, colors='r', linewidths=1)
    ax.add_collection(lc)

# create points
def create_points(N):
    ptsx = np.random.random(N)
    ptsy = np.random.random(N)
    pts = zip(ptsx, ptsy)
    return pts

# create distance matrix
def create_distance_matrix(pts):
    N = len(pts)
    distance_matrix = np.zeros((N, N))
    for i in range(N-1):
        for j in range(i+1,N):
            P = pts[i]
            Q = pts[j]
            distance_matrix[i, j] = np.sqrt((P[0]-Q[0])**2 + (P[1]-Q[1])**2)
            distance_matrix[j, i] = distance_matrix[i, j]
    max_distance = np.max(distance_matrix)
    min_distance = np.min(distance_matrix[distance_matrix > 0])
    return min_distance, max_distance, distance_matrix

# when epsilon slider changes
def update_eps(val):
    eps1 = eps_slider.val
    create_edges(eps1)
    for i in range(len(circles)):
        circles[i].set_radius(eps1)
    fig.canvas.draw_idle()

axis_color = 'lightgoldenrodyellow'
bullet_size = 4

xmin, xmax = 0, 1
ymin, ymax = 0, 1
delta = .2
xlim = [xmin-delta, xmax+delta]
ylim = [ymin-delta, ymax+delta]

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
ax.axis([xlim[0], xlim[1], ylim[0], ylim[1]])
ax.set_aspect("equal")

N_0 = 3
N_max = 10

pts = create_points(N_0)
min_distance, max_distance, distance_matrix = create_distance_matrix(pts)
create_circles(N_0)
eps_0 = min_distance / 3

# create sliders
eps_slider_ax  = fig.add_axes([0.25, 0.15, .65, 0.03], facecolor=axis_color)
N_slider_ax = fig.add_axes([0.25, 0.1, 0.65, 0.03], facecolor=axis_color)
eps_slider = Slider(eps_slider_ax, 'eps', min_distance/3, max_distance, valinit=eps_0)
N_slider = Slider(N_slider_ax, 'Num pts', 1, N_max, valinit=2, valfmt="%i")
eps_slider.on_changed(update_eps)

# Draw the initial plot
desenho = ax.scatter([x[0] for x in pts], [x[1] for x in pts], alpha=1, s=bullet_size)
plt.show()


text:
Q: What are the frequencies of current in computers' external peripheral cables and internal buses? From Wikipedia, three different cases of current frequency are discussed along with the types of cables that are suitable for them:

An Extra Ordinary electrical cables suffice to carry low
  frequency AC, such as mains power, which reverses direction 100 to
  120 times per second (cycling 50 to 60 times per second).
However, they cannot be used to carry currents in the radio frequency
  range or higher, which reverse direction millions to billions of times
  per second, because the energy tends to radiate off the cable as radio
  waves, causing power losses. Radio frequency currents also tend to
  reflect from discontinuities in the cable such as connectors, and
  travel back down the cable toward the source. These reflections act as
  bottlenecks, preventing the power from reaching the destination.
  Transmission lines use specialized construction such as precise conductor dimensions and spacing, and impedance matching, to carry
  electromagnetic signals with minimal reflections and power losses.
  Types of transmission line include ladder line, coaxial cable,
  dielectric slabs, stripline, optical fiber, and waveguides. The higher
  the frequency, the shorter are the waves in a transmission medium.
  Transmission lines must be used when the frequency is high enough
  that the wavelength of the waves begins to approach the length of the
  cable used.
To conduct energy at frequencies above the radio range, such as
  millimeter waves, infrared, and light, the waves become much smaller
  than the dimensions of the structures used to guide them, so
  transmission line techniques become inadequate and the methods of
  optics are used.

I wonder what the frequencies are for the currents in computers' external peripheral cables, such as Ethernet cable, USB cable, and in computers' internal buses? Are the cables also made specially for the frequencies?
Thanks!

A:
I wonder what the frequencies are for the currents in computers' external peripheral cables, such as Ethernet cable, USB cable, and in computers' internal buses?

This information should be available in either the appropriate Wikipedia articles or in the relevant technical standards (which are probably referred to in those articles)
In general the signalling rate or frequency is not the same as the data rate (due to encoding, the use of multiple transmission channels (e.g. pairs) and other factors) but dividing by ten will give you a (very) rough idea.
For example, 1000Base-T Ethernet has a data rate of 10^9 bits/second, so you could assume a signalling frequency that is 100 MHz.
For the actual rate, use Google (which would lead you to relevant articles)

Are the cables also made specially for the frequencies?

Yes.
Sometimes the data transmission standards are made to match an existing cable specification. For example, I believe the original 10Base-T spec was designed so people could use existing premises wiring standards that had been designed for voice telephony not for Ethernet. This reduced the cost of deploying 10Base-T and may (in a small way) have helped sales of Ethernet products.

Update:
If you want a rigorous answer, be careful about using vague terms like electricity.
Note that (so far as I know) most electrical signalling systems used with computer peripherals nowadays look at voltage changes at specific frequencies, they don't look at current (c.f. current-loop interface). So it isn't useful to think of "current frequency".
Note: I am not an electronic engineer.


text:
Q: TextView's text doesn't change? i'm facing a problem that i never came accross before:
well i successfully applyed the 3D transition between a listview and someother layout container some info about the selected item. well the probelm is: some of the textviews are displayed correctly while others display nothing, even the imageview is shown as expected...
any suggestions?
thanks in advance..

A: I fixed this: well i don't know the exact reason but it solved the problem
i changed the textview id in the layout and it worked fine. Weird why it didn't work until this..if any one can explain it would be great^^

A: I guess you had same collision in android:name tags. Acting wierd could happen by many reasons, but one of the most liklly to happen is when you have some collision in names, I mean more views defined with same name
@+id/something definition and @id/something reference is okey
but having @+id/something twice sometimes could be a problem.
This kind of references is usually used in relative layaout when you say I want this view to be to the left (or above, or below) some other view. Then you must give a reference to other view...

A: I have 2 text view with the same id, one of them is inside the parent layout and the other one was in the viewpager which is child of the parent layout. I changed the latter one is and the problem is solved.


text:
Q: looking for approximation/expansion of $f(t)=a(t)/\sqrt{b(t) + \epsilon(t)}$ with $\epsilon(t) << b(t)$ I have the following function
$
f(t) = \frac{a(t)}{\sqrt{b(t) + \epsilon(t)}}
$
defined for $t\geq 0$. I know that $a(t) > 0$, $b(t) > 0$, $\epsilon(t) \geq 0$ and $\epsilon(t) << b(t) $ $\forall t\geq0$ (and, in particular, $\epsilon(0) = 0$, whereas $b(0)=b_0 >> 0$).
What can I do to find an approximation/expansion for $f(t)$ leveraging on the small size of $\epsilon(t)$? May I use some sort of Taylor/Mac-Laurin expansion?
Or some functional-derivative like reasoning?
Thanks in advance


text:
Q: Список городов для сайта Поделитесь опытом разработки пожалуйста. Нужно вывести на выбор список городов России на сайте, потом это значение отправить контроллеру. Как это можно сделать без бд?

A: Есть много сервисов, где по IP определяют местоположения пользователя например этот или этот. Города сохраняешь (можешь добавлять только строго RU) в сессию + каждый раз накапливаешь когда заходят клиенты. Потом когда надо отправляешь в контроллер.


text:
Q: how to allow filter in cassandra with java datastax I created a table and two indexes on it i am not able to do filter query from my spring application

first i created table
CREATE TABLE keyspace.favourite_setting (
id uuid,
user_name text,
filter_name text,
columns LIST<FROZEN<columns_def>>,
filters text,
PRIMARY KEY (id)

);
second i added two indexes
CREATE INDEX IF NOT EXISTS user_name_index ON keyspace.favourite_setting (user_name)
CREATE INDEX IF NOT EXISTS filter_name_index ON keyspace.favourite_setting (filter_name);

then i am trying to filter shows me error you must allow filter although i am doing it already...
My Accessory
@Accessor
 public interface FavouriteSettingAccessor {

@Query("select * from favourite_setting where user_name =:userName allow filtering  " )
Result<FavouriteSetting> getAllByUserName(@Param("userName") String userName );

      }

my Service Impl
@Override
public List<FavouriteSetting> getAllFilterNames(String userName) throws  Exception {

    session = cassandraFactory.getDataSource();

    favouriteSettingAccessor =
            new MappingManager(session).createAccessor(FavouriteSettingAccessor.class);

    return favouriteSettingAccessor.getAllByUserName(userName).all();
}

My Favourite Setting Model
@Table(keyspace = "keyspace", name = "favourite_setting")
public class FavouriteSetting {

@PartitionKey
@Column(name = "id")
private UUID id;

@Column(name = "user_name")
private String userName;

@Column(name = "filter_name")
private String filterName;

@Column(name = "columns")
private List<ColumnsDef> columns;

@Column(name = "filters")
private String filters;

 public FavouriteSetting(UUID id, String userName, String filterName,
 List<ColumnsDef> columns, String filters) {
    this.id = id;
    this.userName = userName;
    this.filterName = filterName;
    this.columns = columns;
    this.filters = filters;
}

public FavouriteSetting() {
}

public UUID getId() {
    return id;
}

public void setId(UUID id) {
    this.id = id;
}

public String getFilterName() {
    return filterName;
}

public void setFilterName(String filterName) {
    this.filterName = filterName;
}

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public List<ColumnsDef> getColumns() {
    return columns;
}

public void setColumns(List<ColumnsDef> columns) {
    this.columns = columns;
}

public String getFilters() {
    return filters;
}

public void setFilters(String filters) {
    this.filters = filters;
}

}
Cannot execute this query as it might involve data filtering and thus may have unpredictable performance. If you want to execute this query despite the performance unpredictability, use ALLOW FILTERING

A: For the query
@Query("select * from favourite_setting where user_name =:userName ... " )

userName is not part of the primary key, you can set it as a clustering key. For more information you can look here or here.
Please note that there is no alter statement to add a clustering key, you will need to recreate the table with:
CREATE TABLE keyspace.favourite_setting (
id uuid,
user_name text,
filter_name text,
columns LIST<FROZEN<columns_def>>,
filters text,
PRIMARY KEY (id, username)

The index created for the username column is considered one of the antipatterns for indexes, as it will be expected to be unique (and therefore, it will have high cardinality); you can find more information of why this is a problem here
allow filtering should never be used, as explained here you should resist the urge to just add ALLOW FILTERING to it. You should think about your data, your model and what you are trying to do.

A: It works Now By adding user_name As Cluster Key and ADD To The End of Query ALLOW FILTERING ..
Thanks :)


text:
Q: Entity Class v Entity Bean What is the difference between an Entity Class and an Entity Bean? When I right click on Enterprise Beans in Netbeans 7.4 there is no Entity Bean option as shown below:

I am a .NET Developer.  I have spent time Googling but have not found an answer.

A: To answer the title question:

*

*Entity Bean refer to the EJB Spec 2.x

*Entity Class is part of Java Persistence API (JPA) and is a "replacement" for Entity Bean, which are no more part of EJB 3.x, although backward compatibility is guaranteed

Then, related to it:

*JPA is the ORM standard since JEE 5, and is basically a standard by Oracle, various vendor provide its concrete implementation (EclipseLink, Hibernate, ecc...). JPA is a specification itself

*EJB 2.x the only transaction demarcation allowed is CMT = Container Managed Transaction, which means the app server (container) will manage the rollback if error occurs

*CMP is not a replacement for JPA

If you are starting from scratch, maybe for learning purpose, always start with classic stack EJB 3.x (stateless, statefull, message driven, singleton) for business logic and Entity Class for persistence part.


text:
Q: making convolution in matlab manualy I want to make convolution image processing in matlab without to use (conv2) command
I want to use (.^) command with 2 for loop
I make this code to make LoG 5x5 filter
but it not work in this line (I(r,c) =sum(sum( Mask.* I( (r-2):(c-2), (r+2):(c+2) ) ));)
clc
clear;
Img = imread ('11.jpg');                                               %reading Image
for x = 1:size(Img,1)                                                  % converting to Gray
    for y =1:size(Img,2)
        G (x,y)= (Img(x,y,1)*0.3 + Img(x,y,2)*0.59 + Img(x,y,1)* 0.11);
    end
end
Mask = [0,0,-1,0,0;0,-1,-2,-1,0;-1,-2,16,-2,-1;0,-1,-2,-1,0;0,0,-1,0,0]; % the mask
I=double(G);Mask=double(Mask);
% I=conv2(G,Mask);                                                      % masking quickly
for r = 3: size(I,1)-2                                                  %masking manualy
   for c = 3: size(I,2)-2
      I(r,c) =sum(sum( Mask.* I( (r-2):(c-2), (r+2):(c+2) ) ));
   end
end
imshow(Img);title('Orginal Image');
figure,imshow(G);title('Gray Image');
figure,imshow(uint8(I));title('Proccessed Image');

A: Debug is a good way to solve some problems.
When c = 4, r = 3(The second loop in "for c = 3: size(I,2)-2")
I( (r-2):(c-2), (r+2):(c+2) ) is a 2 * 2 Matrix,
and Mask is a 5*5 Matrix.
So the error message is "Matrix dimensions must be consistent".


text:
Q: What is the syntax error of below sql code? the following is my code
DELIMITER $$

USE `trealcap_crm`$$

DROP PROCEDURE IF EXISTS `moovpay_update_status`$$

CREATE DEFINER=`trealcap_admin`@`%` PROCEDURE `moovpay_update_status`()
BEGIN
DECLARE id INT;
DECLARE current INT ;
DECLARE totalCount INT ;
DECLARE fundmoney2 DECIMAL;
SET current = 0;
IF (ROW_COUNT() > 0)

BEGIN
END
END$$

DELIMITER ;

but after i execute , it give me the error, the error is there
IF (ROW_COUNT() > 0)
    BEGIN
    END$$
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'BEGIN
END' at line 9
what wrongs with that begin in mysql?

A: The if statement in MySQL has the syntax:
    IF (ROW_COUNT() > 0) THEN
        . . .
    END IF;

You still need the
END$$

for the procedure BEGIN/END block.


text:
Q: Django static files does not load while in the root directory I stored my static files in project root directory but I can't make them load on the browser.

*

*configurations

*

*settings.py

STATIC_DIR = os.path.join(BASE_DIR, 'static')

STATIC_URL = '/static/'
STATICFILES_DIR = [
    STATIC_DIR,
]

*template file

<!DOCTYPE html>
{% load static %}

        <meta charset="utf-8">
        <title>Index</title>

{{temp}}

Click here to veiw user details

A: In the file urls.py add the static url.
urlpatterns = [
    path('admin/', admin.site.urls),
    ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)


text:
Q: Form mysql read and writeback So im able to read data from db to populate the forms the way i want to.
<?php
$dbQuery_custom_toggle = "SELECT * ";

$dbQuery_custom_toggle .= "FROM custompage";
$result_custom_toggle = mysql_query($dbQuery_custom_toggle) or die("Couldn't get file        list");
while($row = mysql_fetch_array($result_custom_toggle)) {
?>
<?php echo $row['np_menu_titel'];?> <input type="checkbox" name="np_menu_active_post" value="" <?php if($row['np_menu_active'] == "1"){echo 'checked="checked"';}?> />

<?php
 }
 ?>

So this will populate the form with all the available rows.
Meaning this will get me as many checkboxes (with name) as there are entry's in the db
The problem im having, how do i return EACH value back to the db?
  update custompages SET np_menu_active ='?' ,

i have no clue here, any help is appreciated,
i want when the form is submitted, that it sends back 1 to each row corrosponding with the checkbox.

A: Better make the checkboxes an array.
<input type="checkbox" name="np_menu_active_post[]" value="" <?php if($row['np_menu_active'] == "1"){echo 'checked="checked"';}?> />

Then post it to wherever you want and process like this.
$chekbox_vals = $_POST['np_menu_active_post']; // This will pass the selected checkbox values as an array

if(count($chekbox_vals) > 0) {
     // Loop it and update the values in DB

}

A: If your database has an id field you can use AJAX to update database using onchange() event
<?php echo $row['np_menu_titel'];?> <input type="checkbox" name="np_menu_active_post" id="<?php echo $row['id'];?>"value="" onchange="doAJAX(<?php echo $row['id'];?>)"<?php if($row['np_menu_active'] == "1"){echo 'checked="checked"';}?> />


text:
Q: PHP: RegEx match all URLs that are outside links so far i've been using this regex code to get the ID of a YouTube video
"/https?:\/\/w*.?(?:youtube.com|youtu.be)\/watch\/\?v=([A-Za-z0-9\-_]+)/i"

i tried extending it, so it would ignore IDs of YouTube videos in HTML links (href="..")
"/[?:(^href=\")]https?:\/\/w*.?(?:youtube.com|youtu.be)\/watch\/\?v=([A-Za-z0-9\-_]+)/i"

unfortunately, that's not doing it. in fact the full code produces the opposite result.
$input = array(
    'http://youtube.com/watch/?v=oKay1',
    'http://youtu.be/watch/?v=oKay2',
    'href="http://youtube.com/watch/?v=NICHToKay"', //this shouldn't be found
    '[url="http://youtube.com/watch/?v=oKay3]'
    );

$pattern = "/[?:(^href=\")]https?:\/\/w*.?(?:youtube.com|youtu.be)\/watch\/\?v=([A-Za-z0-9\-_]+)/i";

foreach($input as $v) {
    $match = preg_match_all($pattern, $v, $result);
    print "$v => $match\n";
    if ($match == 1)
        var_dump($result);
}

any help please?

A: try this (based on your 4 given values in the arrays):
/^(\[url\="){0,1}http[s]{0,1}\:\/\/(www\.){0,1}(youtube\.com|youtu\.be)\/watch\/\?v\=(.+)(\]){0,1}/ims

you will get your ID in 3rd array of results

A: Try this , i got it from another link on this site
preg_match('#<object[^>]+>.+?http://www.youtube.com/v/([A-Za-z0-9\-_]+).+?</object>#s', $markup, $matches);

var_dump($matches[1]);

Source : Get Youtube Video ID from html code with PHP


text:
Q: Convert Seq to Map by custom key How do I convert the following JavaScript array to an Immutable.Map that is keyed by  the 'id' of each object in the list?
    id: 'all',
    label: 'All',
    isSelected: false
  }, {
    id: '1',
    label: '1',
    isSelected: true
  }, {
    id: '2',
    label: '2',
    isSelected: false
  }, {
    id: '3',
    label: '3',
    isSelected: false
}]

I'd like to be able to do:
// {id: 'all', label: 'All', isSelected: true}

A: This can be achieved completing using immutable JS like below.
var buttons = [{
    id: 'all',
    label: 'All',
    isSelected: false
  }, {
    id: '1',
    label: '1',
    isSelected: true
  }, {
    id: '2',
    label: '2',
    isSelected: false
  }, {
    id: '3',
    label: '3',
    isSelected: false
}];

buttonImmutableList = Immutable.fromJS(buttons)
buttonImmutableMap = buttonImmutableList.reduce((a,c)=>  a.set(c.get('id'),c), Immutable.Map())

A: Using immutable:
var buttons = [{
    id: 'all',
    label: 'All',
    isSelected: false
  }, {
    id: '1',
    label: '1',
    isSelected: true
  }, {
    id: '2',
    label: '2',
    isSelected: false
  }, {
    id: '3',
    label: '3',
    isSelected: false
}];

var array = {};

for(var index in buttons) {
    var token = buttons[index];
    array[token.id] = token;
}

var map = new Immutable.Map(array);

var test = map.get('all');

window.alert(test.label);

In case you want to add key -> values later, the map is modified, and thus, the current instance invalidated. To do it, you need to reasign the variable map to the lastest returned valid instance:
map = map.set(key, value);


text:
Q: slice, channel of empty interface as function argument I would like to implement a parallelization function, which in the absence of generics, looks like so:
func Parallelize(s []interface{}, c chan interface{}, f func(interface{}, chan interface{})) {
    var wg sync.WaitGroup
    defer wg.Done()

    for _, si := range s {
        wg.Add(1)
        go f(si, c)
    }

    wg.Wait()
    close(c)
}

I'd like to enable passing objects of any type, but to ensure that the first argument is a slice of objects, second is a channel and third is a function that accepts an object and channel.
Apparently, the go compiler doesn't like the arguments. It is not allowing me to call this function like so:
a := make([]*A)
c := make(chan *A)
f := func(_a *A, _c chan A) {
   ...
}
Parallelize(a, c, f)

What is the right way of going about this?

A: There are several ways you can do this, though the best in my opinion is not to do it. This is one of those common patterns that is best left explicit because it is much easier to read and maintain. However, if you insist:
One way to do it is realizing that you don't really need to pass the slice elements:
func Parallelize(n int, c chan interface{}, f func(int, chan interface{})) {
    var wg sync.WaitGroup
    defer wg.Done()

    for i:=0;i<n;i++ {
        wg.Add(1)
        go f(i, c)
    }

    wg.Wait()
    close(c)
}

And call it using:
Parallelize(len(slice), ch, func(i int,ch chan interface{}) {
   // use slice[i]
})

You also don't need to pass the channel:
func Parallelize(n int, f func(int)) {
    var wg sync.WaitGroup
    defer wg.Done()

    for i:=0;i<n;i++ {
        wg.Add(1)
        go f(i)
    }

    wg.Wait()
}

And call it:
Parallelize(len(slice), func(i int) {
   // use slice[i] and chan ch
})`
close(ch)

Another way of doing this is using reflection. It'll be uglier, and you'll have to deal with runtime errors instead of compile time errors.


text:
Q: Adding break down of grand total in report I'm creating Salesforce.com report, I need a breakdown of the grand total based on different grouping. Is there a supported way to achieve this?
Below is my situation:

                                            Amount
Summarized by field A (Type1)               1000
    Summarized by field B (SubA)             500
    Summarized by field B (SubB)             500

Summarized by field A (Type2)               2000
    Summarized by field B (SubA)            1000
    Summarized by field B (SubC)            1000

Summarized by field A (Type3)               1000
    Summarized by field B (SubB)            1000

Grand Total                                  4000
    Summarized by field B (SubA)            1500
    Summarized by field B (SubB)            1500
    Summarized by field B (SubC)            1000


text:
Q: Removing duplicate entry from an array using hashmap int main(array<System::String ^> ^args)

{

    int arr[]={1,2,3,2,9,8,1,2,3,9};
    int a[9];
    int size = sizeof(arr)/sizeof(arr[0]);
    int str[256]= {'\0'};
    int i = 0;
    for(i ; i < size ; i++)
    {
        if(str[arr[i]] == 0 )
        str[arr[i]]= 1;
    }
    for( i = 0 ; i < size ; i++)
    {
        if( str[arr[i]] == 1)
        {
            a[i] = arr[i];
        }
    }
    for(i=0 ; i < size ; i++)
    {
        printf("%d->",a[i]);

    }

    return 0;
}

still in the new array a,I am getting old data...not sure wats missing here...
Any help would be highly appreciated.
Thanks in advance.

A: Logical mistakes

*

*the final array won't go till size

*the indexing for a is wrong

Simply use one loop to achieve this, analyze following :
int i = 0,j=0;

for( ; i < size ; i++)
{
    if(str[arr[i]] == 0 )
    {
        str[arr[i]]= 1;
        a[j++] = arr[i];
    }
}

Now iterate till j on final array a


text:
Q: Unable to update field security profile for a attribute in crm 2011 Today i did some security update, and then i found some attributes which was enabled by field security profile, in these field data is not showing and data is present in data base. So i try to disable and delete field security profile but it is showing this error
Unhandled Exception:
System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Caller 45844c6e-b79f-df11-aaa1-00155d01f81c does not have full permissions on the attribute 'hrms_lastincrdate' to unsecure the attributeDetail:
 <OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
   <ErrorCode>-2147158771</ErrorCode>
   <ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
   <Message>Caller 45844c6e-b79f-df11-aaa1-00155d01f81c does not have full permissions on the attribute 'hrms_lastincrdate' to unsecure the attribute</Message>
   <Timestamp>2013-07-08T06:32:05.8793184Z</Timestamp>
   <InnerFault i:nil="true" />
   <TraceText i:nil="true" />
 </OrganizationServiceFault>

So please give your precious suggestions.
Thanks.

A: It looks like your security profile might not have the required permissions to make that change, are you a system administrator?


text:
Q: Uncaught in promise, failed to fetch when uploading file to AWS S3 I'm trying to upload files to S3, but am getting this error (I edited the name of the bucket). When putting in a try/catch block, I can  see the error is "access denied."
mockServiceWorker.js:130 Uncaught (in promise) TypeError: Failed to fetch
    at mockServiceWorker.js:130:72
    at handleRequest (mockServiceWorker.js:135:7)
index.js:1227
 POST https://name-of-bucket.s3-us-west-1.amazonaws.com/ net::ERR_ABORTED 400 (Bad Request)
localhost/:1 Uncaught (in promise)
Response {type: 'cors', url: 'https://name-of-bucket.s3-us-west-1.amazonaws.com/', redirected: false, status: 400, ok: false, …}
body: (...)
bodyUsed: false
headers: Headers
[[Prototype]]: Headers
ok: false
redirected: false
status: 400
statusText: "Bad Request"
type: "cors"
url: "https://name-of-bucket.s3-us-west-1.amazonaws.com/"
[[Prototype]]: Response

This is the code I'm using.
import React, { useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import { nanoid } from '@reduxjs/toolkit'
import { postAdded } from './PostsSlice'
import S3 from 'react-aws-s3'

export function AddPostForm() {

//Removed

    const ReactS3Client = new S3(config)
    ReactS3Client.uploadFile(file, newFileName).then((data) => {
      console.log(data)
      if (data.status === 204) {
        console.log('success')
      } else {
        console.log('fail')
      }
    })
  //Removed rest of code
}

This is the CORS policy I'm using for S3. Does anyone know what I could be doing wrong? Does this have to do with CORS, or is it an issue with S3, or is there a syntax error? I checked that the bucket name is correct and the region.
[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "PUT",
            "HEAD",
            "GET",
            "POST"
        ],
        "AllowedOrigins": [
            "http://localhost:3000"
        ],
        "ExposeHeaders": []
    }
]


text:
Q: Clicking a button in Access Form using VBA Excel This is my code below. I am getting an error "Object doesn't support this property or method" on controls.click. Anyone there who can help?
    'create new access object
    Set appAccess = CreateObject("Access.Application")
    'open the acces project
    Call appAccess.OpenCurrentDatabase("D:\NSE Cash\db.accdb")
    appAccess.Visible = True
    With appAccess
        Application.DisplayAlerts = False
        .DoCmd.OpenForm "Form1"
        .Forms("Form1").Controls("Run").Click
    End With
    Set appAccess = Nothing

A: First, the button Click event cannot be Private - remove Private from the procedure declaration. Then, this works for me:
.Forms("Form1").Run_Click


text:
Q: RubyMine project directory disappears after git pull My coworker and I started working on the same project using GitHub and RubyMine.
Our original sin was to push .idea folder (created and updated automatically by RubyMine) in my local repository to GitHub.
This folder creates conflict with my co-worker's local repository every time he pulls from remote.
To fix this issue, we have to delete .idea folder from remote repository. Now, from my master branch, I pull from remote repository, and it seems that .idea files were removed (I am not sure). Therefore, RubyMine won't let me see my project folders (i.e., app, config, public) in Project view, even though these folders are still there.
My question is: how can I restore original setting in RubyMine where I can see my project folders?

A: The only files from .idea folder that you should not push are workspace.xml and tasks.xml.
First you should untrack those files with:
git rm --cached .idea/workspace.xml
git rm --cached .idea/tasks.xml

Next add them to .gitignore:
.idea/workspace.xml
.idea/tasks.xml

Now simply remove .idea folder and reopen the project folder with rubymine.

A: You can try the following:

*

*Make sur your project is versionned with git (run git info)

*Close rubymine and reopen it

*Pay attention to messages on the top right : find the message complaining that "git root is unregistered"

*Click on register git root in the message

*In the configuration window, click the message in red: add git root

*Quickdiffs in files should work now.

If you don't have the message about git when you open rubymine, you can go to the options (command+,), then search version control and click on the first result. Then you should have a table with 2 columns:
/-----------------------------\
| Directory          | VCS    |
+--------------------+--------+
| <Project>          | <none> |
+--------------------+--------+
| /home/user/project | Git    |
\-----------------------------/

If your project is not listed here, try adding it.


text:
Q: Prestashop zero tax on product if product group and user have vat number can anybody now which class i need modify when I need condition if product group id 5 and customer address has vat number, on this product group will be applied 0% tax?

A: You'll need to interact with the
/classes/tax/TaxCalculator.php

file.
Especially you'll need to override the costruct to return the expected taxes array based on your needs.


text:
Q: push local environment variable stored in .env.local to Vercel project How to push all environment variables stored in .env.local to a Vercel project?
Do I really need to add them one by one with
vercel env add [name] [environment] [gitbranch] < [file]
as specified in the docs
https://vercel.com/docs/cli/env


text:
Q: What are upper bounds for the mutual information $I(X:Y)$? The Shannon entropy of a discrete random variable ${\textstyle X}$ with possible values ${\textstyle \left\{x_{1},\ldots ,x_{n}\right\}}$ and probability mass function ${\textstyle \mathrm {P} (X)}$ is defined:
$${\displaystyle \mathrm {H} (X)=-\sum _{i=1}^{n}{\mathrm {P} (x_{i})\log _{2}\mathrm {P} (x_{i})}}.$$
The measure should be maximal if all the outcomes are equally likely (uncertainty is highest when all possible events are equiprobable); in this case $H\leq\log _{2}(n)$.
Let us consider two discrete random variables ${\displaystyle X}$ and ${\displaystyle Y}$. Mutual information can be equivalently expressed as
$$\operatorname {I} (X;Y)=\mathrm {H} (X)+\mathrm {H} (Y)-\mathrm {H} (X,Y),$$
where ${\displaystyle \mathrm {H} (X)}$ and ${\displaystyle \mathrm {H} (Y)}$ are the marginal entropies, and ${\displaystyle \mathrm {H} (X,Y)}$ is the joint entropy of ${\displaystyle X}$ and ${\displaystyle Y}$.
I wonder if there exists an upper bound for $\operatorname {I} $ like the $H\leq\log _{2}(n)$ and if it involves the equiprobability of events.

A: First :

in this case $H\leq\log _{2}(n)$.

should be

in this case $H = \log _{2}(n)$; hence in general $H\leq\log _{2}(n)$

Regarding upper bounds for $I(X;Y)$, you should write
$$I(X;Y)=H(X) -H(X|Y) \implies I(X;Y) \le H(X) \le \log(|\mathcal X|)$$
where $|\mathcal X|$ is the cardinality of the alphabet for $X$ ($n$ above).
Because you can also write $I(X;Y)=H(Y) -H(Y|X)$ you get
$$I(X;Y) \le \log( \min(|\mathcal X|,|\mathcal Y|))$$


text:
Q: google sitemaps and custom tags I would like to add a custom tag or attribute to the google sitemap for internal use.
I can't find any documentation on this so I would like to ask if anybody has done something similar?

A: You can't add your own tags to an XML sitemap as they are not valid as described in the schema. If you do this you run the risk of the sitemap being rejected or causing errors.

A: I am using custom attributes (seem to work fine) and elements (cause errors, but are ignored by Google Webmaster Tools).
See details here:
https://stackoverflow.com/a/32628830/1117929


text:
Q: Why my SVG is responsive but occasionally? I've created a 1000×1000 svg , but when I am running it in Chrome browser , if viewport size is less than 1000 the svg image is cropped automatically, having said that, I am not witnessing this problem in jsFiddle ! I am curious if it has anything to do with viewport dimension?
Take a look at what I'm trying:

<svg viewbox="0 0 1000 1000" xmlns="http://www.w3.org/2000/svg">
  <path d="M100 100 h800 v800 h-800 v-800" fill="black" stroke="red" stroke-width="8" style="  stroke-dasharray: 4000;
  stroke-dashoffset: 4000;
  animation: dash 2s linear forwards infinite;" /><style>@keyframes dash {
  to {
    stroke-dashoffset: 0;
  }
}</style>
  <text x="120" y="200" fill="skyblue" style="font-size:30;">
1: We do not endorse 'Aarogya Setu App'.
<tspan x="120" y="300">
2: To use this App you have to share
</tspan>
<tspan x="120" y="400">
your Name, Age, Sex, Location, Job and
</tspan>
<tspan x="120" y="500">
other details with govt authorities.
 </tspan>
 <tspan x="120" y="600">
3: Also these details are transferred to
 </tspan>
 <tspan x="120" y="700">
nearby devices, via bluetooth using an
 </tspan>
 <tspan x="120" y="800">
encryption model, use only if you trust
 </tspan>
 <tspan x="120" y="870">
  your govt.
  </tspan>
</text>
</svg>

Here is jsFiddle link: https://jsfiddle.net/3fuh7ntj/
To see above svg in your browser, click here: https://covidnmap.000webhostapp.com/graphics.svg


text:
Q: How to move zero axis to the last position in python? How to move zero axis to the last position in python?
I tried
a.swapaxis(0,-1)

but it not only put zero axed to the end, but also put last axis to the beginning.
I tried to play with rollaxis but didn't understand what it does.

A: I think you're looking for moveaxis:
In [11]: a = np.arange(8).reshape(2, 2, 2)

In [12]: a
Out[12]:
array([[[0, 1],
        [2, 3]],

       [[4, 5],
        [6, 7]]])

In [13]: a.swapaxes(0, -1)
Out[13]:
array([[[0, 4],
        [2, 6]],

       [[1, 5],
        [3, 7]]])

In [14]: np.moveaxis(a, 0, -1)
Out[14]:
array([[[0, 4],
        [1, 5]],

       [[2, 6],
        [3, 7]]])


text:
Q: Is there a way to edit the opacity of a font? I've seen plenty of stuff for changing the opacity for jpanel and images, but no matter how hard I look I can't find anything for changing the opacity of the font and only the font. Preferably would like to not have to import a library if possible.
Just normal font code:
   Font font = new Font("SansSerif", Font.BOLD, 15);

   setFont(font);

A: In Swing you should extend LabelUI to achieve label opacity.
Try this
    class OpacityLabelUI extends BasicLabelUI {

        private int alpha = 0x55;

        public void setAlpha(int alpha) {
            this.alpha = alpha;
        }

        @Override
        protected void paintEnabledText(JLabel l, Graphics g, String s, int textX, int textY) {
            int mnemIndex = l.getDisplayedMnemonicIndex();
            g.setColor(applyAlpha(l.getForeground()));
            SwingUtilities2.drawStringUnderlineCharAt(l, g, s, mnemIndex, textX, textY);
        }

        private Color applyAlpha(Color color) {
            color = new Color((color.getRGB() & 0xffffff) | (alpha << 24), true);
            return color;
        }
    }

and then
label.setUI(new OpacityLabelUI());


text:
Q: SharePoint Login prompt cancel redirect I have configured FBA Form authentication and also using window authentication. For form authentication, Until user logged in to site, they stay to login page.
But when we do window authentication, it prompts for authentication. If we pass username and password, it redirect to home page but if we press cancel, it shows access denied page at url http://servername/_windows/default.aspx, but my req is to redirect page to login page again.
is there any to achieve this?
is it possible to redirect to FBA login page from login cancel button?


text:
Q: Can I use Boost's format library to replace iostream? I don't like to use <iostream> in C++ Library. I prefer to use something that is similar to "printf" and "scanf" in <stdio.h>.
Can I use Boost's format library to replace <iostream> in all my C++ program ?

A: Boost Format only does the formatting bit. You still need iostream to actually make something appear on the screen.
Of course, using them together will achieve the parity with printf you are looking for. And it does so without sacrificing type-safety (though that's not a huge issue these days, since the compiler will usually warn about bad printf arguments).

A: Boost.Format works with ostreams. You use it as follows
cout << boost::format("%2% %1%") % 36 % 77;

or like
string s2 = str( format("%2% %1%") % 36 % 77 );

and the print the string as you want.
Boost.Format doesn't works with istreams.

A: You can continue to use printf in C++, nothing wrong with that. Just #include <cstdio> and you're good to go. Of course, iostream has several benefits (type-safety being the big one) - so I'd still recommend switching.

A: printf and scanf are limited in the way you cannot use your own objects with them.
If you're using C++, you'll need to know a bit about streams, because that's the standard of the language. In C++ you can create stream operators for your own objects and have them work perfectly with streams.
Of course, you can use boost::format, but it will only be for formatted output. I like boost::format, and it's very useful, when you're using localisation for instance (translatable strings).

A: The short answer, as given by others, is yes, but there is no equivalent for scanf in Boost-format.  However, an alternative is to use Boost's Spirit library which has both input and output capabilities via the Karma and Qi components, respectively.  This may very well be overkill for what you are doing, though, as it is a full parser/generator implementation.


text:
Q: Angularjs browser back button Hie , I am using angularjs for building an end to end application.My functionality are following :
Default page is Login
After login get successful user is redirected to home page where he can search filter and can save his search.
I m facing problem with following use case: When user search some result and after that if he save some search history.If he press the browser back button the page must be redirect to again search result but page is redirected to login page always.
I want whenever user press back button of browser the page should be redirected to previous page not to login.
The complete home page is single page html and the functionality are managed by ng-if.

A: You have to use guards in application check weather user is logged in or not.
@Injectable()

export class AuthGuard implements CanActivate {

auth: any = {};

constructor(private authService: AuthService, private router: Router) {

}

canActivate() {
    if (/*user is logged in*/) {
        this.router.navigate(['/dashboard']);
        return true;
    }
    else {
        this.router.navigate(['/Login']);
    }
    return false;
}
}


text:
Q: How do I create a SCCM package where the main installation initiates self-contained msi's? I have a few applications that are installed using InstallShield -- during the installation one or two parts of the application are installed with msi's.  I've tried recording an iss file to instruct the installation process, but these installations always seem to freeze up.  I've also tried installing in a sequence, first installing the msi's, but this doesn't prevent the main installation from trying to install these.
Any tips/suggestions/ideas?
Thanks!

A: This is going to be highly dependent on the specific installer you're trying to run.  Most vendors couldn't care less about making unattended deployment easy for admins.  Your best bet is to try and find someone who's already done the work for you.  The Package KB at AppDeploy.com is a great place to start in addition to their forums.  You can also try searching the wiki at WPKG.org.
If all that fails, you will unfortunately have to dig in and figure out the problems yourself.  Enable logging everywhere you can and be prepared to spend a lot of time scouring for specific errors.  Tools like Orca for MSI editing and ProcMon can be invaluable.
SCCM packages run as SYSTEM by default.  You should try manually running your package as local admin on a test box to see if it even works at all first.  If that is successful without any user interaction, try it again running as SYSTEM using something like PsExec.  Some installers make dumb assumptions about who will be running the installer or what pieces of that user's profile will exist.
Repackaging tools that create a new installer based on pre and post snapshots exist, but they can be expensive.  They can also introduce their own problems.

A: For Installshield, the command line setup.exe /s /v/qn is your friend.
This has both the /s switch that tells the Installshield setup to run silently (and use your ISS file), and also /v/qn that tells Installshield to pass a /qn silent install switch onto the MSI(s) when it runs it.
See this page in InstallShield's documentation that lists its command line options Setup.exe and Update.exe Command-Line Parameters for further options.


text: Q: YAML to Dropdown List I am a Linux Admin. Say I have a big yaml file and I want to host it on a webpage on a Linux server in the form of a tree like structure, Exactly just like what windows registry tool REGEDIT looks like. Instead of re-inventing the wheel, is there any freeware tools or source code available that will provide this? I am open to using the source file in a different format other than yaml.


text:
Q: Attempting to write a code that numerically solves for Poiseuille Flow, which is this the right methodology to take? I am looking at writing a C++ code to solve for a Poiseuille Flow between two parallel plates. The way I am thinking about doing this is to break up the second order DE into a system of 2 DE's and then solving the first DE by using Euler's method and then the second equation using RK4 or to run the DE twice through a solver (say Euler for example). So the system is for velocity is:
$$ \frac{d^2 U_x}{dy^2} = \frac{1}{\mu} \frac{d P}{dx} $$
Where $\frac{d P}{dx}$ is a constant and $\mu$ is the viscosity. So since both of these values are essentially known and constant the system is really reduced to:
$$ \frac{d^2 U_x}{dy^2} = C $$
where C is a constant.
Now there are two methods that I was looking at doing.
The first was to run the second order ode through a solver (say Euler for convince) get values, and then run it through the solver a second time.
Or, I was looking at breaking it into a system of first order ODE's but the system the occurs doesn't seem to help with the numerical process.
I know this has an analytical solution but what I am doing is for understanding and trying to see how different boundary conditions (i.e velocity at the boundaries, or different pressure gradients) affect the outcome. My main goal would be able to adapt the code to a general case so I can see the difference between Poiseuille flow, Couette Flow, etc. and see how the velocity profiles change. I also know there is a program like OpenFOAM that can do this but it seems overkill to me to use OpenFOAM for this simple of a problem, because it is essentially solving an ODE. Any help would be greatly appreciated.

A: The system you want to solve can be summarized as
$$\frac{d^2 u}{dx^2} = c,~~~u(0) = u(L) = 0$$
which has the analytical solution $u(x) = \frac{c}{2}x(x-L)$.
This is a boundary value problem apposed to the more common initial value problem where all the conditions are specified at a single point.
The ODE is second order so to evolve it from $x=0$ we need to know both $u(0)$ and $u'(0)$. The first one we know, but the second one is determined by the condition that it gives $u(L) = 0$. A common method to solve such an ODE is to use a shooting method. In this method we simply guess a value for $u'(0)$, evolve the ODE to $x = L$ and check if $u(L) = 0$. If not we go back and guess another value for $u'(0)$ and repeat the process till we have convergence. The "guess" step usually means using a root finding method like bisection or the secant method to determine the new value of $u'(0)$ based on the old value and the difference $\epsilon = u(L) - 0$ (this is a root finding problem since $\epsilon = 0$ when we have the correct $u'(0)$).
As for solving the ODE you can use any method you like. For this purpose writing it as a system of first order equations
$$\frac{d}{dx}\pmatrix{u(x)\\z(x)} = \pmatrix{z(x)\\c},~~~\pmatrix{u(0)\\z(0)} = \pmatrix{u(0)\\u'(0)}$$
might be useful.
Here is an example of how to perform a shooting method using bisection in Mathematica
(* Define the system *)
L = 1;
c = 2;
odesystem[udot_] := NDSolve[{u''[x] == c, u[0] == 0, u'[0] == udot}, u, {x, 0, 1}];
uofL[udot_] := u[L] /. odesystem[udot][[1]];

(* We are to use bisection so check that u[L] < 0 for u'(0) = ulow and u[L] > 0 for u'(0) = uhigh *)
ulow = -2 c L; (* Pick some large negative value *)
uhigh = 2 c L; (* Pick some large positive value *)
Print[uofL[ulow]];
Print[uofL[uhigh]];

(* Do the shooting using bisection *)
epsilon = 0.0001; (* Precision in the u'(0) value we want: for simplicity we use this as convergence criterion *)
While[Abs[uhigh - ulow] > epsilon,

  (* The new value of u'(0) *)
  udotcur = (ulow + uhigh)/2.0;

  (* Solve the ODE and find the new value of u[L] *)
  uofLcur = uofL[udotcur];

  (* Bisection step: update ulow or uhigh depending on if uofLcur is positive or negative *)
  If[uofLcur < 0.0, ulow = udotcur, uhigh = udotcur ];
  ];

(* Output the values we find in the end *)
Print["The u'(0) value we need: ", ulow];
Print["The analytical u'(0) value: ", -c L/2];

which after $16$ iterations outputs:
The u'(0) value we need: -1.00006
The analytical u'(0) value: -1


text:
Q: Multiple svg with same IDs Can i put multiple svgs in a html page and use the same IDs in all of them?

  <svg height="0" width="0">
    <clipPath id="svgPath"> ........
  </svg>
  <svg height="0" width="0">
    <clipPath id="svgPath"> ........
  </svg>
  <svg height="0" width="0">
    <clipPath id="svgPath"> ........
  </svg>

A: Since the specs define the id attribute as unique per document, you should refactor the IDs or use an alternative, e.g. embedding via img or object tag.

<object type="image/svg+xml" data="my.svg" width="100" height="100"></object>

A: If you need the SVGs to be inline you should consider using an SVG injector, which changes the IDs to unique strings when inserting the SVGs into the HTML document
SVGInject adds a random string to the end of the ID for elements defined in the <defs> section. For example, svgPath may become something like svgPath-Dcs83KsE. Other SVG injectors add a running number to the ID.
Both methods were developed so the same SVG can be injected multiple times into a HTML document without creating an ID conflict. But of course it also works for different SVGs with conflicting IDs.

A: You can't write multiple id attribute in your html. Id attribute must be unique in html document.

The id attribute specifies its element's unique identifier (ID). The value must be unique amongst all the IDs in the element's.
https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#the-id-attribute

You need to use class attribute for your purpose.


text:
Q: How can I return the result of a function outside its if statement? I am trying to construct a merge sort that will then return the sorted list as a String[], but the result has to be returned outside of the if statement, and I'm not sure how to go around doing that.
public static String[] mergeSort(String[] wordList)  {
    if (wordList.length >= 2) {
        String[] left = new String[wordList.length / 2];
        String[] right = new String[wordList.length - wordList.length / 2];

        for (int i = 0; i < left.length; i++) {
            left[i] = wordList[i];
        }

        for (int i = 0; i < right.length; i++) {
            right[i] = wordList[i + wordList.length / 2];
        }

        mergeSort(left);
        mergeSort(right);
        return merge(wordList, left, right);

    }

}

public static String[] merge(String[] wordList, String[] left, String[] right) {
    int a = 0;
    int b = 0;
    for (int i = 0; i < wordList.length; i++) {
        if (b >= right.length || (a < left.length && left[a].compareToIgnoreCase(right[b]) < 0)) {
            wordList[i] = left[a];
            a++;
        } else {
            wordList[i] = right[b];
            b++;
        }
    }
    return wordList;
}

The code obviously doesn't work because the return is inside the if statement. Is there any simple way to extract the merge result?

A: Just add an else below the if-statement in your mergeSort-method and return your wordList:
else{
 return wordList;
}

When the wordList-parameter has a lenght smaller than 2, you don't need to sort it, so you can just return it in the else-branch (An array with length 0 or 1 is already sorted).

A: If the code flow reaches outside of the if condition loop, then it indicates that the array has only one element or no elements at all. Reason being, the inner if statement has a return statement, so method call always return from that statement if there are two or more elements in the array. So, you can simply add a return statement to return wordList outside the if loop.
{

  if(...)
  {
      ...
      return ... ;
  }
  return wordList ;
}


text:
Q: How to aggregate and Join or Union into flat Json object with arrays? I have data that looks like:
Customers Table
CustomerId  CustomerName CustomerEmail
------------------------------------------
1           Ben          Ben@gmail.com
2           Robert       Robert@gmail.com
3           Paul         Paul@gmail.com

CustomerContacts Table
CustomerContactId  CustomerId  ContactName   ContactEmail
----------------------------------------------------------
99                 1           Lisa          Lisa@msn.com
98                 3           Jane          Jane@msn.com
97                 3           Wendy         Wendy@msn.com

Here's the result I'm looking for:
[
    {
        "CustomerId": 1,
        "Names": [ "Ben","Lisa" ],
        "Emails": [ "Ben@gmail.com","Lisa@msn.com" ]
    },
    {
        "CustomerId": 2,
        "Names": [ "Robert" ],
        "Emails": [ "Robert@gmail.com" ]
    },
    {
        "CustomerId": 3,
        "Names": [ "Paul","Jane","Wendy" ],
        "Emails": [ "Paul@gmail.com","Jane@msn.com","Wendy@msn.com" ]
    }
]

What I have tried:
I'm embarrassed to say I'm not even close:
SELECT
    Customers.CustomerId,
     STUFF( ISNULL(',' + Customers.CustomerName, '') + ISNULL(',' + CustomerContacts.ContactName, ''),1,1,'') as Names
FROM Customers
FULL JOIN CustomerContacts
ON Customers.CustomerId = CustomerContacts.CustomerId
GROUP BY Customers.CustomerId;

A: Unfortunately, SQL Server jumped on the JSON wagon a bit late in the game (started built in support only in 2016 version), which means it's JSON support is still not great (Though what it does know how to do it does great).
Personally, I don't know of any built-in way to create a JSON array of values as a result of a query
({"Name":["Value1", "Value2"...]}) though it's quite easy to generate an array of key-value pairs
(["Name":"Value1", "Name":"Value2"...]) - at least not by using the FOR JSON clause.
However, Since you're working with 2017 and Azure versions, it is quite easy to generate such arrays yourself, using string_agg (It's a bit more cumbersome in earlier versions - using for xml path and stuff to aggregate strings).
Note the usage of WITHIN GROUP (ORDER BY CustomerContactId), that forces a specific order to the aggregated string.
Without it, the order of the names and emails of the contacts would be arbitrary (though I'm pretty sure they will probably still both be ordered the same way within one run of the query).
That being said - here's my proposed solution:
First, create and populate sample tables (Please save is this step in your future questions):
CREATE TABLE Customers (
    [CustomerId] int,
    [CustomerName] varchar(6),
    [CustomerEmail] varchar(16)
);

INSERT INTO Customers ([CustomerId], [CustomerName], [CustomerEmail]) VALUES
(1, 'Ben', 'Ben@gmail.com'),
(2, 'Robert', 'Robert@gmail.com'),
(3, 'Paul', 'Paul@gmail.com');

CREATE TABLE CustomerContacts (
    [CustomerContactId] int,
    [CustomerId] int,
    [ContactName] varchar(5),
    [ContactEmail] varchar(13)
);

INSERT INTO CustomerContacts ([CustomerContactId], [CustomerId], [ContactName], [ContactEmail]) VALUES
(99, 1, 'Lisa', 'Lisa@msn.com'),
(98, 3, 'Jane', 'Jane@msn.com'),
(97, 3, 'Wendy', 'Wendy@msn.com');

Then, use a query with FOR JSON PATH to get a json output.
The trick here is to generate the inner arrays by concatenating the CustomerName / CustomerEmail with the result of a STRING_AGG subquery of the relevant column in the CustomerContacts table.
Note the JSON_QUERY wrapper around these columns. They are needed to prevent SQL Server to escape the " chars in the json output - by telling it that the content is proper JSON.
Also, note the usage of ISNULL to act as a LEFT JOIN - you'll get all the customers, even if they don't have a corresponding record in the CustomerContacts table.
SELECT  C.CustomerId,
        JSON_QUERY(
            '["' + C.CustomerName + ISNULL('","'+
            (
                SELECT STRING_AGG(CC.ContactName, '","') WITHIN GROUP (ORDER BY CustomerContactId)
                FROM CustomerContacts As CC
                WHERE CC.CustomerId = C.CustomerId
            ), '') + '"]'
        ) As Names,
        JSON_QUERY(
            '["' + C.CustomerEmail + ISNULL('","'+
            (
                SELECT STRING_AGG(CC.ContactEmail, '","') WITHIN GROUP (ORDER BY CustomerContactId)
                FROM CustomerContacts As CC
                WHERE CC.CustomerId = C.CustomerId
            ), '') + '"]'
        ) As Emails
FROM Customers AS C
FOR JSON PATH

Result:
[
    {
        "CustomerId": 1,
        "Names": ["Ben", "Lisa"],
        "Emails": ["Ben@gmail.com", "Lisa@msn.com"]
    }, {
        "CustomerId": 2,
        "Names": ["Robert"],
        "Emails": ["Robert@gmail.com"]
    }, {
        "CustomerId": 3,
        "Names": ["Paul", "Wendy", "Jane"],
        "Emails": ["Paul@gmail.com", "Wendy@msn.com", "Jane@msn.com"]
    }
]

You can see a live demo on DB<>Fiddle
(Unfortunately, json output isn't nicely indented but it's valid none the less)


text:
Q: SQL 2008 evaluation expired - how long will the DB continue to work? We've got an instance of SQL Server 2008 running in production and I had no idea it was a trial version - until it expired! Now I can no longer run SQL Management Studio and SQL Reporting Services will not start, but SQL Server itself (ie. the database engine) continues running and users can still access data as normal (apart from reports). My question is: how long will it continue to work? Is there a time when it will just shut down and refuse to start again?

A: Pretty much the next time you reboot the server, or restart the service it won't start up again.
You can upgrade from the eval to a paid for build by using the /SKUUPGRADE switch when you install the new version from the CD/DVD/ISO.

A: I have not used the trial but as no one else has answered I would say that this is along the lines of other MS trial products - you can continue to use it until the service/program is restarted.
2008 trial to standard is a supported upgrade path, so unless there are features from enterprise you are using, I would upgrade if possible.


text:
Q: How to convert from native php to codeigniter I have the following db and php. I am trying to make a unordered list of category menu.
The original php is working by itself.
I am trying to convert this to MVC in codeigniter and the following is what I got so far and not working.
If someone can point out what I am doing wrong, I will appreciate it.
Database
CREATE TABLE IF NOT EXISTS `categories` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  `shortdesc` varchar(255) NOT NULL,
  `longdesc` text NOT NULL,
  `status` enum('active','inactive') NOT NULL,
  `parentid` int(11) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=10 DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

--
-- Dumping data for table `categories`
--

INSERT INTO `categories` (`id`, `name`, `shortdesc`, `longdesc`, `status`, `parentid`) VALUES (1, 'shoes', 'Shoes for boys and girls.', '', 'active', 7);
INSERT INTO `categories` (`id`, `name`, `shortdesc`, `longdesc`, `status`, `parentid`) VALUES (2, 'shirts', 'Shirts and blouses!', '', 'active', 7);
...
...

menu.php (original php and working)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    <title>View Tasks</title>

Menu

<?php
function make_list ($parent) {

    global $data;
    echo '
';

    foreach ($parent as $task_id => $todo) {

        echo "
$todo";

        if (isset($data[$task_id])) {

            make_list($data[$task_id]);
        }

        echo '
';

    }
    echo '
';

}

$dbc = @mysqli_connect ('localhost', 'root1', 'root', 'ci_day6') OR die ('
Could not connect to the database!
');

$q = 'SELECT id, parentid, name FROM categories ORDER BY parentid ASC';
$r = mysqli_query($dbc, $q);

$data = array();

while (list($id, $parentid, $name) = mysqli_fetch_array($r, MYSQLI_NUM)) {

    $data[$parentid][$id] =  $name;

}

make_list($data[0]);

?>

This php output the following html
Menu

    * clothes
          o shoes
          o shirts
          o pants
          o dresses
    * fun
          o toys
          o games

My MVC so far and not working.
cat_menu_model.php(model)
<?php

class Cat_menu_model extends Model
{
         function Cat_menu_model()
        {
            parent::Model();

        }

        function get_categories_nav()
        {

            $data = array();
            $this->db->select('id,name,parentid');
            $this->db->where('status', 'active');
            $this->db->orderby('parentid','asc');
            $this->db->orderby('name','asc');

            $Q = $this->db->get('categories');
        if ($Q -> num_rows() > 0){
          foreach ($Q -> result_array() as $row){
          $data[$row['parentid']][$row['id']] = $row['name'];
          }
          }

           $Q->free_result();
           return $data;

        }
}

cat_menu.php (controller)
<?php

class Cat_menu extends Controller
{

    function Cat_menu()
    {
        parent::Controller();
    }
    function make_menu($parent)
    {
        $this->load->model('cat_menu_model');

        $data['navlist'] = $this->cat_menu_model->get_categories_nav();
            $this -> load ->view('menu');
    }
}

menu.php(view)
<?php
if (count($navlist))
{
  $this->make_menu($data[0]);
  echo '
';
    foreach ($parent as $id => $catname) {

        echo "
$catname";

        if (isset($data[$id])) {

        make_menu($data[$id]);

        }

        echo '
';

    }
 echo '
';
}
?>

It shows an error messages.
A PHP Error was encountered

Severity: Warning

Message: Missing argument 1 for Cat_menu::make_menu()

Filename: controllers/cat_menu.php

Line Number: 10

A: Given the PHP error message above, it's saying that you've told the method Cat_menu::make_menu() to accept an argument. In this case the function make_menu($parent) in the Cat_menu controller.
If this function does not require any input -- doesn't look like $parent is used -- then just remove the $parent argument from make_menu.
Alternatively, set a default value if you would like the function to accept no arguments. See below:
cat_menu.php (Controller)
<?php

class Cat_menu extends Controller
{

    function Cat_menu()
    {
        parent::Controller();
    }

    function make_menu($parent = FALSE) //Is this $parent argument needed?
    {
        $this->load->model('cat_menu_model');

        $data['navlist'] = $this->cat_menu_model->get_categories_nav();

        //If you want to parse data to a view you need to state it
        $this->load->view('menu', $data);
    }
}

Assuming the rest of your code is correct, this should now work. Please see the CodeIgniter User Guide for reference from now on. Specifically the views documentation on parsing values across.

OP* has since responded in the comments below, this is my response.
**OP = Original Poster*
When running print_r($navlist) in the view. The OP gets the following output:
Array (
    [0] => Array (
        [7] => clothes
        [8] => fun
    )
    [7] => Array (
        [3] => pants
        [2] => shirts
        [1] => shoes
    )
    [8] => Array (
        [6] => games
        [5] => toys
    )
)

However, it is worth noting that the OP's CI model ActiveRecord query is significantly different than the original -- non MVC -- query:
SELECT
    id,
    parentid,
    name
FROM
    categories
ORDER BY
    parentid ASC

vs.
$this->db->select('id,name,parentid');
$this->db->where('status', 'active');
$this->db->orderby('parentid','asc');
$this->db->orderby('name','asc');
$Q = $this->db->get('categories');

The CI model query is different than the original SQL to begin with. When converted into SQL it would produce the following:
SELECT
    id,
    name,
    parentid
FROM
    categories
WHERE
    status = 'active'
ORDER BY
    parentid ASC,
    name ASC

However, it seems that this is the correct data being brought back so I'll continue on.
The OP would like the array formatted like a heirarchy. For future reference, please see: PHP/MySQL - building a nav menu hierarchy. The easiest way to do this, would be to follow the OP's original (non MVC) function and add it as a model function. This model function would create a nested array, rather than the direct html output -- the reason for this is to separate application logic from output.
You can add the following to your model as a function. Originally taken from Nested sets, php array and transformation but since re-written due to errors appearing for OP:
function to_hierarchy($collection = NULL)
{
    if (is_null($collection)) return false;

    $tree = array();

    foreach($collection[0] as $key => $value)
    {
        $tree[$value] = array();

        foreach($collection[$key] as $item)
        {
            array_push($tree[$value], $item);
        }
    }

    return $tree;
}

Now we can update our controller to be the following:
cat_menu.php (Controller)
<?php

class Cat_menu extends Controller
{

    function Cat_menu()
    {
        parent::Controller();
    }

    function make_menu($parent = FALSE) //Is this $parent argument needed?
    {
        $this->load->model('cat_menu_model');

        $get_nav_list = $this->cat_menu_model->get_categories_nav();

        $format_nav_list = $this->cat_menu_model->to_hierarchy($get_nav_list);

        //Load the HTML helper for ul/ol conversion
        $this->load->helper('html');

        $data['navlist'] = $format_nav_list;

        //If you want to parse data to a view you need to state it
        $this->load->view('menu', $data);
    }
}

Now we can update our view to be the following:
menu.php (View)
<?php
    echo ul($navlist);
?>

Disclaimer: None of the above has been tested using PHP as I currently don't have access to the interpreter from this computer. Please make sure you check over any syntax.

A: You might also consider looking at the ul() function in the built-in HTML helper, which lets you create a
 out of an array, recursively.

A: Also, you're not passing the data to the view in the controller.
it should be:
$this -> load ->view('menu',$data);
also, it looks like you would cause an infinite loop the way you currently have it set up. make_menu loads the menu.php view, but then the view calls that method.


text:
Q: java.lang.NoClassDefFoundError with Android Maven Plugin I got my android maven plugin running today and now I want to debug my apk on a real Android Device.
When I execute
cd android-proj
mvn clean install android:redeploy

and start the app on my device, I stumble across this error message in the LogCat:
10-27 21:16:08.857: E/AndroidRuntime(14556): java.lang.NoClassDefFoundError: de.dornathal.planyourmeals.android.database.AndroidDBHelper$SQLiteDatabaseAdapter

However I searched for solutions and came across that some libraries were not included correctly what could cause this problem. The class AndroidDBHelper is not included by an dependency in the maven pom, because it is a nested class in 'android-proj/android-apk'.
Where android-proj is the folder where Maven has 2 modules the apk and core functions.
As the AndroidManifest.xml has no direct link to AndroidDBHelper and AndroidDBHelper is the only class that knows about the SQLiteDatabaseAdapter the apk build by Maven must work at least a bit further than only calling the MainActivity.
MFG Dornathal

A: Okay I found out why I kept on having that issue, and for everyone who experienced the same thing:
I thought I was going to redeploy something to my device, but actually it got skipped.
To use the android:deploy or android:redeploy I had to move to the exact folder in which the pom defining the apk was. As I named two folders the same name I wasn't at the right spot with my Shell.
my tree:
android-app [<--- thats where I was]
   \--- android-app [<---- thats where I should have been]
       \---target (with apk)
   \--- android-app-it (the integration test)