问:
How do I fit labels into a Tkinter frame and canvas with scrollbar functionality?
I am trying to create a list of letters that can be checked, but when the list goes off the window I don't know how to get the scrollbar to work. I have read that you need to put the labels into a frame and then into a canvas, but that is not working for me.

Here is my code:

```<code>import Tkinter as tk

LARGE_FONT = ("Verdana", 12)
NORMAL_FONT = ("Verdana", 10)
SMALL_FONT = ("Verdana", 8)

number_of_rows = 20

def popupmsg(msg):
    popup = tk.Tk()
    popup.wm_title("!")
    label = tk.Label(popup, text=msg, font=NORMAL_FONT)
    label.pack(side="top", fill="x", pady=10)
    B1 = tk.Button(popup, text="Okay", command=popup.destroy)
    B1.pack()
    popup.mainloop()

class Window(tk.Tk):

    def __init__(self, *args, **kwargs):
    tk.Tk.__init__(self, *args, **kwargs)
    master_frame = tk.Frame(self)
    container = tk.Canvas(master_frame, height=300, width=720, scrollregion=(0,0,300,720))

    master_frame.pack(side="top", fill="both", expand=True)

    vbar = tk.Scrollbar(container,orient="vertical")
    vbar.grid(column=1, sticky="ns")
    vbar.config(command=container.yview)

    container.grid_rowconfigure(-0, weight=1)
    container.grid_columnconfigure(-0, weight=1)

    container.config(yscrollcommand=vbar.set)
    container.pack(side="top", fill="both", expand=True)
    #container.create_window(0,0,window=master_frame, anchor='nw')

    child_to_container_frame = tk.Frame(container)
    child_to_container_frame.grid_rowconfigure(-0, weight=1)
    child_to_container_frame.grid_columnconfigure(-0, weight=1)

    self.frames = {}

    menubar = tk.Menu(master_frame)
    filemenu = tk.Menu(menubar, tearoff=0)
    filemenu.add_command(label="Help", command = lambda: popupmsg("Not supported yet"))
    filemenu.add_separator()
    filemenu.add_command(label="Exit", command=quit)
    menubar.add_cascade(label="File", menu=filemenu)
    optionmenu = tk.Menu(menubar, tearoff=0)
    optionmenu.add_command(label="Option #1", command = lambda: popupmsg("You clicked option #1"))
    optionmenu.add_command(label="Option #2", command = lambda: popupmsg("You clicked option #2"))
    optionmenu.add_command(label="Option #3", command = lambda: popupmsg("You clicked option #3"))
    menubar.add_cascade(label="Options", menu=optionmenu)
    menubar.add_command(label="Start", command = lambda: popupmsg("Starting Scan"))

    tk.Tk.config(self, menu=menubar)

    frame = StartPage(child_to_container_frame, self)
    self.frames[StartPage] = frame
    frame.grid(row=0, column=0, sticky="nsew")
    self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):

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

    def PlaceLabels(self):
        self.row = []
        self.checkboxrow = []
        self.text_in_row = []
        self.states = []
        letter = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T"]
        for i in range(number_of_rows):
            self.states.append(tk.IntVar())
            self.row.append(tk.Label(self, bg="white", pady=5, font=(None, 1), height=20, width=720))
            self.row[i].grid(row=i, column=0, sticky="ew", padx=3, pady=5)
            self.checkboxrow.append(tk.Checkbutton(self, bg="white", variable=self.states[i], command= lambda: self.DarkenLabel()))
            self.checkboxrow[i].grid(row=i, column=0, sticky="w", padx=10)
            self.text_in_row.append(tk.Label(self, bg="white", text=letter[i]))
            self.text_in_row[i].grid(row=i, column=0)

    def DarkenLabel(self):
        for i in range(len(self.checkboxrow)):
            if self.states[i].get() == 1:
                self.row[i].config(bg="gray")
                self.checkboxrow[i].config(bg="gray")
                self.text_in_row[i].config(bg="gray")
            else:
                self.row[i].config(bg="white")
                self.checkboxrow[i].config(bg="white")
                self.text_in_row[i].config(bg="white")

app = Window()
app.geometry('733x500')
app.mainloop()
</code>```

I think the problem is somewhere in the beginning of the Windows class, but I don't know.

I have tried:
container.pack(side="top", fill="both", expand=True)
and
container.create_window(0,0,window=master_frame, anchor='nw')
but both didn't work for me.

Any advice?
And thank you for your help

答:
I followed Bryan Oakley's advice from his comment and it really helped me solve this problem. Here is the code I have, with just the bare bones:</p>

```<code>import Tkinter as tk

class Window(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        master_frame = tk.Frame(self)
        master_frame.pack(side="top", fill="both", expand=True)

        vbar = tk.Scrollbar(master_frame)
        vbar.pack(side='right',fill="y")

        container = tk.Canvas(master_frame, height=300, width=720, scrollregion=(0,0,300,720))
        container.pack(side="top", fill="both", expand=True)

        child_to_container_frame = tk.Frame(container)
        container.create_window(0,0,window=child_to_container_frame, anchor='nw')

        vbar.config(command=container.yview)
        container.config(yscrollcommand=vbar.set, scrollregion=(0,0,1000,1500))

        self.frames = {}
        frame = StartPage(child_to_container_frame, self)
        self.frames[StartPage] = frame
        frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.row = []
        self.row.append(tk.Label(self, bg="white", pady=5, font=(None, 1), height=20, width=720))
        self.row[0].grid(row=0, column=0, sticky="ew", padx=3, pady=5)

app = Window()
app.geometry('733x500')
app.mainloop()
</code>```

Body:
I am trying to create a list of letters that can be checked, but when the list goes off the window I don't know how to get the scrollbar to work. I have read that you need to put the labels into a frame and then into a canvas, but that is not working for me.

Here is my code:

import Tkinter as tk

LARGE_FONT = ("Verdana", 12)
NORMAL_FONT = ("Verdana", 10)
SMALL_FONT = ("Verdana", 8)

number_of_rows = 20

def popupmsg(msg):
    popup = tk.Tk()
    popup.wm_title("!")
    label = tk.Label(popup, text=msg, font=NORMAL_FONT)
    label.pack(side="top", fill="x", pady=10)
    B1 = tk.Button(popup, text="Okay", command=popup.destroy)
    B1.pack()
    popup.mainloop()

class Window(tk.Tk):

    def __init__(self, *args, **kwargs):
    tk.Tk.__init__(self, *args, **kwargs)
    master_frame = tk.Frame(self)
    container = tk.Canvas(master_frame, height=300, width=720, scrollregion=(0,0,300,720))

    master_frame.pack(side="top", fill="both", expand=True)

    vbar = tk.Scrollbar(container,orient="vertical")
    vbar.grid(column=1, sticky="ns")
    vbar.config(command=container.yview)

    container.grid_rowconfigure(-0, weight=1)
    container.grid_columnconfigure(-0, weight=1)

    container.config(yscrollcommand=vbar.set)
    container.pack(side="top", fill="both", expand=True)
    #container.create_window(0,0,window=master_frame, anchor='nw')

    child_to_container_frame = tk.Frame(container)
    child_to_container_frame.grid_rowconfigure(-0, weight=1)
    child_to_container_frame.grid_columnconfigure(-0, weight=1)

    self.frames = {}

    menubar = tk.Menu(master_frame)
    filemenu = tk.Menu(menubar, tearoff=0)
    filemenu.add_command(label="Help", command = lambda: popupmsg("Not supported yet"))
    filemenu.add_separator()
    filemenu.add_command(label="Exit", command=quit)
    menubar.add_cascade(label="File", menu=filemenu)
    optionmenu = tk.Menu(menubar, tearoff=0)
    optionmenu.add_command(label="Option #1", command = lambda: popupmsg("You clicked option #1"))
    optionmenu.add_command(label="Option #2", command = lambda: popupmsg("You clicked option #2"))
    optionmenu.add_command(label="Option #3", command = lambda: popupmsg("You clicked option #3"))
    menubar.add_cascade(label="Options", menu=optionmenu)
    menubar.add_command(label="Start", command = lambda: popupmsg("Starting Scan"))

    tk.Tk.config(self, menu=menubar)

    frame = StartPage(child_to_container_frame, self)
    self.frames[StartPage] = frame
    frame.grid(row=0, column=0, sticky="nsew")
    self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):

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

    def PlaceLabels(self):
        self.row = []
        self.checkboxrow = []
        self.text_in_row = []
        self.states = []
        letter = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T"]
        for i in range(number_of_rows):
            self.states.append(tk.IntVar())
            self.row.append(tk.Label(self, bg="white", pady=5, font=(None, 1), height=20, width=720))
            self.row[i].grid(row=i, column=0, sticky="ew", padx=3, pady=5)
            self.checkboxrow.append(tk.Checkbutton(self, bg="white", variable=self.states[i], command= lambda: self.DarkenLabel()))
            self.checkboxrow[i].grid(row=i, column=0, sticky="w", padx=10)
            self.text_in_row.append(tk.Label(self, bg="white", text=letter[i]))
            self.text_in_row[i].grid(row=i, column=0)

    def DarkenLabel(self):
        for i in range(len(self.checkboxrow)):
            if self.states[i].get() == 1:
                self.row[i].config(bg="gray")
                self.checkboxrow[i].config(bg="gray")
                self.text_in_row[i].config(bg="gray")
            else:
                self.row[i].config(bg="white")
                self.checkboxrow[i].config(bg="white")
                self.text_in_row[i].config(bg="white")

app = Window()
app.geometry('733x500')
app.mainloop()

I think the problem is somewhere in the beginning of the Windows class, but I don't know.

I have tried:
container.pack(side="top", fill="both", expand=True)
and
container.create_window(0,0,window=master_frame, anchor='nw')
but both didn't work for me.

Any advice?
And thank you for your help

Body:
I followed Bryan Oakley's advice from his comment and it really helped me solve this problem. Here is the code I have, with just the bare bones:

import Tkinter as tk

class Window(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        master_frame = tk.Frame(self)
        master_frame.pack(side="top", fill="both", expand=True)

        vbar = tk.Scrollbar(master_frame)
        vbar.pack(side='right',fill="y")

        container = tk.Canvas(master_frame, height=300, width=720, scrollregion=(0,0,300,720))
        container.pack(side="top", fill="both", expand=True)

        child_to_container_frame = tk.Frame(container)
        container.create_window(0,0,window=child_to_container_frame, anchor='nw')

        vbar.config(command=container.yview)
        container.config(yscrollcommand=vbar.set, scrollregion=(0,0,1000,1500))

        self.frames = {}
        frame = StartPage(child_to_container_frame, self)
        self.frames[StartPage] = frame
        frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.row = []
        self.row.append(tk.Label(self, bg="white", pady=5, font=(None, 1), height=20, width=720))
        self.row[0].grid(row=0, column=0, sticky="ew", padx=3, pady=5)

app = Window()
app.geometry('733x500')
app.mainloop()


来源: stackexchange

问:
Sorting array of objects by the ascending order of values related to another value
I am looking to sort a JSON array of objects by the ascending order of values related to another value. Sounds confusing because it is. I have properties 'column' and 'order' in each object in an array. I need the order to be like:
lowest number in column 1, lowest number in column 2, lowest number in column 3, second lowest number in column 1, second lowest number in column 2, second lowest number in column 3 and continue on. This is easy when 'order' has the exact same values, you can use a sort function like:

```<code>function sortCourses(a, b){
    if (a.order == b.order) {
        return (a.column - b.column);
    } else {
        return (a.order - b.order);
    }
}
</code>```

The problem is that I don't always have them setup like that. Here is an example array:

```<code>[
    {
        column: 2,
        order: 5
    },
    {
        column: 1,
        order: 1
    },
    {
        column: 3,
        order: 2
    },
    {
        column: 3,
        order: 1
    },
    {
        column: 1,
        order: 4
    },
    {
        column: 2,
        order: 1
    },
    {
        column: 3,
        order: 3
    },
    {
        column: 1,
        order: 3
    },
    {
        column: 2,
        order: 3
    },
    {
        column: 1,
        order: 2
    }
]
</code>```

After sorting, I need this array to look like:

```<code>[
    {
        column: 1,
        order: 1
    },
    {
        column: 2,
        order: 1
    },
    {
        column: 3,
        order: 1
    },
    {
        column: 1,
        order: 2
    },
    {
        column: 2,
        order: 3
    },
    {
        column: 3,
        order: 2
    },
    {
        column: 1,
        order: 3
    },
    {
        column: 2,
        order: 5
    },
    {
        column: 3,
        order: 3
    },
    {
        column: 1,
        order: 4
    }
]
</code>```

Any ideas on how I could accomplish this?

答:
Could be a little faster, but hopefully easy to follow. </p>

```<code>const data = [
    { column: 2, order: 5 }, { column: 1, order: 1 }, { column: 3, order: 2 },
    { column: 3, order: 1 }, { column: 1, order: 4 }, { column: 2, order: 1 },
    { column: 3, order: 3 }, { column: 1, order: 3 }, { column: 2, order: 3 },
    { column: 1, order: 2 }
];

// Sort by order.
data.sort(function (a, b) {
  return (a.order - b.order);
});

// Group by column.
const groups = data.reduce(
  function (acc, value) {
    if (!acc[value.column]) {
      acc[value.column] = [];
    }
    acc[value.column].push(value);
    return acc;
  }, {});

// Get sorted columns.
const cols = Object.keys(groups).map(Number).sort();

// Loop over columns taking lowest value until we're out of values.
const out = [];
while (out.length < data.length) {
  cols.forEach(
    function (col) {
      if (groups[col].length) {
        out.push(groups[col].shift(0));
      }
    });
}

console.log(out);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am looking to sort a JSON array of objects by the ascending order of values related to another value. Sounds confusing because it is. I have properties 'column' and 'order' in each object in an array. I need the order to be like:
lowest number in column 1, lowest number in column 2, lowest number in column 3, second lowest number in column 1, second lowest number in column 2, second lowest number in column 3 and continue on. This is easy when 'order' has the exact same values, you can use a sort function like:

function sortCourses(a, b){
    if (a.order == b.order) {
        return (a.column - b.column);
    } else {
        return (a.order - b.order);
    }
}

The problem is that I don't always have them setup like that. Here is an example array:

[
    {
        column: 2,
        order: 5
    },
    {
        column: 1,
        order: 1
    },
    {
        column: 3,
        order: 2
    },
    {
        column: 3,
        order: 1
    },
    {
        column: 1,
        order: 4
    },
    {
        column: 2,
        order: 1
    },
    {
        column: 3,
        order: 3
    },
    {
        column: 1,
        order: 3
    },
    {
        column: 2,
        order: 3
    },
    {
        column: 1,
        order: 2
    }
]

After sorting, I need this array to look like:

[
    {
        column: 1,
        order: 1
    },
    {
        column: 2,
        order: 1
    },
    {
        column: 3,
        order: 1
    },
    {
        column: 1,
        order: 2
    },
    {
        column: 2,
        order: 3
    },
    {
        column: 3,
        order: 2
    },
    {
        column: 1,
        order: 3
    },
    {
        column: 2,
        order: 5
    },
    {
        column: 3,
        order: 3
    },
    {
        column: 1,
        order: 4
    }
]

Any ideas on how I could accomplish this?

Body:
Could be a little faster, but hopefully easy to follow.

const data = [
    { column: 2, order: 5 }, { column: 1, order: 1 }, { column: 3, order: 2 },
    { column: 3, order: 1 }, { column: 1, order: 4 }, { column: 2, order: 1 },
    { column: 3, order: 3 }, { column: 1, order: 3 }, { column: 2, order: 3 },
    { column: 1, order: 2 }
];

// Sort by order.
data.sort(function (a, b) {
  return (a.order - b.order);
});

// Group by column.
const groups = data.reduce(
  function (acc, value) {
    if (!acc[value.column]) {
      acc[value.column] = [];
    }
    acc[value.column].push(value);
    return acc;
  }, {});

// Get sorted columns.
const cols = Object.keys(groups).map(Number).sort();

// Loop over columns taking lowest value until we're out of values.
const out = [];
while (out.length < data.length) {
  cols.forEach(
    function (col) {
      if (groups[col].length) {
        out.push(groups[col].shift(0));
      }
    });
}

console.log(out);


问:
Formatted elapsed time in C
I'm writing a function that, among other things, must print out an elapsed time counter. It receives by reference a start time _start, and compares it to current, both typed as time_t. I want to use strftime() to print out the observed time delta in ISO 8601 format. Here's what I attempted to do:

```<code>// Negative start time implies program has not begun
if (*_start > 0) {
    time_t elapsed = current - *_start;
    strftime(time_str, sizeof(time_str) - 1, "%T", localtime(&elapsed));
    printf("%s\n", time_str);
}
</code>```

And here is the output I get immediately after running the program

```<code>01:00:00
01:00:00
01:00:01
01:00:01
01:00:01
</code>```

The seconds work fine, if I let it run longer they get incremented as expected, so do the minutes, however the hour starts as 01 as opposed to 00. Why is this happening? How can I get the hours to start zeroed, like the minutes?

答:
To portably find the number of elapsed seconds between 2 time_t, use difftime() as subtracting 2 time_t values is not specified in C to be a difference in seconds.

double difftime(time_t time1, time_t time0);  C11dr §7.26.2.2

  The difftime function returns the difference expressed in seconds as a double.

```<code>double elapsed_seconds = difftime(current, *_start);
printf("elapsed_seconds: %f\n", elapsed_seconds);
</code>```

Title: Formatted elapsed time in C

Body:
I'm writing a function that, among other things, must print out an elapsed time counter. It receives by reference a start time _start, and compares it to current, both typed as time_t. I want to use strftime() to print out the observed time delta in ISO 8601 format. Here's what I attempted to do:

// Negative start time implies program has not begun
if (*_start > 0) {
    time_t elapsed = current - *_start;
    strftime(time_str, sizeof(time_str) - 1, "%T", localtime(&elapsed));
    printf("%s\n", time_str);
}

And here is the output I get immediately after running the program

01:00:00
01:00:00
01:00:01
01:00:01
01:00:01

The seconds work fine, if I let it run longer they get incremented as expected, so do the minutes, however the hour starts as 01 as opposed to 00. Why is this happening? How can I get the hours to start zeroed, like the minutes?

Body:
To portably find the number of elapsed seconds between 2 time_t, use difftime() as subtracting 2 time_t values is not specified in C to be a difference in seconds.

double difftime(time_t time1, time_t time0);  C11dr §7.26.2.2

  The difftime function returns the difference expressed in seconds as a double.

double elapsed_seconds = difftime(current, *_start);
printf("elapsed_seconds: %f\n", elapsed_seconds);


问:
Finding the state of all child actors in akka
Within a supervisor -> child actor model where 10 children are created and work is evenly split between all children via RoundRobinRoutingLogic. Some of the actors are programmed to stop after some duration of time. Eventually, I would like to see the state of all my child actors (whether they are alive or not). But I'm not able to see any documentation for this within ActorRef.

Here is part of my Supervisor class:

```<code>    Router router;
{
    counter = 0;
    List<Routee> routees = new ArrayList<Routee>();
    for (int i = 0; i < 10; i++) {
        ActorRef r = getContext().actorOf(Props.create(Children.class));
        getContext().watch(r);
        routees.add(new ActorRefRoutee(r));
    }
    router = new Router(new RoundRobinRoutingLogic(), routees);
}
</code>```

Here is the condition within the child actor which causes them to stop:

```<code>if (/*some condition*/) {
   getContext().parent().tell(new Response(startTime, messages, Status.SUCCESS), getContext().parent());
   getContext().stop(getSelf());
}
</code>```

Which is the correct API within the akka toolkit I can use to print the status of all the child actors within my Supervisor class?

答:
There are a couple ways.

First, I see that you watch your routees from the supervisor, this is because you have to remove routees from the router when they terminate. Watching an actor means that the watcher (supervisor in your case) will get a Terminated(actorRef) message when a child terminates. You could use this to maintain your own list of active routees (you should already be updating the router when receiving such a message). And because you should already be updating the router, you can always query its routees using router.getRoutees()

Second, the ActorContext offers the getChildren() method which you could use to enumerate the currently alive routees. You can also use the getChild(name) to check for the status of a specific routee by name, but of course you would have to set a name for those when creating them...

Third, you can make your own protocol where the supervisor could broadcast a custom message to all routees, and have them reply with another message of yours. The disadvantage of this method is that you have to introduce some kind of timeout mechanism because you will never know how many routees are receiving your message, and as such how may answers to expect.

I'm stopping here because I think that unless you have more precise requirements, I wouldn't go for anything else than the first solution above... why reinvent the wheel?

Body:
Within a supervisor -> child actor model where 10 children are created and work is evenly split between all children via RoundRobinRoutingLogic. Some of the actors are programmed to stop after some duration of time. Eventually, I would like to see the state of all my child actors (whether they are alive or not). But I'm not able to see any documentation for this within ActorRef.

Here is part of my Supervisor class:

    Router router;
{
    counter = 0;
    List<Routee> routees = new ArrayList<Routee>();
    for (int i = 0; i < 10; i++) {
        ActorRef r = getContext().actorOf(Props.create(Children.class));
        getContext().watch(r);
        routees.add(new ActorRefRoutee(r));
    }
    router = new Router(new RoundRobinRoutingLogic(), routees);
}

Here is the condition within the child actor which causes them to stop:

if (/*some condition*/) {
   getContext().parent().tell(new Response(startTime, messages, Status.SUCCESS), getContext().parent());
   getContext().stop(getSelf());
}

Which is the correct API within the akka toolkit I can use to print the status of all the child actors within my Supervisor class?


问:
Saving downloaded .mp4 videos to photos album ios
So i have downloaded the .mp4 file to the documents folder in the app. I had successfully saved and played it from the documentsPath, but now I want to save it to the camera roll and use this code :

```<code>-(void)saveVideoToAlbum:(NSString *)sampleMoviePath{
 if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(sampleMoviePath)){
  UISaveVideoAtPathToSavedPhotosAlbum(sampleMoviePath, self, @selector(video:didFinishSavingWithError: contextInfo:),nil);
 }
}

-(void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error  contextInfo:(void *)contextInfo{
 NSLog(@"Finished with error: %@", error);
}
</code>```

it is compatible, since it passed the if bracket and no error log from the second procedure. But I keep getting this lldb abort_with_payload error in my log, can someone help me to solve the problem?

here is some screenshots from the lldb error :

答: Dont forget always check your info.plist, and write the necessary permission that needed in your app. for saving video it need Privacy - Photo Library Usage Description. If you are not specify this permission it will crash and there is no error indicating this.</p>

Body:
So i have downloaded the .mp4 file to the documents folder in the app. I had successfully saved and played it from the documentsPath, but now I want to save it to the camera roll and use this code :

-(void)saveVideoToAlbum:(NSString *)sampleMoviePath{
 if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(sampleMoviePath)){
  UISaveVideoAtPathToSavedPhotosAlbum(sampleMoviePath, self, @selector(video:didFinishSavingWithError: contextInfo:),nil);
 }
}

-(void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error  contextInfo:(void *)contextInfo{
 NSLog(@"Finished with error: %@", error);
}

it is compatible, since it passed the if bracket and no error log from the second procedure. But I keep getting this lldb abort_with_payload error in my log, can someone help me to solve the problem?

here is some screenshots from the lldb error :


问:
After Using '.next_siblings' To Scrape divs Between Elements I can't Manage to Pull Just Text
I know this question is asked already but none of the answers are working in my case and I spent all day trying to build from them. I'll spare the code below of my multiple attempts & show what grabs the elements I need.

From the non descript trivia divs I would like just the text.

The link to the site I'm scraping is below if you would like to go inspect the elements.

Starting from the first "soda even" div it grabs the two "soda even" and "soda odd" divs until it gets to the end of the trivia blurbs at the next h4 element and stops just where I want it (code below).

FYI: I can pull just the text from these divs with BeautifulSoup but not without scooping up lots of other divs I don't want. The numbers of divs change from page to page and I would like to make something that works on any of them.

```<code>site = http://www.imdb.com/name/nm0424060/bio?ref_=nm_dyk_trv_sm

content = urllib.request.urlopen(site).read()

soup = BeautifulSoup(content, "html.parser")

for tag in soup.find("div",class_="soda even").next_siblings:
    if tag.name == "h4":
        break
    else:
        print (tag)
</code>```

(in Python)

答:
I (the asker of this question) figured it out...

But I'm sure I'm doing something wrong because it involves reformatting data back and forth too many times, though it gets the job done. So PLEASE HALP!

```<code>site = http://www.imdb.com/name/nm0424060/bio?ref_=nm_dyk_trv_sm

content = urllib.request.urlopen(site).read()

soup = BeautifulSoup(content, "html.parser")

vtg = u""
listo = []
for tag in soup.find("div",class_="soda even").next_siblings:
    if tag.name == "h4":
        break
    else:
        vtg += str(tag)

soup2 = BeautifulSoup(vtg, "html.parser")

q = []

#specify the elements with two more .findAll passes to weed out any href elements still in the soup

for i in soup2.findAll("div",class_="soda even"):
    q.append(i.text)

for k in soup2.findAll("div",class_="soda odd"):
    q.append(k.text)

for h in q:
    print (h)
</code>```

I stored the output from the .next_siblings for loop as a string THEN I put that through BeatifulSoup, (data through BeautifulSoup a second time).

I was able to for loop through that and apply the .text function.

If there's a more data sciency way or just different way I'd love to see your post.

Thanks for the thumbs down on my question, as if this problem was easy or was posted before.

Body:
I know this question is asked already but none of the answers are working in my case and I spent all day trying to build from them. I'll spare the code below of my multiple attempts & show what grabs the elements I need.

From the non descript trivia divs I would like just the text.

The link to the site I'm scraping is below if you would like to go inspect the elements.

Starting from the first "soda even" div it grabs the two "soda even" and "soda odd" divs until it gets to the end of the trivia blurbs at the next h4 element and stops just where I want it (code below).

FYI: I can pull just the text from these divs with BeautifulSoup but not without scooping up lots of other divs I don't want. The numbers of divs change from page to page and I would like to make something that works on any of them.

site = http://www.imdb.com/name/nm0424060/bio?ref_=nm_dyk_trv_sm

content = urllib.request.urlopen(site).read()

soup = BeautifulSoup(content, "html.parser")

for tag in soup.find("div",class_="soda even").next_siblings:
    if tag.name == "h4":
        break
    else:
        print (tag)

(in Python)

Body:
I (the asker of this question) figured it out...

But I'm sure I'm doing something wrong because it involves reformatting data back and forth too many times, though it gets the job done. So PLEASE HALP!

site = http://www.imdb.com/name/nm0424060/bio?ref_=nm_dyk_trv_sm

content = urllib.request.urlopen(site).read()

soup = BeautifulSoup(content, "html.parser")

vtg = u""
listo = []
for tag in soup.find("div",class_="soda even").next_siblings:
    if tag.name == "h4":
        break
    else:
        vtg += str(tag)

soup2 = BeautifulSoup(vtg, "html.parser")

q = []

#specify the elements with two more .findAll passes to weed out any href elements still in the soup

for i in soup2.findAll("div",class_="soda even"):
    q.append(i.text)

for k in soup2.findAll("div",class_="soda odd"):
    q.append(k.text)

for h in q:
    print (h)

I stored the output from the .next_siblings for loop as a string THEN I put that through BeatifulSoup, (data through BeautifulSoup a second time).

I was able to for loop through that and apply the .text function.

If there's a more data sciency way or just different way I'd love to see your post.

Thanks for the thumbs down on my question, as if this problem was easy or was posted before.


答:
If you want to use this method, you should be aware that time() returns UTC. If you then subtract that from your local time (as returned by localtime()), time zones will have an effect on the result (it's likely your particular time zone is removed from UTC by one hour).

Consider the following complete program, similar to your snippet:

```<code>#include <stdio.h>
#include <time.h>
#include <unistd.h>

int main(void) {
    time_t start = time(0);
    char time_str[100];
    for (int i = 5; i > 0; i--) {
        sleep (1);
        time_t elapsed = time(0) - start;
        strftime(time_str, sizeof(time_str) - 1, "%T", localtime(&elapsed));
        printf("%s\n", time_str);
    }

    return 0;
}
</code>```

Also consider that my particular time zone is removed from UTC by eight hours:

```<code>pax> date ; date -u
Thursday 30 March  10:25:57 AWST 2017
Thursday 30 March  02:25:57 UTC 2017
</code>```

When I run it, I see:

```<code>08:00:01
08:00:02
08:00:03
08:00:04
08:00:05
</code>```

You can see there that the eight-hour time difference from UTC affects the value. The fix for that is actually quite simple: don't use local time at all. If you replace the localtime() call with gmtime(), you get the output you expect:

```<code>00:00:01
00:00:02
00:00:03
00:00:04
00:00:05
</code>```

Title: Formatted elapsed time in C

Body:
If you want to use this method, you should be aware that time() returns UTC. If you then subtract that from your local time (as returned by localtime()), time zones will have an effect on the result (it's likely your particular time zone is removed from UTC by one hour).

Consider the following complete program, similar to your snippet:

#include <stdio.h>
#include <time.h>
#include <unistd.h>

int main(void) {
    time_t start = time(0);
    char time_str[100];
    for (int i = 5; i > 0; i--) {
        sleep (1);
        time_t elapsed = time(0) - start;
        strftime(time_str, sizeof(time_str) - 1, "%T", localtime(&elapsed));
        printf("%s\n", time_str);
    }

    return 0;
}

Also consider that my particular time zone is removed from UTC by eight hours:

pax> date ; date -u
Thursday 30 March  10:25:57 AWST 2017
Thursday 30 March  02:25:57 UTC 2017

When I run it, I see:

08:00:01
08:00:02
08:00:03
08:00:04
08:00:05

You can see there that the eight-hour time difference from UTC affects the value. The fix for that is actually quite simple: don't use local time at all. If you replace the localtime() call with gmtime(), you get the output you expect:

00:00:01
00:00:02
00:00:03
00:00:04
00:00:05


问:
What is R's multidimensional equivalent of rbind and cbind?
When working with matrices in R, one can put them side-by-side or stack them top of each other using cbind and rbind, respectively. What is the equivalent function for stacking matrices or arrays in other dimensions?

For example, the following creates a pair of 2x2 matrices, each having 4 elements:

```<code>x = cbind(1:2,3:4)
y = cbind(5:6,7:8)
</code>```

What is the code to combine them into a 2x2x2 array with 8 elements?

答:
See the abind package. If you want them to bind on a 3rd dimension, do this:

```<code>library(abind)
abind(x, y, along = 3)
</code>```

See ?abind

Also, abind gives a lot more convenience, but for simple binding you can just manipulate the values directly, based on the default ordering:

```<code>array(c(x, y), dim = c(2, 2, 2))
</code>```

ContentLicense: CC BY-SA 2.5

Body:
When working with matrices in R, one can put them side-by-side or stack them top of each other using cbind and rbind, respectively. What is the equivalent function for stacking matrices or arrays in other dimensions?

For example, the following creates a pair of 2x2 matrices, each having 4 elements:

x = cbind(1:2,3:4)
y = cbind(5:6,7:8)

What is the code to combine them into a 2x2x2 array with 8 elements?

Body:
See the abind package. If you want them to bind on a 3rd dimension, do this:

library(abind)
abind(x, y, along = 3)

See ?abind

Also, abind gives a lot more convenience, but for simple binding you can just manipulate the values directly, based on the default ordering:

array(c(x, y), dim = c(2, 2, 2))


问:
Error on Provider Service in Angular 2
i'm really new on Angular 2. I want to do a very basic service so i du this:

apitest.service.ts:

```<code>import { Injectable } from '@angular/core';

@Injectable()
export class ApiTest {
    log(msg:string){
        console.log(msg);
    }
}
</code>```

app.module.ts

```<code>import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { HttpModule } from '@angular/http';

import { AppComponent }   from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';

import { DashboardModule } from './dashboard/dashboard.module';
import { SidebarModule } from './sidebar/sidebar.module';
import { FooterModule } from './shared/footer/footer.module';
import { NavbarModule} from './shared/navbar/navbar.module';

import { HashLocationStrategy, LocationStrategy } from '@angular/common';

import {ApiTest} from './shared/apiTest/apitest.service';

@NgModule({
    imports:      [
        BrowserModule,
        DashboardModule,
        SidebarModule,
        NavbarModule,
        FooterModule,
        HttpModule,
        RouterModule.forRoot([])
    ],
    declarations: [ AppComponent, DashboardComponent ],
    providers: [
        {
            provide: LocationStrategy,
            useClass: HashLocationStrategy
        }, ApiTest],
    bootstrap:    [ AppComponent ]
})
export class AppModule { }
</code>```

calendario.component.ts:

```<code> import {ApiTest} from './../../shared/ApiTest/apitest.service';

@Component({
    moduleId: module.id,
    selector: 'calendario',
    templateUrl: 'calendario.component.html'
})
    export class CalendarioComponent{
         constructor( private apitest:ApiTest) {}
        obtenerDatos() {
            this.apitest.log("Hola desde servicio");
        }
    }
</code>```

I got this error:
EXCEPTION: Uncaught (in promise): Error: No provider for ApiTest

If i change my component decorator to:

```<code>@Component({
    moduleId: module.id,
    selector: 'calendario',
    templateUrl: 'calendario.component.html',
    providers: [ApiTest]
})
</code>```

It works.

But... i learn that i cant declare my service on @NgModule and this service can be available on any component that i want! I based my answer on the official Angular 2 Docs

I'm doing something wrong?
Thanks!

[UPDATE 1]

The calendarioComponent is inside another module, dashboardModule.

dashboard.module.ts

```<code>import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { AuthModule } from '../auth.module';
import {ApiTest} from './../shared/apiTest/apitest.service';
import { MODULE_COMPONENTS, MODULE_ROUTES } from './dashboard.routes';

@NgModule({
    imports: [
        RouterModule.forChild(MODULE_ROUTES),
        AuthModule
    ],
    declarations: [ MODULE_COMPONENTS ],
    providers: [ApiTest]
})

export class DashboardModule{

}
</code>```

As you can see, i added here the service import and provider, but still give me the same error.

答:
So... i found the solution. But this solution is very strange. I put my service file next to the module in the same folder where i inject my service and now works.

Before my Service was:

```<code>//calendario.component.ts
import {ApiTest} from './../../shared/ApiTest/apitest.service';
</code>```

Now:

```<code>import {UserService} from '../apitest.service';
</code>```

Before on my module:

```<code>import {ApiTest} from './../shared/apiTest/apitest.service';
</code>```

Now:

```<code>import {UserService} from './apitest.service';
</code>```

Maybe this will help to something else.

But i would like to know why???

Title: Error on Provider Service in Angular 2

Body:
i'm really new on Angular 2. I want to do a very basic service so i du this:

apitest.service.ts:

import { Injectable } from '@angular/core';

@Injectable()
export class ApiTest {
    log(msg:string){
        console.log(msg);
    }
}

app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { HttpModule } from '@angular/http';

import { AppComponent }   from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';

import { DashboardModule } from './dashboard/dashboard.module';
import { SidebarModule } from './sidebar/sidebar.module';
import { FooterModule } from './shared/footer/footer.module';
import { NavbarModule} from './shared/navbar/navbar.module';

import { HashLocationStrategy, LocationStrategy } from '@angular/common';

import {ApiTest} from './shared/apiTest/apitest.service';

@NgModule({
    imports:      [
        BrowserModule,
        DashboardModule,
        SidebarModule,
        NavbarModule,
        FooterModule,
        HttpModule,
        RouterModule.forRoot([])
    ],
    declarations: [ AppComponent, DashboardComponent ],
    providers: [
        {
            provide: LocationStrategy,
            useClass: HashLocationStrategy
        }, ApiTest],
    bootstrap:    [ AppComponent ]
})
export class AppModule { }

calendario.component.ts:

 import {ApiTest} from './../../shared/ApiTest/apitest.service';

@Component({
    moduleId: module.id,
    selector: 'calendario',
    templateUrl: 'calendario.component.html'
})
    export class CalendarioComponent{
         constructor( private apitest:ApiTest) {}
        obtenerDatos() {
            this.apitest.log("Hola desde servicio");
        }
    }

I got this error:
EXCEPTION: Uncaught (in promise): Error: No provider for ApiTest

If i change my component decorator to:

@Component({
    moduleId: module.id,
    selector: 'calendario',
    templateUrl: 'calendario.component.html',
    providers: [ApiTest]
})

It works.

But... i learn that i cant declare my service on @NgModule and this service can be available on any component that i want! I based my answer on the official Angular 2 Docs

I'm doing something wrong?
Thanks!

[UPDATE 1]

The calendarioComponent is inside another module, dashboardModule.

dashboard.module.ts

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { AuthModule } from '../auth.module';
import {ApiTest} from './../shared/apiTest/apitest.service';
import { MODULE_COMPONENTS, MODULE_ROUTES } from './dashboard.routes';

@NgModule({
    imports: [
        RouterModule.forChild(MODULE_ROUTES),
        AuthModule
    ],
    declarations: [ MODULE_COMPONENTS ],
    providers: [ApiTest]
})

export class DashboardModule{

}

As you can see, i added here the service import and provider, but still give me the same error.

Body:
So... i found the solution. But this solution is very strange. I put my service file next to the module in the same folder where i inject my service and now works.

Before my Service was:

//calendario.component.ts
import {ApiTest} from './../../shared/ApiTest/apitest.service';

Now:

import {UserService} from '../apitest.service';

Before on my module:

import {ApiTest} from './../shared/apiTest/apitest.service';

Now:

import {UserService} from './apitest.service';

Maybe this will help to something else.

But i would like to know why???


问:
ValueError: Passed Tensor(...) should have graph attribute that is equal to current graph
I simply can't find the issue with tensorflow. Should be something simple. The example (simple XOR with noise classification) below raises the following issue:

ValueError: Passed Tensor("training_loss:0", shape=(), dtype=float32) should have graph attribute that is equal to current graph <tensorflow.python.framework.ops.Graph object at 0x0000018F142D9AC8>.

I simply do not see the problem.

```<code>import numpy as np
import pandas as pd
import tensorflow as tf

def xor_data():
    np.random.seed(423)
    rows = 1000
    base_cases = [(1, 1, 0), (0, 0, 1), (1, 0, 1), (0, 1, 1)]
    frames = list()

    for case in base_cases:
        tmp_df = pd.DataFrame(
            np.random.uniform(low=-0.3, high=0.3, size=(rows, 2)),
                              columns=['x_1', 'x_2'])
        tmp_df['x_1'] += case[0]
        tmp_df['x_2'] += case[1]
        tmp_df['y'] = case[2]
        frames.append(tmp_df)

    return pd.concat(frames, ignore_index=True)

def xor_fun():
    x_1 = tf.contrib.layers.real_valued_column("x_1")
    x_2 = tf.contrib.layers.real_valued_column("x_2")

    model = tf.contrib.learn.DNNClassifier(hidden_units=[2,2 ],
                                          feature_columns=[x_1, x_2])
    df = xor_data()
    feature_cols = {
        'x_1': tf.constant(value=df['x_1'].values),
        'x_2': tf.constant(value=df['x_2'].values)}

    labels = tf.constant(value=df['y'].values)

    def input_fn():
        return feature_cols, labels

    model.fit(input_fn=input_fn, steps=50)

if __name__ == '__main__':
    xor_fun()
</code>```

答:
Returning the features or labels from a closure fails because a new tf.Graph is created when you call model.fit, so any modifications to the graph (e.g. tf.contrib calls) need to be made from within the input_fn (and therefore after the new graph has been instantiated).

To demonstrate, this works

```<code>import numpy as np
import tensorflow as tf

def input_fn():
    x = np.array([1., 2., 3., 4.])
    y = np.array([0., -1., -2., -3.])
    feature_cols = {'x': tf.constant(x)}
    labels = tf.constant(y)
    return feature_cols, labels

features = [tf.contrib.layers.real_valued_column("x", dimension=1)]
estimator = tf.contrib.learn.LinearRegressor(feature_columns=features)
estimator.fit(input_fn=input_fn, steps=100)
print(estimator.evaluate(input_fn=input_fn, steps=1))
</code>```

but this doesn't

```<code>import numpy as np
import tensorflow as tf

x = np.array([1., 2., 3., 4.])
y = np.array([0., -1., -2., -3.])
feature_cols = {'x': tf.constant(x)}
labels = tf.constant(y)
input_fn = lambda: feature_cols, labels

features = [tf.contrib.layers.real_valued_column("x", dimension=1)]
estimator = tf.contrib.learn.LinearRegressor(feature_columns=features)
estimator.fit(input_fn=input_fn, steps=100)
print(estimator.evaluate(input_fn=input_fn, steps=1))
</code>```

See also this answer https://stackoverflow.com/a/39400592/6536722

Body:
I simply can't find the issue with tensorflow. Should be something simple. The example (simple XOR with noise classification) below raises the following issue:

ValueError: Passed Tensor("training_loss:0", shape=(), dtype=float32) should have graph attribute that is equal to current graph <tensorflow.python.framework.ops.Graph object at 0x0000018F142D9AC8>.

I simply do not see the problem.

import numpy as np
import pandas as pd
import tensorflow as tf

def xor_data():
    np.random.seed(423)
    rows = 1000
    base_cases = [(1, 1, 0), (0, 0, 1), (1, 0, 1), (0, 1, 1)]
    frames = list()

    for case in base_cases:
        tmp_df = pd.DataFrame(
            np.random.uniform(low=-0.3, high=0.3, size=(rows, 2)),
                              columns=['x_1', 'x_2'])
        tmp_df['x_1'] += case[0]
        tmp_df['x_2'] += case[1]
        tmp_df['y'] = case[2]
        frames.append(tmp_df)

    return pd.concat(frames, ignore_index=True)

def xor_fun():
    x_1 = tf.contrib.layers.real_valued_column("x_1")
    x_2 = tf.contrib.layers.real_valued_column("x_2")

    model = tf.contrib.learn.DNNClassifier(hidden_units=[2,2 ],
                                          feature_columns=[x_1, x_2])
    df = xor_data()
    feature_cols = {
        'x_1': tf.constant(value=df['x_1'].values),
        'x_2': tf.constant(value=df['x_2'].values)}

    labels = tf.constant(value=df['y'].values)

    def input_fn():
        return feature_cols, labels

    model.fit(input_fn=input_fn, steps=50)

if __name__ == '__main__':
    xor_fun()

Body:
Returning the features or labels from a closure fails because a new tf.Graph is created when you call model.fit, so any modifications to the graph (e.g. tf.contrib calls) need to be made from within the input_fn (and therefore after the new graph has been instantiated).

To demonstrate, this works

import numpy as np
import tensorflow as tf

def input_fn():
    x = np.array([1., 2., 3., 4.])
    y = np.array([0., -1., -2., -3.])
    feature_cols = {'x': tf.constant(x)}
    labels = tf.constant(y)
    return feature_cols, labels

features = [tf.contrib.layers.real_valued_column("x", dimension=1)]
estimator = tf.contrib.learn.LinearRegressor(feature_columns=features)
estimator.fit(input_fn=input_fn, steps=100)
print(estimator.evaluate(input_fn=input_fn, steps=1))

but this doesn't

import numpy as np
import tensorflow as tf

x = np.array([1., 2., 3., 4.])
y = np.array([0., -1., -2., -3.])
feature_cols = {'x': tf.constant(x)}
labels = tf.constant(y)
input_fn = lambda: feature_cols, labels

features = [tf.contrib.layers.real_valued_column("x", dimension=1)]
estimator = tf.contrib.learn.LinearRegressor(feature_columns=features)
estimator.fit(input_fn=input_fn, steps=100)
print(estimator.evaluate(input_fn=input_fn, steps=1))

See also this answer https://stackoverflow.com/a/39400592/6536722


问:
How do I get the value of a BoundField in a django template?
The built in as_html, as_ul, as_p methods on Django forms don't work for me, nor does the built in {{field}} rendering, so I'm trying to write a custom form rendering.

Here's what I have so far:

```<code>    <input id="id_{{field.html_name}}"
                   type="text"
                   name="{{field.html_name}}"
                   placeholder="{{field.label}}"  <!-- "placeholder" is really the only reason I need to do a custom implementation -->
                   value="{{ XXX }}"      <!-- what goes here? -->
                   maxlength="30"  />
</code>```

The question is, what should go in the value attribute (marked XXX above)?

I've done some looking around and it doesn't appear that BoundField supports a value or data attribute.  I'm using ModelForms if it matters

答: The value attribute landed in trunk in 2010. The patch shows how to retrieve the value using the form/data (not simple in a template unfortunately). There are some template tag code snippets in the ticket comments you may find useful.

Body:
The built in as_html, as_ul, as_p methods on Django forms don't work for me, nor does the built in {{field}} rendering, so I'm trying to write a custom form rendering.

Here's what I have so far:

    <input id="id_{{field.html_name}}"
                   type="text"
                   name="{{field.html_name}}"
                   placeholder="{{field.label}}"
                   value="{{ XXX }}"
                   maxlength="30"  />

The question is, what should go in the value attribute (marked XXX above)?

I've done some looking around and it doesn't appear that BoundField supports a value or data attribute.  I'm using ModelForms if it matters


问:
Relation between sequence of call of fork() and exec()
I got the difference between fork() and exec() system call

A program may be multithreaded--i.e., may contain more than one thread, say T1, T2, andd T3. Now if a particular thread of a program--say T2--executes fork(), a new duplicate (except with a different PID, PC, stack) process will be created with two possiblities:

The process that has been created will contain all the threads T1, T2, T3.

The process that has been created will contain only the thread that executed fork(), i.e., T2. It is a single threaded process

So there are two version of fork() for the above scenario.

Point 1 denotes exec()

Point 2 denotes fork()

Am I correct?

Question

If the sequence of the call is like

fork() is immediately followed by exec()

exec() is immediately followed by fork()

Can anyone please provide a practical example of above two cases?

答:
Am I correct?

Not really. The fork concept is a UNIX-ism. If you call fork() you should should get an almost exact copy of the of the original process. The only different is that the return value of fork in the parent process is the process idea of the child process while the turn value of fork in the child process is 0.

```<code>if (fork () == 0)
{
   // In the child process
   // Usually call exec here.
}
else
{
   //  In the parent process
}
</code>```

On UNIX variants, you should get copies of all the threads of the parent in the child. Other systems may have different behaviors.

A call to fork() is usually immediately followed by a call to exec (or one of its variants) to load a different program. There is rarely any use to simply fork copies of the parent program and just keep it running (exception: this is common in server applications handling network connections).

Can anyone please provide a practical example of above two cases?

First, this sequence does not normally occur:

exec() is immediately followed by fork()

This is the normal use of fork:

fork() is immediately followed by exec()

For example, consider a command line shell. You type in something like this:

```<code>$ ./someapplication param1 param2
</code>```

In order to start someapplication, the shell needs to create a new process. It does that by calling fork(). This just creates a copy of the shell (not very useful). The the child process copy of the shell calls exec to run someapplication.

Yes, this is confusing. In most operating systems you specify the executable when you create a child process. This fork system made sense in the days of the PDP computer and it made sense for certain network programming applications when viewed in the context of the limitations of the UNIX system.

For example, under the RSX operating system that ran on PDP's, there were provisions for software interrupts. A single process could handle multiple network connections and devices. You would queue an I/O request to a device (non-blocking) then receive a software interrupt when the I/O completed. Thus, a single process could have I/O requests pending on multiple devices.

UNIX was much less sophisticated. All I/O was blocking. Where in RSX, you would normally have one process controlling multiple devices, in UNIX you'd have one process per device (keep in mind this is before the days of threads—although blocking I/O calls are still problematic with eunuchs threads). The fork model fit the UNIX way of doing things and provides a simple means of creating a process. In RSX there was much more overhead for process creation.

Body:
Am I correct?

Not really. The fork concept is a UNIX-ism. If you call fork() you should should get an almost exact copy of the of the original process. The only different is that the return value of fork in the parent process is the process idea of the child process while the turn value of fork in the child process is 0.

if (fork () == 0)
{
   // In the child process
   // Usually call exec here.
}
else
{
   //  In the parent process
}

On UNIX variants, you should get copies of all the threads of the parent in the child. Other systems may have different behaviors.

A call to fork() is usually immediately followed by a call to exec (or one of its variants) to load a different program. There is rarely any use to simply fork copies of the parent program and just keep it running (exception: this is common in server applications handling network connections).

Can anyone please provide a practical example of above two cases?

First, this sequence does not normally occur:

exec() is immediately followed by fork()

This is the normal use of fork:

fork() is immediately followed by exec()

For example, consider a command line shell. You type in something like this:

$ ./someapplication param1 param2

In order to start someapplication, the shell needs to create a new process. It does that by calling fork(). This just creates a copy of the shell (not very useful). The the child process copy of the shell calls exec to run someapplication.

Yes, this is confusing. In most operating systems you specify the executable when you create a child process. This fork system made sense in the days of the PDP computer and it made sense for certain network programming applications when viewed in the context of the limitations of the UNIX system.

For example, under the RSX operating system that ran on PDP's, there were provisions for software interrupts. A single process could handle multiple network connections and devices. You would queue an I/O request to a device (non-blocking) then receive a software interrupt when the I/O completed. Thus, a single process could have I/O requests pending on multiple devices.

UNIX was much less sophisticated. All I/O was blocking. Where in RSX, you would normally have one process controlling multiple devices, in UNIX you'd have one process per device (keep in mind this is before the days of threads—although blocking I/O calls are still problematic with eunuchs threads). The fork model fit the UNIX way of doing things and provides a simple means of creating a process. In RSX there was much more overhead for process creation.


问:
With React / Redux, how do I dynamically pre-load state?
I'm having a hard time pre-loading state with React / Redux.

Before marking this as duplicate, I've already read these:

http://redux.js.org/docs/recipes/reducers/InitializingState.htm

Redux - managing preload state

What are your best practices for preloading initialState in your Redux apps?

Here's my scenario:

I'm using Node + React + Redux.

When I load a page, from the server, I load User object from the database. I need this User object to be in the state without a roundtrip to the server.

Because the User object is dynamic, I can't have it in the bundle.

I'm not using server-rendering.

My problem:

How do I initially load the User object from the server into my store in the Client?

In this answer, Dan Abramov says:

On the client, you’d read it from a global variable, and create the client store instance with it. In other words you never have to manually create initialState—you’re supposed to grab it on the server with store.getState(), pass it to client, and create a store with it.

So, I'm assuming that, by global variable, he means something like this:

```<code>// Here, window._initialState.user is being sent to the client in a <script/> tag.
const store = createStore(reducers, { user: window._initialState.user);
</code>```

The above might work, the problem is that I don't have confidence that this is actually a good practice because I didn't find any example on the internet about it.

So, Is this the right thing to do? Is there a better / more recommended way of doing it?

答:
This is taken directly from the redux recipes page:

To pass along the state, we add a  tag that will attach preloadedState to window.__PRELOADED_STATE__.

```<code>function renderFullPage(html, preloadedState) {
return `
    <!doctype html>
    <html>
    <head>
        <title>Redux Universal Example</title>
    </head>
    <body>
        <div id="root">${html}</div>
        <script>
        // WARNING: See the following for security issues around embedding JSON in HTML:
        // http://redux.js.org/docs/recipes/ServerRendering.html#security-considerations
        window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(/</g, '\\u003c')}
        </script>
        <script src="/static/bundle.js"></script>
    </body>
    </html>
    `
}
</code>```

Body:
I'm having a hard time pre-loading state with React / Redux.

Before marking this as duplicate, I've already read these:

http://redux.js.org/docs/recipes/reducers/InitializingState.htm

Redux - managing preload state

What are your best practices for preloading initialState in your Redux apps?

Here's my scenario:

I'm using Node + React + Redux.

When I load a page, from the server, I load User object from the database. I need this User object to be in the state without a roundtrip to the server.

Because the User object is dynamic, I can't have it in the bundle.

I'm not using server-rendering.

My problem:

How do I initially load the User object from the server into my store in the Client?

In this answer, Dan Abramov says:

On the client, you’d read it from a global variable, and create the client store instance with it. In other words you never have to manually create initialState—you’re supposed to grab it on the server with store.getState(), pass it to client, and create a store with it.

So, I'm assuming that, by global variable, he means something like this:

// Here, window._initialState.user is being sent to the client in a

Body:
This is taken directly from the redux recipes page:

To pass along the state, we add a  tag that will attach preloadedState to window.__PRELOADED_STATE__.

function renderFullPage(html, preloadedState) {
return `
    <!doctype html>
    <html>
    <head>
        <title>Redux Universal Example</title>
    </head>
    <body>
        <div id="root">${html}</div>
        <script>
        // WARNING: See the following for security issues around embedding JSON in HTML:
        // http://redux.js.org/docs/recipes/ServerRendering.html#security-considerations
        window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(/</g, '\\u003c')}
        </script>
        <script src="/static/bundle.js"></script>
    </body>
    </html>
    `
}


问:
SQL Server - PIVOT Grouping and Order By
quick question, I need to know how can I insert EmployeeID inside the SELECT DISTINCT.  When I try to insert like this:

```<code>STUFF((SELECT DISTINCT ',' + QUOTENAME(lt.[Description], lc.EmployeeID)
</code>```

It gives me an error:

Msg 145, Level 15, State 1, Line 6
  ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

This is the whole code:

```<code>DECLARE @LoanTypeDesc AS NVARCHAR(MAX)
SELECT @LoanTypeDesc = STUFF((SELECT DISTINCT ',' + QUOTENAME(lt.[Description])
                FROM LoanType lt INNER JOIN LoanContract lc ON lc.LoanTypeID = lt.LoanTypeID
                ORDER BY lc.EmployeeID
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)')
    ,1,1,'')
</code>```

What I am trying to achieve is I am using a PIVOT to get the result of description and set it to columns.

Here is my pivot code:

```<code>SET @strQuery = 'SELECT *
FROM (
SELECT TOP 1000 EmployeeID,
    LoanAmount,
    lt.LoanTypeID,
    lt.[Description]
FROM LoanContract lc
INNER JOIN LoanType lt ON lt.LoanTypeID = lc.LoanTypeID
ORDER BY EmployeeID ASC
) src
PIVOT(
SUM(LoanAmount)
FOR Description IN (' + @LoanTypeDesc + ')
) piv;'
EXECUTE (@strQuery)
</code>```

And I want to achieve something like this:

Any help would be appreciated.

答: Just remove lt.LoanTypeID from select in pivot statement. This is because in pivot statement there are three parts: grouping, aggregation and spreading. In your case aggregation is LoanAmount, spreading is lt.[Description] and  grouping column(s) are detected by elimination. Simply speaking the rest columns. So result is being grouped by EmployeeID and LoanTypeID. As a general rule you will probably want to select 3 columns most of the time for pivot statement.

Body:
quick question, I need to know how can I insert EmployeeID inside the SELECT DISTINCT.  When I try to insert like this:

STUFF((SELECT DISTINCT ',' + QUOTENAME(lt.[Description], lc.EmployeeID)

It gives me an error:

Msg 145, Level 15, State 1, Line 6
  ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

This is the whole code:

DECLARE @LoanTypeDesc AS NVARCHAR(MAX)
SELECT @LoanTypeDesc = STUFF((SELECT DISTINCT ',' + QUOTENAME(lt.[Description])
                FROM LoanType lt INNER JOIN LoanContract lc ON lc.LoanTypeID = lt.LoanTypeID
                ORDER BY lc.EmployeeID
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)')
    ,1,1,'')

What I am trying to achieve is I am using a PIVOT to get the result of description and set it to columns.

Here is my pivot code:

SET @strQuery = 'SELECT *
FROM (
SELECT TOP 1000 EmployeeID,
    LoanAmount,
    lt.LoanTypeID,
    lt.[Description]
FROM LoanContract lc
INNER JOIN LoanType lt ON lt.LoanTypeID = lc.LoanTypeID
ORDER BY EmployeeID ASC
) src
PIVOT(
SUM(LoanAmount)
FOR Description IN (' + @LoanTypeDesc + ')
) piv;'
EXECUTE (@strQuery)

And I want to achieve something like this:

Any help would be appreciated.


问:
React Native WebView Generating invalid render method, says undefined
I'm trying to use Canvas taken from https://github.com/iddan/react-native-canvas
However, when trying to generate, it seems that the WebView creates the following error:

```<code>Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of 'Canvas'
</code>```

I've attached A snippet from the index.ios.js containing Canvas. Any help as to why the WebView generates this error would be super helpful (It works if you remove WebView and just leave View).

```<code>import React, { PropTypes, Component, WebView } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Platform,
  Image,
  TouchableHighlight,
} from 'react-native';
import {
  StackNavigator,
} from 'react-navigation';
import SignatureCapture from 'react-native-signature-capture';
const Sound = require('react-native-sound');

// TEST
class Canvas extends Component {

  propTypes: {
    context: React.PropTypes.object,
    render: React.PropTypes.func.isRequired
  };

  render() {

    var contextString = JSON.stringify(this.props.context);
    var renderString = this.props.render.toString();

    return (
      <View>
        <WebView
          automaticallyAdjustContentInsets={false}
          contentInset={{top: 0, right: 0, bottom: 0, left: 0}}
          html={'<style>*{margin:0;padding:0;}canvas{position:absolute;transform:translateZ(0);}</style><canvas></canvas><script>var canvas = document.querySelector("canvas");(" + renderString + ").call(" + contextString + ", canvas);</script>'}
          opaque={false}
          underlayColor={'transparent'}
          style={this.props.style}/>
      </View>
    );
  };
};
</code>```

答: Try to add your html code in a file and call source={{ uri: require('./myfile.html')}} . Use source prop instead html. html is deprecated. Verify the docs https://facebook.github.io/react-native/docs/webview.html

Body:
I'm trying to use Canvas taken from https://github.com/iddan/react-native-canvas
However, when trying to generate, it seems that the WebView creates the following error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of 'Canvas'

I've attached A snippet from the index.ios.js containing Canvas. Any help as to why the WebView generates this error would be super helpful (It works if you remove WebView and just leave View).

import React, { PropTypes, Component, WebView } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Platform,
  Image,
  TouchableHighlight,
} from 'react-native';
import {
  StackNavigator,
} from 'react-navigation';
import SignatureCapture from 'react-native-signature-capture';
const Sound = require('react-native-sound');

// TEST
class Canvas extends Component {

  propTypes: {
    context: React.PropTypes.object,
    render: React.PropTypes.func.isRequired
  };

  render() {

    var contextString = JSON.stringify(this.props.context);
    var renderString = this.props.render.toString();

    return (
      <View>
        <WebView
          automaticallyAdjustContentInsets={false}
          contentInset={{top: 0, right: 0, bottom: 0, left: 0}}
          html={'<canvas></canvas>'}
          opaque={false}
          underlayColor={'transparent'}
          style={this.props.style}/>
      </View>
    );
  };
};


问:
different login form for user and admin
how do i differentiate redirection page for user and admin?

Database Table:

Here is my code;

```<code><?php

   require ("config.php");

   //connect to mysql
   $link = mysqli_connect($h,$u,$p,$db)
   OR die(mysql_error());

  $query = "select * from login where username='".$_POST["uname"]."'and password='".$_POST["pswd"]."'";

  $result = mysqli_query($link,$query);
  $count =mysqli_num_rows($result);
  //while($row = mysqli_fetch_assoc($result)) {
//}
   if($count==1){
    session_start();
    $_SESSION['username'] = $_POST["uname"];
    $_SESSION['password'] = $_POST["pswd"];
    header("Location: index.html");

   }
    else{
    echo "<script language=\"JavaScript\">\n";
    echo "alert('Username or Password was incorrect!');\n";
    echo "window.location='login.html'";
    echo "</script>";
   }
?>
</code>```

How do i seperate user and admin login, i rather new here so your explanation/code is much appreciate!

Thanks in advance!

答:
Although I'm not a user of mysqli, this might guide you. Just convert it to mysqli version

```<code>if('admin' == $row['usertype']) {
    header('Location:admin.php');
    exit;
}
if('user' == $row['usertype']) {
    header('Location:user.php');
    exit;
}
</code>```

Title: different login form for user and admin

Body:
how do i differentiate redirection page for user and admin?

Database Table:

Here is my code;

<?php

   require ("config.php");

   //connect to mysql
   $link = mysqli_connect($h,$u,$p,$db)
   OR die(mysql_error());

  $query = "select * from login where username='".$_POST["uname"]."'and password='".$_POST["pswd"]."'";

  $result = mysqli_query($link,$query);
  $count =mysqli_num_rows($result);
  //while($row = mysqli_fetch_assoc($result)) {
//}
   if($count==1){
    session_start();
    $_SESSION['username'] = $_POST["uname"];
    $_SESSION['password'] = $_POST["pswd"];
    header("Location: index.html");

   }
    else{
    echo "";
   }
?>

How do i seperate user and admin login, i rather new here so your explanation/code is much appreciate!

Thanks in advance!

Body:
Although I'm not a user of mysqli, this might guide you. Just convert it to mysqli version

if('admin' == $row['usertype']) {
    header('Location:admin.php');
    exit;
}
if('user' == $row['usertype']) {
    header('Location:user.php');
    exit;
}


问:
Problems with the Google Places API AddPlaceRequest - Android Studio
I'm in the process of creating an application on Android Studio which allows a user to select a location on a map and add some details to that location - E.g. Select a football pitch and add some details to it such as 5 a side football match on Sunday at 12 o'clock.
Once these details are saved that location is saved onto the map along with those details.

I've decided to use the Google Places API as it has the AddPlace feature. Instead of adding a business to the map like the API was intended for, I want to tweak it so it can add an event instead.

However, the example found here at:

https://developers.google.com/places/android-api/add-place

Does not work in my application.

Here are the screenshots:

Code Snippet

Any help would be greatly appreciated - Thank you
G

答:
The Add A Place function of the Places API isn't a good fit for what you're trying to do. Add Place is designed to allow users to add places that don't currently exist in Google Maps' database. It sounds like what you want to do is attach some metadata to a place that has meaning only to your app.

So, you'll need some persistent server storage for this metadata. There are lots of ways to do this but you might want to look at Firebase Realtime Database as a solution.

Also, from the screenshot, it looks like your error comes from not having defined mGoogleApiClient in in your app.


问:
How can I extract images from a PDF file?
I need to extract all the images from a PDF file on my server. I don't want the PDF pages, only the images at their original size and resolution.

How could I do this with Perl, PHP or any other UNIX based app (which I would invoke with the exec function from PHP)?

答:
pdfimages does just that. It's is part of the poppler-utils and xpdf-utils packages.

From the manpage:

  Pdfimages saves images from a Portable Document Format  (PDF)  file  as Portable Pixmap (PPM), Portable Bitmap (PBM), or JPEG files.

  Pdfimages  reads  the  PDF file, scans one or more pages, PDF-file, and writes one PPM, PBM, or JPEG file for each  image,  image-root-nnn.xxx, where  nnn  is  the image number and xxx is the image type (.ppm, .pbm, .jpg).

  NB: pdfimages extracts the raw image data from the  PDF  file,  without performing  any  additional  transforms.  Any rotation, clipping, color inversion, etc. done by the PDF content stream is ignored.

LastEditorDisplayName: brian d foy

OwnerDisplayName: Luis


问:
Retrieving data from array of array objects
In my application i am trying to return javascript object of employee who works in all projects. My array of data is like:

```<code>   var data = [
{
    projectName: "project1", projectId: 1,
    employees: [
        {fullName: "John Doe", employeeId: 1},
        {fullName: "Jane Smith", employeeId: 2}
    ]
},

{
    projectName: "project2", projectId: 2,
    employees: [
        {fullName: "John Doe", employeeId: 1},
        {fullName: "Mary Jones", employeeId: 3},
        {fullName: "Bill Evans", employeeId: 4}
    ]
}
</code>```

];

I need to search for employeeid 1 and return both projects. How do i search it.

答:
Hope this works Fine

var data = [{
    projectName: "project1",
    projectId: 1,
    employees: [{
        fullName: "John Doe",
        employeeId: 1
      },
      {
        fullName: "Jane Smith",
        employeeId: 5
      }
    ]
  },

  {
    projectName: "project2",
    projectId: 2,
    employees: [{
        fullName: "John Doe",
        employeeId: 1
      },
      {
        fullName: "Mary Jones",
        employeeId: 3
      },
      {
        fullName: "Bill Evans",
        employeeId: 4
      }
    ]
  }
];

function getEmployeeById(id) {
  var e = $.map(data, function(a) {
    var r = $.grep(a.employees, function(b) {
      return b.employeeId == id;
    });
    if (r.length) {
      console.log(a.projectName, r[0].fullName)
    }
  });
}
getEmployeeById(1)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
In my application i am trying to return javascript object of employee who works in all projects. My array of data is like:

   var data = [
{
    projectName: "project1", projectId: 1,
    employees: [
        {fullName: "John Doe", employeeId: 1},
        {fullName: "Jane Smith", employeeId: 2}
    ]
},

{
    projectName: "project2", projectId: 2,
    employees: [
        {fullName: "John Doe", employeeId: 1},
        {fullName: "Mary Jones", employeeId: 3},
        {fullName: "Bill Evans", employeeId: 4}
    ]
}

];

I need to search for employeeid 1 and return both projects. How do i search it.

Body:
Hope this works Fine

var data = [{
    projectName: "project1",
    projectId: 1,
    employees: [{
        fullName: "John Doe",
        employeeId: 1
      },
      {
        fullName: "Jane Smith",
        employeeId: 5
      }
    ]
  },

  {
    projectName: "project2",
    projectId: 2,
    employees: [{
        fullName: "John Doe",
        employeeId: 1
      },
      {
        fullName: "Mary Jones",
        employeeId: 3
      },
      {
        fullName: "Bill Evans",
        employeeId: 4
      }
    ]
  }
];

function getEmployeeById(id) {
  var e = $.map(data, function(a) {
    var r = $.grep(a.employees, function(b) {
      return b.employeeId == id;
    });
    if (r.length) {
      console.log(a.projectName, r[0].fullName)
    }
  });
}
getEmployeeById(1)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Configuration.resolve has an unknown property 'root'
I get the following error :

Invalid configuration object. Webpack has been initialised using a
  configuration object that does not match the API schema.
   - configuration.resolve has an unknown property 'root'. These properties are valid:    object { alias?, aliasFields?,
  cachePredicate?, descriptionFiles?, enforceExtension?,
  enforceModuleExtension?, extensions?, fileSystem?, mainFields?,
  mainFiles?, moduleExtensions?, modules?, plugins?, resolver?,
  symlinks?, unsafeCache?, useSyncFileSystemCalls? }

I use webpack 2.3.2.

My webpack.config.js looks like this :

```<code>module.exports= {
  entry:'./public/app.jsx',
  output: {
    path: __dirname,
    filename:'./public/bundle.js'
  },
  resolve: {
    root: __dirname,
    alias:{
      Mod1: 'public/components/mod1.jsx',
      Mod2:'public/components/mod2.jsx',
      Mod3: 'public/components/mod3.jsx'
    },
    extensions: ['*','.js','.jsx']
  },
  module :{
    loaders:[{
      loader :'babel-loader',
      query :{
        presets:['react','es2015','es2017']
      },
      test:/\.jsx?$/,
      exclude:/(node_modules|bower_components)/
    }]
  }
};
</code>```

答:
resolve.root is Webpack 1 configuration and doesn't exist for Webpack 2.

For Webpack 2 you can use resolve.modules: https://webpack.js.org/configuration/resolve/#resolve-modules

```<code>module.exports= {
  entry:'./public/app.jsx',
  output: {
    path: __dirname,
    filename:'./public/bundle.js'
  },
  resolve: {
    modules: [__dirname, 'node_modules'],
    alias:{
      Mod1: 'public/components/mod1.jsx',
      Mod2:'public/components/mod2.jsx',
      Mod3: 'public/components/mod3.jsx'
    },
    extensions: ['*','.js','.jsx']
  },
  module :{
    rules:[{
      use : 'babel-loader',
      query :{
        presets:['react','es2015','es2017']
      },
      test: /\.jsx?$/,
      exclude: /(node_modules|bower_components)/
    }]
  }
};
</code>```

I've also updated module.loaders -> module.rules as this is deprecated in Webpack 2.

Body:
I get the following error :

Invalid configuration object. Webpack has been initialised using a
  configuration object that does not match the API schema.
   - configuration.resolve has an unknown property 'root'. These properties are valid:    object { alias?, aliasFields?,
  cachePredicate?, descriptionFiles?, enforceExtension?,
  enforceModuleExtension?, extensions?, fileSystem?, mainFields?,
  mainFiles?, moduleExtensions?, modules?, plugins?, resolver?,
  symlinks?, unsafeCache?, useSyncFileSystemCalls? }

I use webpack 2.3.2.

My webpack.config.js looks like this :

module.exports= {
  entry:'./public/app.jsx',
  output: {
    path: __dirname,
    filename:'./public/bundle.js'
  },
  resolve: {
    root: __dirname,
    alias:{
      Mod1: 'public/components/mod1.jsx',
      Mod2:'public/components/mod2.jsx',
      Mod3: 'public/components/mod3.jsx'
    },
    extensions: ['*','.js','.jsx']
  },
  module :{
    loaders:[{
      loader :'babel-loader',
      query :{
        presets:['react','es2015','es2017']
      },
      test:/\.jsx?$/,
      exclude:/(node_modules|bower_components)/
    }]
  }
};

Body:
resolve.root is Webpack 1 configuration and doesn't exist for Webpack 2.

For Webpack 2 you can use resolve.modules: https://webpack.js.org/configuration/resolve/#resolve-modules

module.exports= {
  entry:'./public/app.jsx',
  output: {
    path: __dirname,
    filename:'./public/bundle.js'
  },
  resolve: {
    modules: [__dirname, 'node_modules'],
    alias:{
      Mod1: 'public/components/mod1.jsx',
      Mod2:'public/components/mod2.jsx',
      Mod3: 'public/components/mod3.jsx'
    },
    extensions: ['*','.js','.jsx']
  },
  module :{
    rules:[{
      use : 'babel-loader',
      query :{
        presets:['react','es2015','es2017']
      },
      test: /\.jsx?$/,
      exclude: /(node_modules|bower_components)/
    }]
  }
};

I've also updated module.loaders -> module.rules as this is deprecated in Webpack 2.


问:
aerospike: delete all record in a set
I am using aerospike for testing. I am using community edition.The cluster has 2 nodes. I am using storage engine as device with SSD. My config file -

```<code>namespace test {
        replication-factor 2
        memory-size 16G
        default-ttl 0

       storage-engine device {
                device /dev/sdb1
                data-in-memory false
                write-block-size 128K
        }
}
</code>```

I have set named data. After adding 1M record in it for testing ,now i want to delete everything in this set (if possible drop set too). I tried this command on both node-

```<code>asinfo -v "set-config:context=namespace;id=test;set=data;set-delete=true;"
</code>```

It worked until i restarted my cluster (sudo /etc/init.d/aerospike restart on both node). After restart all data came back. I went through this link http://www.aerospike.com/launchpad/deleting_sets_and_data.html but doesn't find anything convenient.

答:
As of Aerospike 3.12, which was released in March 2017, the feature of deleting all data in a set or namespace is now supported in the database.

Please see the following documentation:
http://www.aerospike.com/docs/reference/info#truncate

Which provides the command line command that looks like:
asinfo truncate:namespace=;set=;lut=

It can also be truncated from the client APIs, here is the java documentation:
http://www.aerospike.com/apidocs/java/com/aerospike/client/AerospikeClient.html
and scroll down to the "truncate" method.

Please note that this feature can, optionally, take a time specification. This allows you to delete records, then start inserting new records. As timestamps are used, please make certain your server clocks are well synchronized.

Also notice that in the Enterprise edition, these deletes are durable and survive restart.

Title: aerospike: delete all record in a set

Body:
I am using aerospike for testing. I am using community edition.The cluster has 2 nodes. I am using storage engine as device with SSD. My config file -

namespace test {
        replication-factor 2
        memory-size 16G
        default-ttl 0

       storage-engine device {
                device /dev/sdb1
                data-in-memory false
                write-block-size 128K
        }
}

I have set named data. After adding 1M record in it for testing ,now i want to delete everything in this set (if possible drop set too). I tried this command on both node-

asinfo -v "set-config:context=namespace;id=test;set=data;set-delete=true;"

It worked until i restarted my cluster (sudo /etc/init.d/aerospike restart on both node). After restart all data came back. I went through this link http://www.aerospike.com/launchpad/deleting_sets_and_data.html but doesn't find anything convenient.


问:
Unmounting a Component with a SetInterval in React
I'm trying to unmount a component with a setInterval.

This is based on the answer here:

Component:

```<code>class ImageSlider extends React.Component {
  constructor(props) {
    super(props);
    this.state = { activeMediaIndex: 0 };
  }

  componentDidMount() {
    setInterval(this.changeActiveMedia.bind(this), 5000);
  }

  changeActiveMedia() {
    const mediaListLength = this.props.mediaList.length;
    let nextMediaIndex = this.state.activeMediaIndex + 1;

    if(nextMediaIndex >= mediaListLength) {
      nextMediaIndex = 0;
    }

    this.setState({ activeMediaIndex:nextMediaIndex });
  }

  renderSlideshow(){
    const singlePhoto = this.props.mediaList[this.state.activeMediaIndex];
      return(
        <div>
          <img src={singlePhoto.url} />
        </div>
      );
    }

  render(){
    return(
      <div>
          {this.renderSlideshow()}
      </div>
    )
  }
}
</code>```

Right now, when I go to another page, I get this error:

```<code>Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component
</code>```

So I added something like this:

```<code>   componentWillUnmount(){
    clearInterval(this.interval);
  }
</code>```

I've also tried:

```<code>   componentWillUnmount(){
    clearInterval(this.changeActiveMedia);
  }
</code>```

But I'm still getting the above error every 5 seconds. Is there a proper way to clear the interval?

答:
setInterval returns an in interval Id that you can use in clearInterval.

More info on setInterval

Something like this should work:

this.myInterval = setInterval(this.changeActiveMedia.bind(this), 5000)

then in componentWillUnmount:

clearInterval(this.myInterval);

Body:
I'm trying to unmount a component with a setInterval.

This is based on the answer here:

Component:

class ImageSlider extends React.Component {
  constructor(props) {
    super(props);
    this.state = { activeMediaIndex: 0 };
  }

  componentDidMount() {
    setInterval(this.changeActiveMedia.bind(this), 5000);
  }

  changeActiveMedia() {
    const mediaListLength = this.props.mediaList.length;
    let nextMediaIndex = this.state.activeMediaIndex + 1;

    if(nextMediaIndex >= mediaListLength) {
      nextMediaIndex = 0;
    }

    this.setState({ activeMediaIndex:nextMediaIndex });
  }

  renderSlideshow(){
    const singlePhoto = this.props.mediaList[this.state.activeMediaIndex];
      return(

      );
    }

  render(){
    return(

          {this.renderSlideshow()}

    )
  }
}

Right now, when I go to another page, I get this error:

Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component

So I added something like this:

   componentWillUnmount(){
    clearInterval(this.interval);
  }

I've also tried:

   componentWillUnmount(){
    clearInterval(this.changeActiveMedia);
  }

But I'm still getting the above error every 5 seconds. Is there a proper way to clear the interval?


问:
Theme change in Aptana Studio Issue (already downloaded Eclipse Market Place and Eclipse Color Theme Plug in
After following the instructions found in: Aptana Studio 3: How to apply themes to python editor I still can't change my theme.

In Aptana Studio 3 I go to Windows->Preferences->General->Color Theme and choose the appropriate theme but the background remains the standard white color. Thanks.

答: The issue is you have to navigate to Windows->Preferences->Aptana Studio->Themes and check the box at the bottom of the window 'Apply to all (non-Studio) editors'. Then having downloaded Eclipse Market Place and the Color Theme Plug-In you can change the theme (background & font) of your primary work space. </p>


问:
Display distinct text after user has selected a set of filters
I'm currently using the following code to display a text with a Long Text Viewer when the user selects a Country from the slicer:

```<code>Notes =
IF(
    HASONEFILTER(Data[Country]),
    CONCATENATEX(Data, Data[Comments], "\n\n"),
    "Please select only one Country from the list."
)
</code>```

However, I've now separated [Comments] from the Data dataset into another dataset called Comment. I'm not sure how the relationships quite work but I checked the Manage Relationships dialog box and a 1:M relationship is active between the Data and Comment datasets.

This is how both datasets look like:

```
> Data dataset
Month | Year | Region | Prod % | ...
Jan   | 2016 | NAM    | 80%    | ...
Jan   | 2016 | LAM    | 40     | ...
Jan   | 2016 | EUR    | 60%    | ...
Jan   | 2016 | AFR    | 70%    | ...
Jan   | 2016 | SEA    | 80%    | ...
Jan   | 2016 | GCN    | 70%    | ...
```

```
> Comment dataset
Month | Year | Region | Comments
Jan   | 2016 | NAM    | Jan NAM comment here
Jan   | 2016 | LAM    | Jan LAM comment here
Jan   | 2016 | EUR    | Jan EUR comment here
Jan   | 2016 | AFR    | Jan AFR comment here
Jan   | 2016 | SEA    | Jan SEA comment here
Jan   | 2016 | GCN    | Jan GCN comment here
```

Is it possible that when the user selects a [Month], [Year] and [Region] from the Data dataset, it would display the appropriate [Comments] from the Comment dataset? Also, I'm not sure on how Primary Keys work in Power BI (both datasets don't have any Primary Keys).

Edit: So I tried this formula after merging the Comment dataset with the Data dataset:

```<code>Notes =
IF(
    HASONEFILTER(Data[Region]) && HASONEFILTER(Data[Year]) && HASONEFILTER(Data[Month]),
    CONCATENATEX(Data, Data[Comment.Comment], "\n\n"),
    "Please select only one Period and Region from the list"
)
</code>```

However, it is displaying the comment multiple times (there were 4 countries selected in the dataset. Would it be possible to make it display the [Comment] that is unique to that [Month], [Year] and [Region]?

答:
I would add a VALUES function to your CONCATENATEX function to summarize the Comments, e.g.

CONCATENATEX( VALUES ( Data[Comment.Comment] ) , Data[Comment.Comment], "\n\n")

Body:
I'm currently using the following code to display a text with a Long Text Viewer when the user selects a Country from the slicer:

Notes =
IF(
    HASONEFILTER(Data[Country]),
    CONCATENATEX(Data, Data[Comments], "\n\n"),
    "Please select only one Country from the list."
)

However, I've now separated [Comments] from the Data dataset into another dataset called Comment. I'm not sure how the relationships quite work but I checked the Manage Relationships dialog box and a 1:M relationship is active between the Data and Comment datasets.

This is how both datasets look like:

> Data dataset
Month | Year | Region | Prod % | ...
Jan   | 2016 | NAM    | 80%    | ...
Jan   | 2016 | LAM    | 40     | ...
Jan   | 2016 | EUR    | 60%    | ...
Jan   | 2016 | AFR    | 70%    | ...
Jan   | 2016 | SEA    | 80%    | ...
Jan   | 2016 | GCN    | 70%    | ...

> Comment dataset
Month | Year | Region | Comments
Jan   | 2016 | NAM    | Jan NAM comment here
Jan   | 2016 | LAM    | Jan LAM comment here
Jan   | 2016 | EUR    | Jan EUR comment here
Jan   | 2016 | AFR    | Jan AFR comment here
Jan   | 2016 | SEA    | Jan SEA comment here
Jan   | 2016 | GCN    | Jan GCN comment here

Is it possible that when the user selects a [Month], [Year] and [Region] from the Data dataset, it would display the appropriate [Comments] from the Comment dataset? Also, I'm not sure on how Primary Keys work in Power BI (both datasets don't have any Primary Keys).

Edit: So I tried this formula after merging the Comment dataset with the Data dataset:

Notes =
IF(
    HASONEFILTER(Data[Region]) && HASONEFILTER(Data[Year]) && HASONEFILTER(Data[Month]),
    CONCATENATEX(Data, Data[Comment.Comment], "\n\n"),
    "Please select only one Period and Region from the list"
)

However, it is displaying the comment multiple times (there were 4 countries selected in the dataset. Would it be possible to make it display the [Comment] that is unique to that [Month], [Year] and [Region]?


答:
You could add a field in the database that is the redirect page for the user; and when the user logs in, it just redirects to that page. OR you could just do this.

```<code><?php session_start();

   require ("config.php");

   //connect to mysql
   $link = mysqli_connect($h,$u,$p,$db)
   OR die(mysql_error());

  $query = "select * from login where username='".$_POST["uname"]."'and password='".$_POST["pswd"]."'";

  $result = mysqli_query($link,$query);
  $count =mysqli_num_rows($result);
  while($row = mysqli_fetch_assoc($result)) {
    $userType = $row['usertype'];
  }
  if($count==1){
    $_SESSION['username'] = $_POST["uname"];
    $_SESSION['password'] = $_POST["pswd"];
     if ($userType=='admin') {
       header("Location: index.html"); //whereever you want to take admins
      } else {
     header("Location: index.html"); //wherever you want to take all users
     }

   }
    else{
    echo "<script language=\"JavaScript\">\n";
    echo "alert('Username or Password was incorrect!');\n";
    echo "window.location='login.html'";
    echo "</script>";
   }
?>
</code>```

Session_start(); should always be the first thing in the document, FYI.

Title: different login form for user and admin

Body:
You could add a field in the database that is the redirect page for the user; and when the user logs in, it just redirects to that page. OR you could just do this.

<?php session_start();

   require ("config.php");

   //connect to mysql
   $link = mysqli_connect($h,$u,$p,$db)
   OR die(mysql_error());

  $query = "select * from login where username='".$_POST["uname"]."'and password='".$_POST["pswd"]."'";

  $result = mysqli_query($link,$query);
  $count =mysqli_num_rows($result);
  while($row = mysqli_fetch_assoc($result)) {
    $userType = $row['usertype'];
  }
  if($count==1){
    $_SESSION['username'] = $_POST["uname"];
    $_SESSION['password'] = $_POST["pswd"];
     if ($userType=='admin') {
       header("Location: index.html"); //whereever you want to take admins
      } else {
     header("Location: index.html"); //wherever you want to take all users
     }

   }
    else{
    echo "<script language=\"JavaScript\">\n";
    echo "alert('Username or Password was incorrect!');\n";
    echo "window.location='login.html'";
    echo "</script>";
   }
?>

Session_start(); should always be the first thing in the document, FYI.

ContentLicense: CC BY-SA 4.0


问:
Swift: Overlay rectangle with text over view
If our app has a network connectivity error we would like to overlay a colored and transparent rectangle over the top of the screen with some "Network not available" like text.  The rectangle should cover the full width of the screen and the height should be enough to just show the text.   We would use a timer to only show the rectangle for a brief period of time.  How can you do this?

The actual view may be a UITableViewController, a UIViewController, or something else...

答:
The way I have done overlays is to drag a new UIViewController into a storyboard, and drag a UIView into that. While laying out the UI it can be helpful to make the background color of the UIViewController black. When you're done laying out your elements inside the UIView, change the background color of the UIViewController to transparent.

Here's an example of a profile overlay:

In this case I've actually made the UIViewController background a gray color with an alpha of about 50%. Then when I present this view controller using a fade transition it looks like it appears over top the current context:

```<code>func showOverlay() {
    //
    guard let vc = UIStoryboard(name: "MyStoryboard", bundle: nil).instantiateViewController(withIdentifier: "myOverlay") as? UIViewController else {
        print("failed to get myOverlay from MyStoryboard")
        return
    }

    vc.modalPresentationStyle = .overCurrentContext
    vc.modalTransitionStyle = .crossDissolve

    self.present(vc, animated: true, completion: {
        // after 3 seconds, dismiss the overlay
        dispatchAfterSeconds(3) {
            vc.dismiss(animated: true)
        }
    })
}
</code>```

This uses a handy function, dispatchAfterSeconds:

```<code>// execute function after delay using GCD
func dispatchAfterSeconds(_ seconds: Double, completion: @escaping (() -> Void)) {
    let triggerTime = Int64(Double(NSEC_PER_SEC) * seconds)
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(triggerTime) / Double(NSEC_PER_SEC), execute: { () -> Void in
        completion()
    })
}
</code>```

Note that when I talk about changing the background color of the UIViewController, what I actually mean by that is the background color of the view created by default inside of a UIViewController that has been created in a storyboard.

Body:
The way I have done overlays is to drag a new UIViewController into a storyboard, and drag a UIView into that. While laying out the UI it can be helpful to make the background color of the UIViewController black. When you're done laying out your elements inside the UIView, change the background color of the UIViewController to transparent.

Here's an example of a profile overlay:

In this case I've actually made the UIViewController background a gray color with an alpha of about 50%. Then when I present this view controller using a fade transition it looks like it appears over top the current context:

func showOverlay() {
    //
    guard let vc = UIStoryboard(name: "MyStoryboard", bundle: nil).instantiateViewController(withIdentifier: "myOverlay") as? UIViewController else {
        print("failed to get myOverlay from MyStoryboard")
        return
    }

    vc.modalPresentationStyle = .overCurrentContext
    vc.modalTransitionStyle = .crossDissolve

    self.present(vc, animated: true, completion: {
        // after 3 seconds, dismiss the overlay
        dispatchAfterSeconds(3) {
            vc.dismiss(animated: true)
        }
    })
}

This uses a handy function, dispatchAfterSeconds:

// execute function after delay using GCD
func dispatchAfterSeconds(_ seconds: Double, completion: @escaping (() -> Void)) {
    let triggerTime = Int64(Double(NSEC_PER_SEC) * seconds)
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(triggerTime) / Double(NSEC_PER_SEC), execute: { () -> Void in
        completion()
    })
}

Note that when I talk about changing the background color of the UIViewController, what I actually mean by that is the background color of the view created by default inside of a UIViewController that has been created in a storyboard.


问:
Pythonic way to check if: all elements evaluate to False -OR- all elements evaluate to True
I want the results of the function to be:

All values evaluate to False (None, 0, empty string) -> True

All values evaluate to True -> True

Every other case -> False

This is my try at it:

```<code>>>> def consistent(x):
...  x_filtered = filter(None, x)
...  return len(x_filtered) in (0, len(x))
...
>>> consistent((0,1))
False
>>> consistent((1,1))
True
>>> consistent((0,0))
True
</code>```

[Bonus]

What should this function be named?

答:
```<code>def all_bools_equal(lst):
    return all(lst) or not any(lst)
</code>```

See: http://docs.python.org/library/functions.html#all

See: http://docs.python.org/library/functions.html#any

Body:
I want the results of the function to be:

All values evaluate to False (None, 0, empty string) -> True

All values evaluate to True -> True

Every other case -> False

This is my try at it:

>>> def consistent(x):
...  x_filtered = filter(None, x)
...  return len(x_filtered) in (0, len(x))
...
>>> consistent((0,1))
False
>>> consistent((1,1))
True
>>> consistent((0,0))
True

[Bonus]

What should this function be named?

Body:
def all_bools_equal(lst):
    return all(lst) or not any(lst)

See: http://docs.python.org/library/functions.html#all

See: http://docs.python.org/library/functions.html#any


问:
How to delete whole set from Aerospike namespace?
Is there any way to delete a set from namespace (Aerospike) from aql or CLI ???

My set also contains Ldts .

Please suggest me a way to delete whole Set from LDT

答:
As of Aerospike 3.12, which was released in March 2017, the feature of deleting all data in a set or namespace is now supported in the database.

Please see the following documentation:
http://www.aerospike.com/docs/reference/info#truncate

Which provides the command line command that looks like:
asinfo truncate:namespace=;set=;lut=

It can also be truncated from the client APIs, here is the java documentation:
http://www.aerospike.com/apidocs/java/com/aerospike/client/AerospikeClient.html
and scroll down to the "truncate" method.

Please note that this feature can, optionally, take a time specification. This allows you to delete records, then start inserting new records. As timestamps are used, please make certain your server clocks are well synchronized.


问:
HostingEnvironment.QueueBackgroundWorkItem with ASP.NET Web API using OWIN
I'm looking to leverage the QueueBackgroundWorkItem feature in available in .NET 4.5.2+ on our ASP.NET Web API application, however, I consistently am getting "Invalid Operation" exceptions when attempting to put something into the queue. I believe this may be related to the fact that our app is self-hosted using OWIN and the queueing of the work item is an IIS only feature? If this is true, just wanted to see if there would be any suggestions at all in regards to queueing background work from an owin-self hosted API.</p>

答:
HostingEnvironment.QueueBackgroundWorkItem() is part of System.Web and as a result, it will only work in the classic ASP.NET pipeline. It won't work in self-hosted OWIN pipeline.

Hangfire is your only option to run long background tasks