text:
Q: I got a memory leak and the responsible frame is strdup. who can give me some clues? I got a memory leak when I detect with instrument. I don`t have so much experience about memory-management, so I can not figure out what is the possible cause for this problem, the memory leak is as below:

I want to know the possible reason about this kind of memory leak. Is some one who can give me some clues?

A: strdup uses malloc internally, so anything that has been strdup-ed has to be freed using free.
For example:
char *duplicate = strdup("abcdef");
...
free(duplicate);

A: strdup() is a library function, so you need to go back up the backtrace until you find a caller that's in your code.  There you'll find a library call which is resulting in memory being allocated - it should have a corresponding freeing call elsewhere in your program.
(The freeing function is not necessarily a direct call to free() - for example if you call the getaddrinfo() library function the corresponding freeing function is freeaddrinfo()).


text:
Q: Set up loop to run several crosstabs simultaneously in R I am trying to find the weighted cross tabulations of several columns. My actual data has over 500 columns so I am trying to automate the process as much as possible.
This is a snippet of my data:
data_in <- read_table2("Q50_1   Q50_2   Q38 Q90 pov gender  wgt
1   3   Yes 2   High    M   1.3
2   4   No  2   Med F   0.4
4   2   Yes 4   Low F   1.2
3   3   No  2   High    M   0.5
1   2   No  4   High    M   0.7
2   2   Yes 3   Low F   0.56
4   4   Yes 2   Med F   0.9
")

What I have tried:
I could use the library(pollster) package to find the weighted frequencies one at a time like this. I'm using pivot longer here because I need each of these to look similar so that I rbind them into a single dataset.
crosstab(df = data_in, pov, Q50_1, wgt,format = "long") %>% pivot_longer(cols = starts_with("Q"))
crosstab(df = data_in, pov, Q38, wgt, format = "long") %>% pivot_longer(cols = starts_with("Q"))

crosstab(df = data_in, gender, Q50_1, wgt,format = "long")%>% pivot_longer(cols = starts_with("Q"))
crosstab(df = data_in, gender, Q50_2, wgt,format = "long")%>% pivot_longer(cols = starts_with("Q"))

This is my desired output:
data_out <- read_table2("group  pct n   question    response    group_level
High    80  2.5 Q50_1   1   pov
High    20  2.5 Q50_1   3   pov
Low 31.8    1.76    Q50_1   2   pov
Low 68.2    1.76    Q50_1   4   pov
Med 30.8    1.3 Q50_1   2   pov
Med 69.2    1.3 Q50_1   4   pov
High    48  2.5 Q38 No  pov
High    52  2.5 Q38 Yes pov
Low 100 1.76    Q38 Yes pov
Med 30.8    1.3 Q38 No  pov
Med 69.2    1.3 Q38 Yes pov
F   31.4    3.06    Q50_1   2   gender
F   68.6    3.06    Q50_1   4   gender
M   80  2.5 Q50_1   1   gender
M   20  2.5 Q50_1   3   gender
")

More of what I have tried:
I had the idea of creating some kind of function, that loops through two vectors. The first vector contains each of the X values that will go into cross tabs and the second will contain each of the Y values that will feed into cross tabs. This is what I have so far. I have been tweaking this for some time now to no avail.
  vect <- c("gender", "pov")
vect2 <- c("Q50_1","Q38")

func2 <- function(.data, vector, vector2) {
  .data <- data_in
  wgt <- .data$wgt

  for (i in 1:length(vector))
    for (j in 1:length(vector2)) {
    out <- crosstab(df = .data, vector[i], vector2[j], wgt,format = "long")
  }
  out
}

func2(vect, vect2)

Help with:

*

*Is this a good approach to achieve my desired output? If so, why do I keep getting an error? :(

*I would like to add the functionality to this so that I create single data set with all my crosstabs (as shown in the desired output).

Any suggestions appreciated! Thank you for your help!!

A: Here is one possible way to do this. I'm sure there are better ways, but not in my current pay grade:
library(tidyverse)
library(pollster)

# Create a function that runs your crosstabs and pivots data:

xtab_func <- function(data, col, target){
  col <- sym(col)
  target <- enquo(target)
  crosstab(df = data, !!target, !!col, wgt, format = "long") %>% pivot_longer(cols = starts_with("Q"))
}

# Select 'Q' columns for your loops
cols <- data_in %>% select(starts_with("Q")) %>% names(.)

Loop through your data.frame for gender variables
d <- list()
for (i in cols){
  x <- xtab_func(data_in, i, gender)
  x$i <- i
  x$group_level <- "gender"
  d[[i]] <- x
}

Create data.frame of gender data
df <- do.call(rbind, d) %>%
  rename(group = gender)

Do the same as above for pov data
d <- list()
for (i in cols){
  x <- xtab_func(data_in, i, pov)
  x$i <- i
  x$group_level <- "pov"
  d[[i]] <- x
}

df2 <- do.call(rbind, d) %>%
  rename(group = pov)

Clean up column names and drop "i" column
final <- rbind(df, df2) %>%
  select(-i, question = name, response = value)

Final looks like this:
# A tibble: 37 x 6
   group   pct     n question value group_level
   <fct> <dbl> <dbl> <chr>    <fct> <chr>
 1 F      31.4  3.06 Q50_1    2     gender
 2 F      68.6  3.06 Q50_1    4     gender
 3 M      80    2.5  Q50_1    1     gender
 4 M      20    2.5  Q50_1    3     gender
 5 F      57.5  3.06 Q50_2    2     gender
 6 F      42.5  3.06 Q50_2    4     gender
 7 M      28.0  2.5  Q50_2    2     gender
 8 M      72    2.5  Q50_2    3     gender
 9 F      13.1  3.06 Q38      No    gender
10 F      86.9  3.06 Q38      Yes   gender

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tkinter scrollbar for frame My objective is to add a vertical scroll bar to a frame which has several labels in it. The scroll bar should automatically enabled as soon as the labels inside the frame exceed the height of the frame. After searching through, I found this useful post. Based on that post I understand that in order to achieve what i want, (correct me if I am wrong, I am a beginner) I have to create a Frame first, then create a Canvas inside that frame and stick the scroll bar to that frame as well. After that, create another frame and put it inside the canvas as a window object. So, I finally come up with this:
from Tkinter import *

def data():
    for i in range(50):
       Label(frame,text=i).grid(row=i,column=0)
       Label(frame,text="my text"+str(i)).grid(row=i,column=1)
       Label(frame,text="..........").grid(row=i,column=2)

def myfunction(event):
    canvas.configure(scrollregion=canvas.bbox("all"),width=200,height=200)

root=Tk()
sizex = 800
sizey = 600
posx  = 100
posy  = 100
root.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))

myframe=Frame(root,relief=GROOVE,width=50,height=100,bd=1)
myframe.place(x=10,y=10)

canvas=Canvas(myframe)
frame=Frame(canvas)
myscrollbar=Scrollbar(myframe,orient="vertical",command=canvas.yview)
canvas.configure(yscrollcommand=myscrollbar.set)

myscrollbar.pack(side="right",fill="y")
canvas.pack(side="left")
canvas.create_window((0,0),window=frame,anchor='nw')
frame.bind("<Configure>",myfunction)
data()
root.mainloop()

*

*Am I doing it right? Is there better/smarter way to achieve the output this code gave me?

*Why must I use grid method? (I tried place method, but none of the labels appear on the canvas.)

*What so special about using anchor='nw' when creating window on canvas?

Please keep your answer simple, as I am a beginner.

A: Here's example code adapted from the VerticalScrolledFrame page on the now defunct Tkinter Wiki that's been modified to run on Python 2.7 and 3+.
try:  # Python 2
    import tkinter as tk
    import tkinter.ttk as ttk
    from tkinter.constants import *
except ImportError:  # Python 2
    import Tkinter as tk
    import ttk
    from tkinter.constants import *

# Based on
#   https://web.archive.org/web/20170514022131id_/http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame

class VerticalScrolledFrame(ttk.Frame):
    """A pure Tkinter scrollable frame that actually works!
    * Use the 'interior' attribute to place widgets inside the scrollable frame.
    * Construct and pack/place/grid normally.
    * This frame only allows vertical scrolling.
    """
    def __init__(self, parent, *args, **kw):
        ttk.Frame.__init__(self, parent, *args, **kw)

        # Create a canvas object and a vertical scrollbar for scrolling it.
        vscrollbar = ttk.Scrollbar(self, orient=VERTICAL)
        vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
        canvas = tk.Canvas(self, bd=0, highlightthickness=0,
                           yscrollcommand=vscrollbar.set)
        canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
        vscrollbar.config(command=canvas.yview)

        # Reset the view
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        # Create a frame inside the canvas which will be scrolled with it.
        self.interior = interior = ttk.Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior,
                                           anchor=NW)

        # Track changes to the canvas and frame width and sync them,
        # also updating the scrollbar.
        def _configure_interior(event):
            # Update the scrollbars to match the size of the inner frame.
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # Update the canvas's width to fit the inner frame.
                canvas.config(width=interior.winfo_reqwidth())
        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # Update the inner frame's width to fill the canvas.
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
        canvas.bind('<Configure>', _configure_canvas)

if __name__ == "__main__":

    class SampleApp(tk.Tk):
        def __init__(self, *args, **kwargs):
            root = tk.Tk.__init__(self, *args, **kwargs)

            self.frame = VerticalScrolledFrame(root)
            self.frame.pack()
            self.label = ttk.Label(self, text="Shrink the window to activate the scrollbar.")
            self.label.pack()
            buttons = []
            for i in range(10):
                buttons.append(ttk.Button(self.frame.interior, text="Button " + str(i)))
                buttons[-1].pack()

    app = SampleApp()
    app.mainloop()

It does not yet have the mouse wheel bound to the scrollbar but it is possible. Scrolling with the wheel can get a bit bumpy, though.
edit:
to 1)
IMHO scrolling frames is somewhat tricky in Tkinter and does not seem to be done a lot. It seems there is no elegant way to do it.
One problem with your code is that you have to set the canvas size manually - that's what the example code I posted solves.
to 2)
You are talking about the data function? Place works for me, too. (In general I prefer grid).
to 3)
Well, it positions the window on the canvas.
One thing I noticed is that your example handles mouse wheel scrolling by default while the one I posted does not. Will have to look at that some time.

A: For anyone who stumbles across this (as it did when looking for my own gist) I maintain a gist for exactly this purpose at https://gist.github.com/mp035/9f2027c3ef9172264532fcd6262f3b01  It has scrollwheel support for various operating systems, is commented, and has a built-in demo in the file.

A:
"Am i doing it right?Is there better/smarter way to achieve the output this code gave me?"

Generally speaking, yes, you're doing it right. Tkinter has no native scrollable container other than the canvas. As you can see, it's really not that difficult to set up. As your example shows, it only takes 5 or 6 lines of code to make it work -- depending on how you count lines.

"Why must i use grid method?(i tried place method, but none of the labels appear on the canvas?)"

You ask about why you must use grid. There is no requirement to use grid. Place, grid and pack can all be used. It's simply that some are more naturally suited to particular types of problems. In this case it looks like you're creating an actual grid -- rows and columns of labels -- so grid is the natural choice.

"What so special about using anchor='nw' when creating window on canvas?"

The anchor tells you what part of the window is positioned at the coordinates you give. By default, the center of the window will be placed at the coordinate. In the case of your code above, you want the upper left ("northwest") corner to be at the coordinate.

A: We can add scroll bar even without using Canvas. I have read it in many other post we can't add vertical scroll bar in frame directly etc etc. But after doing many experiment found out way to add vertical as well as horizontal scroll bar :). Please find below code which is used to create scroll bar in treeView and frame.
f = Tkinter.Frame(self.master,width=3)
f.grid(row=2, column=0, columnspan=8, rowspan=10, pady=30, padx=30)
f.config(width=5)
self.tree = ttk.Treeview(f, selectmode="extended")
scbHDirSel =tk.Scrollbar(f, orient=Tkinter.HORIZONTAL, command=self.tree.xview)
scbVDirSel =tk.Scrollbar(f, orient=Tkinter.VERTICAL, command=self.tree.yview)
self.tree.configure(yscrollcommand=scbVDirSel.set, xscrollcommand=scbHDirSel.set)
self.tree["columns"] = (self.columnListOutput)
self.tree.column("#0", width=40)
self.tree.heading("#0", text='SrNo', anchor='w')
self.tree.grid(row=2, column=0, sticky=Tkinter.NSEW,in_=f, columnspan=10, rowspan=10)
scbVDirSel.grid(row=2, column=10, rowspan=10, sticky=Tkinter.NS, in_=f)
scbHDirSel.grid(row=14, column=0, rowspan=2, sticky=Tkinter.EW,in_=f)
f.rowconfigure(0, weight=1)
f.columnconfigure(0, weight=1)

A: Please see my class that is a scrollable frame. It's vertical scrollbar is binded to <Mousewheel> event as well. So, all you have to do is to create a frame, fill it with widgets the way you like, and then make this frame a child of my ScrolledWindow.scrollwindow. Feel free to ask if something is unclear.
Used a lot from @ Brayan Oakley answers to close to this questions
class ScrolledWindow(tk.Frame):
    """
    1. Master widget gets scrollbars and a canvas. Scrollbars are connected
    to canvas scrollregion.

    2. self.scrollwindow is created and inserted into canvas

    Usage Guideline:
    Assign any widgets as children of <ScrolledWindow instance>.scrollwindow
    to get them inserted into canvas

    __init__(self, parent, canv_w = 400, canv_h = 400, *args, **kwargs)
    docstring:
    Parent = master of scrolled window
    canv_w - width of canvas
    canv_h - height of canvas

    """

    def __init__(self, parent, canv_w = 400, canv_h = 400, *args, **kwargs):
        """Parent = master of scrolled window
        canv_w - width of canvas
        canv_h - height of canvas

       """
        super().__init__(parent, *args, **kwargs)

        self.parent = parent

        # creating a scrollbars
        self.xscrlbr = ttk.Scrollbar(self.parent, orient = 'horizontal')
        self.xscrlbr.grid(column = 0, row = 1, sticky = 'ew', columnspan = 2)
        self.yscrlbr = ttk.Scrollbar(self.parent)
        self.yscrlbr.grid(column = 1, row = 0, sticky = 'ns')
        # creating a canvas
        self.canv = tk.Canvas(self.parent)
        self.canv.config(relief = 'flat',
                         width = 10,
                         heigh = 10, bd = 2)
        # placing a canvas into frame
        self.canv.grid(column = 0, row = 0, sticky = 'nsew')
        # accociating scrollbar comands to canvas scroling
        self.xscrlbr.config(command = self.canv.xview)
        self.yscrlbr.config(command = self.canv.yview)

        # creating a frame to inserto to canvas
        self.scrollwindow = ttk.Frame(self.parent)

        self.canv.create_window(0, 0, window = self.scrollwindow, anchor = 'nw')

        self.canv.config(xscrollcommand = self.xscrlbr.set,
                         yscrollcommand = self.yscrlbr.set,
                         scrollregion = (0, 0, 100, 100))

        self.yscrlbr.lift(self.scrollwindow)
        self.xscrlbr.lift(self.scrollwindow)
        self.scrollwindow.bind('<Configure>', self._configure_window)
        self.scrollwindow.bind('<Enter>', self._bound_to_mousewheel)
        self.scrollwindow.bind('<Leave>', self._unbound_to_mousewheel)

        return

    def _bound_to_mousewheel(self, event):
        self.canv.bind_all("<MouseWheel>", self._on_mousewheel)

    def _unbound_to_mousewheel(self, event):
        self.canv.unbind_all("<MouseWheel>")

    def _on_mousewheel(self, event):
        self.canv.yview_scroll(int(-1*(event.delta/120)), "units")

    def _configure_window(self, event):
        # update the scrollbars to match the size of the inner frame
        size = (self.scrollwindow.winfo_reqwidth(), self.scrollwindow.winfo_reqheight())
        self.canv.config(scrollregion='0 0 %s %s' % size)
        if self.scrollwindow.winfo_reqwidth() != self.canv.winfo_width():
            # update the canvas's width to fit the inner frame
            self.canv.config(width = self.scrollwindow.winfo_reqwidth())
        if self.scrollwindow.winfo_reqheight() != self.canv.winfo_height():
            # update the canvas's width to fit the inner frame
            self.canv.config(height = self.scrollwindow.winfo_reqheight())

A: It is nessesery to configure Scrollbar in case of using with Canvas
by sending to Canvas xscrollcommand attribute Scrollbar.set method and
to Scrollbar command attribute Canvas.yview (xview) method.
Canvas.yview method after scrollbar was moved recieve *args in next formatting:
tuple('move_to', '<some_absolute_float_value_of_top_of_scrollbar_region>')
In case of implementing scrollability to widget,
Recieving region and translating scrollbar_region (whith element viewable and whith not) features must be created.
Region is `tuple(float, float)' representing open to see part of all elements.
Not ideal bechavior showed in this solution (without using tk.Canvas)
import tkinter as tk
from tkinter import ttk

class ItemizeFrame(ttk.Frame, list):
    def __init__(self,
                *args,
                scroll_upd_callback = lambda x: x,
                visible_els: int = 10,
                **kwargs):
        list.__init__(self)
        ttk.Frame.__init__(self, *args, **kwargs)

        ttk.Style().configure('Small.TButton', background='red', width=2, height=2, padx=3, pady=3)
        ttk.Style().configure('Sep.TFrame', padx=3, pady=3)

        self.scroll_upd_callback = scroll_upd_callback
        self.visible_els = visible_els
        self.visible_st_idx = 0
        self.pseudo_scroll_element_cursor_line = 0.5*1/visible_els

    def append(self, item: ttk.Widget, **kw):
        e = item(self, **kw)
        super().append(e)
        e.pack(fill='x')
        self._update_visible_els()

    def _update_visable_id_callback(self):
        for id_, entry_ in enumerate(self):
            entry_.set_id(id_)

    def pop(self, index=None):
        e = super().pop(index)
        e.destroy()
        self._update_visible_els()

    def __getitem__(self, idx) -> ttk.Widget:
        return list.__getitem__(self, idx)

    # indicators computing and application
    @property
    def visible_end_idx(self):
        return self.visible_st_idx + self.visible_els -1

    @property
    def visible_area_ratio(self) -> tuple[float, float]:
        total = len(self)
        st_val = 0.0
        end_val = 1.0
        if total > self.visible_els:
            end_val = 1.0 - (total-self.visible_end_idx)/total
            st_val = self.visible_st_idx / total
        st_val = st_val + self.pseudo_scroll_element_cursor_line
        end_val = end_val + self.pseudo_scroll_element_cursor_line
        return (st_val, end_val)

    def _update_scroll_widget(self):
        self.scroll_upd_callback(*self.visible_area_ratio)

    def set_yview(self, move_to_ratio):
        base_pseudo_ratio = 0.5*1/self.visible_els
        total = len(self)
        max_ratio = (total - self.visible_els)/total+base_pseudo_ratio
        if move_to_ratio < 0:
            possible_st_el_pseudo_part = base_pseudo_ratio
            possible_st_el_idx = 0
        if max_ratio < move_to_ratio:
            possible_st_el_idx = total - self.visible_els
            possible_st_el_pseudo_part = base_pseudo_ratio
        else :
            el_idx_raw = move_to_ratio * total
            el_idx_round = round(el_idx_raw)
            el_idx_pseudo = (el_idx_raw - el_idx_round)*1/self.visible_els
            possible_st_el_idx = el_idx_round
            possible_st_el_pseudo_part = el_idx_pseudo
        self.visible_st_idx = possible_st_el_idx
        self.pseudo_scroll_element_cursor_line = possible_st_el_pseudo_part
        self._update_visible_els()

    def _update_visible_els(self):
        for el in self:
            el.pack_forget()
        for num, el in enumerate(self):
            if self.visible_st_idx <= num and num <= self.visible_end_idx:
                el.pack()
        self._update_scroll_widget()

class ScrollableFrame(ttk.Frame):
    def __init__(self, *args, **kwargs):
        kw = dict(width=400, height=300)
        kw.update(kwargs)
        super().__init__(*args, **kw)
        self.scroll = ttk.Scrollbar(self, command=self.on_scroll)
        self.scroll.pack(expand=True, fill='y', side='right')

        self.view = ItemizeFrame(
            self,
            scroll_upd_callback=self.scroll.set,
            **kwargs
        )
        self.view.pack(expand=True, fill='both')#, side='left')

    def on_scroll(self, *args, **kwargs):
        value_raw = float(args[1])
        self.view.set_yview(value_raw)

Usecase
class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.frame = ScrollableFrame(self)
        self.frame.pack()

    def test_fill(self):
        for i in range(15):
            self.frame.view.append(ttk.Entry)

class Test:
    @staticmethod
    def v2():
        app = App()
        app.test_fill()
        app.mainloop()

Test.v2()

A: After I watching many answers, I got it:
import tkinter as tk
root = tk.Tk()
root.title("音樂編輯器")
root.geometry("600x480")

def onFrameConfigure(canvas):
    '''Reset the scroll region to encompass the inner frame'''
    canvas.configure(scrollregion=canvas.bbox("all"))
    '''When window size change, canvas size will change,
       use this line to change its item size (width).'''
    canvas.itemconfigure(wrapFrame, width=canvas.winfo_width())

canvas = tk.Canvas(root, highlightthickness=0)
frame = tk.Frame(canvas, background="#FFFFFF")
vsb = tk.Scrollbar(root, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=vsb.set)

vsb.pack(side="right", fill="y")
canvas.pack(fill="both", expand=1, anchor="nw") #canvas size is relative to window size.
wrapFrame = canvas.create_window((0,0), window=frame, anchor="nw")

# When the window size change, it will call this function
canvas.bind("<Configure>", lambda event, canvas=canvas: onFrameConfigure(canvas))

L1 = tk.Label(frame, text="音樂編輯器", bg="#556644", font=("",25))
L1.pack(anchor="n")

for i in range(100):
    input = tk.Entry(frame)
    input.pack()

root.mainloop()

Specifies the size of the scrollable frame by changing canvas and scrollbar position and size.
import tkinter as tk
root = tk.Tk()
root.title("音樂編輯器")
root.geometry("600x480")

def onFrameConfigure(canvas):
    '''Reset the scroll region to encompass the inner frame'''
    canvas.configure(scrollregion=canvas.bbox("all"))
    canvas.itemconfigure(wrapFrame, width=canvas.winfo_width())

canvas = tk.Canvas(root, highlightthickness=0)
frame = tk.Frame(canvas, background="#FFFFFF")
vsb = tk.Scrollbar(root, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=vsb.set)

vsb.place(relx=0.9, y=0, relwidth=0.1, relheight=0.5)
canvas.place(x=0, y=0, relwidth=0.9, relheight=0.5)
wrapFrame = canvas.create_window((0,0), window=frame, anchor="nw")

canvas.bind("<Configure>", lambda event, canvas=canvas: onFrameConfigure(canvas))

L1 = tk.Label(frame, text="音樂編輯器", bg="#556644", font=("",25))
L1.pack(anchor="n")

for i in range(100):
    input = tk.Entry(frame)
    input.pack()

root.mainloop()

Specifies the size of the scrollable frame by writing them to outerFrame.
import tkinter as tk
root = tk.Tk()
root.title("音樂編輯器")
root.geometry("600x480")

def onFrameConfigure(canvas):
    '''Reset the scroll region to encompass the inner frame'''
    canvas.configure(scrollregion=canvas.bbox("all"))
    canvas.itemconfigure(wrapFrame, width=canvas.winfo_width())

outerFrame = tk.Frame(root)
canvas = tk.Canvas(outerFrame, highlightthickness=0)
frame = tk.Frame(canvas, background="#FFFFFF")
vsb = tk.Scrollbar(outerFrame, orient="vertical", command=canvas.yview)
canvas.config(yscrollcommand=vsb.set)

outerFrame.place(relx=0.25, rely=0.1, relwidth=0.5, relheight=0.5)
vsb.pack(side="right", fill="y")
canvas.pack(fill="both", expand=1, anchor="nw")
wrapFrame = canvas.create_window((0,0), window=frame, anchor="nw")

canvas.bind("<Configure>", lambda event, canvas=canvas: onFrameConfigure(canvas))

L1 = tk.Label(frame, text="音樂編輯器", bg="#556644", font=("",25))
L1.pack(anchor="n")

for i in range(100):
    input = tk.Entry(frame)
    input.pack()

root.mainloop()

The items inner the frame can use pack or grid (only choose one), but place cannot be used alone. If you want to use place, you need to expand the layout(height) with pack or grid first.
import tkinter as tk
root = tk.Tk()
root.title("音樂編輯器")
root.geometry("600x480")

def onFrameConfigure(canvas):
    '''Reset the scroll region to encompass the inner frame'''
    canvas.configure(scrollregion=canvas.bbox("all"))
    canvas.itemconfigure(wrapFrame, width=canvas.winfo_width())

canvas = tk.Canvas(root, highlightthickness=0)
frame = tk.Frame(canvas, background="#FFFFFF")
vsb = tk.Scrollbar(root, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=vsb.set)

vsb.pack(side="right", fill="y")
canvas.pack(fill="both", expand=1, anchor="nw")
wrapFrame = canvas.create_window((0,0), window=frame, anchor="nw")

canvas.bind("<Configure>", lambda event, canvas=canvas: onFrameConfigure(canvas))

L1 = tk.Label(frame, text="音樂編輯器", bg="#556644", font=("",25))
L1.pack(anchor="n")

for i in range(100):
    input = tk.Entry(frame)
    input.pack()

L1 = tk.Label(frame, text="我是Label")
L1.place(x=0, rely=0.5)
root.mainloop()

Use mouse wheel:
tkinter: binding mousewheel to scrollbar
import tkinter as tk
root = tk.Tk()
root.title("音樂編輯器")
root.geometry("600x480")

def onFrameConfigure(canvas):
    canvas.configure(scrollregion=canvas.bbox("all"))
    canvas.itemconfigure(wrapFrame, width=canvas.winfo_width())

def on_mouse_wheel(event, scale=3):
    #only care event.delta is - or +, scroll down or up
    if event.delta<0:
        canvas.yview_scroll(scale, "units")
    else:
        canvas.yview_scroll(-scale, "units")

canvas = tk.Canvas(root, highlightthickness=0)
frame = tk.Frame(canvas, background="#FFFFFF")
vsb = tk.Scrollbar(root, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=vsb.set)

vsb.pack(side="right", fill="y")
canvas.pack(fill="both", expand=1, anchor="nw")
wrapFrame = canvas.create_window((0,0), window=frame, anchor="nw")

canvas.bind("<Configure>", lambda event, canvas=canvas: onFrameConfigure(canvas))
canvas.bind("<Enter>", lambda event: canvas.bind_all("<MouseWheel>", on_mouse_wheel)) # on mouse enter
canvas.bind("<Leave>", lambda event: canvas.unbind_all("<MouseWheel>")) # on mouse leave

L1 = tk.Label(frame, text="音樂編輯器", bg="#556644", font=("",25))
L1.pack(anchor="n")

for i in range(100):
    input = tk.Entry(frame)
    input.pack()

root.mainloop()

Export to class:
import tkinter as tk
root = tk.Tk()
root.title("音樂編輯器")
root.geometry("600x480")

class scrollFrame():
    def __init__(self, **options):
        outerFrame = tk.Frame(root)
        canvas = tk.Canvas(outerFrame, highlightthickness=0)
        vsb = tk.Scrollbar(outerFrame, orient="vertical", command=canvas.yview)
        vsb.pack(side="right", fill="y")
        canvas.pack(fill="both", expand=1, anchor="nw")
        frame = tk.Frame(canvas, **options)
        wrapFrameId = canvas.create_window((0,0), window=frame, anchor="nw")
        canvas.config(yscrollcommand=vsb.set)
        canvas.bind("<Configure>", lambda event: self.onFrameConfigure())
        canvas.bind("<Enter>", lambda event: canvas.bind_all("<MouseWheel>", self.on_mouse_wheel)) # on mouse enter
        canvas.bind("<Leave>", lambda event: canvas.unbind_all("<MouseWheel>")) # on mouse leave
        self.outerFrame, self.canvas, self.vsb, self.frame, self.wrapFrameId = outerFrame, canvas, vsb, frame, wrapFrameId
    def onFrameConfigure(self):
        canvas = self.canvas
        '''Reset the scroll region to encompass the inner frame'''
        canvas.configure(scrollregion=canvas.bbox("all"))
        canvas.itemconfigure(self.wrapFrameId, width=canvas.winfo_width())
    def on_mouse_wheel(self, event, scale=3):
        canvas = self.canvas
        #only care event.delta is - or +, scroll down or up
        if event.delta<0:
            canvas.yview_scroll(scale, "units")
        else:
            canvas.yview_scroll(-scale, "units")

frame = scrollFrame(background="#FFFFFF")
frame.outerFrame.place(relx=0.15, rely=0.1, relwidth=0.7, relheight=0.8)

L1 = tk.Label(frame.frame, text="音樂編輯器", bg="#556644", font=("",25))
L1.pack(anchor="n")

for i in range(100):
    input = tk.Entry(frame.frame)
    input.pack()

root.mainloop()

According:
https://stackoverflow.com/a/3092341/19470749
https://stackoverflow.com/a/16198198/19470749
https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/create_window.html

A: Not 100% sure if this solution is on topic (since it explicitely asks for a scrollable FRAME), but the text widget is basically a scrollable Frame.
From documentation of the Text widget:
"Like canvas widgets, text widgets can contain images and any other Tk widgets (including frames containing many other widgets). In a sense, this allows the text widget to work as a geometry manager in its own right. "
Text widgets are very easy to use, and can be made scrollable. So instead of using a special Class like the Scrollable Frame, I think the Text widget is a great option.
Below my code, for a basic example of a scrollable text widget holding 100 buttons:
from tkinter import Tk, Button, Text,Scrollbar

class test:
    def __init__(self):
        self.win = Tk()
        text = Text(self.win, width=40, height=10, wrap = "none")
        ys = Scrollbar(self.win, orient = 'vertical', command = text.yview)
        text['yscrollcommand'] = ys.set
        text.grid(column = 0, row = 0, sticky = 'nwes')
        ys.grid(column = 1, row = 0, sticky = 'ns')
        for x in range(1,100):
            b = Button(text, text='Push Me')
            text.window_create("end", window=b)
            text.insert("end",'\n')
        self.win.mainloop()

test = test()

This is at least the method I am going to use for my scrollable frames. Not sure if there is a better solution then the newline insertion to make the widgets organised vertically. But it works.


text:
Q: Can we execute cron jobs from bash script? This is more of discussion rather than programming question.
I am new to cron and playing around it to understand. I have a use case where the linux job or task needs to be executed within the bash script. For example, if we use systemd then this can be done using systemctl start app. But how this could be achieved using cron jobs? Can I execute */30 * * * * root /usr/bin/app from bash script? or call crontab file from bash script? I know that cron jobs needs to be included in crontab file. But I would like to know if this use case is valid? Can anyone please let me know if it works like this?
Your help will be much appreciated
Thanks in advance.


text:
Q: Debugging JavaScript cookies I'm debugging a site that sets cookies via javascript, and I'd like to know exactly which lines are setting cookies as I run the page.  Simply combing through the script is not an option because its so convoluted.. (it's not my script if you're wondering)
How can I easily find out which lines are setting cookies?  I'm new to this, so if you can explain the exact steps in doing this I'd be very thankful.
I presume that document.cookie is the only way to set cookies with javascript, but if there's another way(s) that'd definitely be helpful to know, as I might've ignored said lines in reading through the script..
Background: I'm on Windows XP

A: Yes, document.cookie is how JS sets cookies.  But remember:

*

*Other parts of the page can set cookies.  Cookies are primarily set in the HTTP response headers.  Plugins, like Flash, set tons of cookies too.

*The actual JS code that sets the cookie may be buried in a library.

*It is possible that some programmers obfuscate the JS code, so that a search for "cookie" will fail.
Things to do:

*

*Install the Web Developer add-on.  This will allow you to easily see, edit, or delete cookies, for a given page -- including 3rd party cookies.
It also allows you to View the response headers -- to easily see if the cookies are being set that way.  (clear cookies, reload the page, click: Information --> View Response Headers.)

*Install the Firebug add-on and then the Firecookie plugin for Firebug.
Firecookie can show cookie events as they are happening.  This, coupled with observation and use of JS breakpoints (Firebug feature) can help you narrow down where cookies are being manipulated.

A: Use firebug & firecookie to find the cookie's name. then search that name through the JS files using your IDE search feature.


text:
Q: Passport does not redirect after successful auth I cannot figure out why passport would nod redirect me after a successful auth to my /dashboard page. I can see the request in the Network tab of my broswer, but my page does not change, and stays on the current login page.
app.use(passport.initialize());
app.use(passport.session());

passport.use(new LocalStrategy(
    function(username, password, done) {
        database.query('SELECT * FROM users WHERE email = ?', username, (error, result, fields) => {
            if(error){
                return done(error);
            }
            if(result[0] == undefined){
                return done(null, false);
            }
            bcrypt.compare(password, result[0].password, function(err, res) {
                if(!res){return done(null, false);}
            });

            return done(null, result[0]);
        });
    }
));

passport.serializeUser(function(user, done) {
    done(null, user.email);
});

// used to deserialize the user
passport.deserializeUser(function(email, done) {
    database.query("SELECT * FROM users WHERE email = ? ", email, function(err, result, fields){
        done(err, result[0]);
    });
});

router.post('/login',
    passport.authenticate('local', { successRedirect: '/dashboard',
                                    failureRedirect: '/' }));

router.get('/login', function(request, response){
    response.render(path.resolve(__dirname, 'views', 'login.pug'));
})

router.get('/', function(request, response){
    response.render(path.resolve(__dirname, 'views', 'register.pug'));
})

Could you please help me identifying the problem?

A: The problem was that I was preventing the default behavior of the button I as using to submit the form, so the page never refreshed, resulting in the web page never updating.


text:
Q: C# Generic Type error after reflector I exported a source with reflector and i fix alot of problems there is one i haven't be able to.
    EnhancedTypeSubMenu!1.cs(28,27): error CS0305: Using the generic type 'Name.CoreDataTypes.EnhancedTypeSubMenu<T>.MenuItem<TT>' requires 1 type arguments
EnhancedTypeSubMenu!1.cs(86,22): (Related location)
EnhancedTypeSubMenu!1.cs(33,22): error CS0305: Using the generic type 'Name.CoreDataTypes.EnhancedTypeSubMenu<T>.MenuItem<TT>' requires 1 type arguments
\EnhancedTypeSubMenu!1.cs(86,22): (Related location)

Here is the class, i have the same problem in other class . Would appreciate any help.
  using System;
using System.Collections.Generic;
using System.Windows.Forms;

public abstract class EnhancedTypeSubMenu<T> : AGeeksToyToolStripMenuItem<EnhancedType<T>>
{
    public EnhancedTypeSubMenu(EnhancedType<T> DataItem, T[] ChoiceItems, string Text) : base(DataItem, Text, null)
    {
        if (ChoiceItems != null)
        {
            foreach (MenuItem<T, T> item in this.MenuItems(ChoiceItems))
            {
                base.DropDownItems.Add(new EnhancedTypeMenuItem<T, T>(DataItem, item));
            }
        }
    }

    public EnhancedTypeSubMenu(EnhancedType<T> DataItem, T[] ChoiceItems, string Text, Control ctrl) : base(DataItem, Text, ctrl)
    {
        foreach (MenuItem<T, T> item in this.MenuItems(ChoiceItems))
        {
            base.DropDownItems.Add(new EnhancedTypeMenuItem<T, T>(DataItem, item, ctrl));
        }
    }

    protected virtual MenuItem<T, T> GetMenuItem(T value)
    {
        return new MenuItem<T, T>(value);
    }

    private List<MenuItem<T, T>> MenuItems(T[] ChoiceItems)
    {
        List<MenuItem<T, T>> list = new List<MenuItem<T, T>>();
        foreach (T local in ChoiceItems)
        {
            list.Add(this.GetMenuItem(local));
        }
        return list;
    }

    public class EnhancedTypeMenuItem<TT> : AGeeksToyToolStripMenuItem<EnhancedType<TT>>
    {
        public bool CheckIfMatched;
        public readonly EnhancedTypeSubMenu<T>.MenuItem<TT> MenuItem;
        public string TranslationCategory;

        public EnhancedTypeMenuItem(EnhancedType<TT> Data, EnhancedTypeSubMenu<T>.MenuItem<TT> menuItem) : base(Data, menuItem.Text, null)
        {
            this.TranslationCategory = "Enhanced Menu";
            this.CheckIfMatched = true;
            this.MenuItem = menuItem;
        }

        public EnhancedTypeMenuItem(EnhancedType<TT> Data, EnhancedTypeSubMenu<T>.MenuItem<TT> menuItem, string translationCategory) : base(Data, menuItem.Text, null)
        {
            this.TranslationCategory = "Enhanced Menu";
            this.CheckIfMatched = true;
            this.MenuItem = menuItem;
            this.TranslationCategory = translationCategory;
        }

        public EnhancedTypeMenuItem(EnhancedType<TT> Data, EnhancedTypeSubMenu<T>.MenuItem<TT> menuItem, Control ctrl) : base(Data, menuItem.Text, ctrl)
        {
            this.TranslationCategory = "Enhanced Menu";
            this.CheckIfMatched = true;
            this.MenuItem = menuItem;
        }

        protected override void OnClick(EventArgs e)
        {
            base.MenuObject.Value = this.MenuItem.Data;
            base.OnClick(e);
        }

        public override void SetMenu()
        {
            base.Checked = this.CheckIfMatched && base.MenuObject.Equals(this.MenuItem.Data);
            this.Text = TranslationManager.Translate(this.TranslationCategory, this.MenuItem.Text.Replace('_', ' '));
            base.SetMenu();
            this.Enabled = !base.Checked;
        }
    }

    public class MenuItem<TT>
    {
        public readonly TT Data;

        public MenuItem(TT data)
        {
            this.Data = data;
        }

        public virtual string Text
        {
            get
            {
                return this.Data.ToString().Replace("__", " / ").Replace("_", " ");
            }
        }
    }
}

}
And here is a printscreen
![visual studio print][1]
http://i.stack.imgur.com/n9rpu.png
Cant post with image tag due to reputation, dont remenber my previous account :/
UPDATE //
i changed the  to  and that works but i have one last error.
private void ChangeStakingType(AGeeksToyToolStripMenuItem>.MenuData newType)
    {
        this.StakeBox.StakingType.Value = newType.Data.Value;
    }
requires 1 type argument
Is the error.
Menudata class is this one:
   namespace AGeeksToy.CoreDataTypes
{
    using System;
    using System.Windows.Forms;

    public abstract class AGeeksToyToolStripMenuItem<T> : ToolStripMenuItem, AGeeksToyMenu
    {
        public MouseButtons LastMouseButton;
        public MenuData<T> menuData;
        public static readonly VoidEventWithParam<MenuData<T>> RightClicked;

        static AGeeksToyToolStripMenuItem()
        {
            AGeeksToyToolStripMenuItem<T>.RightClicked = new VoidEventWithParam<MenuData<T>>();
        }

        protected AGeeksToyToolStripMenuItem(T obj, string text) : this(obj, text, null)
        {
        }

        protected AGeeksToyToolStripMenuItem(T obj, string text, Control ctrl)
        {
            base.DropDown.ImageList = IconManager.m_ImageList;
            this.menuData = new MenuData<T>(obj, ctrl);
            this.Text = text;
        }

        protected override void Dispose(bool disposing)
        {
            base.DropDown.ImageList = null;
            base.Dispose(disposing);
        }

        protected override void OnClick(EventArgs e)
        {
            if (this.MenuControl != null)
            {
                this.MenuControl.Refresh();
            }
            base.OnClick(e);
            if (this.LastMouseButton == MouseButtons.Right)
            {
                AGeeksToyToolStripMenuItem<T>.RightClicked.TriggerEvent(this.menuData);
            }
        }

        protected override void OnMouseDown(MouseEventArgs e)
        {
            this.LastMouseButton = e.Button;
            base.OnMouseDown(e);
        }

        public virtual void SetMenu()
        {
            this.LastMouseButton = MouseButtons.Left;
            if (this.MenuControl != null)
            {
                base.Visible = this.MenuControl.Visible;
                this.Enabled = this.MenuControl.Enabled;
            }
            foreach (ToolStripItem item in base.DropDownItems)
            {
                if (item is AGeeksToyMenu)
                {
                    (item as AGeeksToyMenu).SetMenu();
                }
            }
        }

        public T Menu_Data
        {
            get
            {
                return this.MenuObject;
            }
        }

        protected Control MenuControl
        {
            get
            {
                return this.menuData.Control;
            }
        }

        protected T MenuObject
        {
            get
            {
                return this.menuData.Data;
            }
            set
            {
                this.menuData.Data = value;
            }
        }

        public class MenuData<T>
        {
            public System.Windows.Forms.Control Control;
            public T Data;

            public MenuData(T obj, System.Windows.Forms.Control ctrl)
            {
                this.Data = obj;
                this.Control = ctrl;
            }
        }
    }

If anyone can run the project here and check the problem i would really appreciate
here is the download link:
http://code.google.com/p/agt-betfair-bot/downloads/list

A: You have defined MenuItem<TT>.
But yet you are using MenuItem<T, T> which it is complaining about.

A: Not sure if this was some sort of search and replace error, but try replacing all instances of this:
MenuItem<T, T>

with this:
MenuItem<T>

This seems to be the source of the problem. This seems to be the correct name for the type parameter in the context I see the original.

A: MenuItem only uses a single type argument, that's what the error says.
See the declaration of the class: MenuItem<TT>. So you only need to pass one type argument to it.


text:
Q: What do you say when you don't know someone's gender? For example, I want to refer to someone on the internet, but I don't know this person's gender. Which personal-pronoun do I use? (as article I mean he, she, it, etc)

A: It's perfectly fine to use they in the singular sense. (Verbs are conjugated the same as they would be in the plural sense: "are they joking?", "did they break anything?".)
All the same, when the gender is not known, some authors prefer constructions like (s)he, he/she, he or she, she or he, etc., some prefer to stick with the masculine pronoun as default (he), others prefer to stick with the feminine pronoun for balance (she), some will alternate using he and she in their writing.

A: When talking about a hypothetical person, "they" is quite established usage, although "he or she" is more formal.

Someone posting a question should always clearly indicate the type of answer they want.

or

Someone posting a question should always clearly indicate the type of answer he or she wants.

However, you can risk offending someone if you use "they" about that person in particular -- almost as much as if you guessed and used the wrong gender.  In that case, I would re-write the sentence to reuse the user name or to use other nouns:

As @ntrx clearly states in the question...

or

As the original poster clearly stated...


text:
Q: Erdös cardinals in $L$ I've readed in Jech's book that the existence of the $\omega-$Erdös cardinal $\kappa(\omega)$ (that is the minimumm cardinal $\kappa$ for which $\kappa\rightarrow (\omega)^{<\omega}$) it is compatible with the axiom of constructibility $V=L$. More precisely, it can be shown that if $\kappa=\kappa(\omega)$ exists then $L\vDash\kappa\rightarrow (\omega)^{<\omega}$.
In this regard, I would like to ask some things about some of the details of that proof. First of all assuming the existence of a monochromatic set $H$ (in $V$) for a colouring $c:[\kappa(\omega)]^{<\omega}\longrightarrow 2$ in $L$, we want to see that there exists a monochromatic set $H'\in L$ for $c$. For this purpouse Jech defines a tree $T$ formed by finite increasing sequences $\langle \alpha_1,\ldots,\alpha_{n-1}\rangle$ such that for every $k\leq n$ then $[\{\alpha_1,\ldots,\alpha_{n-1}\}]^k$ is monochromatic, and endows it with the reverse order $\supset$.
I feel that I understand the reasons why $T\in L$ and $c$ has a monochromatic set iff $T$ is illfounded. Despite of this, I'm not sure of which is the role played by the term ''increasing sequences'' and $\supset$.
More precisely, my questions are the following:

*

*Why couldn't we take as the elements of the tree any finite sequence like before paying no attention to their order and $\subset$ instead of $\supset$?

*If $\alpha<\omega_1^L$ then is it true that the existence of $\kappa(\alpha)$ implies $L\models\kappa(\alpha)\to(\alpha)^{<\omega}$? If this would be true, how could I prove it?

Best,
Cesare.

A: Whether to use $\subset$ or $\supset$ is just a matter of convention: Do your trees grow upwards or downwards? All you want is to have your tree consist of finite approximations to the homogeneous set you are after.
Similarly, to have the sequences increase does not matter much. The intention is simply that if at the end you have a branch through the tree, that gives you an increasing sequence $\alpha_0<\alpha_1<\dots$, and the set $H=\{\alpha_n\mid n<\omega\}$ is homogeneous and of order type $\omega$. Had we not paid attention to the sequences being increasing, your set $H$ would at the end still be infinite, so its initial segment of type $\omega$ would have been the homogeneous set you were after, but $H$ could in principle be better and have a larger order type.
Actually, that should suggest you how to modify the proof to answer your second question: Fix a bijection $\pi$ in $L$ between $\omega$ and $\alpha$. Now you could take as elements of your tree finite sequences $(\alpha_0,\dots,\alpha_k)$ such that for all $i,j$, we have $\alpha_i<\alpha_j$ iff $\pi(i)<\pi(j)$ (plus, the appropriate homogeneity requirement, of course). At the end, an infinite sequence gives you a (homogeneous) set of order type $\alpha$.


text:
Q: Keybord events are not working in text boxes of an iframe inside Flex application I have a text box in an iframe which is included in a Flex application.
My keyboard events are not getting triggered while i am typing in the text box like Home,End ,Up down arrows..
<input id="addressSearch" type="text" placeholder="Search Location" >

Please help me to get resolved this issue.


text:
Q: Different compilation results not using extern in C vs in C++ When I declare a global variable in two different source files and only define it in one of the source files, I get different results compiling for C++ than for C. See the following example:
main.c
#include <stdio.h>
#include "func.h" // only contains declaration of void print();

int def_var = 10;

int main() {
    printf("%d\n", def_var);
    return 0;
}

func.c
#include <stdio.h>
#include "func.h"

/* extern */int def_var; // extern needed for C++ but not for C?

void print() {
    printf("%d\n", def_var);
}

I compile with the following commands:
gcc/g++ -c main.c -o main.o
gcc/g++ -c func.c -o func.o
gcc/g++ main.o func.o -o main

g++/clang++ complain about multiple definition of def_var (this is the behaviour I expected, when not using extern).
gcc/clang compile just fine. (using gcc 7.3.1 and clang 5.0)
According to this link:

A tentative definition is a declaration that may or may not act as a definition. If an actual external definition is found earlier or later in the same translation unit, then the tentative definition just acts as a declaration.

So my variable def_var should be defined at the end of each translation unit and then result in multiple definitions (as it is done for C++). Why is that not the case when compiling with gcc/clang?

A: I believe you are observing an extension to C known as "common symbols", implemented by most, but not all, Unix-lineage C compilers, originally (IIUC) for compatibility with FORTRAN.  The extension generalizes the "tentative definitions" rule described in StoryTeller's answer to multiple translation units.  All external object definitions with the same name and no initializer,
int foo; // at file scope

are collapsed into one, even if they appear in more than one TU, and if there exists an external definition with an initializer for that name,
int foo = 1; // different TU, also file scope

then all of the external definitions with no initializers are treated as external declarations.  C++ compilers do not implement this extension, because (oversimplifying) nobody wanted to figure out what it should do in the presence of templates.  For GCC and Clang, you can disable the extension with -fno-common, but other Unix C compilers may not have any way to turn it off.

A: This isn't valid C either, strictly speaking. Says as much in
6.9 External definitions - p5

An external definition is an external declaration that is also a
  definition of a function (other than an inline definition) or an
  object. If an identifier declared with external linkage is used in an
  expression (other than as part of the operand of a sizeof or _Alignof
  operator whose result is an integer constant), somewhere in the entire
  program there shall be exactly one external definition for the
  identifier; otherwise, there shall be no more than one.

You have two definitions for an identifier with external linkage. You violate that requirement, the behavior is undefined. The program linking and working is not in opposition to that. It's not required to be diagnosed.
And it's worth noting that C++ is no different in that regard.
[basic.def.odr]/4

Every program shall contain exactly one definition of every non-inline
  function or variable that is odr-used in that program outside of a
  discarded statement; no diagnostic required. The definition can appear
  explicitly in the program, it can be found in the standard or a
  user-defined library, or (when appropriate) it is implicitly defined
  (see [class.ctor], [class.dtor] and [class.copy]). An inline function
  or variable shall be defined in every translation unit in which it is
  odr-used outside of a discarded statement.

Again, a "shall" requirement, and it says explicitly that no diagnostic is required. As you may have noticed, there's quite a bit more machinery that this paragraph can apply to. So the front ends for GCC and Clang probably need to work harder, and as such are able to diagnose it, despite not being required to.
The program is ill-formed either way.

As M.M pointed out in a comment, the C standard has an informative section that mentions the very extension in zwol's answer.
J.5.11 Multiple external definitions

There may be more than one external definition for the identifier of
  an object, with or without the explicit use of the keyword extern; if
  the definitions disagree, or more than one is initialized, the
  behavior is undefined (6.9.2).


text:
Q: How do I parse this JSON (using JSON.NET)? I have some JSON which is valid but a little quirky looking. Here it is:
{
"server":"some server name",
"files":
{
"filename1":{"source":"original","format":"text"},
"filename2":{"source":"original","format":"text"},
"filename3":{"source":"original","format":"text"}
}
}

As you can see, the "files" section contains one JSON object per "file" so I can get this as array of JTokens but not sure how to get the values of "filename1", "filename2", etc. out.
I'm using JSON.NET and C# so please don't provide an answer that requires the JavaScriptSerializer from System.Web.Extensions.dll. Either pure JObject/JToken calls or JConvert.DeserializeObject<> would be okay.
Thanks.

A: Try this
public class Data
{
    public Data()
    {
        Files = new Dictionary<string, FileData>();
    }
    public string Server { get; set; }
    public IDictionary<string, FileData> Files { get; set; }
}
public class FileData
{
    public string Source { get; set; }
    public string Format { get; set; }
}

Then Access it using this
var result = JsonConvert.DeserializeObject<Data>(JsonValue);

A: How about using dynamic deserialization? See Deserialize json object into dynamic object using Json.net
string json = @"{""server"":""some server name"",""files"":{""filename1"":{""source"":""original"",""format"":""text""},""filename2"":{""source"":""original"",""format"":""text""},""filename3"":{""source"":""original"",""format"":""text""}}}";
dynamic result = JObject.Parse(json);

Console.WriteLine(result.server);
foreach (dynamic file in result.files)
{
    Console.WriteLine(file.Name);
    dynamic value = file.Value;
    Console.WriteLine(value.source);
    Console.WriteLine(value.format);
}

Output
some server name
filename1
original
text
filename2
original
text
filename3
original
text

A: You must define a class like this:
class ClassName
{
    public string server;
    public ClassName2 files;
}

and define ClassName2:
class ClassName2
{
    ClassName3 filename1;
    ClassName3 filename2;
    ClassName3 filename3;
}

and finally ClassName3
ClassName3
{
    public string source;
    public string format;
}

supporse you have saved your json data in a string variable like 'result'
 ClassName fin = JsonConvert.DeserializeObject<ClassName>(result);

this will give you anything you need.


text:
Q: Groovy Project Setting in IDEA IntelliJ I'm using IDEA to write groovy scripts for my jenkins job.  So I have these imports
import groovy.json.JsonSlurper
import hudson.FilePath
import hudson.model.Node
import hudson.model.Slave
import jenkins.model.Jenkins

Before I added jenkins-core-2.9.jar into the project dependency, those jenkins classes are marked in red.  Then I added the jar as a dependency by "File"->"Project Structure"->"Modules"->"Dependencies"
Then those red marks are gone.  However, when I tried to run the script, it says Error:(14, 1) Groovyc: unable to resolve class jenkins.model.Jenkins.  What else do I need to do?

A: I had the same problem and it was a permission issue. For me this command fixed it: sudo chmod o=r jenkins-core-2.73.3.jar

A: As stated in this link,

Note that if you configure a dependency through the Project Structure dialog, the dependency will only appear in the IntelliJ IDEA Project tool window, not in the Gradle tool window.

Adding the dependency like this only adds the dependency in the idea workspace. When you run the task either from the gradle tool window, or from an external command line tool, that dependency no longer exists. You should add it to your gradle dependencies:
dependencies {
    compile "org.jenkins-ci.main:jenkins-core:2.9"
}

You can configure a repository to load this dependency from. This repository can be a file path, or a maven repository etc.
See here for more details on gradle dependency management.


text:
Q: Laravel Mail cannot found view This is really strange. I have a laravel app where I use the module library
https://github.com/nWidart/laravel-modules

I don't know if it has with the issue to do, but just want to point it out.
Basically, I am writing phpunit tests. The first test is calling an endpoint. In that case, the controller will call a repository class(basically a php-class inside the folder "Repositories", nothing stranger than that) which in turn calls
Mail::queue(new MyFirstMail($arg));

Well, this works. And I can also have a chech in the test to verify the mail has been queued:
Mail::assertQueued(MyFirstMail::class, 1);

The second test, instead, is calling an artisan command, this way:
$this->artisan('a_command_job');

This will basically run the method "handle" inside a class that is located at "Modules/Console/Commands/MyCommand.php"
From inside that handle method, I will call this:
Mail::queue(new MySecondMail($arg));

This test fails. The error is
View [emails.second_email] not found

MySecondMail.php is a class that extends "BaseMail". Which is the same for MyFirstMail.php.
They look more or less exactly the same. Of course they include two different views.
MyFirstMail has no problem in including the view. While MySecondMail cannot find the view.
I also tried by passing the same view name for MySecondMail. But I still get the same error.
I suspect that this has to do with the fact that the first one is triggered by a call to an endpoint. While the second one is called by an artisan command. But I really don't understand how to make MySecondMail to pick up the right path to the view. I also have tried with "base_path". But it did not work and Im not sure it is the right way to do it.

A: Add this in front of Mail

\

For example
\Mail::queue(new MyFirstMail($arg));

A: Check your view folder if you have a blade file called second_mail.blade.php under emails folder
-views
 -emails
  -second_mail.blade.php

Else create the blade file


text:
Q: DRUPAL problems I am having problem installing Drupal; I usually use Wampserver or Acquia, but the problem is they do not work for a long time. Whenever I install Drupal, the next day it won't work.
Is there any other software I can use, aside from Wampserver and Acquia?

A: You're not specific enough so it will be impossible to address your issue, there are a lot of tutorials online, go to drupal.org and find the resources for beginners.
Also you need to have some form of idea of how a local server works, you don't really need to go into details, start to understand the general workflow of a PHP application such as Drupal. Find tutorials about basic PHP, local servers etc...
It doesn't seem that your problem is Drupal related by the way. Not working the next day would seem to point to your local server settings, something as basic as not starting it for instance.

A: Can you be clear on what problem you are facing? what u mean by not working?? basically both of them are bundled software apache+mysql+php pre-configured for small site..
Can you please tell little more about your drupal instance like..
Site traffic, server configuration..
If u feel it has slown down.. check ur MySQL, PHP and Apache Configuration..

A: I will use the XAMP from (https://www.apachefriends.org/index.html) . It is a lot more stable than WAMP.

*

*First install the XAMP on your computer (It will take care of all the PHP, MySQL, Apache, and PHPMyAdmin installation)

*Go to the XAMP interface on your browser, http://localhost

*Go to the PHPMyAdmin interface

*Create username, password, and database through PHPMyAdmin Interface

*Then Go to Drupal.org and download the latest Drupal installation package.

*Unzip the Drupal to the XAMP htdocs folder

*Install Drupal with the database name and user name that you created

*and you are done! you can go to starbucks, buy coffee and watch netflix now :)

A: Other options to consider are VirtualBox, Lando, & Docker Desktop.


text:
Q: How to calculate off a filtered table in Excel, possibly use VBA Brand new VBA user here:
I'm trying to have a calculated table form from a filtered table in excel. I know the filtered table only hides values so doing any offset or indexing still returns the hidden filtered values, so the internet has pushed me towards using VBA.
In using VBA I can't seem to plug a variable into a range.value that grows over each loop so the cells grow until the visible filtered table is finished. I believe the Do Until function is what I'm supposed to use to achieve this, but I need some major help on my code, or I'm unaware of an easier process:
Current Broken Code:
Sub TableCreate()

iRow = 1

iPlug = 1

Do Until IsEmpty(Cells(iRow, 1))

Set Rng = Range("A"iPlug)

' Store the current cell value in the dCellValues array

Range(Rng).Value = Cells(iRow, 1).Value

iRow = iRow + 1

iPlug = iPlug + 1

Loop

End Sub

Thank You,
EEE

A: If you want to use a numeric variable in a cell address, you have to concatenate the number with an ampersand & sign.
Set Rng = Range("A" & iPlug)

It also looks like you only need one variable, because iPlug and iRow will always be the same value.
If you declare the Rng variable as a range, then you can use the variable directly.
    Dim Rng as Range
'... code leading up to this ...
    Set Rng = Range("A"&iPlug)

    ' Store the current cell value in the dCellValues array

    Rng = Cells(iRow, 1).Value

You could also use the Range method directly, without using a variable.
Range("A"&iPlug) = Cells(iRow, 1).Value


text:
Q: Android video is rotated when play from web server I'm playing video from web server, the video is playing on videoview nicely, but some samsung mobile playing the video on 90 degree rotation. But the same video playing without ration on others devices.
public void playVideo(String videoPath) {
    try {
        vidFull.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                    @Override
                    public boolean onInfo(MediaPlayer mp, int what, int extra) {
                        switch (what) {
                            case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                                progressBar.setVisibility(View.VISIBLE);
                                break;
                            case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                                progressBar.setVisibility(View.GONE);
                                break;
                        }
                        return false;
                    }
                });
            }
        });

        MediaController mediaController = new MediaController(this);
        mediaController.setAnchorView(vidFull);
        vidFull.setMediaController(mediaController);
        vidFull.setVideoPath(videoPath);
        vidFull.requestFocus();
        vidFull.start();
        videoArrayLength = videoArrayLength -1;
        vidpointer = 1;
        //Goutam 17.03.2016

        vidFull.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                logCollection.setLogERed(""+videoArrayLength);
                try {
                    if (videoArrayLength > 0){
                        MediaController mediaController = new MediaController(FullPost.this);
                        mediaController.setAnchorView(vidFull);
                        vidFull.setMediaController(mediaController);
                        //vidFull.setVideoPath("http://www.sample-videos.com/video/mp4/480/big_buck_bunny_480p_1mb.mp4");
                        logCollection.setLogERed(basevideourl+videoArray.optJSONObject(vidpointer).getString("vdLink"));
                        vidFull.setVideoPath(basevideourl + videoArray.optJSONObject(vidpointer).getString("vdLink"));
                        vidFull.requestFocus();
                        vidFull.start();
                        videoArrayLength = videoArrayLength - 1;
                        vidpointer = vidpointer + 1;
                       }else {
                        logCollection.showToastLong("No more video to play.");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    } catch (Exception e) {
        // TODO: handle exception
        Toast.makeText(this, "Error connecting", Toast.LENGTH_SHORT).show();
    }
}

Please help, thanks in advance.

A: I think you telling about orientation change. You can handle this by setting screenOrientation to activity in AndroidManifest.
        <activity android:name=".Main2Activity"
            android:screenOrientation="portrait">
        </activity>


text:
Q: Is there any way to fine which js file ajax function send a request to java servlet I have two js files one.js and two.js in both js i make the ajax request to same java servlet class(AppController.java //servlet class name).
one.js
function addOne(){
    var formData = $('#form1').serialize();
    $.ajax({
        type: "POST",
        data: formData,
        dataType: "json",
        success: function (response) {
            ...
        }
    });
}

two.js
function removeMulti(){
    var formData = $('#form').serialize();
    $.ajax({
        type: "POST",
        data: formData,
        dataType: "json",
        success: function (response) {
            ...
        }
    });
}

is there any way to fine or identify which js file ajax send the request to AppController.java servlet class. Because i need to block some jsp file access via url enter and ajax call. That jsp file access only in jsp include in another jsp file and particular js file ajax call.
Note : Already I block the url and ajax request to access the specific jsp page using filter class. but I need to access that jsp file specific js file ajax request only.

A: Just add a header to your ajax call to identify which file is calling.


text:
Q: NameError: global name 'AlreadyExists' is not defined when using try/except within a function I know many of these questions exist but I can't seem to find one that works for the problem I am having.
I have the following:
def function():
  try:
    # function to create a table on hbase
  except AlreadyExists, ae:
    print "WARN: " + ae.message

when I call it from another python script it gives me
NameError: global name 'AlreadyExists' is not defined

...but if I remove the def function() and run it on its own, it works and doesn't complain about the global name.
I tried putting global AlreadyExists and that didn't work.  I also looked at this similar problem but I'm not sure how to apply it because it works on its own (without me having to import anything specific, but as soon as I wrap it in a function it fails).
Any suggestions?

A: Python only tries to access the name when an exception is thrown. When you ran the code outside of the function it probably didn't throw the exception and that's why you think it worked.
You need to import the AlreadyExists exception from wherever it lives.

A: change
from hbase import ttypes

...

except AlreadyExists, ae:

to
except ttypes.AlreadyExists, ae:

http://www.ros.org/doc/api/hbase/html/classhbase_1_1ttypes_1_1AlreadyExists.html


text:
Q: Boolean algebra on Logic Circuit I need help with this function to create a truth table:
F(a, b, c) = a'c' + abc + ac'
Use Boolean laws and theorems to reduce the given function
I need the reduced and original function truth table
From there I will be able to create a logic gate circuit
Thanks

A: Notice $F(a,b,c) = c'(a'+a) +abc.$ The term $a' + a$ will always be $1$. So we have $F(a,b,c) = c' + abc$. To find the truth table just input all different combinations of $a, b, c$ and write down the respective outputs.


text:
Q: Redefinition of generic for plot function breaks plot.formula CRAN policies do not allow that single methods (for generic functions) which are defined in base or recommended packages are replaced. They advice package authors to replace the standard generic and use a xxx.default method which then calls the original standard generic.
An example from my package papeR is as follows:
## overwrite standard generic
plot <- function(x, y, ...)
    UseMethod("plot")

## per default fall back to standard generic
plot.default <- function(x, y, ...)
    graphics::plot(x, y, ...)

## now specify modified plot function for data frames
plot.data.frame <- function(x, variables = names(x), ...)

The complete code can be found on GitHub.
For various generics such as toLatex this method works perfectly. Yet, the above plot method definitions break the standard plot.formula function:
library("devtools")
install_github("hofnerb/papeR")

## still works:
example(plot.formula, package="graphics")

### But:
library("papeR")
example(plot.formula, package="graphics")
## Error in eval(expr, envir, enclos) : object 'Ozone' not found

I can still use
graphics:::plot.formula(Ozone ~ Wind, data = airquality)

though. Other plot functions keep working, see e.g.
example("plot", package = "graphics")

Additional Information
In my NAMESPACE I have
importFrom("graphics", "plot", "plot.default", ...)
export(plot, plot.data.frame, ...)
S3method(plot, default)
S3method(plot, data.frame)

For a previous discussion on this topic (with a different focus) see also here.

A: For a discussion and solution (define a new_class and use plot.new_class) see
https://stat.ethz.ch/pipermail/r-package-devel/2015q3/000463.html


text:
Q: Current X driver How do I know, by which X driver, the X started.
Looking at configuration file or log file is not trustworthy, I guess. These files can be manipulated in one or other way post bootup.
Is there any way to find out which X driver was in charge to start the X ?
(e.g. Either it could be VIA, openchrome or VESA)

A: As has been mentioned, it's fairly straightforward to determine the kernel driver in use, but without the Xorg logs, it's a little more tricky to determine which userland X server driver is being used.
For systems that have it, glxinfo can be used (although that will only give you general device information, not the actual driver name).

glxinfo | grep OpenGL
OpenGL vendor string: nouveau
OpenGL renderer string: Gallium 0.4 on NVE6
OpenGL core profile version string: 3.1 (Core Profile) Mesa 9.2.5
OpenGL core profile shading language version string: 1.40
OpenGL core profile context flags: (none)
OpenGL core profile extensions:
OpenGL version string: 3.0 Mesa 9.2.5
OpenGL shading language version string: 1.30
OpenGL context flags: (none)
OpenGL extensions:

Another option is to check what modules Xorg has loaded (taken from this thread on Reddit):
lsof -p $(pidof X) | grep xorg | rev | cut -f 1 -d '/' | rev

A: lspci -k will show devices and modules loaded for them.
You can grep it for the specific device you are looking for, such as 'VGA'
lspci -k|grep -A2 VGA


text:
Q: Text classification using Naive Bayes (Hashing Term Frequnecy) I am trying to build a text classification model using Naive-bayes algorithm.
Here's my sample data (label and feature):
1|combusting [chemical]
1|industrial purposes
1|
2|salt for preserving,
2|other for foodstuffs
2|auxiliary
2|fluids for use with abrasives
3|vulcanisation
3|accelerators
3|anti-frothing solutions for batteries
4|anti-frothing solutions for accumulators
4|acetates
4|[chemicals]*
4|acetate of cellulose, unprocessed

Following is my sample code
import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
import org.apache.spark.mllib.classification.{NaiveBayes,     NaiveBayesModel}
import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.mllib.util.MLUtils
import org.apache.spark.mllib.evaluation.MulticlassMetrics
import org.apache.spark.mllib.feature.HashingTF

val rawData = sc.textFile("~/data.csv")

val rawData1 = rawData.map(x => x.replaceAll(",",""))

val htf = new HashingTF(1000)

val parsedData = rawData1.map { line =>
val values = (line.split("|").toSeq)
val featureVector = htf.transform(values(1).split(" "))
val label = values(0).toDouble
LabeledPoint(label, featureVector)
}

val splits = parsedData.randomSplit(Array(0.8, 0.2), seed = 11L)
val training = splits(0)
val test = splits(1)

val model = NaiveBayes.train(training, lambda = 2.0, modelType = "multinomial")

val predictionAndLabels = test.map { point =>
val score = model.predict(point.features)
(score, point.label)
}

val metrics = new MulticlassMetrics(predictionAndLabels)
metrics.labels.foreach( l => println(metrics.fMeasure(l)))

val testData1 = htf.transform("salt")
val predictionAndLabels1 = model.predict(testData1)

I am getting approx 33% accuracy (very less), and testing data predict wrong label. I have printed parsedData which contains label and feature as below:
(1.0,(1000,[48],[1.0]))
(3.0,(1000,[49],[1.0]))
(1.0,(1000,[48],[1.0]))
(3.0,(1000,[49],[1.0]))
(1.0,(1000,[48],[1.0]))

I am not able to find it out what's missing; hashing term frequency function seems generating repeated data term frequency. Kindly suggest me to improve the model performance, Thanks in advance

A: You have to ask yourself many questions before starting implementing your algorithm:

*

*Your texts looks very short, what is the size of your vocabulary, answering this will help you in tuning the value of the HashingTF dimensionality. In your case, you might need to use lower value.

*You might need to consider doing some pre-processing on your texts. e.g. using StopWordsRemover, stemming, Tokenizer?

*A tokenizer will construct a better text than the ad-hoc text processing you are doing.

*Change your parameters, namely the NumFeatures of the HashingTF and the lambda of the Naive Bayes.

*Basically in Machin Learning you will need to do CrossValidation on a set of parameters in order to optimise your results. Check this example and try to do something similar by tuning your HashingTF and the lambda as follow:

val paramGrid = new ParamGridBuilder()
 .addGrid(hashingTF.numFeatures, Array(10, 100, 1000))
 .addGrid(naiveBayes.lambda, Array(0.1, 0.01))
 .build()

In general, using Pipelines and CrossValidation works with Naive Bayes for multi-class classification, so have a look on here rather than hardcoding all septs with your hands.


text:
Q: WPF custom panel child initialization I am currently working on a custom Panel implementation (based on Canvas) with a specific behavior.
As I need to make several actions depending on child properties. In order to implement the control, I also developed specific child control (based on ContentControl) with some dependency properties, to set up the child option directly in the xaml.
As I also need to make verification at the AddChild call, I intercept the AddChild call by defining the  [ContentProperty("NotifiableChildren")] attribute on my Control and then make some checks before adding the child to the Canvas children.
    public interface INotifiableParent
    {
        int AddChild(UIElement child);
        void RemoveChild(UIElement child);
    }

    [ContentProperty("NotifiableChildren")]
    public class MyPanel : Canvas, INotifiableParent
    {
        public MyPanel()
        {
            NotifiableChildren = new NotifiableUIElementCollection(this, this);
        }

        public NotifiableUIElementCollection NotifiableChildren { get; }

        #region INotifiableParent members

        public int AddChild(UIElement child)
        {
            // Add your custom code here

            // Add the child to the InternalChildren
            return this.Children.Add(child);
        }

        public void RemoveChild(UIElement child)
        {
            this.Children.Remove(child);
        }

        #endregion
    }

It works fine, expects during the AddChild call, all my child are not completely initialized. Each instance is created and not null, but all dependency properties are not initialized (I have the same behavior with framework native controls). You can see below the corresponding xaml example with native controls.
<Window x:Class="ProtoPanel.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ProtoPanel"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <local:MyPanel>
            <Rectangle Fill="Aqua"
                       Width="200"
                       Height="100"/>
            <Ellipse Fill="Bisque"
                     Canvas.Left="300"
                     Canvas.Top="150"
                     Height="100"
                     Width="100"></Ellipse>
        </local:MyPanel>
    </Grid>
</Window>

I put some breakpoints in my custom ContentControls and I saw that all dependency properties (Fill, Width, Heigth, ...) are initialized with xaml values after the child being added to the Canvas.
Does anyone knows if there is a way/trick to have these dep properties initialized at AddChild call ?
Thanks in advance


text:
Q: How to avoid CSRF failure using android? I got a CSRF failure when connecting django server using POST method in an android app.
The httpResponse saying as below:

Forbidden (403)
  CSRF verification failed. Request aborted.

Reason given for failure:

CSRF cookie not set.

In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:
Your browser is accepting cookies.
The view function uses RequestContext for the template, instead of Context.
In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.
You can customize this page using the CSRF_FAILURE_VIEW setting.
It seems the server treats my code as an attacker. But how to add a CSRF template in an android view?  In my app, there is no form. I am confused.
And, my code is here:
public int login(){
try {
    HttpPost httpPost = new HttpPost(loginURL);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("username", userID));
    params.add(new BasicNameValuePair("password", password));
    httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpResponse httpResponse = httpClient.execute(httpPost);
    cookies = httpClient.getCookieStore().getCookies();
    Log.e("Cookies", cookies.isEmpty() + "");
    HttpEntity httpEntity = httpResponse.getEntity();
    if(httpResponse.getStatusLine().getStatusCode() == 200){
        Log.v("HTTPResponse", "200");
    } else {
        Log.v("HTTPResponse","" + httpResponse.getStatusLine().getStatusCode());
    }
    String result = EntityUtils.toString(httpEntity, "UTF-8");
} catch (MalformedURLException e){
    Log.e("UserInfoCollectorMalformedURLException", e.toString());
    return 0;
} catch (UnsupportedEncodingException e){
    Log.e("UnsupportedIOException", e.toString());
    return 5;
} catch (IOException e){
    Log.e("UserInfoCollectorIOException", e.toString());
    return 1;
} catch (ParseException e){
    Log.e("ParseException", e.toString());
    return 3;
}
Log.v("Login", "Unknown Error");
return 1000;
}

A: If you have access to the server code, you could remove your CSRF protection on you API views using the csrf_exempt decorator.
See this answer for more details Do CSRF attacks apply to API's?


text:
Q: python: round/format float/string to specific decimal/fraction I've found many posts regarding rounding in python, but from my understanding none so far solves my problem.
Two solutions I'm looking for:

*

*Round closest: float/string numbers which need to be rounded differently depending on their size.

*Round down: float/string numbers which need to be rounded down differently depending on their size.

*Round up: float/string numbers which need to be rounded up differently depending on their size.
Example:

*

*+500: 0 decimals (whole numbers) (e.g., Closest: 500.5 -> 501; Down: 500.99 -> 500; Up: 500.01 -> 501)

*+100: 1 decimals (fraction: 0.2) (e.g., Closest: 100.29 -> 100.2; Down: 100.39 -> 100.2; Up: 100.21 -> 100.4). So, the value must end with .0, .2, .4, .6 or .8

*+5: 2 decimals (fraction: 0.01) (e.g., Closest: 5.019 -> 5.02; Down: 5.019 -> 5.01; Up: 5.011 -> 5.02). So, the value must end with .x0, .x1, .x2, .x3, .x4, .x5, .x6, .x7, .x8 or .x9

The resulting variable should be a string.
The neat thing I'm, looking for is a function in which i can pass number of decimals and fraction

A: You can use the Decimal module for highly customizable rounding:
import decimal

def rnd(f,n,r=decimal.ROUND_HALF_DOWN):
    pat='1.'+'0'*n
    return str(decimal.Decimal(str(f)).quantize(decimal.Decimal(pat),r))

Now to test:
for n in (500.99,100.39,5.019):
    for i in (0,1,2):
        print('n={:10}, i={:2}, Down: {:>10}, Closest: {:>10}'.format(n,i, rnd(n,i,decimal.ROUND_FLOOR),rnd(n,i)))

Prints:
n=    500.99, i= 0, Down:        500, Closest:        501
n=    500.99, i= 1, Down:      500.9, Closest:      501.0
n=    500.99, i= 2, Down:     500.99, Closest:     500.99
n=    100.39, i= 0, Down:        100, Closest:        100
n=    100.39, i= 1, Down:      100.3, Closest:      100.4
n=    100.39, i= 2, Down:     100.39, Closest:     100.39
n=     5.019, i= 0, Down:          5, Closest:          5
n=     5.019, i= 1, Down:        5.0, Closest:        5.0
n=     5.019, i= 2, Down:       5.01, Closest:       5.02

(Note: This is different output in the case of 1 decimal and the input of 100.39. Please clarify the desired output of 100.2 in that case? Shouldn't the output be 100.3?)

With the clarification, I think you just need to use fmod:
import math

def rnd(n,f,prec,direction='down'):
    if direction=='down':
        if prec==0:
            return str(int(n))
        return str(round(n-math.fmod(n,f),prec))
    else:
        if prec==0:
            return str(int(round(n)))
        n+=f
        return str(round(n-math.fmod(n,f),prec))

Works with all examples given:
>>> rnd(500.99,0.1,0)
'500'
>>> rnd(500.99,0.1,0,'')
'501'
>>> rnd(100.39,0.2,1,'')
'100.4'
>>> rnd(100.39,0.2,1)
'100.2'
>>> rnd(100.59,0.2,1,'')
'100.6'
>>> rnd(100.59,0.2,1)
'100.4'
>>> rnd(5.019,0.01,2)
'5.01'
>>> rnd(5.019,0.01,2,'')
'5.02'

(Call the function with the direction= keyword argument with any string value other than 'down' to get up. Change to your liking...)

Edit 2
This returns the method closest to the input number:
def rnd(n,f,prec):
    n1=int(n) if prec==0 else round(n-math.fmod(n,f),prec)
    n2=float(int(round(n))) if prec==0 else round((n+f)-math.fmod((n+f),f),prec)
    return str(min((n1,n2), key=lambda e: math.fabs(e-n)))

A: How about something like this?
def round_accordingly(num):

    if num>=500:
        return str(round(num))
    elif num>=100:
        return str(round(num, 1))
    elif num>=5:
        return str(round(num, 2))

print(round_accordingly(550.73424))
print(round_accordingly(200.234245))
print(round_accordingly(7.564743))


text:
Q: Change a currently non used class implementation at runtime I have a C++ code being executing on a big file(~15 GB). The code has two phases and the first phase will take much time to finish. But in the mean time I have got a better implementation technique for its phase 2, and don't want to restart the whole execution right from start. The two phases are categorized by the two classes actually being used. Take an idea from it:
Parser.parse(filePath);    // phase one
Processor.processAndLog(); // phase two

So, is there some method to change the implementation of Processor class before it starts executing? The end of phase 1 (or even how much it has completed) can be distinguished from some time to time messages(say logs) I have printed.

A: If Processor.processAndLog is a member function pointer than you can change it anytime before it's called.
An alternative is to have Processor.processAndLog be a wrapper function for other functions - a dispatch function.
There's also the matter of hooking a function. there's a library called detours. Use this only if you can't change the source code if the program.

A: So if I understand this correctly: You have a program that is currently running, but which hasn't yet gotten to executing the code in a particular class. And you want to find a way to update it to use a new version of the code for that class without stopping the program.
In theory that could be done. But in practice, it's likely to be far more trouble than it's worth, especially if this is a one-time need. C++ was not designed for this kind of thing. It's not like there is simply human-readable source code sitting in the process's memory that could be overwritten easily.
Doing this correctly would almost certainly take a significant amount of time and effort, most likely involving a lot of experimenting and trail-and-error. If you get something about it wrong (which is likely the first time) then you've probably just corrupted your process and your results, and would thus need to restart it anyway.
I don't know how long your process is currently taking, but trying to figure how to accomplish this idea might very well take more time than just restarting the process after building the new version of the program.


text:
Q: Django queryset - Filtering related table objects before aggregation Consider this model in Django documentation:
Aggregation and Avg
There is a queryset like this:
Author.objects.annotate(average_rating=Avg('book__rating'))

which returns all authors annotated by average rate of all of their books.
What if I want to query authors annotated by average rate of their books which have been published for example in 2016.
Note that I want to get results with as few queries as possible.

A: Given that the Book model has an attribute pubdate which is a DateField, you can use:
from datetime import datetime

y2016 = datetime(2016,1,1)

Author.objects.filter(book__pubdate__lt=y2016) \
              .annotate(average_rating=Avg('book__rating'))
So book__pubdate__lt means that you check that the pubdate of the book is less than (__lt) y2016 (the first of january 2016).
In case the filter is applied before the annotate it will filter the books away which are publised before 2016. Note that authors that have not publised before 2016 will not be in the resulting QuerySet. But this seems logical (since you can not calculate an average over an empty set).


text:
Q: "void value not ignored as it ought to be" error I am getting an error "void value not ignored as it ought to be" on the line:
home = [[Home alloc] initWithPhoto:imageView.image];
Please help.

A: Your Home class' -initWithPhoto: function is probably returning void. Initializer functions are supposed to return id.

A: What is the return value of initWithPhoto? The error means that the method is returning void but you are assigning that to something. initWithPhoto should look something like this:
- (id)initWithPhoto:(UIImage *)image {
    if (self = [super init]) {
         // do your tasks
    }

    return self;
}

The method should return id, not void.

A: Your initWithPhoto method is returning an object of type void when it should be returning an object of type id, especially if you're expecting the home variable to contain anything useful. Try editing the initWithPhoto method to return an object of type id.


text:
Q: ReferenceError: resolve is not defined after added the @ path config I want to use @ with the import path like this in vue 3:
import Options from '@/popup/components/Options.vue'

so I added this config in the webpack 5.x:
'@': resolve('src'),

this is the full webpack 5.x config:
const path = require('path');
const webpack = require( 'webpack' );
const MiniCssExtractPlugin = require( 'mini-css-extract-plugin');
const HtmlWebpackPlugin = require( 'html-webpack-plugin');
const CopyPlugin = require("copy-webpack-plugin");
const { VueLoaderPlugin } = require("vue-loader");

module.exports = {
  entry : {
    'popup/popup' : './src/popup/'
  } ,
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
    alias: {
        // https://stackoverflow.com/questions/50805384/module-not-found-error-cant-resolve-vue-path-not-correct
        vue: 'vue/dist/vue.esm-bundler.js',
        '@': resolve('src'),
    },
  },
  output : {
    path : path.resolve(__dirname, '../../bundle') ,
    filename : '[name].js'
  },
  module : {
    rules : [
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /\.ts$/,
        loader: 'ts-loader',
        options: {
          appendTsSuffixTo: [/\.vue$/]
        },
        exclude: /node_modules/
      },

      {
        test : /\.js$/ ,
        exclude : [ /node_modules(?!(\/|\\?\\)(translation\.js|selection-widget|connect\.io|chrome-env)\1)/ ] ,
        loader : 'babel-loader'
      } ,
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
      {
        test : /\.(scss)$/ ,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
      }
    ]
  },
  plugins : [
    new VueLoaderPlugin(),
    new CopyPlugin({
      patterns: [
        { from: "src/manifest.json", to: "manifest.json" },
        { from: "src/resource/image", to: "resource/image" },
      ],
    }),
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css",
    }),
    new HtmlWebpackPlugin({
      filename: 'popup/popup.html',
      template: 'src/popup/index.html'
    }),
    new webpack.DefinePlugin({
      __VUE_OPTIONS_API__: false,
      __VUE_PROD_DEVTOOLS__: false,
    }),
  ]
};

but the compile output error like this:
[webpack-cli] Failed to load '/Users/xiaoqiangjiang/source/reddwarf/frontend/reddwaf-translate-plugin/src/resource/config/webpack.dev.config.js' config
[webpack-cli] ReferenceError: resolve is not defined
    at Object.<anonymous> (/Users/xiaoqiangjiang/source/reddwarf/frontend/reddwaf-translate-plugin/src/resource/config/webpack.base.config.js:17:14)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/Users/xiaoqiangjiang/source/reddwarf/frontend/reddwaf-translate-plugin/src/resource/config/webpack.dev.config.js:3:10)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)

where is the problem? what should I do to fix this?

A: On line 17 of your webpack.config.js, you are referencing resolve. It is a part of the path module. So, you need to do the following instead:
'@': path.resolve(__dirname, 'src')


text:
Q: How do I update git to the latest version? I'm Japanese boy.
I am using git version 2.1.4 on GCE.
$ git --version
git version 2.1.4

I'd like to update to the latest version, but it was not updated when I executed the following command.
sudo add-apt-repository ppa:git-core/ppa
sudo apt-get update
sudo apt-get upgrade

Is my way wrong?

After that,I tried the following but it got an error.
sudo add-apt-repository ppa:git-core/ppa
sudo apt-get update

The following error has occurred.
W: ppa.launchpad.net/git-core/candidate/ubuntu/dists/jessie/main/… 404 Not Found
W: ppa.launchpad.net/git-core/ppa/ubuntu/dists/jessie/main/… 404 Not Found

I found out how to fix with ubuntu, but do you know how to fix GCE (debian)?

A: Add the Git Maintainers repository to get the latest Git version.
sudo add-apt-repository ppa:git-core/ppa
sudo apt-get update
sudo apt-get install git

A: In ubuntu 16.04 the following worked for me. before running the below commands my git version is 2.7, now it's the latest version
sudo add-apt-repository -y ppa:git-core/ppa
sudo apt-get update
sudo apt-get install git -y


text:
Q: search listbox in WP8 by a textbox input my  requirement :-
  searching  in  txtsearch letter  by  letter  and  showing  the   matched  letters  of  ITMNAME( textblock  inside  listbox)    and  highlight  that  particular  string..
my  xaml...
<phone:PhoneApplicationPage.Resources>
    <DataTemplate x:Key="DataTemplate1" >
        <Border BorderBrush="LightGray" BorderThickness="1" Height="150" Width="500" >
            <Grid Width="500" Height="150" Background="White" >
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="0.9*"/>
                    <ColumnDefinition Width="2.5*"/>
                    <ColumnDefinition Width="1.5*"/>

                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <Image Name="imgitem"  Grid.Column="0" Height="Auto" Width="Auto" Source="{Binding ImgSource}" Margin="0,5,4,4" HorizontalAlignment="Left" />
                <TextBlock x:Name="txtbindprice"  Text="{Binding _PRICE,ConverterCulture=en-IN,StringFormat=C}" TextWrapping="Wrap"  Grid.Column="1"  Width="350"  Foreground="Black" Height="60" Margin="40,70,20,-10"/>
                <TextBlock x:Name="txtFinalTotal"  Text="{Binding _FinalTotal}" TextWrapping="Wrap"  Grid.Column="1"  Width="350"  Foreground="Red" Height="60" Margin="40,115,20,-10"/>

                <TextBlock x:Name="txtITMNAME"  Text="{Binding _ITMNAME }" Padding="1"  Tap="ItmName_Tapped" TextDecorations="Underline" FontSize="24" TextWrapping="Wrap" Grid.Column="1"  FontWeight="Normal" TextTrimming="WordEllipsis"  Foreground="OrangeRed" Width="Auto"  Height="150"  Margin="30,25,10,-10"/>

                <c4f:RoundButton    Grid.Column="2" Name="btntick" Click="btntick_Click" Grid.Row="0" FontSize="25" HorizontalAlignment="Right" Background="LightGray" Foreground="DarkGray" Margin="10,20,45,10"   />

            </Grid>
        </Border>
    </DataTemplate>

<ListBox Height="Auto" Name="lstbxmanual" SelectionMode="Extended" ItemTemplate="{StaticResource DataTemplate1 }"  Width="475" Margin="2,192,0,-39" Background="White"  HorizontalAlignment="Left" Grid.RowSpan="2">
    </ListBox>

  <TextBox x:Name="txtSearch" BorderThickness="1" BorderBrush="CadetBlue" KeyUp="txtSearch_KeyUp" GotFocus="txtsearch_gotFocus" LostFocus="txtsearch_lostFocus"  FontSize="24" Background="White" Height="85" TextAlignment="Left"  Margin="1,-30,-2,30"   />

my  viewmodel
  #region "Bind"
    public class BindData
{
    public BitmapImage ImgSource { get; set; }
    public string _ITMNAME { get; set; }
    public string _PRICE { get; set; }
    public string _FinalTotal { set; get; }
}
    #endregion

my  binding
foreach ()
 {
     lstbxmanual.Items.Add(new BindData() { ImgSource = base64image(h[2]), _ITMNAME = h[3], _PRICE =string.Concat(ClsCommon.str_CurrencySymbol,h[1]), _FinalTotal = "" });

 }

by  this  I am  binding  entire  iterations  data  to  listbox(lstbxmanual)..
textbox  event  I  have  included

  private void txtSerach_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
    {

       //  the  followig  throws  an  error  at  li.Equals

        //var selectedItems = from li in lstbxmanual.Items
        //                    where li.Equals == txtSearch.Text
        //                    select li.Text;
       //  the  following  searches  only  by index  of  lstbox

       // if (lstbxmanual.Items.Contains(txtSearch.Text))
       //{

       //}
         }

check  this
in the  above  link..they  binded all data   to  list  and   and then  searching..i am  not  using  any  kind  of list ..so  i  cant  implement it..
please help  regarding  this...
for  any  queries  revert  back..


text:
Q: discord.py: Is there anything that could be making it where kick/ban commands don't work? I am trying to code a Discord bot and I would like to add commands so that people with kick/ban permissions can use the kick/ban commands. I have added many different forms of kick and ban commands, but none of them function correctly. I am absolutely positive the kick/ban commands were correct. I am starting to get the feeling that there is something is wrong with the rest of my code, making it where kick/ban commands don't function.
Here is what I currently have:
from discord.ext import commands
import os
from dotenv import load_dotenv
import logging

# Enables logging
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)

# Assigns the Discord client to a variable called client
client = commands.Bot(command_prefix='$')

# Loads .env
load_dotenv()

# Prints a message stating that the bot is loggen in
@client.event
async def on_ready():
    print('Logged in as {0.user}'.format(client))

# Prints the help message when a user says $help
@client.event
async def on_message(message):
    if message.content.startswith('$help'):
        await message.channel.send('''**Hydra Help**
*This message contains a list of commands and what they do.*

__help__: Prints this message.''')

# Starts the bot
client.run(os.getenv('TOKEN'))

Is there anything wrong with my code so far that may be causing kick/ban commands to not work?

A: You have to just do this:
Kick:
await ???(For example member or ctx.author).kick(reason=???)

Ban:
await ???(For example member or ctx.author).ban(reason=???)