问:
gtk helloworld compile error on ubuntu
I installed gtk on ubuntu with command
sudo apt-get install libgtk-3-dev

then I copied code into vi editor

I copied the following code for helloworld in GTK which gives compile error

```<code>#include <gtk/gtk.h>

/* this is a callback function. the data arguments are ignored in this example..
 * More on callbacks below. */
void hello (GtkWidget *widget, gpointer *data)
{
    g_print ("Hello World\n");
}

/* another callback */
void destroy (GtkWidget *widget, gpointer *data)
{
    gtk_main_quit ();
}

int main (int argc, char *argv[])
{
    /* GtkWidget is the storage type for widgets */
    GtkWidget *window;
    GtkWidget *button;

    /* this is called in all GTK applications.  arguments are parsed from
     * the command line and are returned to the application. */
    gtk_init (&argc, &argv);

    /* create a new window */
    window = gtk_window_new (GTK_WINDOW_TOPLEVEL);

    /* when the window is given the "destroy" signal (this can be given
    * by the application, or the window manager, the function destroy
    * will be called as defined above.  The data passed to the callback
    * function is NULL and is ignored in the callback. */
    gtk_signal_connect (GTK_OBJECT (window), "destroy",
                        GTK_SIGNAL_FUNC (destroy), NULL);

    /* sets the border width of the window. */
    gtk_container_border_width (GTK_CONTAINER (window), 10);

    /* creates a new button with the label "Hello World". */
    button = gtk_button_new_with_label ("Hello World");

    /* When the button receives the "clicked" signal, it will call the
     * function hello() passing it NULL as it's argument.  The hello() function is
     * defined above. */
    gtk_signal_connect (GTK_OBJECT (button), "clicked",
                        GTK_SIGNAL_FUNC (hello), NULL);

    /* This will cause the window to be destroyed by calling
     * gtk_widget_destroy(window) when "clicked.  Again, the destroy
     * signal could come from here, or the window manager. */
    gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
                               GTK_SIGNAL_FUNC (gtk_widget_destroy),
                               GTK_OBJECT (window));

    /* this packs the button into the window (a gtk container). */
    gtk_container_add (GTK_CONTAINER (window), button);

    /* the final step is to display this newly created widget... */
    gtk_widget_show (button);

    /* and the window */
    gtk_widget_show (window);

    /* all GTK applications must have a gtk_main().     Control ends here
     * and waits for an event to occur (like a key press or mouse event). */
    gtk_main ();

    return 0;
}
</code>```

then I compiled with

```<code>gcc -Wall -g HelloWorld.c -o hello_world -L/usr/X11R6/lib -lglib -lgdk -lgtk -lX11 -lXext -lm
</code>```

it gives compile error

HelloWorld.c:4:25: fatal error: gtk/gtk.h: No such file or directory
 #include

where locate gtk.h gives
/home/user/linux-3.13.0/tools/perf/ui/gtk/gtk.h

I would like to use gtk for trvelling from one GPS co-ordinate to another using shortest path. Is it possible? what about gtkmap API? Where can I find more details and examples?

答:
I'm not sure but your code seems kind of old. I dare to say it's probably using some version circa Gtk+ 1.2.

Anyway, I would advise you to read a Gtk tutorial from GNOME's website, Getting Started with Gtk+. It targets Gtk+3 which currently is at version 3.26 (stable).

To compile a simple Gtk+ C application you will use pkg-config to translate the correct paths to the indicate libs.

Let's take a very simple example from the previously indicated guide and save it as main.c:

```<code>#include <gtk/gtk.h>

static void
print_hello (GtkWidget *widget,
             gpointer   data)
{
  g_print ("Hello World\n");
}

static void
activate (GtkApplication *app,
          gpointer        user_data)
{
  GtkWidget *window;
  GtkWidget *grid;
  GtkWidget *button;

  /* create a new window, and set its title */
  window = gtk_application_window_new (app);
  gtk_window_set_title (GTK_WINDOW (window), "Window");
  gtk_container_set_border_width (GTK_CONTAINER (window), 10);

  /* Here we construct the container that is going pack our buttons */
  grid = gtk_grid_new ();

  /* Pack the container in the window */
  gtk_container_add (GTK_CONTAINER (window), grid);

  button = gtk_button_new_with_label ("Button 1");
  g_signal_connect (button, "clicked", G_CALLBACK (print_hello), NULL);

  /* Place the first button in the grid cell (0, 0), and make it fill
   * just 1 cell horizontally and vertically (ie no spanning)
   */
  gtk_grid_attach (GTK_GRID (grid), button, 0, 0, 1, 1);

  button = gtk_button_new_with_label ("Button 2");
  g_signal_connect (button, "clicked", G_CALLBACK (print_hello), NULL);

  /* Place the second button in the grid cell (1, 0), and make it fill
   * just 1 cell horizontally and vertically (ie no spanning)
   */
  gtk_grid_attach (GTK_GRID (grid), button, 1, 0, 1, 1);

  button = gtk_button_new_with_label ("Quit");
  g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);

  /* Place the Quit button in the grid cell (0, 1), and make it
   * span 2 columns.
   */
  gtk_grid_attach (GTK_GRID (grid), button, 0, 1, 2, 1);

  /* Now that we are done packing our widgets, we show them all
   * in one go, by calling gtk_widget_show_all() on the window.
   * This call recursively calls gtk_widget_show() on all widgets
   * that are contained in the window, directly or indirectly.
   */
  gtk_widget_show_all (window);

}

int
main (int    argc,
      char **argv)
{
  GtkApplication *app;
  int status;

  app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
  g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
  status = g_application_run (G_APPLICATION (app), argc, argv);
  g_object_unref (app);

  return status;
}
</code>```

Then compile it with:

```<code>gcc -o main main.c `pkg-config --cflags --libs gtk+-3.0`
</code>```

Regarding the maps question, well I would suggest libchamplain, there are some examples on the github project page in the demos folder.

Don't forget to check GNOME's Map application and their github page.

Title: gtk helloworld compile error on ubuntu

Body:
I installed gtk on ubuntu with command
sudo apt-get install libgtk-3-dev

then I copied code into vi editor

I copied the following code for helloworld in GTK which gives compile error

#include <gtk/gtk.h>

/* this is a callback function. the data arguments are ignored in this example..
 * More on callbacks below. */
void hello (GtkWidget *widget, gpointer *data)
{
    g_print ("Hello World\n");
}

/* another callback */
void destroy (GtkWidget *widget, gpointer *data)
{
    gtk_main_quit ();
}

int main (int argc, char *argv[])
{
    /* GtkWidget is the storage type for widgets */
    GtkWidget *window;
    GtkWidget *button;

    /* this is called in all GTK applications.  arguments are parsed from
     * the command line and are returned to the application. */
    gtk_init (&argc, &argv);

    /* create a new window */
    window = gtk_window_new (GTK_WINDOW_TOPLEVEL);

    /* when the window is given the "destroy" signal (this can be given
    * by the application, or the window manager, the function destroy
    * will be called as defined above.  The data passed to the callback
    * function is NULL and is ignored in the callback. */
    gtk_signal_connect (GTK_OBJECT (window), "destroy",
                        GTK_SIGNAL_FUNC (destroy), NULL);

    /* sets the border width of the window. */
    gtk_container_border_width (GTK_CONTAINER (window), 10);

    /* creates a new button with the label "Hello World". */
    button = gtk_button_new_with_label ("Hello World");

    /* When the button receives the "clicked" signal, it will call the
     * function hello() passing it NULL as it's argument.  The hello() function is
     * defined above. */
    gtk_signal_connect (GTK_OBJECT (button), "clicked",
                        GTK_SIGNAL_FUNC (hello), NULL);

    /* This will cause the window to be destroyed by calling
     * gtk_widget_destroy(window) when "clicked.  Again, the destroy
     * signal could come from here, or the window manager. */
    gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
                               GTK_SIGNAL_FUNC (gtk_widget_destroy),
                               GTK_OBJECT (window));

    /* this packs the button into the window (a gtk container). */
    gtk_container_add (GTK_CONTAINER (window), button);

    /* the final step is to display this newly created widget... */
    gtk_widget_show (button);

    /* and the window */
    gtk_widget_show (window);

    /* all GTK applications must have a gtk_main().     Control ends here
     * and waits for an event to occur (like a key press or mouse event). */
    gtk_main ();

    return 0;
}

then I compiled with

gcc -Wall -g HelloWorld.c -o hello_world -L/usr/X11R6/lib -lglib -lgdk -lgtk -lX11 -lXext -lm

it gives compile error

HelloWorld.c:4:25: fatal error: gtk/gtk.h: No such file or directory
 #include

where locate gtk.h gives
/home/user/linux-3.13.0/tools/perf/ui/gtk/gtk.h

I would like to use gtk for trvelling from one GPS co-ordinate to another using shortest path. Is it possible? what about gtkmap API? Where can I find more details and examples?

Body:
I'm not sure but your code seems kind of old. I dare to say it's probably using some version circa Gtk+ 1.2.

Anyway, I would advise you to read a Gtk tutorial from GNOME's website, Getting Started with Gtk+. It targets Gtk+3 which currently is at version 3.26 (stable).

To compile a simple Gtk+ C application you will use pkg-config to translate the correct paths to the indicate libs.

Let's take a very simple example from the previously indicated guide and save it as main.c:

#include <gtk/gtk.h>

static void
print_hello (GtkWidget *widget,
             gpointer   data)
{
  g_print ("Hello World\n");
}

static void
activate (GtkApplication *app,
          gpointer        user_data)
{
  GtkWidget *window;
  GtkWidget *grid;
  GtkWidget *button;

  /* create a new window, and set its title */
  window = gtk_application_window_new (app);
  gtk_window_set_title (GTK_WINDOW (window), "Window");
  gtk_container_set_border_width (GTK_CONTAINER (window), 10);

  /* Here we construct the container that is going pack our buttons */
  grid = gtk_grid_new ();

  /* Pack the container in the window */
  gtk_container_add (GTK_CONTAINER (window), grid);

  button = gtk_button_new_with_label ("Button 1");
  g_signal_connect (button, "clicked", G_CALLBACK (print_hello), NULL);

  /* Place the first button in the grid cell (0, 0), and make it fill
   * just 1 cell horizontally and vertically (ie no spanning)
   */
  gtk_grid_attach (GTK_GRID (grid), button, 0, 0, 1, 1);

  button = gtk_button_new_with_label ("Button 2");
  g_signal_connect (button, "clicked", G_CALLBACK (print_hello), NULL);

  /* Place the second button in the grid cell (1, 0), and make it fill
   * just 1 cell horizontally and vertically (ie no spanning)
   */
  gtk_grid_attach (GTK_GRID (grid), button, 1, 0, 1, 1);

  button = gtk_button_new_with_label ("Quit");
  g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window);

  /* Place the Quit button in the grid cell (0, 1), and make it
   * span 2 columns.
   */
  gtk_grid_attach (GTK_GRID (grid), button, 0, 1, 2, 1);

  /* Now that we are done packing our widgets, we show them all
   * in one go, by calling gtk_widget_show_all() on the window.
   * This call recursively calls gtk_widget_show() on all widgets
   * that are contained in the window, directly or indirectly.
   */
  gtk_widget_show_all (window);

}

int
main (int    argc,
      char **argv)
{
  GtkApplication *app;
  int status;

  app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
  g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
  status = g_application_run (G_APPLICATION (app), argc, argv);
  g_object_unref (app);

  return status;
}

Then compile it with:

gcc -o main main.c `pkg-config --cflags --libs gtk+-3.0`

Regarding the maps question, well I would suggest libchamplain, there are some examples on the github project page in the demos folder.

Don't forget to check GNOME's Map application and their github page.


来源: stackexchange

问:
Fold with closure that returns a Result
I'm using the regex crate to find some text with this regex:

```<code>lazy_static! {
    static ref FIND_STEPS_RE: Regex =
        Regex::new(r"my regex").unwrap();
}
</code>```

I want to find all possible captures and iterate over them:

```<code>FIND_STEPS_RE.captures_iter(script_slice)
</code>```

Each captured element consists of 2 values: an operation and a number. For example, the output could be:

[("+", "10"), ("-", "20"), ("*", "2")]
```

<p>I want to iterate over it, parse the numbers and apply the operation.</p>

<p>I tried:</p>

```let e = FIND_STEPS_RE.captures_iter(script_slice)
    .fold(0, |sum, value| apply_decoding_step)?;
```

<p>where <code>apply_decoding_step</code> is:</p>

```fn apply_decoding_step(sum: i32, capture: regex::Captures<>) -> Result<i32> {
    let number = parse_number(&capture[2])?;

    match  &capture[1] {
        "+" => Ok(s + number),
        "-" => Ok(s - number),
        "*" => Ok(s * number),
        "/" => Ok(s / number),
        _ => bail!("Unknown step operator"),
    }
}
```

<p>But I got this error:</p>

<pre class="lang-none prettyprint-override"><code>error[E0271]: type mismatch resolving `<fn(i32, regex::Captures<'_>) -> std::result::Result<i32, Error> {apply_decoding_step} as std::ops::FnOnce<(i32, regex::Captures<'_>)>>::Output == i32`
   --> src/main.rs:122:10
    |
122 |         .fold(seed, apply_decoding_step);
    |          ^^^^ expected enum `std::result::Result`, found i32
    |
    = note: expected type `std::result::Result<i32, Error>`
               found type `i32`
</code>```

I assume this is because I'm trying to fold a Result into a i32, but since I need to parse the second capture value and also need that otherwise case in my match, how can I fix that?

答:
As jupp0r states, the initial value of Iterator::fold must be of the same type as the return value of the closure.

Rust 1.26

You can use Iterator::try_fold instead. This will exit iteration on the first failure:

```<code>let result = x.iter().try_fold(0, |acc, &i| apply_decoding_step(acc, i));
</code>```

Complete example:

```<code>fn main() {
    let x = [("+", "10"), ("-", "20"), ("*", "2")];

    let result = x.iter().try_fold(0, |acc, &i| apply_decoding_step(acc, i));

    println!("{:?}", result);
}

fn apply_decoding_step(sum: i32, capture: (&str, &str)) -> Result<i32, ()> {
    let number: i32 = capture.1.parse().expect("nope");

    match capture.0 {
        "+" => Ok(sum + number),
        "-" => Ok(sum - number),
        "*" => Ok(sum * number),
        "/" => Ok(sum / number),
        _ => Err(()),
    }
}
</code>```

Rust 1.0

I'd recommend using Result::and_then to skip nothing in the fold when an error has occurred:

```<code>let result = x.iter().fold(Ok(0), |acc, &i| {
    acc.and_then(|acc| apply_decoding_step(acc, i))
});
</code>```

The problem here is that the fold body is executed for every element in the iterator, even once an error occurs.

Here's an enterprise-grade solution where the main benefit is that iteration will end as soon as the first Err is encountered, instead of spinning through the rest of the list. Secondary benefits include the ability to write very fine-grained tests for each piece (parsing from a string, arithmetic operations, accumulation, etc.):

```<code>fn main() {
    let x = [("+", "10"), ("-", "20"), ("*", "2")];

    let result: Result<Accumulator, ()> = x
        .iter()
        .map(|&(op, val)| {
            let op = op.parse::<Op>()?;
            let val = val.parse::<i32>().map_err(|_| ())?;
            Ok((op, val))
        })
        .collect();

    println!("{:?}", result);
}

use std::iter::FromIterator;
use std::str::FromStr;

#[derive(Debug)]
enum Op {
    Add,
    Sub,
    Mul,
    Div,
}

impl Op {
    fn apply(&self, a: i32, b: i32) -> i32 {
        use Op::*;

        match *self {
            Add => a + b,
            Sub => a - b,
            Mul => a * b,
            Div => a / b,
        }
    }
}

impl FromStr for Op {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, ()> {
        use Op::*;

        match s {
            "+" => Ok(Add),
            "-" => Ok(Sub),
            "*" => Ok(Mul),
            "/" => Ok(Div),
            _ => Err(()),
        }
    }
}

#[derive(Debug)]
struct Accumulator(i32);

impl<'a> FromIterator<(Op, i32)> for Accumulator {
    fn from_iter<I>(iter: I) -> Self
    where
        I: IntoIterator<Item = (Op, i32)>,
    {
        Accumulator(
            iter.into_iter()
                .fold(0, |acc, (op, val)| op.apply(acc, val)),
        )
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Fold with closure that returns a Result

Body:
I'm using the regex crate to find some text with this regex:

lazy_static! {
    static ref FIND_STEPS_RE: Regex =
        Regex::new(r"my regex").unwrap();
}

I want to find all possible captures and iterate over them:

FIND_STEPS_RE.captures_iter(script_slice)

Each captured element consists of 2 values: an operation and a number. For example, the output could be:

[("+", "10"), ("-", "20"), ("*", "2")]

I want to iterate over it, parse the numbers and apply the operation.

I tried:

let e = FIND_STEPS_RE.captures_iter(script_slice)
    .fold(0, |sum, value| apply_decoding_step)?;

where apply_decoding_step is:

fn apply_decoding_step(sum: i32, capture: regex::Captures<>) -> Result<i32> {
    let number = parse_number(&capture[2])?;

    match  &capture[1] {
        "+" => Ok(s + number),
        "-" => Ok(s - number),
        "*" => Ok(s * number),
        "/" => Ok(s / number),
        _ => bail!("Unknown step operator"),
    }
}

But I got this error:

error[E0271]: type mismatch resolving `<fn(i32, regex::Captures<'_>) -> std::result::Result<i32, Error> {apply_decoding_step} as std::ops::FnOnce<(i32, regex::Captures<'_>)>>::Output == i32`
   --> src/main.rs:122:10
    |
122 |         .fold(seed, apply_decoding_step);
    |          ^^^^ expected enum `std::result::Result`, found i32
    |
    = note: expected type `std::result::Result<i32, Error>`
               found type `i32`

I assume this is because I'm trying to fold a Result into a i32, but since I need to parse the second capture value and also need that otherwise case in my match, how can I fix that?

Body:
As jupp0r states, the initial value of Iterator::fold must be of the same type as the return value of the closure.

Rust 1.26

You can use Iterator::try_fold instead. This will exit iteration on the first failure:

let result = x.iter().try_fold(0, |acc, &i| apply_decoding_step(acc, i));

Complete example:

fn main() {
    let x = [("+", "10"), ("-", "20"), ("*", "2")];

    let result = x.iter().try_fold(0, |acc, &i| apply_decoding_step(acc, i));

    println!("{:?}", result);
}

fn apply_decoding_step(sum: i32, capture: (&str, &str)) -> Result<i32, ()> {
    let number: i32 = capture.1.parse().expect("nope");

    match capture.0 {
        "+" => Ok(sum + number),
        "-" => Ok(sum - number),
        "*" => Ok(sum * number),
        "/" => Ok(sum / number),
        _ => Err(()),
    }
}

Rust 1.0

I'd recommend using Result::and_then to skip nothing in the fold when an error has occurred:

let result = x.iter().fold(Ok(0), |acc, &i| {
    acc.and_then(|acc| apply_decoding_step(acc, i))
});

The problem here is that the fold body is executed for every element in the iterator, even once an error occurs.

Here's an enterprise-grade solution where the main benefit is that iteration will end as soon as the first Err is encountered, instead of spinning through the rest of the list. Secondary benefits include the ability to write very fine-grained tests for each piece (parsing from a string, arithmetic operations, accumulation, etc.):

fn main() {
    let x = [("+", "10"), ("-", "20"), ("*", "2")];

    let result: Result<Accumulator, ()> = x
        .iter()
        .map(|&(op, val)| {
            let op = op.parse::<Op>()?;
            let val = val.parse::<i32>().map_err(|_| ())?;
            Ok((op, val))
        })
        .collect();

    println!("{:?}", result);
}

use std::iter::FromIterator;
use std::str::FromStr;

#[derive(Debug)]
enum Op {
    Add,
    Sub,
    Mul,
    Div,
}

impl Op {
    fn apply(&self, a: i32, b: i32) -> i32 {
        use Op::*;

        match *self {
            Add => a + b,
            Sub => a - b,
            Mul => a * b,
            Div => a / b,
        }
    }
}

impl FromStr for Op {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, ()> {
        use Op::*;

        match s {
            "+" => Ok(Add),
            "-" => Ok(Sub),
            "*" => Ok(Mul),
            "/" => Ok(Div),
            _ => Err(()),
        }
    }
}

#[derive(Debug)]
struct Accumulator(i32);

impl<'a> FromIterator<(Op, i32)> for Accumulator {
    fn from_iter<I>(iter: I) -> Self
    where
        I: IntoIterator<Item = (Op, i32)>,
    {
        Accumulator(
            iter.into_iter()
                .fold(0, |acc, (op, val)| op.apply(acc, val)),
        )
    }
}

ContentLicense: CC BY-SA 4.0


问:
Insertion sort on vector
I want to do insertion sort on a vector using vector::begin and vector::end.
This is my code:

```<code>#include <iostream>
#include <vector>

using namespace std;

//Checking if vector is sorted
bool isSorted(vector<int>::iterator x, vector<int>::iterator y) {
    for (vector<int>::iterator it = x; it != y; ++it) {
        if (*x > *it) return false;
    }

    return true;
}

//Doing insertion sort algorithm
void insertionSort(vector<int>::iterator x, vector<int>::iterator y) {
    while(!isSorted(x, y)) {
        int smallest = *x;
        int* pointer;
        for (vector<int>::iterator it = x; it != y; ++it) {
            if (*it < smallest) {
                smallest = *it;
                *pointer = *it;
            }
        }

        int buffer = *x;
        *x = smallest;
        *pointer = buffer;
    }
}

int main() {
    vector<int> list;
    list.push_back(5);
    list.push_back(3);
    list.push_back(4);
    list.push_back(0);
    list.push_back(10);
    list.push_back(1);

    //Displaying
    for (int i = 0; i < list.size(); i++) {
        cout << list[i] << endl;
    }

    insertionSort(list.begin(), list.end());

    //Displaying after sort
    cout << "\nafter sort" << endl;
    for (int i = 0; i < list.size(); i++) {
        cout << list[i] << endl;
    }
}
</code>```

And this is the output:

```<code>5
3
4
0
10
1

 after sort
0
3
4
0
10
1
</code>```

Expected output of after sort: 0,0,1,3,4,10.
The insertion sort ain't working as expected. In the function insertionSort() I want to iterate until smallest element found, if found place that one on the first index in place.

I guess the problem is occurs somewhere on line 28, however I can't figure out what the problem is because the pointers etc make it somewhat complex.

答:
Just a few notes.
First, as @appleapple suggested, your implementation of isSorted is incorrect, because you are comparing only the first element with each other element of the array. (i.e. if the first element is smaller then all the others, you consider the array as sorted).

At line 19

int *pointer;

this pointer is not initialized, and would be better to initialize it pointing it to some element of the array.

At line 23

*pointer = *it;

Here you are assigning the value pointed to by it to the address pointed to by pointer. However, this means that if pointer was uninitialized, you may crash the application. If it was initialized, you'll override the value of the array pointed to by pointer.

I guess what you are trying to do is to have pointer point at the same address as the iterator.

In that case you can replace the line with

pointer = &(*it);

Finally, I think you are missing one loop, since every time you loop you take the global minimum as the current minimum, while you should slide forward in the vector at each new minimum.

The problem is at the line

int smallest = *x;

You should have another loop between the while and this line, so that at each loop, you can set the smallest to the first non-sorted element, instead of the first element of the array.

Title: Insertion sort on vector

Body:
I want to do insertion sort on a vector using vector::begin and vector::end.
This is my code:

#include <iostream>
#include <vector>

using namespace std;

//Checking if vector is sorted
bool isSorted(vector<int>::iterator x, vector<int>::iterator y) {
    for (vector<int>::iterator it = x; it != y; ++it) {
        if (*x > *it) return false;
    }

    return true;
}

//Doing insertion sort algorithm
void insertionSort(vector<int>::iterator x, vector<int>::iterator y) {
    while(!isSorted(x, y)) {
        int smallest = *x;
        int* pointer;
        for (vector<int>::iterator it = x; it != y; ++it) {
            if (*it < smallest) {
                smallest = *it;
                *pointer = *it;
            }
        }

        int buffer = *x;
        *x = smallest;
        *pointer = buffer;
    }
}

int main() {
    vector<int> list;
    list.push_back(5);
    list.push_back(3);
    list.push_back(4);
    list.push_back(0);
    list.push_back(10);
    list.push_back(1);

    //Displaying
    for (int i = 0; i < list.size(); i++) {
        cout << list[i] << endl;
    }

    insertionSort(list.begin(), list.end());

    //Displaying after sort
    cout << "\nafter sort" << endl;
    for (int i = 0; i < list.size(); i++) {
        cout << list[i] << endl;
    }
}

And this is the output:

5
3
4
0
10
1

 after sort
0
3
4
0
10
1

Expected output of after sort: 0,0,1,3,4,10.
The insertion sort ain't working as expected. In the function insertionSort() I want to iterate until smallest element found, if found place that one on the first index in place.

I guess the problem is occurs somewhere on line 28, however I can't figure out what the problem is because the pointers etc make it somewhat complex.


问:
'NSRangeException', reason: [__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray -> it is keep getting out of index bounds
```<code>[["The Cheesecake Factory", 3.8], ["Dave & Buster\'s", 3.8], ["Paul Martin\'s American Grill", 4.2], ["Yard House", 4.3], ["Javier\'s Restaurant - Irvine", 4], ["CUCINA enoteca Irvine", 4.4], ["SUBWAY®Restaurants", 3.2], ["SUBWAY®Restaurants", 4], ["Wendy\'s", 3.8], ["Izakaya Wasa", 3.7], ["Veggie Grill", 4.5], ["Bruegger\'s Bagels", 4.5], ["Capital Seafood Restaurant - Irvine Spectrum", 4], ["Burger King", 3.5], ["SUBWAY®Restaurants", 2.6], ["Corner Bakery Cafe", 3.9], ["Taiko Japanese Restaurant", 4.3], ["Red Robin Gourmet Burgers", 3.7], ["Johnny Rockets", 2.9], ["Chipotle Mexican Grill", 4]]
</code>```

```<code>20
</code>```

```<code>2017-11-15 13:26:36.367072-0800 E-Bike App[2584:1830704] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray'
*** First throw call stack:
(0x183ef5d04 0x183144528 0x183e510c4 0x102debe4c 0x102cafc84   0x184480f94 0x1844983b4 0x1848c1310 0x1848019e4 0x1847f1620 0x10532545c 0x105331b74 0x10532545c 0x105331b74 0x105331a34 0x1848c2fe8 0x10532545c 0x105332800 0x10533109c 0x105336b54 0x105336880 0x183b1f120 0x183b1ec20)
libc++abi.dylib: terminating with uncaught exception of type NSException'
</code>```

Once I get the place name, rating and location (CLLocationCoordinate2D) above and save in the double array and parse index and location to drawPolylineAmongMultiplePoints function to find the distance and duration and append or push to the double array. NSRangeException is keep poping up..

Anyone has good idea to solve this?

```<code>func drawPolylineAmongMultiplePoints(coordinate: CLLocationCoordinate2D, pinPoint: Int) {

    guard let lat = mapView.myLocation?.coordinate.latitude else {return}
    guard let long = mapView.myLocation?.coordinate.longitude else {return}

    let aPointCoordinate = "\(lat),\(long)"

    let bPointCoordinate = "\(coordinate.latitude),\(coordinate.longitude)"

    let url = "http://maps.googleapis.com/maps/api/directions/json?origin=\(aPointCoordinate)&destination=\(bPointCoordinate)&sensor=false&mode=\(DrivingMode.DRIVING)"

    guard let urlString = URL(string: url) else {
        print("Error: Cannot create URL")
        return
    }

    let urlRequest = URLRequest(url: urlString)

    // Set up the session

    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)

    // Make the request

    let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in

        do{

            if error != nil{
                print("Error: \(String(describing: error?.localizedDescription))")

            } else {

                guard let data = data else {
                    throw JSONError.NoData
                }
                guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary else {
                    throw JSONError.ConversionFailed
                }

                let arrayRoutes = json["routes"] as! NSArray
                let dicOfPoints = arrayRoutes[0] as! NSDictionary
                let dic1 = dicOfPoints["overview_polyline"] as! NSDictionary
                let points = dic1["points"] as! String

                let arrayLegs = (arrayRoutes[0] as! NSDictionary).object(forKey: "legs") as! NSArray
                let arraySteps = arrayLegs[0] as! NSDictionary

                let dicDistance = arraySteps["distance"] as! NSDictionary
                let totalDistance = dicDistance["text"] as! String
                self.totalremainingDistance = (dicDistance["value"] as! Double)*(1/1000)*(1.61)

                let dicDuration = arraySteps["duration"] as! NSDictionary
                let totalDuration = dicDuration["text"] as! String
                self.totalremainingDuration = dicDuration["value"] as! Double

                let position = CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude)

                //self.eachCarouselDataDic[index] += [totalDistance, totalDuration]

                //print(self.eachCarouselDataDic)
                self.eachCarouselDataDic[pinPoint] += [totalDistance, totalDuration, points, position]
                //print(self.eachCarouselDataDic)

            }

        }catch let error as JSONError {
            print(error.rawValue)
        }catch let error as NSError {
            print(error.debugDescription)

        }

    })
    task.resume()

}

@objc func POIForPlaces(sender: UIButton) {
    print("I am here~~~")

    //mapView.clear()

    //For Carousel view to have access to the POI elements
    isThisFirstTime = false
    self.eachCarouselDataDic.removeAll()

    var typeOfPlace = String()

    var markerImage = UIImage()

    switch sender.tag {
    case 0:
        typeOfPlace = "cafe"
        markerImage = UIImage(named: "cafe")!
    case 1:
        typeOfPlace = "restaurant"
        markerImage = UIImage(named: "restaurant")!
    default:
        break
    }
    let markerView = UIImageView(image: markerImage)

    guard let lat = mapView.myLocation?.coordinate.latitude else {return}
    guard let long = mapView.myLocation?.coordinate.longitude else {return}

    var arrayOfLocations = [CLLocationCoordinate2D()]
    arrayOfLocations.removeFirst()
    var arrayOfNames = [String()]
    arrayOfNames.removeFirst()
    var arrayOfAddress = [String()]
    arrayOfAddress.removeFirst()
    var arrayOfRating = [Double()]
    arrayOfRating.removeFirst()
    var name = String()
    var counter = 0

    let jsonURLString = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=\(lat),\(long)&maxprice=3&radius=3200&opennow&type=\(typeOfPlace)&key=\(Config.GOOGLE_API_KEY)"

    guard let urlString = URL(string: jsonURLString) else {
        print("Error: Cannot create URL")
        return
    }

    //markerView.tintColor = UIColor.DTIBlue()

    let urlRequest = URLRequest(url: urlString)

    // Set up the session

    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)

    let task = session.dataTask(with: urlRequest) { (data, response, error) in

        guard let httpResponse = response as? HTTPURLResponse else { return }

        switch httpResponse.statusCode {
        case 200:
            do{

                guard let data = data else { return }

                guard let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary else { return }

                //print(json)

                DispatchQueue.global(qos: .background).async {

                    let arrayPlaces = json["results"] as! NSArray

                    if arrayPlaces.count > 0 {
                        for i in 0..<arrayPlaces.count {
                            print("-----------------------------------------------------------------------------------------------------")

                            print(arrayPlaces.count)

                            print("-----------------------------------------------------------------------------------------------------")

                            self.eachCarouselDataDic.append([])
                            let arrayForLocations = (((arrayPlaces[i] as! NSDictionary).object(forKey: "geometry") as! NSDictionary).object(forKey: "location") as! NSDictionary)
                            let lat = arrayForLocations.object(forKey: "lat")
                            let long = arrayForLocations.object(forKey: "lng")
                            let position = CLLocationCoordinate2D(latitude: lat as! CLLocationDegrees, longitude: long as! CLLocationDegrees)

                            let arrayForName = (arrayPlaces[i] as! NSDictionary).object(forKey: "name") as! String
                            let arrayForAddress = (arrayPlaces[i] as! NSDictionary).object(forKey: "vicinity") as! String

                            if let arrayForRating = (arrayPlaces[i] as! NSDictionary).object(forKey: "rating") as? NSNumber {
                                arrayOfRating.append(Double(truncating: arrayForRating).rounded(toPlaces: 1))
                                self.eachCarouselDataDic[i] += [arrayForName, arrayForRating]
                                print(self.eachCarouselDataDic)
                            } else {
                                arrayOfRating.append(0.0)
                                self.eachCarouselDataDic[i] += [arrayForName,0.0]
                                print(self.eachCarouselDataDic)
                            }
                            print("-----------------------------------------------------------------------------------------------------")

                            print(self.eachCarouselDataDic.count)

                            print("-----------------------------------------------------------------------------------------------------")
                            arrayOfNames.append(arrayForName)
                            arrayOfAddress.append(arrayForAddress)

                            arrayOfLocations.append(position)

                            //self.eachCarouselDataDic[i] += [arrayForName,arrayForRating]

                            //self.drawPolylineAmongMultiplePoints(coordinate: position, index: counter)
                            counter += 1
                            let nearbyMarker = GMSMarker()
                            //var position = CLLocationCoordinate2D()
                            nearbyMarker.iconView = markerView

                            name = arrayOfNames[i]
                            nearbyMarker.tracksViewChanges = true
                            nearbyMarker.title = name

                            nearbyMarker.position = position
                            nearbyMarker.snippet = "Rating = \(arrayOfRating[i]) \(self.ratingSystem(rating: arrayOfRating[i]))\n Address = \(arrayOfAddress[i])"

                            nearbyMarker.map = self.mapView
                        }

                    }

                    for i in 0..<counter {
                        self.drawPolylineAmongMultiplePoints(coordinate: arrayOfLocations[i], pinPoint: i)
                    }

                }

            }catch let error as NSError {
                print(error.debugDescription)
            }

        default:
            print("HTTP Reponse Code: \(httpResponse.statusCode)")

        }

    }
    task.resume()

    UIView.animate(withDuration: 3, animations: {
        self.isCarouselActive = true
        self.myLocationButton.setImage(UIImage(named: "carousel"), for: .normal)
    })
}
</code>```

答:
The error tells you the problem:

```<code>index 0 beyond bounds for empty NSArray
</code>```

So you have an empty array when you don't expect one.

Use the debugger and/or print() statements to examine the values of your variables. Work back from the point of failure to discover where it goes wrong.

You really need to do this yourself, you've provided a lot of code for people to work through. If you get stuck and cannot figure out the problem all a new question, include just sufficient code to show issue, explain what you've done and can't figure out, etc. Someone will undoubtedly help you at that point.

Body:
[["The Cheesecake Factory", 3.8], ["Dave & Buster\'s", 3.8], ["Paul Martin\'s American Grill", 4.2], ["Yard House", 4.3], ["Javier\'s Restaurant - Irvine", 4], ["CUCINA enoteca Irvine", 4.4], ["SUBWAY®Restaurants", 3.2], ["SUBWAY®Restaurants", 4], ["Wendy\'s", 3.8], ["Izakaya Wasa", 3.7], ["Veggie Grill", 4.5], ["Bruegger\'s Bagels", 4.5], ["Capital Seafood Restaurant - Irvine Spectrum", 4], ["Burger King", 3.5], ["SUBWAY®Restaurants", 2.6], ["Corner Bakery Cafe", 3.9], ["Taiko Japanese Restaurant", 4.3], ["Red Robin Gourmet Burgers", 3.7], ["Johnny Rockets", 2.9], ["Chipotle Mexican Grill", 4]]

20

2017-11-15 13:26:36.367072-0800 E-Bike App[2584:1830704] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray'
*** First throw call stack:
(0x183ef5d04 0x183144528 0x183e510c4 0x102debe4c 0x102cafc84   0x184480f94 0x1844983b4 0x1848c1310 0x1848019e4 0x1847f1620 0x10532545c 0x105331b74 0x10532545c 0x105331b74 0x105331a34 0x1848c2fe8 0x10532545c 0x105332800 0x10533109c 0x105336b54 0x105336880 0x183b1f120 0x183b1ec20)
libc++abi.dylib: terminating with uncaught exception of type NSException'

Once I get the place name, rating and location (CLLocationCoordinate2D) above and save in the double array and parse index and location to drawPolylineAmongMultiplePoints function to find the distance and duration and append or push to the double array. NSRangeException is keep poping up..

Anyone has good idea to solve this?

func drawPolylineAmongMultiplePoints(coordinate: CLLocationCoordinate2D, pinPoint: Int) {

    guard let lat = mapView.myLocation?.coordinate.latitude else {return}
    guard let long = mapView.myLocation?.coordinate.longitude else {return}

    let aPointCoordinate = "\(lat),\(long)"

    let bPointCoordinate = "\(coordinate.latitude),\(coordinate.longitude)"

    let url = "http://maps.googleapis.com/maps/api/directions/json?origin=\(aPointCoordinate)&destination=\(bPointCoordinate)&sensor=false&mode=\(DrivingMode.DRIVING)"

    guard let urlString = URL(string: url) else {
        print("Error: Cannot create URL")
        return
    }

    let urlRequest = URLRequest(url: urlString)

    // Set up the session

    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)

    // Make the request

    let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in

        do{

            if error != nil{
                print("Error: \(String(describing: error?.localizedDescription))")

            } else {

                guard let data = data else {
                    throw JSONError.NoData
                }
                guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary else {
                    throw JSONError.ConversionFailed
                }

                let arrayRoutes = json["routes"] as! NSArray
                let dicOfPoints = arrayRoutes[0] as! NSDictionary
                let dic1 = dicOfPoints["overview_polyline"] as! NSDictionary
                let points = dic1["points"] as! String

                let arrayLegs = (arrayRoutes[0] as! NSDictionary).object(forKey: "legs") as! NSArray
                let arraySteps = arrayLegs[0] as! NSDictionary

                let dicDistance = arraySteps["distance"] as! NSDictionary
                let totalDistance = dicDistance["text"] as! String
                self.totalremainingDistance = (dicDistance["value"] as! Double)*(1/1000)*(1.61)

                let dicDuration = arraySteps["duration"] as! NSDictionary
                let totalDuration = dicDuration["text"] as! String
                self.totalremainingDuration = dicDuration["value"] as! Double

                let position = CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude)

                //self.eachCarouselDataDic[index] += [totalDistance, totalDuration]

                //print(self.eachCarouselDataDic)
                self.eachCarouselDataDic[pinPoint] += [totalDistance, totalDuration, points, position]
                //print(self.eachCarouselDataDic)

            }

        }catch let error as JSONError {
            print(error.rawValue)
        }catch let error as NSError {
            print(error.debugDescription)

        }

    })
    task.resume()

}

@objc func POIForPlaces(sender: UIButton) {
    print("I am here~~~")

    //mapView.clear()

    //For Carousel view to have access to the POI elements
    isThisFirstTime = false
    self.eachCarouselDataDic.removeAll()

    var typeOfPlace = String()

    var markerImage = UIImage()

    switch sender.tag {
    case 0:
        typeOfPlace = "cafe"
        markerImage = UIImage(named: "cafe")!
    case 1:
        typeOfPlace = "restaurant"
        markerImage = UIImage(named: "restaurant")!
    default:
        break
    }
    let markerView = UIImageView(image: markerImage)

    guard let lat = mapView.myLocation?.coordinate.latitude else {return}
    guard let long = mapView.myLocation?.coordinate.longitude else {return}

    var arrayOfLocations = [CLLocationCoordinate2D()]
    arrayOfLocations.removeFirst()
    var arrayOfNames = [String()]
    arrayOfNames.removeFirst()
    var arrayOfAddress = [String()]
    arrayOfAddress.removeFirst()
    var arrayOfRating = [Double()]
    arrayOfRating.removeFirst()
    var name = String()
    var counter = 0

    let jsonURLString = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=\(lat),\(long)&maxprice=3&radius=3200&opennow&type=\(typeOfPlace)&key=\(Config.GOOGLE_API_KEY)"

    guard let urlString = URL(string: jsonURLString) else {
        print("Error: Cannot create URL")
        return
    }

    //markerView.tintColor = UIColor.DTIBlue()

    let urlRequest = URLRequest(url: urlString)

    // Set up the session

    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)

    let task = session.dataTask(with: urlRequest) { (data, response, error) in

        guard let httpResponse = response as? HTTPURLResponse else { return }

        switch httpResponse.statusCode {
        case 200:
            do{

                guard let data = data else { return }

                guard let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary else { return }

                //print(json)

                DispatchQueue.global(qos: .background).async {

                    let arrayPlaces = json["results"] as! NSArray

                    if arrayPlaces.count > 0 {
                        for i in 0..<arrayPlaces.count {
                            print("-----------------------------------------------------------------------------------------------------")

                            print(arrayPlaces.count)

                            print("-----------------------------------------------------------------------------------------------------")

                            self.eachCarouselDataDic.append([])
                            let arrayForLocations = (((arrayPlaces[i] as! NSDictionary).object(forKey: "geometry") as! NSDictionary).object(forKey: "location") as! NSDictionary)
                            let lat = arrayForLocations.object(forKey: "lat")
                            let long = arrayForLocations.object(forKey: "lng")
                            let position = CLLocationCoordinate2D(latitude: lat as! CLLocationDegrees, longitude: long as! CLLocationDegrees)

                            let arrayForName = (arrayPlaces[i] as! NSDictionary).object(forKey: "name") as! String
                            let arrayForAddress = (arrayPlaces[i] as! NSDictionary).object(forKey: "vicinity") as! String

                            if let arrayForRating = (arrayPlaces[i] as! NSDictionary).object(forKey: "rating") as? NSNumber {
                                arrayOfRating.append(Double(truncating: arrayForRating).rounded(toPlaces: 1))
                                self.eachCarouselDataDic[i] += [arrayForName, arrayForRating]
                                print(self.eachCarouselDataDic)
                            } else {
                                arrayOfRating.append(0.0)
                                self.eachCarouselDataDic[i] += [arrayForName,0.0]
                                print(self.eachCarouselDataDic)
                            }
                            print("-----------------------------------------------------------------------------------------------------")

                            print(self.eachCarouselDataDic.count)

                            print("-----------------------------------------------------------------------------------------------------")
                            arrayOfNames.append(arrayForName)
                            arrayOfAddress.append(arrayForAddress)

                            arrayOfLocations.append(position)

                            //self.eachCarouselDataDic[i] += [arrayForName,arrayForRating]

                            //self.drawPolylineAmongMultiplePoints(coordinate: position, index: counter)
                            counter += 1
                            let nearbyMarker = GMSMarker()
                            //var position = CLLocationCoordinate2D()
                            nearbyMarker.iconView = markerView

                            name = arrayOfNames[i]
                            nearbyMarker.tracksViewChanges = true
                            nearbyMarker.title = name

                            nearbyMarker.position = position
                            nearbyMarker.snippet = "Rating = \(arrayOfRating[i]) \(self.ratingSystem(rating: arrayOfRating[i]))\n Address = \(arrayOfAddress[i])"

                            nearbyMarker.map = self.mapView
                        }

                    }

                    for i in 0..<counter {
                        self.drawPolylineAmongMultiplePoints(coordinate: arrayOfLocations[i], pinPoint: i)
                    }

                }

            }catch let error as NSError {
                print(error.debugDescription)
            }

        default:
            print("HTTP Reponse Code: \(httpResponse.statusCode)")

        }

    }
    task.resume()

    UIView.animate(withDuration: 3, animations: {
        self.isCarouselActive = true
        self.myLocationButton.setImage(UIImage(named: "carousel"), for: .normal)
    })
}

Body:
The error tells you the problem:

index 0 beyond bounds for empty NSArray

So you have an empty array when you don't expect one.

Use the debugger and/or print() statements to examine the values of your variables. Work back from the point of failure to discover where it goes wrong.

You really need to do this yourself, you've provided a lot of code for people to work through. If you get stuck and cannot figure out the problem all a new question, include just sufficient code to show issue, explain what you've done and can't figure out, etc. Someone will undoubtedly help you at that point.


问:
bash: extract an attribute value between quotes using awk or sed(GNU grep is not an option)
I have a xml file with data like below

```<code><temp>
<a="something" total="50" b="something" total="0" c="something" total="20">
</temp>
</code>```

I need to get first value of total i.e, 50 but my sed solution is giving value of last occurrence of total i.e, 20

```<code>sed -n 's/.*total="\([^"]*\).*/\1/p' temp.xml
</code>```

output : 20

desired output: 50

I appreciate the help. Thank you

答:
The proper way is to use xml/html parsers, like xmllint and/or xmlstarlet.

xmllint solution:

```<code>xmllint --html --xpath "string(//a/@total)" temp.xml 2>/dev/null
50
</code>```

Body:
I have a xml file with data like below

<temp>

</temp>

I need to get first value of total i.e, 50 but my sed solution is giving value of last occurrence of total i.e, 20

sed -n 's/.*total="\([^"]*\).*/\1/p' temp.xml

output : 20

desired output: 50

I appreciate the help. Thank you

Body:
The proper way is to use xml/html parsers, like xmllint and/or xmlstarlet.

xmllint solution:

xmllint --html --xpath "string(//a/@total)" temp.xml 2>/dev/null
50


问:
Error installing xampp on windows 7
For Screenshot

http://imgur.com/a/PRzun

I have problem, so before I got these error i have installed xampp v.5.6.30 / PHP 5.6.30 and i want to update to xampp v.7.0.18 / PHP 7.0.18 and i uninstall the old version and install the latest version.

Before I get the error I have error on api-ms-"...".dll but i finished to this error with download the .dll files and the error(1) is show up.

I try to fix this problem so I change the port, but not take effect.
This for screenshot port list/netstat.

http://imgur.com/a/RVfoD

I change the httpd.conf port 80 to 8080, and httpd-ssl.conf port 443 to 4433. But didn't take effect.

So what solution to install xamp on my windows 7? Thanks in advance.

Extra : I don't install skype on my windows

答:
Try checking on your 32 system file located on the windows file (C) if you have msvcr100.dll

If it is missing go to a dll.com site and download it and insert it on your system 32 file.

Another dll that might be missing is the API-MS-WIN-CRT-RUNTIME-L1-1-0.DLL

This video explain how to fix this if this is due to a crash like in your print.

https://www.youtube.com/watch?v=gmtV1Xew9o4

I hope it helps.

Wish you the best of luck.

Title: Error installing xampp on windows 7


问:
String array comparison using Jasmine toContains or toMatch
I have a string array names which gets dynamically filled with the names from a dataset. Three names in this array are always the same even though the dataset is changed. So, in my spec I want to check if the names array contains these three specific names. But the matchers aren't helping me in Jasmine.

Example:

```<code>names = ["a", "b", "c", "d", "e", "f", "g"];
expect(names).toContain("b","d","c"); // this should return true as b, d, and c are in the names array
</code>```

The above expect statement doesn't work. Is there a way to use toMatch and use a regex to solve this problem?

Could anyone help me out with this.

Thank you.

答:
.toContain method takes only one argument, that is your mistake

So you can call three .toContain

Or try something like
expect(_.difference(["b","d","c"], names).length).toBe(0, 'names "b","d","c" are not contained in ' + names)

read more about difference method https://lodash.com/docs/4.17.4#difference

Body:
I have a string array names which gets dynamically filled with the names from a dataset. Three names in this array are always the same even though the dataset is changed. So, in my spec I want to check if the names array contains these three specific names. But the matchers aren't helping me in Jasmine.

Example:

names = ["a", "b", "c", "d", "e", "f", "g"];
expect(names).toContain("b","d","c"); // this should return true as b, d, and c are in the names array

The above expect statement doesn't work. Is there a way to use toMatch and use a regex to solve this problem?

Could anyone help me out with this.

Thank you.


问:
Python Uniform distribution of points on 4 dimensional sphere
I need a uniform distribution of points on a 4 dimensional sphere. I know this is not as trivial as picking 3 angles and using polar coordinates.

In 3 dimensions I use

```<code>from random import random

u=random()
costheta = 2*u -1 #for distribution between -1 and 1
theta = acos(costheta)
phi = 2*pi*random

x=costheta
y=sin(theta)*cos(phi)
x=sin(theta)*sin(phi)
</code>```

This gives a uniform distribution of x, y and z.

How can I obtain a similar distribution for 4 dimensions?

答:
I like @unutbu's answer if the gaussian sampling really creates an evenly spaced spherical distribution (unlike sampling from a cube), but to avoid sampling on a Gaussian distribution and to have to prove that, there is a simple solution: to sample on a uniform distribution on a sphere (not on a cube).

Generate points on a uniform distribution.

Compute the squared radius of each point (avoid the square root).

Discard points:

Discard points for which the squared radius is greater than 1 (thus, for which the unsquared radius is greater than 1).

Discard points too close to a radius of zero to avoid numerical instabilities related to the division in the next step.

For each sampled point kept, divide the sampled point by the norm so as to renormalize it the unit radius.

Wash and repeat for more points because of discarded samples.

This obviously works in an n-dimensional space, since the radius is always the L2-norm in higher dimensions.

It is fast so as avoiding a square-root and sampling on a Gaussian distribution, but it's not a vectorized algorithm.

Body:
I need a uniform distribution of points on a 4 dimensional sphere. I know this is not as trivial as picking 3 angles and using polar coordinates.

In 3 dimensions I use

from random import random

u=random()
costheta = 2*u -1 #for distribution between -1 and 1
theta = acos(costheta)
phi = 2*pi*random

x=costheta
y=sin(theta)*cos(phi)
x=sin(theta)*sin(phi)

This gives a uniform distribution of x, y and z.

How can I obtain a similar distribution for 4 dimensions?


问:
Prerender not detecting the token with Nginx
We have an angular app, and we are trying to implement prerender.io for SEO purposes.

We cached all the url's using the sitemap and followed the official Nginx tutorial: https://gist.github.com/thoop/8165802

But prerender.io keeps displaying this message:
We haven't seen a request with your Prerender token yet.

You can check our Nginx code here:

```<code>server {
  listen 443;
  server_name example.com;
  access_log /var/log/nginx/example.com.ssl.access.log;
  error_log /var/log/nginx/example.com.ssl.error.log debug;

  #SSL conf

  location / {

    try_files $uri @prerender;

    if ($request_filename ~* ^.*?/([^/]*?)$)
    {
        set $filename $1;
    }

    if ($filename ~* ^.*?\.(eot)|(ttf)|(woff)$){
        add_header Access-Control-Allow-Origin *;
    }

    proxy_redirect off;
    proxy_set_header   X-Real-IP            $remote_addr;
    proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Proto $scheme;
    proxy_set_header   Host                   $http_host;
    proxy_set_header   X-NginX-Proxy    true;
    proxy_set_header   Connection "";
    proxy_http_version 1.1;
    proxy_cache one;
    proxy_cache_key sfs$request_uri$scheme;

    proxy_pass http://example.com;
  }

  location @prerender {
      #proxy_set_header X-Prerender-Token YOUR_TOKEN;

      set $prerender 0;
      if ($http_user_agent ~* "baiduspider|twitterbot|facebookexternalhit|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator") {
          set $prerender 1;
      }
      if ($args ~ "_escaped_fragment_") {
          set $prerender 1;
      }
      if ($http_user_agent ~ "Prerender") {
          set $prerender 0;
      }
      if ($uri ~* "\.(js|css|xml|less|png|jpg|jpeg|gif|pdf|doc|txt|ico|rss|zip|mp3|rar|exe|wmv|doc|avi|ppt|mpg|mpeg|tif|wav|mov|psd|ai|xls|mp4|m4a|swf|dat|dmg|iso|flv|m4v|torrent|ttf|woff|svg|eot)") {
          set $prerender 0;
      }

      #resolve using Google's DNS server to force DNS resolution and prevent caching of IPs
      resolver 8.8.8.8;

      if ($prerender = 1) {

          #setting prerender as a variable forces DNS resolution since nginx caches IPs and doesnt play well with load balancing
          set $prerender "service.prerender.io";
          rewrite .* /$scheme://$host$request_uri? break;
          proxy_pass http://$prerender;
      }
      if ($prerender = 0) {
          rewrite .* /index.html break;
      }
  }

}
</code>```

We tried different solutions from stackoverflow to similar problems but nothing works...

答:
I'm wondering if the try_files isn't working here for some reason. Can you try putting the prerender config inline instead?</p>

```<code>server {
  listen 443;
  server_name example.com;
  access_log /var/log/nginx/example.com.ssl.access.log;
  error_log /var/log/nginx/example.com.ssl.error.log debug;

  #SSL conf

  location / {

    if ($request_filename ~* ^.*?/([^/]*?)$)
    {
        set $filename $1;
    }

    if ($filename ~* ^.*?\.(eot)|(ttf)|(woff)$){
        add_header Access-Control-Allow-Origin *;
    }

    #proxy_set_header X-Prerender-Token YOUR_TOKEN;

    set $prerender 0;
    if ($http_user_agent ~* "baiduspider|twitterbot|facebookexternalhit|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator") {
        set $prerender 1;
    }
    if ($args ~ "_escaped_fragment_") {
        set $prerender 1;
    }
    if ($http_user_agent ~ "Prerender") {
        set $prerender 0;
    }
    if ($uri ~* "\.(js|css|xml|less|png|jpg|jpeg|gif|pdf|doc|txt|ico|rss|zip|mp3|rar|exe|wmv|doc|avi|ppt|mpg|mpeg|tif|wav|mov|psd|ai|xls|mp4|m4a|swf|dat|dmg|iso|flv|m4v|torrent|ttf|woff|svg|eot)") {
        set $prerender 0;
    }

    #resolve using Google's DNS server to force DNS resolution and prevent caching of IPs
    resolver 8.8.8.8;

    if ($prerender = 1) {

        #setting prerender as a variable forces DNS resolution since nginx caches IPs and doesnt play well with load balancing
        set $prerender "service.prerender.io";
        rewrite .* /$scheme://$host$request_uri? break;
        proxy_pass http://$prerender;
    }

    proxy_redirect off;
    proxy_set_header   X-Real-IP            $remote_addr;
    proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Proto $scheme;
    proxy_set_header   Host                   $http_host;
    proxy_set_header   X-NginX-Proxy    true;
    proxy_set_header   Connection "";
    proxy_http_version 1.1;
    proxy_cache one;
    proxy_cache_key sfs$request_uri$scheme;

    proxy_pass http://example.com;
  }

}
</code>```

Body:
We have an angular app, and we are trying to implement prerender.io for SEO purposes.

We cached all the url's using the sitemap and followed the official Nginx tutorial: https://gist.github.com/thoop/8165802

But prerender.io keeps displaying this message:
We haven't seen a request with your Prerender token yet.

You can check our Nginx code here:

server {
  listen 443;
  server_name example.com;
  access_log /var/log/nginx/example.com.ssl.access.log;
  error_log /var/log/nginx/example.com.ssl.error.log debug;

  #SSL conf

  location / {

    try_files $uri @prerender;

    if ($request_filename ~* ^.*?/([^/]*?)$)
    {
        set $filename $1;
    }

    if ($filename ~* ^.*?\.(eot)|(ttf)|(woff)$){
        add_header Access-Control-Allow-Origin *;
    }

    proxy_redirect off;
    proxy_set_header   X-Real-IP            $remote_addr;
    proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Proto $scheme;
    proxy_set_header   Host                   $http_host;
    proxy_set_header   X-NginX-Proxy    true;
    proxy_set_header   Connection "";
    proxy_http_version 1.1;
    proxy_cache one;
    proxy_cache_key sfs$request_uri$scheme;

    proxy_pass http://example.com;
  }

  location @prerender {
      #proxy_set_header X-Prerender-Token YOUR_TOKEN;

      set $prerender 0;
      if ($http_user_agent ~* "baiduspider|twitterbot|facebookexternalhit|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator") {
          set $prerender 1;
      }
      if ($args ~ "_escaped_fragment_") {
          set $prerender 1;
      }
      if ($http_user_agent ~ "Prerender") {
          set $prerender 0;
      }
      if ($uri ~* "\.(js|css|xml|less|png|jpg|jpeg|gif|pdf|doc|txt|ico|rss|zip|mp3|rar|exe|wmv|doc|avi|ppt|mpg|mpeg|tif|wav|mov|psd|ai|xls|mp4|m4a|swf|dat|dmg|iso|flv|m4v|torrent|ttf|woff|svg|eot)") {
          set $prerender 0;
      }

      #resolve using Google's DNS server to force DNS resolution and prevent caching of IPs
      resolver 8.8.8.8;

      if ($prerender = 1) {

          #setting prerender as a variable forces DNS resolution since nginx caches IPs and doesnt play well with load balancing
          set $prerender "service.prerender.io";
          rewrite .* /$scheme://$host$request_uri? break;
          proxy_pass http://$prerender;
      }
      if ($prerender = 0) {
          rewrite .* /index.html break;
      }
  }

}

We tried different solutions from stackoverflow to similar problems but nothing works...

Body:
I'm wondering if the try_files isn't working here for some reason. Can you try putting the prerender config inline instead?

server {
  listen 443;
  server_name example.com;
  access_log /var/log/nginx/example.com.ssl.access.log;
  error_log /var/log/nginx/example.com.ssl.error.log debug;

  #SSL conf

  location / {

    if ($request_filename ~* ^.*?/([^/]*?)$)
    {
        set $filename $1;
    }

    if ($filename ~* ^.*?\.(eot)|(ttf)|(woff)$){
        add_header Access-Control-Allow-Origin *;
    }

    #proxy_set_header X-Prerender-Token YOUR_TOKEN;

    set $prerender 0;
    if ($http_user_agent ~* "baiduspider|twitterbot|facebookexternalhit|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator") {
        set $prerender 1;
    }
    if ($args ~ "_escaped_fragment_") {
        set $prerender 1;
    }
    if ($http_user_agent ~ "Prerender") {
        set $prerender 0;
    }
    if ($uri ~* "\.(js|css|xml|less|png|jpg|jpeg|gif|pdf|doc|txt|ico|rss|zip|mp3|rar|exe|wmv|doc|avi|ppt|mpg|mpeg|tif|wav|mov|psd|ai|xls|mp4|m4a|swf|dat|dmg|iso|flv|m4v|torrent|ttf|woff|svg|eot)") {
        set $prerender 0;
    }

    #resolve using Google's DNS server to force DNS resolution and prevent caching of IPs
    resolver 8.8.8.8;

    if ($prerender = 1) {

        #setting prerender as a variable forces DNS resolution since nginx caches IPs and doesnt play well with load balancing
        set $prerender "service.prerender.io";
        rewrite .* /$scheme://$host$request_uri? break;
        proxy_pass http://$prerender;
    }

    proxy_redirect off;
    proxy_set_header   X-Real-IP            $remote_addr;
    proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Proto $scheme;
    proxy_set_header   Host                   $http_host;
    proxy_set_header   X-NginX-Proxy    true;
    proxy_set_header   Connection "";
    proxy_http_version 1.1;
    proxy_cache one;
    proxy_cache_key sfs$request_uri$scheme;

    proxy_pass http://example.com;
  }

}


问:
what HTML tags broke page layout?
I want posting in my website to be as rich HTML tags as possible, but safe.

this is tags used in my website:

```<code><a> <p> <span> <div> <h1> <h2> <h3> <h4> <h5> <h6> <img> <map> <area> <hr> <br> <br /> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <em> <b> <u> <i> <strong> <font> <del> <ins> <sub> <sup> <quote> <blockquote> ``` <address>   <embed> <object> <param>
 <s> <textarea>
```

my website is in drupal.. and when viewing front page (/node), the layout broken

答:
What is your DOCTYPE? If your type is XHTML then

```<code><hr> and <br>
</code>```

should never be used.

ContentLicense: CC BY-SA 2.5

Title: what HTML tags broke page layout?

Body:
I want posting in my website to be as rich HTML tags as possible, but safe.

this is tags used in my website:

  <map> <area>

            <quote>

 <address>   <embed> <object> <param>
 <s> <textarea>

my website is in drupal.. and when viewing front page (/node), the layout broken

Body:
What is your DOCTYPE? If your type is XHTML then

<hr> and <br>

should never be used.


问:
EWS Getting all occurences from a master recurrence appointment
I use EWS FindAppointment to get all appointments between dates (see here for why Im using FindAppointments rather the FindItems)

```<code>// Set the start and end time and number of appointments to retrieve.
CalendarView cView = new CalendarView(start, end, 1000);
// Retrieve a collection of appointments by using the calendar view.
FindItemsResults<Appointment> findAppointmentResults = calendar.FindAppointments(cView);
</code>```

I enumerate the results and create just a basic List of Appointments

Since FindAppointment does not return the Master for recurring meetings I use the AppointmentType.Occurrence appointments returned to get their Master

```<code>Appointment.BindToRecurringMaster(this.exchangeService, new ItemId(occurrence.Id.ToString()));
</code>```

With this I form another List of all my Master Appointments.

I'm trying to use the Masters to retrieve every appointment in the series however thats where Im having trouble.

I tried to iterate through the list (as shown here, MSDN)

```<code> public List<Appointment> getAllOccurrencesFromMaster(Appointment masterOccurrence) {
            List<Appointment> retVal = new List<Appointment>();

            int iCurrentIndex = 1;
            DateTime occurStart = masterOccurrence.Start;
            try {
                // Get the appointment that is located at the current index in the series.
                Appointment seriesAppt = Appointment.BindToOccurrence(this.exchangeService, new ItemId(masterOccurrence.Id.ToString()), iCurrentIndex);
                retVal.Add(seriesAppt);

                while (true) {
                    try {
                        Appointment appt = Appointment.BindToOccurrence(this.exchangeService, new ItemId(masterOccurrence.Id.ToString()), iCurrentIndex + 1);
                        retVal.Add(appt);
                    } catch (ServiceResponseException sre) {
                        Console.WriteLine("Occurrence with this index was previously deleted from the recurrence. " + sre.ToString());
                    } catch (Exception e) {
                            throw e;
                        }
                    }
                    iCurrentIndex++;
                }
            }catch (Exception e) {
                if (e.Message == "Occurrence index is out of recurrence range.") {
                    Console.WriteLine("The end of the series has been reached.");
                } else {
                    Console.WriteLine("bad error. " + e.ToString());
                    throw e;
                }
            }

            return retVal;
        }
</code>```

My problem with the above code is that when a deleted item is reached it throws the same exception as when the index is out of range: ServiceResponseException.

Which is a problem because for one I want to continue and the other I want to break and Im not going to switch that based on the message text.  And furthermore I need the deleted occurrences.  How do I get all appointments in a recurring series?

I have also tried to use the DeletedOccurances property of the Master Appointment but none of the entries had their IDs populated.  We do a Unidirectional sync from Exchange to our system, and I need to know whats deleted so I can remove it from our system.  We keep track of the calenderItem.ID and so I need that when something is deleted to know which meeting to delete in our system.

答: Pretty old to follow up, but I had a need to iterate over a series and came across this post.  The short answer to the original question is to use the ServiceResponseException.ErrorCode and you get ErrorCalendarOccurrenceIsDeletedFromRecurrence when you hit a missing instance, and ErrorCalendarOccurrenceIndexIsOutOfRecurrenceRange when you've hit the end of the series. HTH someone.

Body:
I use EWS FindAppointment to get all appointments between dates (see here for why Im using FindAppointments rather the FindItems)

// Set the start and end time and number of appointments to retrieve.
CalendarView cView = new CalendarView(start, end, 1000);
// Retrieve a collection of appointments by using the calendar view.
FindItemsResults<Appointment> findAppointmentResults = calendar.FindAppointments(cView);

I enumerate the results and create just a basic List of Appointments

Since FindAppointment does not return the Master for recurring meetings I use the AppointmentType.Occurrence appointments returned to get their Master

Appointment.BindToRecurringMaster(this.exchangeService, new ItemId(occurrence.Id.ToString()));

With this I form another List of all my Master Appointments.

I'm trying to use the Masters to retrieve every appointment in the series however thats where Im having trouble.

I tried to iterate through the list (as shown here, MSDN)

 public List<Appointment> getAllOccurrencesFromMaster(Appointment masterOccurrence) {
            List<Appointment> retVal = new List<Appointment>();

            int iCurrentIndex = 1;
            DateTime occurStart = masterOccurrence.Start;
            try {
                // Get the appointment that is located at the current index in the series.
                Appointment seriesAppt = Appointment.BindToOccurrence(this.exchangeService, new ItemId(masterOccurrence.Id.ToString()), iCurrentIndex);
                retVal.Add(seriesAppt);

                while (true) {
                    try {
                        Appointment appt = Appointment.BindToOccurrence(this.exchangeService, new ItemId(masterOccurrence.Id.ToString()), iCurrentIndex + 1);
                        retVal.Add(appt);
                    } catch (ServiceResponseException sre) {
                        Console.WriteLine("Occurrence with this index was previously deleted from the recurrence. " + sre.ToString());
                    } catch (Exception e) {
                            throw e;
                        }
                    }
                    iCurrentIndex++;
                }
            }catch (Exception e) {
                if (e.Message == "Occurrence index is out of recurrence range.") {
                    Console.WriteLine("The end of the series has been reached.");
                } else {
                    Console.WriteLine("bad error. " + e.ToString());
                    throw e;
                }
            }

            return retVal;
        }

My problem with the above code is that when a deleted item is reached it throws the same exception as when the index is out of range: ServiceResponseException.

Which is a problem because for one I want to continue and the other I want to break and Im not going to switch that based on the message text.  And furthermore I need the deleted occurrences.  How do I get all appointments in a recurring series?

I have also tried to use the DeletedOccurances property of the Master Appointment but none of the entries had their IDs populated.  We do a Unidirectional sync from Exchange to our system, and I need to know whats deleted so I can remove it from our system.  We keep track of the calenderItem.ID and so I need that when something is deleted to know which meeting to delete in our system.


问:
PostgreSQL Sum and Percent of Total Subquery
Table has sales and i'm trying to calculate the sales dollars and percent of total.

```<code>WITH t1 AS (
    SELECT
    product_id,
    sum(financial_charge_cents) as cents
    FROM "account_charges"
    WHERE account_id = 5
    AND status = 'Charged'
    GROUP BY product_id
    ORDER BY cents DESC
)
SELECT
    product_id,
    cast(cents as money) / 100.0 AS dollars,
    cents / (sum(cents) OVER (PARTITION BY product_id)) as percent
FROM t1
ORDER BY dollars DESC
</code>```

but this is returning all the percents to be 1 and not sure why.

not sure if this is a type problem or what.

答:
OVER (PARTITION BY produuct_id) causes that the sums are the same as cents. You do not need partitions:

```<code>SELECT
    product_id,
    cast(cents as money) / 100.0 AS dollars,
    cents* 1.0 / (sum(cents) OVER ()) as percent
FROM t1
ORDER BY dollars DESC
</code>```

Note, I have added *1.0 to get numeric results. Skip it if cents are numeric (not integer).

Body:
Table has sales and i'm trying to calculate the sales dollars and percent of total.

WITH t1 AS (
    SELECT
    product_id,
    sum(financial_charge_cents) as cents
    FROM "account_charges"
    WHERE account_id = 5
    AND status = 'Charged'
    GROUP BY product_id
    ORDER BY cents DESC
)
SELECT
    product_id,
    cast(cents as money) / 100.0 AS dollars,
    cents / (sum(cents) OVER (PARTITION BY product_id)) as percent
FROM t1
ORDER BY dollars DESC

but this is returning all the percents to be 1 and not sure why.

not sure if this is a type problem or what.

Body:
OVER (PARTITION BY produuct_id) causes that the sums are the same as cents. You do not need partitions:

SELECT
    product_id,
    cast(cents as money) / 100.0 AS dollars,
    cents* 1.0 / (sum(cents) OVER ()) as percent
FROM t1
ORDER BY dollars DESC

Note, I have added *1.0 to get numeric results. Skip it if cents are numeric (not integer).


问:
Subclassing a Java Builder class
Give this Dr Dobbs article, and the Builder Pattern in particular, how do we handle the case of subclassing a Builder? Taking a cut-down version of the example where we want to subclass to add GMO labelling, a naive implementation would be:

```<code>public class NutritionFacts {

    private final int calories;

    public static class Builder {
        private int calories = 0;

        public Builder() {}

        public Builder calories(int val) { calories = val; return this; }

        public NutritionFacts build() { return new NutritionFacts(this); }
    }

    protected NutritionFacts(Builder builder) {
        calories = builder.calories;
    }
}
</code>```

Subclass:

```<code>public class GMOFacts extends NutritionFacts {

    private final boolean hasGMO;

    public static class Builder extends NutritionFacts.Builder {

        private boolean hasGMO = false;

        public Builder() {}

        public Builder GMO(boolean val) { hasGMO = val; return this; }

        public GMOFacts build() { return new GMOFacts(this); }
    }

    protected GMOFacts(Builder builder) {
        super(builder);
        hasGMO = builder.hasGMO;
    }
}
</code>```

Now, we can write code like this:

```<code>GMOFacts.Builder b = new GMOFacts.Builder();
b.GMO(true).calories(100);
</code>```

But, if we get the order wrong, it all fails:

```<code>GMOFacts.Builder b = new GMOFacts.Builder();
b.calories(100).GMO(true);
</code>```

The problem is of course that NutritionFacts.Builder returns a NutritionFacts.Builder, not a GMOFacts.Builder, so how do we solve this problem, or is there a better Pattern to use?

Note: this answer to a similar question offers up the classes I have above; my question is regarding the problem of ensuring the builder calls are in the correct order.

答:
I created a parent, abstract generic builder class that accepts two formal type parameters. First is for the type of object returned by build(), the second is the type returned by each optional parameter setter. Below are parent and child classes for illustrative purpose:

```<code>// **Parent**
public abstract static class Builder<T, U extends Builder<T, U>> {
    // Required parameters
    private final String name;

    // Optional parameters
    private List<String> outputFields = null;

    public Builder(String pName) {
        name = pName;
    }

    public U outputFields(List<String> pOutFlds) {
        outputFields = new ArrayList<>(pOutFlds);
        return getThis();
    }

    /**
     * This helps avoid "unchecked warning", which would forces to cast to "T" in each of the optional
     * parameter setters..
     * @return
     */
    abstract U getThis();

    public abstract T build();

    /*
     * Getters
     */
    public String getName() {
        return name;
    }
}

 // **Child**
 public static class Builder extends AbstractRule.Builder<ContextAugmentingRule, ContextAugmentingRule.Builder> {
    // Required parameters
    private final Map<String, Object> nameValuePairsToAdd;

    // Optional parameters
    private String fooBar;

    Builder(String pName, Map<String, String> pNameValPairs) {
        super(pName);
        /**
         * Must do this, in case client code (I.e. JavaScript) is re-using
         * the passed in for multiple purposes. Doing {@link Collections#unmodifiableMap(Map)}
         * won't caught it, because the backing Map passed by client prior to wrapping in
         * unmodifiable Map can still be modified.
         */
        nameValuePairsToAdd = new HashMap<>(pNameValPairs);
    }

    public Builder fooBar(String pStr) {
        fooBar = pStr;
        return this;
    }

    @Override
    public ContextAugmentingRule build() {
        try {
            Rule r = new ContextAugmentingRule(this);
            storeInRuleByNameCache(r);
            return (ContextAugmentingRule) r;
        } catch (RuleException e) {
            throw new IllegalArgumentException(e);
        }
    }

    @Override
    Builder getThis() {
        return this;
    }
}
</code>```

This one has met my needs to satisfaction.

Title: Subclassing a Java Builder class

Body:
Give this Dr Dobbs article, and the Builder Pattern in particular, how do we handle the case of subclassing a Builder? Taking a cut-down version of the example where we want to subclass to add GMO labelling, a naive implementation would be:

public class NutritionFacts {

    private final int calories;

    public static class Builder {
        private int calories = 0;

        public Builder() {}

        public Builder calories(int val) { calories = val; return this; }

        public NutritionFacts build() { return new NutritionFacts(this); }
    }

    protected NutritionFacts(Builder builder) {
        calories = builder.calories;
    }
}

Subclass:

public class GMOFacts extends NutritionFacts {

    private final boolean hasGMO;

    public static class Builder extends NutritionFacts.Builder {

        private boolean hasGMO = false;

        public Builder() {}

        public Builder GMO(boolean val) { hasGMO = val; return this; }

        public GMOFacts build() { return new GMOFacts(this); }
    }

    protected GMOFacts(Builder builder) {
        super(builder);
        hasGMO = builder.hasGMO;
    }
}

Now, we can write code like this:

GMOFacts.Builder b = new GMOFacts.Builder();
b.GMO(true).calories(100);

But, if we get the order wrong, it all fails:

GMOFacts.Builder b = new GMOFacts.Builder();
b.calories(100).GMO(true);

The problem is of course that NutritionFacts.Builder returns a NutritionFacts.Builder, not a GMOFacts.Builder, so how do we solve this problem, or is there a better Pattern to use?

Note: this answer to a similar question offers up the classes I have above; my question is regarding the problem of ensuring the builder calls are in the correct order.

Body:
I created a parent, abstract generic builder class that accepts two formal type parameters. First is for the type of object returned by build(), the second is the type returned by each optional parameter setter. Below are parent and child classes for illustrative purpose:

// **Parent**
public abstract static class Builder<T, U extends Builder<T, U>> {
    // Required parameters
    private final String name;

    // Optional parameters
    private List<String> outputFields = null;

    public Builder(String pName) {
        name = pName;
    }

    public U outputFields(List<String> pOutFlds) {
        outputFields = new ArrayList<>(pOutFlds);
        return getThis();
    }

    /**
     * This helps avoid "unchecked warning", which would forces to cast to "T" in each of the optional
     * parameter setters..
     * @return
     */
    abstract U getThis();

    public abstract T build();

    /*
     * Getters
     */
    public String getName() {
        return name;
    }
}

 // **Child**
 public static class Builder extends AbstractRule.Builder<ContextAugmentingRule, ContextAugmentingRule.Builder> {
    // Required parameters
    private final Map<String, Object> nameValuePairsToAdd;

    // Optional parameters
    private String fooBar;

    Builder(String pName, Map<String, String> pNameValPairs) {
        super(pName);
        /**
         * Must do this, in case client code (I.e. JavaScript) is re-using
         * the passed in for multiple purposes. Doing {@link Collections#unmodifiableMap(Map)}
         * won't caught it, because the backing Map passed by client prior to wrapping in
         * unmodifiable Map can still be modified.
         */
        nameValuePairsToAdd = new HashMap<>(pNameValPairs);
    }

    public Builder fooBar(String pStr) {
        fooBar = pStr;
        return this;
    }

    @Override
    public ContextAugmentingRule build() {
        try {
            Rule r = new ContextAugmentingRule(this);
            storeInRuleByNameCache(r);
            return (ContextAugmentingRule) r;
        } catch (RuleException e) {
            throw new IllegalArgumentException(e);
        }
    }

    @Override
    Builder getThis() {
        return this;
    }
}

This one has met my needs to satisfaction.


问:
How to read the csv and convert to RDD in sparkR
As i am a R programmer i want to use R as a interface to spark, with the sparkR package i installed sparkR in R.

I'm new to sparkR. I want to perform some operations on particular data in a CSV record.  I'm trying to read a csv file and convert it to rdd.

```<code>This is the code i did:
sc <- sparkR.init(master="local") # created spark content
data <- read.csv(sc, "/home/data1.csv")
#It throws an error, to use read.table

Data i have to load and convert - http://i.stack.imgur.com/sj78x.png

if am wrong, how to read this data in csv and convert to RDD in sparkR
</code>```

TIA

答:
This below code will let you read a csv with header . All the best </p>

```<code>val csvrdd = spark.read.options(“header”,”true”).csv(filename)
</code>```

Body:
As i am a R programmer i want to use R as a interface to spark, with the sparkR package i installed sparkR in R.

I'm new to sparkR. I want to perform some operations on particular data in a CSV record.  I'm trying to read a csv file and convert it to rdd.

This is the code i did:
sc <- sparkR.init(master="local") # created spark content
data <- read.csv(sc, "/home/data1.csv")
#It throws an error, to use read.table

Data i have to load and convert - http://i.stack.imgur.com/sj78x.png

if am wrong, how to read this data in csv and convert to RDD in sparkR

TIA

Body:
This below code will let you read a csv with header . All the best

val csvrdd = spark.read.options(“header”,”true”).csv(filename)


问:
MongoDB updates incorrect array element
Hello I have a document with some user records.

```<code>    "profile":{
     "records":[
              {
                "classId":   "LngdsQfL",
                "moduleId":  "5CDEezDJ",
                "sectionId": "nFMu3mwa",
                "dateFinished": "",
                "dateOpened": "2017-11-15T19:48:20.819Z"
              },
              {
                "classId":   "7Smq5sG",
                "moduleId":  "5CDEezDJ",
                "sectionId": "nFMu3mwa",
                "dateFinished": "",
                "dateOpened": "2017-11-15T19:19:08.669Z"
              }
            ]
      }
</code>```

But when I am trying to update the second record the query updates the first one. And the second one stays the same.

```<code> var classId= "7Smq5sG";
 var moduleId = "5CDEezDJ";
 var sectionId = "nFMu3mwa";
 var date = new Date();

Users.update(
              { _id:Meteor.userId() ,

                'profile.records.classId' : classId,
                'profile.records.moduleId' : moduleId,
                'profile.records.sectionId' :  sectionId,
              },{
              $set : {
                "profile.records.$.dateOpened": date
                }
             });
    }
</code>```

What am I missing?

答:
Try to use a request as follows:

```<code>Users.update(
  {_id:Meteor.userId(),
   'profile.records': {$elemMatch: {
                                     'moduleId': {$eq: moduleId},
                                     'sectionId': {$eq: sectionId},
                                     'classId': {$eq: classId}
                                   }
                      }
  },
  {$set: {'profile.records.$.dateOpened': date}});
</code>```

It uses $elemMatch operator to find array element that matches multiple query criteria.

Title: MongoDB updates incorrect array element

Body:
Hello I have a document with some user records.

    "profile":{
     "records":[
              {
                "classId":   "LngdsQfL",
                "moduleId":  "5CDEezDJ",
                "sectionId": "nFMu3mwa",
                "dateFinished": "",
                "dateOpened": "2017-11-15T19:48:20.819Z"
              },
              {
                "classId":   "7Smq5sG",
                "moduleId":  "5CDEezDJ",
                "sectionId": "nFMu3mwa",
                "dateFinished": "",
                "dateOpened": "2017-11-15T19:19:08.669Z"
              }
            ]
      }

But when I am trying to update the second record the query updates the first one. And the second one stays the same.

 var classId= "7Smq5sG";
 var moduleId = "5CDEezDJ";
 var sectionId = "nFMu3mwa";
 var date = new Date();

Users.update(
              { _id:Meteor.userId() ,

                'profile.records.classId' : classId,
                'profile.records.moduleId' : moduleId,
                'profile.records.sectionId' :  sectionId,
              },{
              $set : {
                "profile.records.$.dateOpened": date
                }
             });
    }

What am I missing?

Body:
Try to use a request as follows:

Users.update(
  {_id:Meteor.userId(),
   'profile.records': {$elemMatch: {
                                     'moduleId': {$eq: moduleId},
                                     'sectionId': {$eq: sectionId},
                                     'classId': {$eq: classId}
                                   }
                      }
  },
  {$set: {'profile.records.$.dateOpened': date}});

It uses $elemMatch operator to find array element that matches multiple query criteria.


问:
How to save parent entity without inserting child in one to one relationship by shared primary key in hibernate?

I am using one to one relation by shared primary key in hibernate,
  whenever I call the save method to insert parent entity without inserying child entity I get below
  exception

```<code>org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [com.example.sms.domain.Child.parent]
</code>```

Code of child class entity with mapping of parent class entity is
  given below

```<code>@Entity
@Table(name = "t_child")
public class Child {

@Id
    @Column(name="user_id", unique=true, nullable=false)
    @GeneratedValue(generator="gen")
    @GenericGenerator(name="gen", strategy="foreign", parameters=@Parameter(name="property", value="user"))
    private Long id;

@OneToOne(optional = false,fetch = FetchType.LAZY)
    @PrimaryKeyJoinColumn
    private Parent parent;
</code>```

And in parent class entity i have mapped child class entity like below

```<code>@OneToOne(mappedBy="parent", cascade=CascadeType.ALL)
    private Child child;
</code>```

Is there any way to save only parent entity without inserting child entity?

答:
Finally after 1 day I have found the solution myself

This code Was correct. Mapstruct was creating a problem while
  converting Dto to domain object

```<code>@Mappings({

            @Mapping(source = "fatherName", target = "child.childDetail.fatherName"),
            @Mapping(source = "motherName", target = "child.childDetail.motherName"),
            @Mapping(source = "firstName", target = "child.childDetail.firstName"),
            @Mapping(source = "lastName", target = "child.childDetail.lastName"),
            @Mapping(source = "dateOfBirth", target = "child.childDetail.dateOfBirth"),
        })
    public User ParentDtoToParent(ParentDto parentDto);
</code>```

I was using the Same DTO object that I was using while storing every
  child detail But to store only parent entity I was not sending any
  child details value in the Json Format. So mapstruct Automatically
  assigned NULL value to the Child attribute(firstname,lastname etc)
  When Hibernate Was saving the object it got object With the Null value
  of Attributes instead of NULL Object

Body:
I am using one to one relation by shared primary key in hibernate,
  whenever I call the save method to insert parent entity without inserying child entity I get below
  exception

org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [com.example.sms.domain.Child.parent]

Code of child class entity with mapping of parent class entity is
  given below

@Entity
@Table(name = "t_child")
public class Child {

@Id
    @Column(name="user_id", unique=true, nullable=false)
    @GeneratedValue(generator="gen")
    @GenericGenerator(name="gen", strategy="foreign", parameters=@Parameter(name="property", value="user"))
    private Long id;

@OneToOne(optional = false,fetch = FetchType.LAZY)
    @PrimaryKeyJoinColumn
    private Parent parent;

And in parent class entity i have mapped child class entity like below

@OneToOne(mappedBy="parent", cascade=CascadeType.ALL)
    private Child child;

Is there any way to save only parent entity without inserting child entity?

Body:
Finally after 1 day I have found the solution myself

This code Was correct. Mapstruct was creating a problem while
  converting Dto to domain object

@Mappings({

            @Mapping(source = "fatherName", target = "child.childDetail.fatherName"),
            @Mapping(source = "motherName", target = "child.childDetail.motherName"),
            @Mapping(source = "firstName", target = "child.childDetail.firstName"),
            @Mapping(source = "lastName", target = "child.childDetail.lastName"),
            @Mapping(source = "dateOfBirth", target = "child.childDetail.dateOfBirth"),
        })
    public User ParentDtoToParent(ParentDto parentDto);

I was using the Same DTO object that I was using while storing every
  child detail But to store only parent entity I was not sending any
  child details value in the Json Format. So mapstruct Automatically
  assigned NULL value to the Child attribute(firstname,lastname etc)
  When Hibernate Was saving the object it got object With the Null value
  of Attributes instead of NULL Object