问:
Cygwin and Python 2.6
New to python (and programming).  What exactly do I need from Cygwin?  I'm running python 2.6 on winxp.  Can I safely download the complete Cygwin?  It just seems like a huge bundle of stuff.

Well, I keep running into modules and functionality (i.e. piping output) which suggest downloading various cygwin components. Will cygwin change or modify any other os functionality or have any other side effects?

答:
There are builds of python which don't require cygwin. For instance (from python.org):

link text

Also, there is the .NET version called Iron Python:

link text

Title: Cygwin and Python 2.6

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: K. Brian Kelley


来源: stackexchange

问:
iTerm2 & MacVim: Why light white shadow overlays the screen?
When a file is opened within iTerm using vim, light white shadow overlays the entire screen making the text unreadable.
How can I get this fixed?

Open within iTerm:

Open in vim app:

答:
It's related to the theme that you chose in iTerm2.
As alex said, feel free to play around with the iTerm2' color settings.

ContentLicense: CC BY-SA 3.0


问:
Return a list of similar authors
I'm trying to write a function that will return a list of items from a key from a key (if that makes sense). For example, here's a dictionary of authors, and similar authors.

```<code>authors = {
    'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'],
    'Harlan Ellison': ['Neil Stephenson', 'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'],
    'Kurt Vonnegut': ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer'],
    'Thomas Pynchon': ['Isaac Asimov', 'Jorges Borges', 'Robert Heinlein'],
    'Isaac Asimov': ['Stephen Baxter', 'Ray Bradbury', 'Arthur Clarke', 'Kurt Vonnegut', 'Neil Stephenson'],
    'Douglas Adams': ['Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
}
</code>```

And the function I came up with is this:

```<code>def get_similar(author_list, author):
    for item in author_list[author]:
        return author_list[author]
</code>```

Which only returns the items for the first key. I'd like it to return all of the similar authors, like this:

```<code>get_similar(authors, 'Harlan Ellison')

['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson',
 'Jeff Vandemeer','Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
</code>```

Where it finds the key given (author), looks at the items listed for that key, and then returns those key's items. In this case Harlan Ellison has four authors listed - Neil Stephenson, Kurt Vonnegut, Richard Morgan, and Douglas Adams. The function then looks up those authors, and returns the items listed for them - Kurt Vonnegut returns Terry Pratchett, Tom Robbins, Douglas Adams, Neil Stephenson, and Jeff Vandemeer, and Douglas Adams returns Terry Pratchett, Chris Moore, and Kurt Vonnegut,

Duplicates are fine, and I'd like it in alphabetical order (I assume you could just use a sort command at the end) Any help would be much appreciated, I'm stumped!

答:
You are very close but instead of returning after finding the first list of similar authors, you should store all of the authors you find in a list and then return them all after your for loop has finished:

```<code>def get_similar(author_list, author):
    similar_authors = []
    for item in author_list[author]:
        if item in author_list:
            similar_authors.extend(author_list[item])
    return similar_authors
</code>```

Notice that I also added an if statement to make sure that the item is in fact one of the keys in your dictionary so you don't get an error later on (for example: 'Neil Stephenson' is in the dictionary as a member of one of the values but is not a key).

EXTRA INFO:

(if you are interested)

Another option is to turn your function into a generator instead.  This has the advantage of not having to store all the similar authors in a list and instead yields each author as it is found:

```<code>def get_similar2(author_list, author):
    for item in author_list[author]:
        if item in author_list:
            for other_author in author_list[item]:
                yield other_author
</code>```

Or if you are using python 3.3+ you can simplify this a bit by using the yield from expression to get functionally the same code as in get_similar2:

```<code>def get_similar3(author_list, author):
    for item in author_list[author]:
        if item in author_list:
            yield from author_list[item]
</code>```

All three of the functions/generators above will give you the same results (just remember to get all the values yielded from the generators):

```<code>print(get_similar(authors, 'Harlan Ellison'))
['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer', 'Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']

print(list(get_similar2(authors, 'Harlan Ellison')))
['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer', 'Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']

print(list(get_similar3(authors, 'Harlan Ellison')))
['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer', 'Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
</code>```

Title: Return a list of similar authors

Body:
I'm trying to write a function that will return a list of items from a key from a key (if that makes sense). For example, here's a dictionary of authors, and similar authors.

authors = {
    'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'],
    'Harlan Ellison': ['Neil Stephenson', 'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'],
    'Kurt Vonnegut': ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer'],
    'Thomas Pynchon': ['Isaac Asimov', 'Jorges Borges', 'Robert Heinlein'],
    'Isaac Asimov': ['Stephen Baxter', 'Ray Bradbury', 'Arthur Clarke', 'Kurt Vonnegut', 'Neil Stephenson'],
    'Douglas Adams': ['Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
}

And the function I came up with is this:

def get_similar(author_list, author):
    for item in author_list[author]:
        return author_list[author]

Which only returns the items for the first key. I'd like it to return all of the similar authors, like this:

get_similar(authors, 'Harlan Ellison')

['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson',
 'Jeff Vandemeer','Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']

Where it finds the key given (author), looks at the items listed for that key, and then returns those key's items. In this case Harlan Ellison has four authors listed - Neil Stephenson, Kurt Vonnegut, Richard Morgan, and Douglas Adams. The function then looks up those authors, and returns the items listed for them - Kurt Vonnegut returns Terry Pratchett, Tom Robbins, Douglas Adams, Neil Stephenson, and Jeff Vandemeer, and Douglas Adams returns Terry Pratchett, Chris Moore, and Kurt Vonnegut,

Duplicates are fine, and I'd like it in alphabetical order (I assume you could just use a sort command at the end) Any help would be much appreciated, I'm stumped!

Body:
You are very close but instead of returning after finding the first list of similar authors, you should store all of the authors you find in a list and then return them all after your for loop has finished:

def get_similar(author_list, author):
    similar_authors = []
    for item in author_list[author]:
        if item in author_list:
            similar_authors.extend(author_list[item])
    return similar_authors

Notice that I also added an if statement to make sure that the item is in fact one of the keys in your dictionary so you don't get an error later on (for example: 'Neil Stephenson' is in the dictionary as a member of one of the values but is not a key).

EXTRA INFO:

(if you are interested)

Another option is to turn your function into a generator instead.  This has the advantage of not having to store all the similar authors in a list and instead yields each author as it is found:

def get_similar2(author_list, author):
    for item in author_list[author]:
        if item in author_list:
            for other_author in author_list[item]:
                yield other_author

Or if you are using python 3.3+ you can simplify this a bit by using the yield from expression to get functionally the same code as in get_similar2:

def get_similar3(author_list, author):
    for item in author_list[author]:
        if item in author_list:
            yield from author_list[item]

All three of the functions/generators above will give you the same results (just remember to get all the values yielded from the generators):

print(get_similar(authors, 'Harlan Ellison'))
['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer', 'Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']

print(list(get_similar2(authors, 'Harlan Ellison')))
['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer', 'Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']

print(list(get_similar3(authors, 'Harlan Ellison')))
['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer', 'Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']


问:
Get the AllowDrop propert of a Model in a ViewModel in WPF Treeview
I have a model class ViewItem that has the property AllowDrop.  My View Model ViewModel is an observable collection of ViewItem.

The ViewItem property

```<code>    public bool AllowDrop
    {
        get
        {
            return _allowDrop;
        }
    }
</code>```

I have a ViewTree thats data source is bound to an instance of the ViewModel, MyItems.

I would like to be able to access bind the ViewTreeItems AllowDrop property to the underlying model, however I can't figure out the correct way to access it.

My XAML for the TreeView looks like this

```<code>        <TreeView x:Name="ViewsTree"
                  AllowDragDrop="True"
                  DragOver="ViewsTree_DragOver"
                  ItemsSource="{Binding MyItems}"
                  ItemTemplate="{StaticResource ViewTemplate}"
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="AllowDrop" Value="{Binding}"/>
        </Style>
    </TreeView>
</code>```

I am stuck on how to access the ViewItem in the MyView collection to bind to the AllowDrop property.

答:
Here's a bare minimum example.

XAML:

```<code><Grid>
    <Grid.Resources>
        <ResourceDictionary>
            <Style TargetType="{x:Type TreeViewItem}">
                <Setter Property="AllowDrop" Value="{Binding AllowDrop}"/>
            </Style>
        </ResourceDictionary>
    </Grid.Resources>

    <TreeView ItemsSource="{Binding MyItems}">
        <TreeView.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Id}"/>
                    <TextBlock Margin="5,0" Text="{Binding AllowDrop}"/>
                </StackPanel>
            </DataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>
</Grid>
</code>```

Code behind :

```<code>public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        DataContext = new ViewModel();
    }
}

public class ViewModel
{
    public ViewModel()
    {
        MyItems = new List<ViewItem>();
        for (int i = 0; i < 10; i++)
            MyItems.Add(new ViewItem { Id = i, AllowDrop = i % 2 == 0 });
    }

    public List<ViewItem> MyItems { get; set; }
}

public class ViewItem
{
    public int Id { get; set; }
    public bool AllowDrop { get; set; }
}
</code>```

Trying to drag something on the TreeListView will work on items with even Id only.

Body:
I have a model class ViewItem that has the property AllowDrop.  My View Model ViewModel is an observable collection of ViewItem.

The ViewItem property

    public bool AllowDrop
    {
        get
        {
            return _allowDrop;
        }
    }

I have a ViewTree thats data source is bound to an instance of the ViewModel, MyItems.

I would like to be able to access bind the ViewTreeItems AllowDrop property to the underlying model, however I can't figure out the correct way to access it.

My XAML for the TreeView looks like this

        <TreeView x:Name="ViewsTree"
                  AllowDragDrop="True"
                  DragOver="ViewsTree_DragOver"
                  ItemsSource="{Binding MyItems}"
                  ItemTemplate="{StaticResource ViewTemplate}"

    </TreeView>

I am stuck on how to access the ViewItem in the MyView collection to bind to the AllowDrop property.

Body:
Here's a bare minimum example.

XAML:

<Grid>
    <Grid.Resources>
        <ResourceDictionary>
            <Style TargetType="{x:Type TreeViewItem}">
                <Setter Property="AllowDrop" Value="{Binding AllowDrop}"/>
            </Style>
        </ResourceDictionary>
    </Grid.Resources>

    <TreeView ItemsSource="{Binding MyItems}">
        <TreeView.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Id}"/>
                    <TextBlock Margin="5,0" Text="{Binding AllowDrop}"/>
                </StackPanel>
            </DataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>
</Grid>

Code behind :

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        DataContext = new ViewModel();
    }
}

public class ViewModel
{
    public ViewModel()
    {
        MyItems = new List<ViewItem>();
        for (int i = 0; i < 10; i++)
            MyItems.Add(new ViewItem { Id = i, AllowDrop = i % 2 == 0 });
    }

    public List<ViewItem> MyItems { get; set; }
}

public class ViewItem
{
    public int Id { get; set; }
    public bool AllowDrop { get; set; }
}

Trying to drag something on the TreeListView will work on items with even Id only.


问:
How can i use ffmpeg to extract audio from an video every 5 seconds
I need to extract audio from live stream. I want to generate an audio file every 5s.

if i use the command
ffmpeg -i ***.flv -c:a aac -fs 128k output.aac
I can only get one file. but i want generate a file every 5s.

if i use the commmand
ffmpeg -i ***.mp4 -vf fps=1/5.0 E:\image%d.jpg
I got an image every 1s.
How can i do the same thing to extract audio.

答:
Use the segment muxer:

```<code>ffmpeg -i input -map 0:a -f segment -segment_time 5 output_%03d.aac
</code>```

Add -c copy and use a compatible output container format if you don't want to re-encode.

Body:
Use the segment muxer:

ffmpeg -i input -map 0:a -f segment -segment_time 5 output_%03d.aac

Add -c copy and use a compatible output container format if you don't want to re-encode.


问:
Angular 2 upload Image button is refreshing page
I have a html form with two buttons on it:-

[1] One button is used to upload an image file (.jpg)
[2] and the second one is to submit the form.

The problem is that the upload image button seems to be refreshing the page after the method for uploading the image has completed. Below is my html:-

```<code><div class="m-b-18px">
  <div class="col-m-12">
    <a (click)="readRecipes()" class="btn btn-primary pull-right">
      <span class="glyphicon glyphicon-plus"></span>Read Recipes
    </a>
  </div>
</div>

<div class="row">
  <div class="col-md-12">
    <form [formGroup]="create_recipe_form" (ngSubmit)="createRecipe()">
      <table class="table table-hover table-responsive table-bordered">
        <tr>
          <td>
            Name
          </td>
          <td>
            <input name="name" formControlName="name" type="text" class="form-control" required />
            <div *ngIf="create_recipe_form.get('name').touched && create_recipe_form.get('name').hasError('required')"
              class="alert alert-danger">Name is required
            </div>
          </td>
        </tr>

        <tr>
          <td>
            Description
          </td>
          <td>
            <textarea name="description" formControlName="description" class="form-control" required>

            </textarea>
            <div *ngIf="create_recipe_form.get('description').touched && create_recipe_form.get('description').hasError('required')"
              class="alert alert-danger">
              Description is required
            </div>
          </td>
        </tr>

        <tr>
          <td>
            Image
          </td>
          <td>
            <input name="selectFile" id="selectFile" type="file" class="form-control btn btn-success" />
            <button type="button" class="btn btn-primary" (click)="uploadImage($event)" value="Upload Image">Upload Image</button>
            <input type='hidden' id='image_id' name='img_id' value="6" formControlName="image_id" />
          </td>
        </tr>

        <tr>
          <td></td>
          <td>
            <button class="btn btn-primary" type="submit" [disabled]="!create_recipe_form.valid">
                <span class="glyphicon glyphicon-plus"></span> Create
            </button>
          </td>
        </tr>
      </table>
    </form>
  </div>
</div>
</code>```

My code for the uploadImage method is below:-

```<code> uploadImage(e) {
    let files = this.elem.nativeElement.querySelector('#selectFile').files;
    let formData = new FormData();
    let file = files[0];

    formData.append('selectFile', file, file.name);

    this._imageService.uploadImage(formData)
      .subscribe(
        image => {
          console.log(image);
          this.addImageIdToHtml(image)
          e.preventDefault();
          e.stopPropagation();
        },
        error => console.log(error)
      );
  }
</code>```

As soon as the above method has finished running the page appears to refreshing causing my app to go back to the land page. This is not the behaviour I want. What I actually want is the form page to be retained until the Submit form button is pressed. Can anyone help me please?

答:
Use div tags instead of form tag.

Change the button type as button.

```<code><button type="button">Upload Image</button>
</code>```

Modify the code as follows.

```<code><div class="m-b-18px">
  <div class="col-m-12">
    <a (click)="readRecipes()" class="btn btn-primary pull-right">
      <span class="glyphicon glyphicon-plus"></span>Read Recipes
    </a>
  </div>
</div>

<div class="row">
  <div class="col-md-12">
    <div [formGroup]="create_recipe_form" (ngSubmit)="createRecipe()">
      <table class="table table-hover table-responsive table-bordered">
        <tr>
          <td>
            Name
          </td>
          <td>
            <input name="name" formControlName="name" type="text" class="form-control" required />
            <div *ngIf="create_recipe_form.get('name').touched && create_recipe_form.get('name').hasError('required')"
              class="alert alert-danger">Name is required
            </div>
          </td>
        </tr>

        <tr>
          <td>
            Description
          </td>
          <td>
            <textarea name="description" formControlName="description" class="form-control" required>

            </textarea>
            <div *ngIf="create_recipe_form.get('description').touched && create_recipe_form.get('description').hasError('required')"
              class="alert alert-danger">
              Description is required
            </div>
          </td>
        </tr>

        <tr>
          <td>
            Image
          </td>
          <td>
            <input name="selectFile" id="selectFile" type="file" class="form-control btn btn-success" />
            <button type="button" class="btn btn-primary" (click)="uploadImage($event)" value="Upload Image">Upload Image</button>
            <input type='hidden' id='image_id' name='img_id' value="6" formControlName="image_id" />
          </td>
        </tr>

        <tr>
          <td></td>
          <td>
            <button class="btn btn-primary" type="button" [disabled]="!create_recipe_form.valid">
                <span class="glyphicon glyphicon-plus"></span> Create
            </button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</div>
</code>```

Body:
I have a html form with two buttons on it:-

[1] One button is used to upload an image file (.jpg)
[2] and the second one is to submit the form.

The problem is that the upload image button seems to be refreshing the page after the method for uploading the image has completed. Below is my html:-

      Read Recipes

    <form [formGroup]="create_recipe_form" (ngSubmit)="createRecipe()">

            Name

            <input name="name" formControlName="name" type="text" class="form-control" required />

Name is required

            Description

            <textarea name="description" formControlName="description" class="form-control" required>

            </textarea>

              Description is required

            Image

            <input name="selectFile" id="selectFile" type="file" class="form-control btn btn-success" />
            <button type="button" class="btn btn-primary" (click)="uploadImage($event)" value="Upload Image">Upload Image</button>
            <input type='hidden' id='image_id' name='img_id' value="6" formControlName="image_id" />

            <button class="btn btn-primary" type="submit" [disabled]="!create_recipe_form.valid">
                 Create
            </button>

    </form>

My code for the uploadImage method is below:-

 uploadImage(e) {
    let files = this.elem.nativeElement.querySelector('#selectFile').files;
    let formData = new FormData();
    let file = files[0];

    formData.append('selectFile', file, file.name);

    this._imageService.uploadImage(formData)
      .subscribe(
        image => {
          console.log(image);
          this.addImageIdToHtml(image)
          e.preventDefault();
          e.stopPropagation();
        },
        error => console.log(error)
      );
  }

As soon as the above method has finished running the page appears to refreshing causing my app to go back to the land page. This is not the behaviour I want. What I actually want is the form page to be retained until the Submit form button is pressed. Can anyone help me please?

Body:
Use div tags instead of form tag.

Change the button type as button.

<button type="button">Upload Image</button>

Modify the code as follows.

<div class="m-b-18px">
  <div class="col-m-12">
    <a (click)="readRecipes()" class="btn btn-primary pull-right">
      <span class="glyphicon glyphicon-plus"></span>Read Recipes
    </a>
  </div>
</div>

<div class="row">
  <div class="col-md-12">
    <div [formGroup]="create_recipe_form" (ngSubmit)="createRecipe()">
      <table class="table table-hover table-responsive table-bordered">
        <tr>
          <td>
            Name
          </td>
          <td>
            <input name="name" formControlName="name" type="text" class="form-control" required />
            <div *ngIf="create_recipe_form.get('name').touched && create_recipe_form.get('name').hasError('required')"
              class="alert alert-danger">Name is required
            </div>
          </td>
        </tr>

        <tr>
          <td>
            Description
          </td>
          <td>
            <textarea name="description" formControlName="description" class="form-control" required>

            </textarea>
            <div *ngIf="create_recipe_form.get('description').touched && create_recipe_form.get('description').hasError('required')"
              class="alert alert-danger">
              Description is required
            </div>
          </td>
        </tr>

        <tr>
          <td>
            Image
          </td>
          <td>
            <input name="selectFile" id="selectFile" type="file" class="form-control btn btn-success" />
            <button type="button" class="btn btn-primary" (click)="uploadImage($event)" value="Upload Image">Upload Image</button>
            <input type='hidden' id='image_id' name='img_id' value="6" formControlName="image_id" />
          </td>
        </tr>

        <tr>
          <td></td>
          <td>
            <button class="btn btn-primary" type="button" [disabled]="!create_recipe_form.valid">
                <span class="glyphicon glyphicon-plus"></span> Create
            </button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</div>


问:
new never fails?
In C++, we usually see and write code like,

```<code>Sample sample=new Sample();
if ( sample == NULL )
{
     std::cout<<"Memory allocation failed" << std::endl;
}
</code>```

But in C#, I rarely see this: (at least I've never seen this)

```<code>Sample sample = new Sample();
if ( sample == null )
{
     Console.WriteLine("Memory allocation failed\n");
}
</code>```

Means, in C#, we rarely check if a new failed or not. Why is it so? Does it have something to do with "In C#, new never fails"?  Is there such a thing in C# that new never fails?

If it fails, then why such "check" is so rare in C#? I'm not talking about OutOfMemoryException, that is after all exception, not "check". I'm talking about the coding style.

答:
In C#, new throws an OutOfMemoryException if it fails, so a NULL check is not necessary.

Incidentally, the same applies in C++ as well - new throws std::bad_alloc if it fails, so there really is no need to test against NULL in C++ either.

ContentLicense: CC BY-SA 2.5

Title: new never fails?

Body:
In C++, we usually see and write code like,

Sample sample=new Sample();
if ( sample == NULL )
{
     std::cout<<"Memory allocation failed" << std::endl;
}

But in C#, I rarely see this: (at least I've never seen this)

Sample sample = new Sample();
if ( sample == null )
{
     Console.WriteLine("Memory allocation failed\n");
}

Means, in C#, we rarely check if a new failed or not. Why is it so? Does it have something to do with "In C#, new never fails"?  Is there such a thing in C# that new never fails?

If it fails, then why such "check" is so rare in C#? I'm not talking about OutOfMemoryException, that is after all exception, not "check". I'm talking about the coding style.


问:
How can I execute pl/pgsql code without creating a function?
With SQL Server, I can execute code ad hoc T-SQL code with full procedural logic through SQL Server Management Studio, or any other client. I've begun working with PostgreSQL and have run into a bit of a difference in that PGSQL requires any logic to be embedded in a function.

Is there a way to execute PL/PGSQL code without creating an executing a function?

答:
I struggled to get this working because it's fairly strict about adding semi colons in exactly the right places. But once you get used to that it works well. Besides the inability to return records of course, however you can raise notices & exceptions and do the other workarounds like using temp tables as @ErwinBrandstetter pointed out in a comment above.

e.g.:

```<code>DO
$$
BEGIN
  IF EXISTS(SELECT 'any rows?'
              FROM {your_table}
              WHERE {your_column} = 'blah')
  THEN
      RAISE NOTICE 'record exists';
  ELSE
      RAISE EXCEPTION 'record does not exist';
  END IF;

  DROP TABLE IF EXISTS foo;

  CREATE TEMP TABLE foo AS
  SELECT 'bar'::character varying(5) as baz;
END
$$;

SELECT * FROM foo;
</code>```

Body:
I struggled to get this working because it's fairly strict about adding semi colons in exactly the right places. But once you get used to that it works well. Besides the inability to return records of course, however you can raise notices & exceptions and do the other workarounds like using temp tables as @ErwinBrandstetter pointed out in a comment above.

e.g.:

DO
$$
BEGIN
  IF EXISTS(SELECT 'any rows?'
              FROM {your_table}
              WHERE {your_column} = 'blah')
  THEN
      RAISE NOTICE 'record exists';
  ELSE
      RAISE EXCEPTION 'record does not exist';
  END IF;

  DROP TABLE IF EXISTS foo;

  CREATE TEMP TABLE foo AS
  SELECT 'bar'::character varying(5) as baz;
END
$$;

SELECT * FROM foo;


问:
Webpack does not preserve symlinks in project path
I created a symlink for my "Dropbox (Personal)" folder so I could have an asset path without spaces. If I build my webpack project from a project there, however, it still uses the original path when running and referencing assets. I'm on OSX btw.

Current behavior

```<code>$ pwd
/Users/<me>/<SYMLINK>/<project>

$ webpack
> <project> dev /Users/<me>/<ORIGINAL>/<project>
</code>```

Desired behavior

```<code>$ pwd
/Users/<me>/<SYMLINK>/<project>

$ webpack
> <project> dev /Users/<me>/<SYMLINK>/<project>
</code>```

Does anyone know of a way to achieve the above? Thanks.

UPDATE

Turns out I needed to use a hard link for the Dropbox folder instead of a soft link. The soft link just meant it was basically an alias that always gets resolved to the real path. A hard link means it acts as an actual folder that contains links to the same data as the original. I used the following steps to do it properly:

Quit Dropbox app

$ mv "Dropbox (Personal)" Dropbox

$ ln -s Dropbox "Dropbox (Personal)"

I can now effectively use the Dropbox directory exactly the same as Dropbox Personal.

Also removing the webpack tag since the issue turned out to be unrelated to webpack.

Body:
I created a symlink for my "Dropbox (Personal)" folder so I could have an asset path without spaces. If I build my webpack project from a project there, however, it still uses the original path when running and referencing assets. I'm on OSX btw.

Current behavior

$ pwd
/Users/<me>/<SYMLINK>/<project>

$ webpack
> <project> dev /Users/<me>/<ORIGINAL>/<project>

Desired behavior

$ pwd
/Users/<me>/<SYMLINK>/<project>

$ webpack
> <project> dev /Users/<me>/<SYMLINK>/<project>

Does anyone know of a way to achieve the above? Thanks.

UPDATE

Turns out I needed to use a hard link for the Dropbox folder instead of a soft link. The soft link just meant it was basically an alias that always gets resolved to the real path. A hard link means it acts as an actual folder that contains links to the same data as the original. I used the following steps to do it properly:

Quit Dropbox app

$ mv "Dropbox (Personal)" Dropbox

$ ln -s Dropbox "Dropbox (Personal)"

I can now effectively use the Dropbox directory exactly the same as Dropbox Personal.

Also removing the webpack tag since the issue turned out to be unrelated to webpack.


问:
pthread_create Memory Leaks
I am trying to code a very basic multi-threaded TCP client server system and have managed to get the main functionality working as well as sorted any memory problems except for one.

When its time for the server to shutdown, I have it set up to receive and handle a SIGINT signal which will close the listen and connfd as well as do some arbitrary output.

The problem being that valgrind reports a memory leak on exit which it says is from pthread_create and threads being left active on exit. The leak is the size of 272 bytes for each connected user at the time.

The code for the sig handler and main are as follows:

```<code>struct timeval t1, t2;
int connfd = 0;
int listenfd = 0;
pthread_t sniffer_thread;

static void SIGhandler(int sig, siginfo_t *siginfo, void *context)
{

    pthread_join(sniffer_thread, NULL);

    shutdown(connfd, SHUT_RDWR);
    shutdown(listenfd, SHUT_RDWR);

gettimeofday(&t2, NULL);

    double totalSeconds = (double) (t2.tv_usec - t1.tv_usec) / 1000000 + (double) (t2.tv_sec - t1.tv_sec) ;

    int seconds = ((int)totalSeconds % 60);
    int minutes = ((int)totalSeconds % 3600) / 60;
    int hours = ((int)totalSeconds % 86400) / 3600;
    int days = ((int)totalSeconds % (86400 * 30)) / 86400;

    printf("\n\nServer shutdown request received");
    printf ("\nTotal server up time = %d days %d hours %d minutes and %d seconds\n\n",days, hours ,minutes , seconds);

    close(connfd);
    close(listenfd);

exit(EXIT_SUCCESS);
}

int main(void)
{

    gettimeofday(&t1, NULL);

struct sigaction act;

memset(&act, '\0', sizeof(act));

// this is a pointer to a function
act.sa_sigaction = &SIGhandler;

// the SA_SIGINFO flag tells sigaction() to use the sa_sigaction field, not sa_handler
act.sa_flags = SA_SIGINFO;

if (sigaction(SIGINT, &act, NULL) == -1) {
perror("sigaction");
exit(EXIT_FAILURE);
}

struct sockaddr_in serv_addr;
struct sockaddr_in client_addr;
socklen_t socksize = sizeof(struct sockaddr_in);
listenfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, '0', sizeof(serv_addr));

serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(50001);

bind(listenfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));

if (listen(listenfd, 10) == -1) {
perror("Failed to listen");
exit(EXIT_FAILURE);
}
// end socket setup

//Accept and incoming connection
puts("Waiting for incoming connections...");
while (1) {
printf("Waiting for a client to connect...\n\n");
connfd =
    accept(listenfd, (struct sockaddr *) &client_addr, &socksize);

printf("\n\nConnection established with: %s\n", inet_ntoa(client_addr.sin_addr));
printf("%s is connected on socket:  %d\n",inet_ntoa(client_addr.sin_addr),connfd);

    // third parameter is a pointer to the thread function, fourth is its actual parameter
if (pthread_create
    (&sniffer_thread, NULL, client_handler,
     (void *) &connfd) < 0) {
    perror("could not create thread");
    exit(EXIT_FAILURE);
}

printf("Handler assigned\n\n");
}

// never reached...
exit(EXIT_SUCCESS);
} // end main()
</code>```

The client handler code is:

```<code>// thread function - one instance of each for each connected client
void *client_handler(void *socket_desc)
{
    pthread_detach(pthread_self());
//Get the socket descriptor
int connfd = *(int *) socket_desc;

send_conConfirm(connfd);

char choice[8];

do {
            get_menu_choice(connfd,choice);
            switch (*choice) {
            case '1':
                printf("Executing IP/ID return for socket: %d\n",connfd);
            send_studentID(connfd);
        break;
            case '2':
                printf("Executing server time return for socket: %d\n",connfd);
            send_serverTime(connfd);
        break;
            case '3':
                printf("Executing sys info return for socket: %d\n",connfd);
            send_uname(connfd);
        break;
            case '4':
                printf("Executing file list return for socket: %d\n",connfd);
            send_filenames(connfd,choice);
        break;
            case '5':
            send_filenames(connfd,choice);
        break;
            case '6':
                printf("Disconection choice on socket: %d\n",connfd);
        break;
            default:
            printf("Client on socket %d has been disconnected\n", connfd);
                goto jump;
        break;
        }
} while (*choice != '6' );

    jump: //jump for goto statement

shutdown(connfd, SHUT_RDWR);
close(connfd);

printf("Thread %lu exiting\n", (unsigned long) pthread_self());

return 0;
}  // end client_handler()
</code>```

I have tried many different ways including detaching the threads upon completion but always end up with this memory leak. Occasional the memory leak will occur even if the client has only connected and the server ends and other times it will only occur if the client connects and interacts with the server.

答:
You need to put a join before the end of your while loop, rather than in your signal catching function

I would recommend looking through the last few sections of this guide, a few problems with your code that they handle are:

joining the threads so that threads dont stay open because you are using
threading,

your connfd can be overwritten (as it exists in same
memory space across different threads)

adjusting your while loop to
run only while the connection is open (changing it to be on the
return of accept)

http://www.binarytides.com/socket-programming-c-linux-tutorial/

Title: pthread_create Memory Leaks

Body:
I am trying to code a very basic multi-threaded TCP client server system and have managed to get the main functionality working as well as sorted any memory problems except for one.

When its time for the server to shutdown, I have it set up to receive and handle a SIGINT signal which will close the listen and connfd as well as do some arbitrary output.

The problem being that valgrind reports a memory leak on exit which it says is from pthread_create and threads being left active on exit. The leak is the size of 272 bytes for each connected user at the time.

The code for the sig handler and main are as follows:

struct timeval t1, t2;
int connfd = 0;
int listenfd = 0;
pthread_t sniffer_thread;

static void SIGhandler(int sig, siginfo_t *siginfo, void *context)
{

    pthread_join(sniffer_thread, NULL);

    shutdown(connfd, SHUT_RDWR);
    shutdown(listenfd, SHUT_RDWR);

gettimeofday(&t2, NULL);

    double totalSeconds = (double) (t2.tv_usec - t1.tv_usec) / 1000000 + (double) (t2.tv_sec - t1.tv_sec) ;

    int seconds = ((int)totalSeconds % 60);
    int minutes = ((int)totalSeconds % 3600) / 60;
    int hours = ((int)totalSeconds % 86400) / 3600;
    int days = ((int)totalSeconds % (86400 * 30)) / 86400;

    printf("\n\nServer shutdown request received");
    printf ("\nTotal server up time = %d days %d hours %d minutes and %d seconds\n\n",days, hours ,minutes , seconds);

    close(connfd);
    close(listenfd);

exit(EXIT_SUCCESS);
}

int main(void)
{

    gettimeofday(&t1, NULL);

struct sigaction act;

memset(&act, '\0', sizeof(act));

// this is a pointer to a function
act.sa_sigaction = &SIGhandler;

// the SA_SIGINFO flag tells sigaction() to use the sa_sigaction field, not sa_handler
act.sa_flags = SA_SIGINFO;

if (sigaction(SIGINT, &act, NULL) == -1) {
perror("sigaction");
exit(EXIT_FAILURE);
}

struct sockaddr_in serv_addr;
struct sockaddr_in client_addr;
socklen_t socksize = sizeof(struct sockaddr_in);
listenfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, '0', sizeof(serv_addr));

serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(50001);

bind(listenfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));

if (listen(listenfd, 10) == -1) {
perror("Failed to listen");
exit(EXIT_FAILURE);
}
// end socket setup

//Accept and incoming connection
puts("Waiting for incoming connections...");
while (1) {
printf("Waiting for a client to connect...\n\n");
connfd =
    accept(listenfd, (struct sockaddr *) &client_addr, &socksize);

printf("\n\nConnection established with: %s\n", inet_ntoa(client_addr.sin_addr));
printf("%s is connected on socket:  %d\n",inet_ntoa(client_addr.sin_addr),connfd);

    // third parameter is a pointer to the thread function, fourth is its actual parameter
if (pthread_create
    (&sniffer_thread, NULL, client_handler,
     (void *) &connfd) < 0) {
    perror("could not create thread");
    exit(EXIT_FAILURE);
}

printf("Handler assigned\n\n");
}

// never reached...
exit(EXIT_SUCCESS);
} // end main()

The client handler code is:

// thread function - one instance of each for each connected client
void *client_handler(void *socket_desc)
{
    pthread_detach(pthread_self());
//Get the socket descriptor
int connfd = *(int *) socket_desc;

send_conConfirm(connfd);

char choice[8];

do {
            get_menu_choice(connfd,choice);
            switch (*choice) {
            case '1':
                printf("Executing IP/ID return for socket: %d\n",connfd);
            send_studentID(connfd);
        break;
            case '2':
                printf("Executing server time return for socket: %d\n",connfd);
            send_serverTime(connfd);
        break;
            case '3':
                printf("Executing sys info return for socket: %d\n",connfd);
            send_uname(connfd);
        break;
            case '4':
                printf("Executing file list return for socket: %d\n",connfd);
            send_filenames(connfd,choice);
        break;
            case '5':
            send_filenames(connfd,choice);
        break;
            case '6':
                printf("Disconection choice on socket: %d\n",connfd);
        break;
            default:
            printf("Client on socket %d has been disconnected\n", connfd);
                goto jump;
        break;
        }
} while (*choice != '6' );

    jump: //jump for goto statement

shutdown(connfd, SHUT_RDWR);
close(connfd);

printf("Thread %lu exiting\n", (unsigned long) pthread_self());

return 0;
}  // end client_handler()

I have tried many different ways including detaching the threads upon completion but always end up with this memory leak. Occasional the memory leak will occur even if the client has only connected and the server ends and other times it will only occur if the client connects and interacts with the server.


问:
Comparing arrays in javascript where order doesn't matter
I am learning Javascript, and I saw a function on SO for comparing arrays to check if they are same. However, my current function returns false if the two arrays are [string1,string2] & [string2,string1]. Basically, the two positions are interchanged. The code is as follows:

```<code>function _compareArrays(arr1,arr2){
    var result = arr1 != null && arr2 != null && arr1.length == arr2.length && arr1.every(function(element) {
            return arr2.indexOf(element);
        });
    return result ;
}
</code>```

However, I want these two arrays to be returned as same. So, I changed .every to .indexOf() and it seemed to work. But, I have a doubt, how exactly is the counter getting incremented here to make sure the comparison is being done for every element?
I mean, like, in C++, we do,

```<code>for (int i = 0; i < 10; i++)
    if (arr1[i] == arr2[i]
      cout<<"Elements are same\n";
</code>```

Here, I have an explicit i++ which increments the counter. How does it happen in the above function?

Thanks!

答:
Your current has these issues:

It will return true for these 2 arrays (I hope that you understand that this is not specific to these 2): [1, 2, 2], [1,1,2]. This problem is why I set indices to undefined after a match in my solution below.

indexOf returns -1 for element's it cannot find, and any number >= 0 if it can find the element, -1 is truthy, so if an element cannot be found, your comparison will return true, and 0 is falsy, so if an element is located in the first index of the second array, your method will return false (which means the whole thing will become false, because of every...). So, you should add a ~ before the result of indexOf call: ~arr2.indexOf(element).

See this
MDN page on the Bitwise Not operator (~) and how it solves the
indexOf problem I mentioned.

I also recommend that you take a look at this answer of mine on truthy/falsy values and how they interact with && and ||.

So Try this out (it's mostly your example, except there is no indexOf used and I have fixed problem #2):

function _compareArrays(arr1,arr2){
  if(!(arr1 != null && arr2 != null && arr1.length == arr2.length)) {
    return false;
  }

  /* copy the arrays so that the original arrays are not affected when we set the indices to "undefined" */
  arr1 = [].concat(arr1);
  arr2 = [].concat(arr2);

  return arr1.every(function(element, index) {
    return arr2.some(function(e, i) {
      return e === element && (arr2[i] = undefined, true);
    });
  });
}

var x = ["str", "boo", "str"];
var y = ["boo", "str", "str"];
var z = ["abc", "def", "ghi"]

console.log(_compareArrays(x, y));
console.log(_compareArrays(x, z));
console.log(_compareArrays(z, z));```

It won't work if the array has any undefined elements, though.

Body:
I am learning Javascript, and I saw a function on SO for comparing arrays to check if they are same. However, my current function returns false if the two arrays are [string1,string2] & [string2,string1]. Basically, the two positions are interchanged. The code is as follows:

function _compareArrays(arr1,arr2){
    var result = arr1 != null && arr2 != null && arr1.length == arr2.length && arr1.every(function(element) {
            return arr2.indexOf(element);
        });
    return result ;
}

However, I want these two arrays to be returned as same. So, I changed .every to .indexOf() and it seemed to work. But, I have a doubt, how exactly is the counter getting incremented here to make sure the comparison is being done for every element?
I mean, like, in C++, we do,

for (int i = 0; i < 10; i++)
    if (arr1[i] == arr2[i]
      cout<<"Elements are same\n";

Here, I have an explicit i++ which increments the counter. How does it happen in the above function?

Thanks!

Body:
Your current has these issues:

It will return true for these 2 arrays (I hope that you understand that this is not specific to these 2): [1, 2, 2], [1,1,2]. This problem is why I set indices to undefined after a match in my solution below.

indexOf returns -1 for element's it cannot find, and any number >= 0 if it can find the element, -1 is truthy, so if an element cannot be found, your comparison will return true, and 0 is falsy, so if an element is located in the first index of the second array, your method will return false (which means the whole thing will become false, because of every...). So, you should add a ~ before the result of indexOf call: ~arr2.indexOf(element).

See this
MDN page on the Bitwise Not operator (~) and how it solves the
indexOf problem I mentioned.

I also recommend that you take a look at this answer of mine on truthy/falsy values and how they interact with && and ||.

So Try this out (it's mostly your example, except there is no indexOf used and I have fixed problem #2):

function _compareArrays(arr1,arr2){
  if(!(arr1 != null && arr2 != null && arr1.length == arr2.length)) {
    return false;
  }

  /* copy the arrays so that the original arrays are not affected when we set the indices to "undefined" */
  arr1 = [].concat(arr1);
  arr2 = [].concat(arr2);

  return arr1.every(function(element, index) {
    return arr2.some(function(e, i) {
      return e === element && (arr2[i] = undefined, true);
    });
  });
}

var x = ["str", "boo", "str"];
var y = ["boo", "str", "str"];
var z = ["abc", "def", "ghi"]

console.log(_compareArrays(x, y));
console.log(_compareArrays(x, z));
console.log(_compareArrays(z, z));

It won't work if the array has any undefined elements, though.


问:
Angular condition and cssclass in same ngClass
I need to use both condition and class in same "ngClass" is there any possible way?

[ngClass]="{cssclass1 : object.cssclass1status , object.cssclass2}"

The bold part is the condition and italic part is a CSS class that can be changed. I have used this options separately like,

```<code>conditional [ngClass]="{cssclass1 : object.cssclass1status}"

object.cssclass1status : Boolean

classes [ngClass]="object.cssclass2"

object.cssclass2 : string
</code>```

答:
try like this :</p>

```<code><div [ngClass]="(object.cssclass1status && object.cssclass2=='stringVal') ? 'cssclass1' : ''"></div>
</code>```

Body:
I need to use both condition and class in same "ngClass" is there any possible way?

[ngClass]="{cssclass1 : object.cssclass1status , object.cssclass2}"

The bold part is the condition and italic part is a CSS class that can be changed. I have used this options separately like,

conditional [ngClass]="{cssclass1 : object.cssclass1status}"

object.cssclass1status : Boolean

classes [ngClass]="object.cssclass2"

object.cssclass2 : string

Body:
try like this :

<div [ngClass]="(object.cssclass1status && object.cssclass2=='stringVal') ? 'cssclass1' : ''"></div>


问:
Rails - two queries combining them without SCOPES
Given two queries like:

```<code>@users1 = Users.find_by_company_id(2)
@users2 = Users.find_by_office_id(2)
</code>```

I want to combine the two:

```<code>@users_to_show = @users1 + @users2
</code>```

Issue is how how to prevent duplicate users from showing. Is there a way to combine the two (array?) And then ensure that duplicate records are removed?

Thanks

UPDATED:

```<code># This QUERY gives all of a user's project members, people they work with
@project_ids = @projects.map(&:project_id)

@users = User.find_by_sql [
                            "SELECT DISTINCT users.*
                            FROM users
                              INNER JOIN permissions ON permissions.user_id = users.id
                            WHERE project_id IN (?) AND permissions.user_id != ?
                            UNION ALL
                            SELECT DISTINCT users.*
                            FROM users
                            WHERE instance_id = ?",
                            @project_ids, current_user.id, current_user.instance_id
                          ]
</code>```

答:
This is a manual SQL approach that may work for you:

```<code>@users = User.find_by_sql("
     SELECT DISTINCT * FROM USERS WHERE [Place your First complicated where clauses Here]
     UNION
     SELECT * FROM USERS WHERE instance_id = ?
", current_user.instance_id)
</code>```

EDIT:
UNION will elimate duplicate records between the two queries.

EDIT: Be sure that each of the queries do not produce duplicates independently. Union will not remove duplicates inside single queries.

Body:
Given two queries like:

@users1 = Users.find_by_company_id(2)
@users2 = Users.find_by_office_id(2)

I want to combine the two:

@users_to_show = @users1 + @users2

Issue is how how to prevent duplicate users from showing. Is there a way to combine the two (array?) And then ensure that duplicate records are removed?

Thanks

UPDATED:

# This QUERY gives all of a user's project members, people they work with
@project_ids = @projects.map(&:project_id)

@users = User.find_by_sql [
                            "SELECT DISTINCT users.*
                            FROM users
                              INNER JOIN permissions ON permissions.user_id = users.id
                            WHERE project_id IN (?) AND permissions.user_id != ?
                            UNION ALL
                            SELECT DISTINCT users.*
                            FROM users
                            WHERE instance_id = ?",
                            @project_ids, current_user.id, current_user.instance_id
                          ]

Body:
This is a manual SQL approach that may work for you:

@users = User.find_by_sql("
     SELECT DISTINCT * FROM USERS WHERE [Place your First complicated where clauses Here]
     UNION
     SELECT * FROM USERS WHERE instance_id = ?
", current_user.instance_id)

EDIT:
UNION will elimate duplicate records between the two queries.

EDIT: Be sure that each of the queries do not produce duplicates independently. Union will not remove duplicates inside single queries.


问:
Java Read Text File not completely
I write a program to read line by line result from a text file to check for certain condition using below code.

```<code>for (File f : readAllTxtFile) {
    if (f.getName().endsWith(".txt") && f.getName().length() > 28) {

                Scanner input = new Scanner(f);

                while (input.hasNextLine()) {
                    String lineResult = input.nextLine();

                    System.out.println(lineResult); // I print out the line result here

                    if (lineResult.contains("TER_GetCarrierInfo")) {
                       ...//do something
                        break;
                    }
                }
   }
 }
</code>```

My question is, why system only read until half of my txt file and stopped ?? it didnt continue reading the next line eventhough the condition if (lineResult.contains("TER_GetCarrierInfo")) is not exist/hit.
My txt file got thousand of line around 900++ kb

Can someone explain with me ?

Thanks and appreaciate

答:
Alright..
I try to change to use </p>

```<code>BufferedReader br = new BufferedReader(new FileReader(f));
</code>```

<p>and it work fine... hmmmm.... </p>

Title: Java Read Text File not completely

Body:
I write a program to read line by line result from a text file to check for certain condition using below code.

for (File f : readAllTxtFile) {
    if (f.getName().endsWith(".txt") && f.getName().length() > 28) {

                Scanner input = new Scanner(f);

                while (input.hasNextLine()) {
                    String lineResult = input.nextLine();

                    System.out.println(lineResult); // I print out the line result here

                    if (lineResult.contains("TER_GetCarrierInfo")) {
                       ...//do something
                        break;
                    }
                }
   }
 }

My question is, why system only read until half of my txt file and stopped ?? it didnt continue reading the next line eventhough the condition if (lineResult.contains("TER_GetCarrierInfo")) is not exist/hit.
My txt file got thousand of line around 900++ kb

Can someone explain with me ?

Thanks and appreaciate

Body:
Alright..
I try to change to use

BufferedReader br = new BufferedReader(new FileReader(f));

and it work fine... hmmmm....


问:
Using hardcoded data instead of CSV file in D3 graphs

Although I'm quite familiar with javasript.
For the first time I'm using D3 and example svg graph: http://bl.ocks.org/bbest/2de0e25d4840c68f2db1

in the example above, CSV file is used as data. (the file from example is aster_data.csv)

I want to use data array defined within the script instead of the file.

Instead of:

```<code>d3.csv('aster_data.csv', function(error, data) {
...
</code>```

I've added my array-

```<code>var myData= [
      {"id":"ABC","order":1,"score":50,"weight":1,"color":"#9E0041","label": "Line1"},
      {"id":"CDE","order":2,"score":60,"weight": 1,"color":"#C32F4B", "label": "Line2"}
];
d3.selection(myData, function(error, data) {
...
</code>```

However it doesn't work, not I can't see any errors in console.

答:
No selection.  The csv function fetches the csv, then calls the lambda with the corresponding data.  Just call the body of that lambda with your data in the data variable.

```<code>var data= [
  {"id":"ABC","order":1,"score":50,"weight":1,"color":"#9E0041","label": "Line1"},
  {"id":"CDE","order":2,"score":60,"weight": 1,"color":"#C32F4B", "label": "Line2"}
];

data.forEach(function(d) {
    d.id     =  d.id;
    d.order  = +d.order;
    d.color  =  d.color;
    d.weight = +d.weight;
    d.score  = +d.score;
    d.width  = +d.weight;
    d.label  =  d.label;
  });
// etc
</code>```

Body:
Although I'm quite familiar with javasript.
For the first time I'm using D3 and example svg graph: http://bl.ocks.org/bbest/2de0e25d4840c68f2db1

in the example above, CSV file is used as data. (the file from example is aster_data.csv)

I want to use data array defined within the script instead of the file.

Instead of:

d3.csv('aster_data.csv', function(error, data) {
...

I've added my array-

var myData= [
      {"id":"ABC","order":1,"score":50,"weight":1,"color":"#9E0041","label": "Line1"},
      {"id":"CDE","order":2,"score":60,"weight": 1,"color":"#C32F4B", "label": "Line2"}
];
d3.selection(myData, function(error, data) {
...

However it doesn't work, not I can't see any errors in console.

Body:
No selection.  The csv function fetches the csv, then calls the lambda with the corresponding data.  Just call the body of that lambda with your data in the data variable.

var data= [
  {"id":"ABC","order":1,"score":50,"weight":1,"color":"#9E0041","label": "Line1"},
  {"id":"CDE","order":2,"score":60,"weight": 1,"color":"#C32F4B", "label": "Line2"}
];

data.forEach(function(d) {
    d.id     =  d.id;
    d.order  = +d.order;
    d.color  =  d.color;
    d.weight = +d.weight;
    d.score  = +d.score;
    d.width  = +d.weight;
    d.label  =  d.label;
  });
// etc


问:
How can you pass a function as a template parmater where the function return is same as the template parameter?
I am trying to figure out how I can make a template class that works like the following:

```<code>template<typename T, typename Fn>
class Point
{
public:
    T x;
    T y;

    void pt(const std::string& x_str, const std::string& y_str)
    {
          x = Fn(x_str);
          y = Fn(y_str);
    }
    .... more Point stuff ....
};

typedef Point<float, std::stof> FPoint;
typedef Point<int, std::stoi> IPoint;
.....
</code>```

and then when I read a string - say "100.25,200.25", I could split on "," (which I actually have figured out how to do, and then say, set that point:

```<code>FPoint a;
a.pt("100.25","200.25")
</code>```

so far I have tried defining directly as I have above, I have tried:

```<code>template<typename T, T (C*)(const std::string&)>
.....
</code>```

and

```<code>template<typename T, T Fn(const std::string&)>
......
</code>```

and then doing:
    typedef Point FloatPoint;

and I get various errors like  cannot convert from 'overloaded-function' to 'float (__cdecl *)(const std::string &)'or 'std::stof' is not a valid template type argument for parameter 'convert_func' depending on how I try to define the parameter.  Any hints - nothing I have googled has seemed to help.

Thanks!

答: I think I figured it out - std::stof is actually std::stof(const string&, size_t*).  I put that in the template parameter (T (C*)(const std::string&, size_t*) and now I get errors in paces where I use Point as not having enough parameters.  After I fix that up, if I am still wrong, I'll come back and remove this answer.</p>

Body:
I am trying to figure out how I can make a template class that works like the following:

template<typename T, typename Fn>
class Point
{
public:
    T x;
    T y;

    void pt(const std::string& x_str, const std::string& y_str)
    {
          x = Fn(x_str);
          y = Fn(y_str);
    }
    .... more Point stuff ....
};

typedef Point<float, std::stof> FPoint;
typedef Point<int, std::stoi> IPoint;
.....

and then when I read a string - say "100.25,200.25", I could split on "," (which I actually have figured out how to do, and then say, set that point:

FPoint a;
a.pt("100.25","200.25")

so far I have tried defining directly as I have above, I have tried:

template<typename T, T (C*)(const std::string&)>
.....

and

template<typename T, T Fn(const std::string&)>
......

and then doing:
    typedef Point FloatPoint;

and I get various errors like  cannot convert from 'overloaded-function' to 'float (__cdecl *)(const std::string &)'or 'std::stof' is not a valid template type argument for parameter 'convert_func' depending on how I try to define the parameter.  Any hints - nothing I have googled has seemed to help.

Thanks!


答:
```<code>Sample sample=new Sample();
if ( sample == NULL )
{
     // You will never get here!
     std::cout<<"Memory allocation failed" << std::endl;
}
</code>```

We don't write this in C++ either. "Memory allocation failed" will never appear. In both languages you get an exception if the allocation fails. In C++ it's std::bad_alloc, in C# it's OutOfMemoryException.

Title: new never fails?

Body:
Sample sample=new Sample();
if ( sample == NULL )
{
     // You will never get here!
     std::cout<<"Memory allocation failed" << std::endl;
}

We don't write this in C++ either. "Memory allocation failed" will never appear. In both languages you get an exception if the allocation fails. In C++ it's std::bad_alloc, in C# it's OutOfMemoryException.


答:
Here's a simple solution using a set and list comprehension:

```<code>def get_similar(author_list, author):
    similar = set(author_list.get(author, []))
    similar.update(*[author_list.get(item, []) for item in similar])
    return sorted(similar)

get_similar(authors, 'Harlan Ellison')
</code>```

Output:

```<code>['Chris Moore', 'Douglas Adams', 'Jeff Vandemeer', 'Kurt Vonnegut',
 'Neil Stephenson', 'Richard Morgan', 'Terry Pratchett', 'Tom Robbins']
</code>```

Title: Return a list of similar authors

Body:
I'm trying to write a function that will return a list of items from a key from a key (if that makes sense). For example, here's a dictionary of authors, and similar authors.

authors = {
    'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'],
    'Harlan Ellison': ['Neil Stephenson', 'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'],
    'Kurt Vonnegut': ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer'],
    'Thomas Pynchon': ['Isaac Asimov', 'Jorges Borges', 'Robert Heinlein'],
    'Isaac Asimov': ['Stephen Baxter', 'Ray Bradbury', 'Arthur Clarke', 'Kurt Vonnegut', 'Neil Stephenson'],
    'Douglas Adams': ['Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
}

And the function I came up with is this:

def get_similar(author_list, author):
    for item in author_list[author]:
        return author_list[author]

Which only returns the items for the first key. I'd like it to return all of the similar authors, like this:

get_similar(authors, 'Harlan Ellison')

['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson',
 'Jeff Vandemeer','Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']

Where it finds the key given (author), looks at the items listed for that key, and then returns those key's items. In this case Harlan Ellison has four authors listed - Neil Stephenson, Kurt Vonnegut, Richard Morgan, and Douglas Adams. The function then looks up those authors, and returns the items listed for them - Kurt Vonnegut returns Terry Pratchett, Tom Robbins, Douglas Adams, Neil Stephenson, and Jeff Vandemeer, and Douglas Adams returns Terry Pratchett, Chris Moore, and Kurt Vonnegut,

Duplicates are fine, and I'd like it in alphabetical order (I assume you could just use a sort command at the end) Any help would be much appreciated, I'm stumped!

Body:
Here's a simple solution using a set and list comprehension:

def get_similar(author_list, author):
    similar = set(author_list.get(author, []))
    similar.update(*[author_list.get(item, []) for item in similar])
    return sorted(similar)

get_similar(authors, 'Harlan Ellison')

Output:

['Chris Moore', 'Douglas Adams', 'Jeff Vandemeer', 'Kurt Vonnegut',
 'Neil Stephenson', 'Richard Morgan', 'Terry Pratchett', 'Tom Robbins']


问:
Sort an array of names except for one item
Considering that I have an object like the following where it's possible to have many names and that 'The others' can appear at any index, how can I sort the array having 'The others' always as the first element and the rest of the names sorted in alphabetical order?

```<code>var friends = [
{ id: 1, name: 'Paul' },
{ id: 2, name: 'Mary' },
{ id: 3, name: 'The others' },
{ id: 4, name: 'John' }
];
</code>```

For the sample array above, the desired result would be:

```<code>[
   { id: 3, name: 'The others' },
   { id: 4, name: 'John' },
   { id: 2, name: 'Mary' },
   { id: 1, name: 'Paul' }
]
</code>```

答:
Simply check for either value in the sort callback being The others - return -1 if a is that, or 1 if it's b - otherwise return the localeCompare of a and b

```<code>friends.sort(({name: a}, {name:b}) => a == "The others" ? -1 : (b == "The others" ? 1 : a.localeCompare(b)));
</code>```

The "readable" and non-ES2015+ version of that

```<code>friends.sort(function (a, b) {
  if (a.name == "The others") return -1;
  if (b.name == "The others") return 1;
  return a.name.localeCompare(b.name);
});
</code>```

Body:
Considering that I have an object like the following where it's possible to have many names and that 'The others' can appear at any index, how can I sort the array having 'The others' always as the first element and the rest of the names sorted in alphabetical order?

var friends = [
{ id: 1, name: 'Paul' },
{ id: 2, name: 'Mary' },
{ id: 3, name: 'The others' },
{ id: 4, name: 'John' }
];

For the sample array above, the desired result would be:

[
   { id: 3, name: 'The others' },
   { id: 4, name: 'John' },
   { id: 2, name: 'Mary' },
   { id: 1, name: 'Paul' }
]

Body:
Simply check for either value in the sort callback being The others - return -1 if a is that, or 1 if it's b - otherwise return the localeCompare of a and b

friends.sort(({name: a}, {name:b}) => a == "The others" ? -1 : (b == "The others" ? 1 : a.localeCompare(b)));

The "readable" and non-ES2015+ version of that

friends.sort(function (a, b) {
  if (a.name == "The others") return -1;
  if (b.name == "The others") return 1;
  return a.name.localeCompare(b.name);
});


答:
Following are steps that you need to follow

Sort : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Move : Move an array element from one array position to another

Please see following working example.

var friends = [{
    id: 1,
    name: 'Paul'
  },
  {
    id: 2,
    name: 'Mary'
  },
  {
    id: 3,
    name: 'The others'
  },
  {
    id: 4,
    name: 'John'
  }
];

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
friends.sort(function(a, b) {
  var nameA = a.name.toUpperCase(); // ignore upper and lowercase
  var nameB = b.name.toUpperCase(); // ignore upper and lowercase
  if (nameA < nameB) {
    return -1;
  }
  if (nameA > nameB) {
    return 1;
  }

  // names must be equal
  return 0;
});

var indexOfTheOters = friends.reduce(function(acc, friend, index) {
  if(!acc && friend.name === 'The others') {
    acc = index;
  }
  return acc;
}, null);

// https://stackoverflow.com/questions/5306680/move-an-array-element-from-one-array-position-to-another
Array.prototype.move = function (old_index, new_index) {
    if (new_index >= this.length) {
        var k = new_index - this.length;
        while ((k--) + 1) {
            this.push(undefined);
        }
    }
    this.splice(new_index, 0, this.splice(old_index, 1)[0]);
    return this; // for testing purposes
};
friends.move(indexOfTheOters, 0)
console.log(friends);```

Title: Sort an array of names except for one item


问:
Group a collection by a certain criteria
so I have a collection in mongoDB that has an structure like the following:

```<code>{
    "_id": 129flaslkfja,
    "number": 10
}
</code>```

in this collection some elements have the number field set to 1 others to 2, others to 3, etc. in random order. I want to get an array that has in the first position all models with the number 1 in the next position all the models with the number  2 and so on. I know I can do this with a loop and a simple find or where but I want to know if there's a simpler, cleaner and more effective way in terms of performance.

I have tried with $group, $match but this is not what I want.

For example this is the data in my database:

```<code>[{
  "_id": a1,
  "number": 1
},
{
  "_id": a2,
  "number": 3
},
{
  "_id": a3,
  "number": 2
},
{
  "_id": a4,
  "number": 2
},
{
  "_id": a5,
  "number": 2
},
{
  "_id": a6,
  "number": 1
}]
</code>```

So I want to group by number value like this:

```<code>[
    [{
      "_id": a1,
      "number": 1
    },
    {
      "_id": a6,
      "number": 1
    }],

    [{
      "_id": a3,
      "number": 2
    },
    {
      "_id": a4,
      "number": 2
    },
    {
      "_id": a5,
      "number": 2
    }],

    [{
      "_id": a2,
      "number": 3
    }]
]
</code>```

答:
In ruby you can do:

```<code>original_list.group_by {|x| x[:number]}.values
</code>```

It's not clear if you were asking for a Ruby solution, though.

Body:
so I have a collection in mongoDB that has an structure like the following:

{
    "_id": 129flaslkfja,
    "number": 10
}

in this collection some elements have the number field set to 1 others to 2, others to 3, etc. in random order. I want to get an array that has in the first position all models with the number 1 in the next position all the models with the number  2 and so on. I know I can do this with a loop and a simple find or where but I want to know if there's a simpler, cleaner and more effective way in terms of performance.

I have tried with $group, $match but this is not what I want.

For example this is the data in my database:

[{
  "_id": a1,
  "number": 1
},
{
  "_id": a2,
  "number": 3
},
{
  "_id": a3,
  "number": 2
},
{
  "_id": a4,
  "number": 2
},
{
  "_id": a5,
  "number": 2
},
{
  "_id": a6,
  "number": 1
}]

So I want to group by number value like this:

[
    [{
      "_id": a1,
      "number": 1
    },
    {
      "_id": a6,
      "number": 1
    }],

    [{
      "_id": a3,
      "number": 2
    },
    {
      "_id": a4,
      "number": 2
    },
    {
      "_id": a5,
      "number": 2
    }],

    [{
      "_id": a2,
      "number": 3
    }]
]

Body:
In ruby you can do:

original_list.group_by {|x| x[:number]}.values

It's not clear if you were asking for a Ruby solution, though.


问:
ng-repeat for nested array in angular
I am getting data in nested array.

I am trying to display my data in this format

```<code>Jan

01 Mon newyear
13 sat bhogi
14 sun pongal

Feb

14 tue Valentine's day
</code>```

Am little bit confused to loop it.

This is what I have tried

```<code><table ng-repeat="list in holidayList" style="width:100%">
                            <thead>
                                <tr>
                                    @*<th>{{list.}}</th>*@
                                </tr>
                            </thead>
                            <tbody>
                                <tr ng-repeat="leave in list">
                                    <td width="14%">{{leave.date}}</td>
                                    <td width="20%">{{leave.monthCode}}</td>
                                    <td>{{leave.holiday_name}}</td>
                                </tr>
                            </tbody>
                        </table>
</code>```

Converting date is doesn't matter I wrote custom filter and method for that so I can get expected date format by using this filter and method:

```<code>app.filter('jsonDate', function () {
    return function (date) {
        return new Date(date.match(/\d+/)[0] * 1);
    }
})

$scope.dateFormat = function (date) {
        $scope.formattedDate = date.getFullYear() + "-" + (((date.getMonth() + 1).length) == 2 ? (date.getMonth() + 1) : ("0" + (date.getMonth() + 1))) + "-" + ((date.getDay().length) == 2 ? date.getDay() : ("0" + date.getDay()));
        return $scope.formattedDate
    }
</code>```

Current output:

```<code>/Date(1484397151447)/   1   pongal
/Date(1484310751447)/   1   Bhogi
/Date(1483273951447)/   1   new year
/Date(1494855933060)/   5   may day
</code>```

Can any one tell me that how should I loop to get expected format.

答:
You could just directly access the object: (I am assuming that the month is defined in each array item)

```<code><table ng-repeat="list in holidayList" style="width:100%">
    <tbody>
        <tr>
            <td>{{list[0].month}}</td>
        </td>
        <tr ng-repeat="leave in list">
            <td width="14%">{{leave.date}}</td>
            <td width="20%">{{leave.monthCode}}</td>
            <td>{{leave.holiday_name}}</td>
        </tr>
    </tbody>
</table>
</code>```

If month is not defined then use javascript array for months:

```<code>$scope.months = ["Jan", "February, "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
</code>```

Then on your html:

```<code><td>{{months(list[0].monthCode - 1)}}</td>
</code>```

or just list[0].monthCode if monthCode starts with 0 for Jan.

Title: ng-repeat for nested array in angular

Body:
I am getting data in nested array.

I am trying to display my data in this format

Jan

01 Mon newyear
13 sat bhogi
14 sun pongal

Feb

14 tue Valentine's day

Am little bit confused to loop it.

This is what I have tried

                                    @*{{list.}}	*@

                                    {{leave.date}}
                                    {{leave.monthCode}}
                                    {{leave.holiday_name}}

Converting date is doesn't matter I wrote custom filter and method for that so I can get expected date format by using this filter and method:

app.filter('jsonDate', function () {
    return function (date) {
        return new Date(date.match(/\d+/)[0] * 1);
    }
})

$scope.dateFormat = function (date) {
        $scope.formattedDate = date.getFullYear() + "-" + (((date.getMonth() + 1).length) == 2 ? (date.getMonth() + 1) : ("0" + (date.getMonth() + 1))) + "-" + ((date.getDay().length) == 2 ? date.getDay() : ("0" + date.getDay()));
        return $scope.formattedDate
    }

Current output:

/Date(1484397151447)/   1   pongal
/Date(1484310751447)/   1   Bhogi
/Date(1483273951447)/   1   new year
/Date(1494855933060)/   5   may day

Can any one tell me that how should I loop to get expected format.

Body:
You could just directly access the object: (I am assuming that the month is defined in each array item)

<table ng-repeat="list in holidayList" style="width:100%">
    <tbody>
        <tr>
            <td>{{list[0].month}}</td>
        </td>
        <tr ng-repeat="leave in list">
            <td width="14%">{{leave.date}}</td>
            <td width="20%">{{leave.monthCode}}</td>
            <td>{{leave.holiday_name}}</td>
        </tr>
    </tbody>
</table>

If month is not defined then use javascript array for months:

$scope.months = ["Jan", "February, "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

Then on your html:

<td>{{months(list[0].monthCode - 1)}}</td>

or just list[0].monthCode if monthCode starts with 0 for Jan.


问:
Numpy Zeros and String Data Type
I have an 18x18 grid of Numpy Zeros and I have 1's and 2's randomly filling the board using the code below.

```<code>import numpy as np
a=np.zeros(324)
p=np.random.permutation(324)
a[p[:30]]=1
a[p[30:60]]=2
a.reshape(18,18)
</code>```

And it returns the correct numpy array. However, I want to add a random X in there so I changed the first line of the code above to look like

```<code>a=np.zeros(324,dtype=str)
</code>```

However, when I run the code, all of the zeros in the array disappears. It just shows up as '_'(without the underscore). Any thoughts to be able to have strings in the array but also have zeros?

Or a better way to create an 18x18 grid that can have strings in it?

Title: Numpy Zeros and String Data Type

Body:
I have an 18x18 grid of Numpy Zeros and I have 1's and 2's randomly filling the board using the code below.

import numpy as np
a=np.zeros(324)
p=np.random.permutation(324)
a[p[:30]]=1
a[p[30:60]]=2
a.reshape(18,18)

And it returns the correct numpy array. However, I want to add a random X in there so I changed the first line of the code above to look like

a=np.zeros(324,dtype=str)

However, when I run the code, all of the zeros in the array disappears. It just shows up as '_'(without the underscore). Any thoughts to be able to have strings in the array but also have zeros?

Or a better way to create an 18x18 grid that can have strings in it?

Body:
A 'zero' for dtype=str is a blank, not 0 or even '0':

In [1]: a = np.zeros((3,3))
In [2]: a
Out[2]:
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])
In [3]: a = np.zeros((3,3),int)
In [4]: a
Out[4]:
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])
In [5]: a = np.zeros((3,3),bool)
In [6]: a
Out[6]:
array([[False, False, False],
       [False, False, False],
       [False, False, False]], dtype=bool)
In [7]: a = np.zeros((3,3),str)
In [8]: a
Out[8]:
array([['', '', ''],
       ['', '', ''],
       ['', '', '']],
      dtype='<U1')

Often it is better to specify the string length as well, but you still get blanks:

In [9]: a = np.zeros((3,3),'U4')
In [10]: a
Out[10]:
array([['', '', ''],
       ['', '', ''],
       ['', '', '']],
      dtype='<U4')

You could convert an integer array to string, and add other string values:

In [11]: a = np.zeros((3,3),int)
In [12]: a[[0,1,2],[2,0,1]] = [1,2,3]
In [13]: a
Out[13]:
array([[0, 0, 1],
       [2, 0, 0],
       [0, 3, 0]])
In [14]: A = a.astype(str)
In [15]: A
Out[15]:
array([['0', '0', '1'],
       ['2', '0', '0'],
       ['0', '3', '0']],
      dtype='<U11')
In [16]: A[[0,1,2],[0,1,2]] = 'X'
In [17]: A
Out[17]:
array([['X', '0', '1'],
       ['2', 'X', '0'],
       ['0', '3', 'X']],
      dtype='<U11')

The original 0s turn into string '0'.


问:
Dagger2 annotation processor is not working
I try to use Dagger2 in my Android project;
When I use apt, every things is right.But apt is not supported in AndroidStudio 3.0, so I use annotation processor.But no Dagger2 code created after I click "Make Project";
And I'm sure the annotetion processing is enable in AndroidStudio,because the Butterknife annotation processor is all right.
the follow is the build.gradle:</p>

```<code>dependencies {
    annotationProcessor 'com.google.dagger:dagger-android-processor:2.13'
    compile 'com.google.dagger:dagger-android:2.13'
    compile 'com.google.dagger:dagger-android-support:2.13'
    compile 'com.jakewharton:butterknife:8.6.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0'
}
</code>```

答:
these are the dependences for dagger2 and butter in andriod studio 3.0</p>

```<code>  //ButterKniffe
compile "com.jakewharton:butterknife:8.8.1"
kapt "com.jakewharton:butterknife-compiler:8.8.1"

//dagger
compile "com.google.dagger:dagger:$dagger_version"
kapt "com.google.dagger:dagger-compiler:$dagger_version"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I try to use Dagger2 in my Android project;
When I use apt, every things is right.But apt is not supported in AndroidStudio 3.0, so I use annotation processor.But no Dagger2 code created after I click "Make Project";
And I'm sure the annotetion processing is enable in AndroidStudio,because the Butterknife annotation processor is all right.
the follow is the build.gradle:

dependencies {
    annotationProcessor 'com.google.dagger:dagger-android-processor:2.13'
    compile 'com.google.dagger:dagger-android:2.13'
    compile 'com.google.dagger:dagger-android-support:2.13'
    compile 'com.jakewharton:butterknife:8.6.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0'
}

Body:
these are the dependences for dagger2 and butter in andriod studio 3.0

  //ButterKniffe
compile "com.jakewharton:butterknife:8.8.1"
kapt "com.jakewharton:butterknife-compiler:8.8.1"

//dagger
compile "com.google.dagger:dagger:$dagger_version"
kapt "com.google.dagger:dagger-compiler:$dagger_version"


答:
Make the second parameter be a function pointer:
template
class Point
{};

Note that neither std::stof or std::stoi would be valid arguments for that template (they both take additional arguments), but it would be fairly easy to create wrappers that rely on the default parameters (the template argument has to match types exactly, while the call does not):
typedef Point fPoint;

Title: How can you pass a function as a template parmater where the function return is same as the template parameter?


问:
Read remote file beginning with "smb://" using R
To read a file in R, I'd normally do something like the following:

```<code>read.csv('/Users/myusername/myfilename.csv')
</code>```

But, I'm trying to read a file located on a remote server (Windows SMB/CIFS share) which I access on my Mac via the Finder → Go → Connect to Server menu item.

When I view that file's properties, the file path is different than what I'm used to. Instead of beginning with: /Users/myusername/..., it is smb://server.msu.edu/.../myfilename.csv.

Trying to read the file, I tried the following:

```<code>read.csv('smb://server.msu.edu/.../myfilename.csv')
</code>```

But, this didn't work.

Instead of the usual "No such file or directory" error, this returned:

smb://server.msu.edu/.../myfilename.csv does not exist in current working directory

I imagine the file path needs a different format, but I can't figure what.

How can you read this type of file in R?

答:
Explanation

smb://educ-srvmedia1.campusad.msu.edu/... is actually a URL not a file path.

Let's break this down

smb:// means use the server message block protocol (file sharing)

educ-srvmedia1.campusad.msu.edu is the name of the server

/.../myfilename.csv is the file share/path on the remote server

You are able to navigate to this directory using Finder on OSX because it has built in support for the SMB protocol. Finder connects to the remote service using the URL and allows you to browse the files.

However R has no understanding of the SMB protocol so can't interpret the file path properly.

The R function read.csv() uses file() internally, see https://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html

url and file support URL schemes file://, http://, https:// and ftp://

So R returns "unable to locate the file" message because the file cannot be found because the protocol is unsupported. yes, slightly confusing.

Fix

You need to mount the file share on your local filesystem.

All this means is that the details of the SMB protocol will be handled behind the scenes by the OS and the fileshare will be presented as a local directory.

This will allow R (and other programs) to treat the remote files for all intents and purposes, like any other local files.
This discussion shows some options for doing so.

e.g.

```<code># need to create /LocalFolder first
mount -t cifs //username:password@hostname/sharename /LocalFolder
</code>```

then in R:

```<code>read.csv('/LocalFolder/myfilename.csv')
</code>```

Extra

Windows users can accomplish this easier with UNC paths

How to read files from a UNC-specified directory in R?

Body:
To read a file in R, I'd normally do something like the following:

read.csv('/Users/myusername/myfilename.csv')

But, I'm trying to read a file located on a remote server (Windows SMB/CIFS share) which I access on my Mac via the Finder → Go → Connect to Server menu item.

When I view that file's properties, the file path is different than what I'm used to. Instead of beginning with: /Users/myusername/..., it is smb://server.msu.edu/.../myfilename.csv.

Trying to read the file, I tried the following:

read.csv('smb://server.msu.edu/.../myfilename.csv')

But, this didn't work.

Instead of the usual "No such file or directory" error, this returned:

smb://server.msu.edu/.../myfilename.csv does not exist in current working directory

I imagine the file path needs a different format, but I can't figure what.

How can you read this type of file in R?

Body:
Explanation

smb://educ-srvmedia1.campusad.msu.edu/... is actually a URL not a file path.

Let's break this down

smb:// means use the server message block protocol (file sharing)

educ-srvmedia1.campusad.msu.edu is the name of the server

/.../myfilename.csv is the file share/path on the remote server

You are able to navigate to this directory using Finder on OSX because it has built in support for the SMB protocol. Finder connects to the remote service using the URL and allows you to browse the files.

However R has no understanding of the SMB protocol so can't interpret the file path properly.

The R function read.csv() uses file() internally, see https://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html

url and file support URL schemes file://, http://, https:// and ftp://

So R returns "unable to locate the file" message because the file cannot be found because the protocol is unsupported. yes, slightly confusing.

Fix

You need to mount the file share on your local filesystem.

All this means is that the details of the SMB protocol will be handled behind the scenes by the OS and the fileshare will be presented as a local directory.

This will allow R (and other programs) to treat the remote files for all intents and purposes, like any other local files.
This discussion shows some options for doing so.

e.g.

# need to create /LocalFolder first
mount -t cifs //username:password@hostname/sharename /LocalFolder

then in R:

read.csv('/LocalFolder/myfilename.csv')

Extra

Windows users can accomplish this easier with UNC paths

How to read files from a UNC-specified directory in R?


问:
JavaScript for loop adding objects to objects
I have an array (data) formatted like so:

["1", "open_order", "form", "county", "San Diego", "title_officer", "Peter", "0"]
["2", "open_order", "form", "county", "San Diego", "branch", "MV", "0"]```
</div>
</div>
</p>

<p>When I put this through a for loop and add it to the dataObject, console.log(dataObject) gives me all of the entries (this is what I want!)
However, console.log(o) shows that the last entry is going into the o object for both records.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() {
  var o = {};
  var dataObject = {};
  var i = 0;
  var predata = $('#preferences').text();
  var data = JSON.parse(predata);
    for(i = 0; i < data.length; i++) {
      dataObject['preferenceId'] = data[i][0];
      dataObject['pageName'] = data[i][1];
      dataObject['preferenceType'] = data[i][2];
      dataObject['baseField'] = data[i][3];
      dataObject['baseValue'] = data[i][4];
      dataObject['targetField'] = data[i][5];
      dataObject['targetValue'] = data[i][6];
      dataObject['conditionalId'] = data[i][7];
        o[i] = dataObject;
        console.log(dataObject);
    }
  console.log(o);
});</code>```

```

Any ideas why dataObject would be the same for all objects added to the o object?

答:
You should init the dataObject inside the loop to make a new variable.

```<code>for(i = 0; i < data.length; i++) {
    var dataObject = {}; /* Init the variable here */
    dataObject['preferenceId'] = data[i][0];
    dataObject['pageName'] = data[i][1];
    dataObject['preferenceType'] = data[i][2];
    dataObject['baseField'] = data[i][3];
    dataObject['baseValue'] = data[i][4];
    dataObject['targetField'] = data[i][5];
    dataObject['targetValue'] = data[i][6];
    dataObject['conditionalId'] = data[i][7];
    o[i] = dataObject;
    onsole.log(dataObject);
}
</code>```

This will result to:

```<code>0: {
    baseField: "county",
    baseValue: "San Diego",
    conditionalId: "0",
    pageName: "open_order",
    preferenceId: "1",
    preferenceType: "form",
    targetField: "title_officer",
    targetValue: "Peter"
}
    1: {
    baseField: "county",
    baseValue: "San Diego",
    conditionalId: "0",
    pageName: "open_order",
    preferenceId: "2",
    preferenceType: "form",
    targetField: "branch",
    targetValue: "MV",
}
</code>```

The reason why all of the values on the final array is the same is that, you are just assigning the dataObject by reference and you are not making a new variable.

Body:
I have an array (data) formatted like so:

["1", "open_order", "form", "county", "San Diego", "title_officer", "Peter", "0"]
["2", "open_order", "form", "county", "San Diego", "branch", "MV", "0"]

When I put this through a for loop and add it to the dataObject, console.log(dataObject) gives me all of the entries (this is what I want!)
However, console.log(o) shows that the last entry is going into the o object for both records.

$(function() {
  var o = {};
  var dataObject = {};
  var i = 0;
  var predata = $('#preferences').text();
  var data = JSON.parse(predata);
    for(i = 0; i < data.length; i++) {
      dataObject['preferenceId'] = data[i][0];
      dataObject['pageName'] = data[i][1];
      dataObject['preferenceType'] = data[i][2];
      dataObject['baseField'] = data[i][3];
      dataObject['baseValue'] = data[i][4];
      dataObject['targetField'] = data[i][5];
      dataObject['targetValue'] = data[i][6];
      dataObject['conditionalId'] = data[i][7];
        o[i] = dataObject;
        console.log(dataObject);
    }
  console.log(o);
});

Any ideas why dataObject would be the same for all objects added to the o object?

Body:
You should init the dataObject inside the loop to make a new variable.

for(i = 0; i < data.length; i++) {
    var dataObject = {}; /* Init the variable here */
    dataObject['preferenceId'] = data[i][0];
    dataObject['pageName'] = data[i][1];
    dataObject['preferenceType'] = data[i][2];
    dataObject['baseField'] = data[i][3];
    dataObject['baseValue'] = data[i][4];
    dataObject['targetField'] = data[i][5];
    dataObject['targetValue'] = data[i][6];
    dataObject['conditionalId'] = data[i][7];
    o[i] = dataObject;
    onsole.log(dataObject);
}

This will result to:

0: {
    baseField: "county",
    baseValue: "San Diego",
    conditionalId: "0",
    pageName: "open_order",
    preferenceId: "1",
    preferenceType: "form",
    targetField: "title_officer",
    targetValue: "Peter"
}
    1: {
    baseField: "county",
    baseValue: "San Diego",
    conditionalId: "0",
    pageName: "open_order",
    preferenceId: "2",
    preferenceType: "form",
    targetField: "branch",
    targetValue: "MV",
}

The reason why all of the values on the final array is the same is that, you are just assigning the dataObject by reference and you are not making a new variable.


问:
how to reorder an string xml in c#
I have an XML-string and a unique tag value. Based on that tag value, how can I reorder the below XML? I want the specific tag value to be on the top.

<DataSet>
  <Row>
    <APPROVER>DSQF</APPROVER>
    <LEVEL>3</LEVEL>
    <LEVELDECODE>Supervisor</LEVELDECODE>
  </Row>
  <Row>
    <APPROVER>ASDQD</APPROVER>
    <LEVEL>3</LEVEL>
    <LEVELDECODE>Supervisor</LEVELDECODE>
  </Row>
  <Row>
    <APPROVER>ASDQTH</APPROVER>
    <LEVEL>3</LEVEL>
    <LEVELDECODE>Supervisor</LEVELDECODE>
  </Row>
</DataSet>
```

I want the row  with approver = ASDQD to be on the top (approver is selected by user).

答:
You can use XElement to manipulate the XML and move the desired row to the top.

Here is how to do it:

```<code>// Parse the xml into an XElement
XElement dataSet = XElement.Parse(xml);

// Find the desired row based on the value of the APPROVER child element
XElement row = dataSet.Elements("Row")
                      .FirstOrDefault(r => r.Element("APPROVER").Value == approver);

// If the row is found
if (row != null)
{
    // Remove the row from its parent element (the dataSet)
    row.Remove();

    // Reinsert the row as the first child of the dataSet
    dataSet.AddFirst(row);

    // Convert the XElement back to an xml string
    xml = dataSet.ToString();
}
</code>```

Working demo: https://dotnetfiddle.net/spmoM2

Title: how to reorder an string xml in c#

Body:
I have an XML-string and a unique tag value. Based on that tag value, how can I reorder the below XML? I want the specific tag value to be on the top.

<DataSet>
  <Row>
    <APPROVER>DSQF</APPROVER>
    <LEVEL>3</LEVEL>
    <LEVELDECODE>Supervisor</LEVELDECODE>
  </Row>
  <Row>
    <APPROVER>ASDQD</APPROVER>
    <LEVEL>3</LEVEL>
    <LEVELDECODE>Supervisor</LEVELDECODE>
  </Row>
  <Row>
    <APPROVER>ASDQTH</APPROVER>
    <LEVEL>3</LEVEL>
    <LEVELDECODE>Supervisor</LEVELDECODE>
  </Row>
</DataSet>

I want the row  with approver = ASDQD to be on the top (approver is selected by user).

Body:
You can use XElement to manipulate the XML and move the desired row to the top.

Here is how to do it:

// Parse the xml into an XElement
XElement dataSet = XElement.Parse(xml);

// Find the desired row based on the value of the APPROVER child element
XElement row = dataSet.Elements("Row")
                      .FirstOrDefault(r => r.Element("APPROVER").Value == approver);

// If the row is found
if (row != null)
{
    // Remove the row from its parent element (the dataSet)
    row.Remove();

    // Reinsert the row as the first child of the dataSet
    dataSet.AddFirst(row);

    // Convert the XElement back to an xml string
    xml = dataSet.ToString();
}

Working demo: https://dotnetfiddle.net/spmoM2


问:
Bootstrap cells with equal height
I have the following

```<code><div class="row">
  <div class="col-md-6">
    <div class = "box-cell">
      <p>
        Slightly short text
      </p>
    </div>
  </div>
  <div class="col-md-6">
    <div class = "box-cell">
      <p>
        Text that<br>literally<br>spans<br>4 lines
      </p>
    </div>
  </div>
</div>
</code>```

and css

```<code>.box-cell
{
    position:        relative;
    margin:          3px;
    border-style:    groove ridge ridge groove;
    border-width:    3px;
    background-size: cover;
}
</code>```

So the problem that I am facing is that one of the cells is usually taller than the other.IS there any way for me to equalize how much height each cell takes up?
Searching didn't yield me which property I can manipulate to get same height :(

Here is jsfiddle
However in this fiddle I can not get them to be side by side to prove my point

EDIT: I guess I didn't specify it properly. I would like to have the borders be as tall as the tallest cell. So all the examples provided here actually take out the borders and instead color the background. If I do that then yes it gives illusion of every cell being the same, but I would like there to be a border of same height.

答:
.row {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display:         flex;
}
.row > [class*='col-'] {
  display: flex;
  flex-direction: column;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="row">
  <div class="col-xs-12 col-sm-4" style="background-color: green">
  some content
  </div>
  <div class="col-xs-6 col-sm-4" style="background-color: orange">
  some content
  <img src="http://placehold.it/100x120">
  </div>
  <div class="col-xs-6 col-sm-4" style="background-color: magenta">
  some of content
  </div>
</div></code>```

Title: Bootstrap cells with equal height

Body:
I have the following

        Slightly short text

        Text that
literally
spans
4 lines

and css

.box-cell
{
    position:        relative;
    margin:          3px;
    border-style:    groove ridge ridge groove;
    border-width:    3px;
    background-size: cover;
}

So the problem that I am facing is that one of the cells is usually taller than the other.IS there any way for me to equalize how much height each cell takes up?
Searching didn't yield me which property I can manipulate to get same height :(

Here is jsfiddle
However in this fiddle I can not get them to be side by side to prove my point

EDIT: I guess I didn't specify it properly. I would like to have the borders be as tall as the tallest cell. So all the examples provided here actually take out the borders and instead color the background. If I do that then yes it gives illusion of every cell being the same, but I would like there to be a border of same height.

Body:
.row {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display:         flex;
}
.row > [class*='col-'] {
  display: flex;
  flex-direction: column;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="row">
  <div class="col-xs-12 col-sm-4" style="background-color: green">
  some content
  </div>
  <div class="col-xs-6 col-sm-4" style="background-color: orange">
  some content
  <img src="http://placehold.it/100x120">
  </div>
  <div class="col-xs-6 col-sm-4" style="background-color: magenta">
  some of content
  </div>
</div>