问:
TabControl bind ItemsSource to List with an existing TabItem
I have not been able to bind to my data such as TabControl.ItemsSource = CourtCases because it throws an exception:

Items collection must be empty before using ItemsSource.

...and using TabControl.Items.Add(newTabItem) might require more work since some tabs will have to be closed.

I have a TabControl where the first tab contains a DataGrid with a list of people and I want that whenever an item is clicked in the DataGrid a new tab is created containing the details for the person.

I want to pass the person object to the TabItem "scope/class" and should display the content of the person. I have created a DataTemplate for the person detail TabItem which you can see below;

```<code><TabControl Name="AttorneysTabControl" Grid.Column="2"  Grid.Row="0">
    <TabControl.Resources>
        <DataTemplate x:Key="AttorneyTabHeader">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Attorney.Names}" Margin="2,0,0,0" FontSize="16" VerticalAlignment="Center" />
            </StackPanel>
        </DataTemplate>
        <DataTemplate x:Key="AttorneyTabContent">
            <StackPanel>
                <TextBlock Text="{Binding Attorney.Names}" />
                <TextBlock Text="{Binding Attorney.Age}"/>
                <ToolBar>
                    <Button ToolTip="">Delete</Button>
                    <Button ToolTip="">Edit</Button>
                </ToolBar>
            </StackPanel>
        </DataTemplate>
    </TabControl.Resources>
    <TabItem>
        <TabItem.Header>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="Attorneys" Margin="2,0,0,0" FontSize="16" VerticalAlignment="Center" />
            </StackPanel>
        </TabItem.Header>
        <TabItem.Content>
            <Grid Background="#FFE5E5E5" Height="Auto">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="1*" />
                    <ColumnDefinition Width="5" />
                    <ColumnDefinition Width="3*" />
                </Grid.ColumnDefinitions>
                ...
            </Grid>
        </TabItem.Content>
    </TabItem>
    <!-- This part here -->
    <!-- I want this to repeat. I think I should use a UserControl for this since I want the content to have it's own class -->
    <TabItem ContentTemplate="{StaticResource AttorneyTabContent}" HeaderTemplate="{StaticResource AttorneyTabHeader}" />
</TabControl>
</code>```

答:
It's not impossible unless I'm missing something about your request. I will say that it doesn't sound like a good UX, but you know your users and your use case better than I would.

I put together something that I think will do what you want. You'd need to adapt it to your data. I hope it helps regardless. Please keep in mind this is very much only proof of concept code.

First is the XAML for the MainWindow. There's nothing special here. It starts off as a simple TabControl hosting a TabItem with a Listbox.

```<code><Window x:Class="WpfTabControl1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfTabControl1"
        mc:Ignorable="d"
        Title="TabControl Sample" Height="350" Width="525">
    <Window.Resources>
        <x:Array x:Key="Items" Type="{x:Type local:Item}">
            <local:Item Name="Item A" Value="1" />
            <local:Item Name="Item B" Value="2" />
            <local:Item Name="Item C" Value="3" />
        </x:Array>
    </Window.Resources>
    <Grid>
        <TabControl x:Name="ItemTabControl">
            <TabItem Header="Items">
                <ListBox x:Name="ItemListBox" ItemsSource="{StaticResource Items}"
                         SelectionChanged="ListBox_SelectionChanged" />
            </TabItem>
        </TabControl>
    </Grid>
</Window>
</code>```

The code behind is where most of the interesting things happen. I do one of two things in the event handler based on whether the tab for the item already exists -- I create the tab or I select the tab.

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

    void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (ItemListBox.SelectedItem is Item item) {
            // select the tab if one was already created for the item;
            // otherwise, create a new tab for it
            if (TabExists(item.Name, out TabItem tab)) {
                ItemTabControl.SelectedItem = tab;
            }
            else {
                var newItem = new ItemTabItem() {
                    Item = (Item)ItemListBox.SelectedItem
                };

                int newIndex = ItemTabControl.Items.Add(newItem);
                ItemTabControl.SelectedIndex = newIndex;
            }
        }
    }

    bool TabExists(string name, out TabItem tab)
    {
        tab = (from object item in ItemTabControl.Items
               let t = item as ItemTabItem
               where t != null && t.Item.Name == name
               select t).FirstOrDefault();

        return (tab != null);
    }
}
</code>```

My ItemTabItem (I know awesome name right) takes care of displaying the Item class instance. Here's the XAML followed by the code behind.

```<code><TabItem x:Class="WpfTabControl1.ItemTabItem"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:WpfTabControl1"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <TextBlock Text="Name" />
        <TextBlock Grid.Row="1" Text="Value" />
        <TextBox Grid.Column="1" Text="{Binding Name, Mode=TwoWay}" />
        <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Value, Mode=TwoWay}" />
    </Grid>
</TabItem>
</code>```

Now the code behind. We could just set the DataContext directly, but the property makes it more clear and allows me to set the header as well (probably could data bind it).

```<code>public partial class ItemTabItem : TabItem
{
    private Item item;

    public ItemTabItem() => InitializeComponent();

    public Item Item
    {
        get => item;
        set
        {
            item = value;
            DataContext = value;
            Header = item?.Name;
        }
    }
}
</code>```

The Item class is nothing special.

```<code>public class Item
{
    public string Name { get; set; }
    public int Value { get; set; }

    public override string ToString() => Name;
}
</code>```

Body:
I have not been able to bind to my data such as TabControl.ItemsSource = CourtCases because it throws an exception:

Items collection must be empty before using ItemsSource.

...and using TabControl.Items.Add(newTabItem) might require more work since some tabs will have to be closed.

I have a TabControl where the first tab contains a DataGrid with a list of people and I want that whenever an item is clicked in the DataGrid a new tab is created containing the details for the person.

I want to pass the person object to the TabItem "scope/class" and should display the content of the person. I have created a DataTemplate for the person detail TabItem which you can see below;

<TabControl Name="AttorneysTabControl" Grid.Column="2"  Grid.Row="0">
    <TabControl.Resources>
        <DataTemplate x:Key="AttorneyTabHeader">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Attorney.Names}" Margin="2,0,0,0" FontSize="16" VerticalAlignment="Center" />
            </StackPanel>
        </DataTemplate>
        <DataTemplate x:Key="AttorneyTabContent">
            <StackPanel>
                <TextBlock Text="{Binding Attorney.Names}" />
                <TextBlock Text="{Binding Attorney.Age}"/>
                <ToolBar>
                    <Button ToolTip="">Delete</Button>
                    <Button ToolTip="">Edit</Button>
                </ToolBar>
            </StackPanel>
        </DataTemplate>
    </TabControl.Resources>
    <TabItem>
        <TabItem.Header>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="Attorneys" Margin="2,0,0,0" FontSize="16" VerticalAlignment="Center" />
            </StackPanel>
        </TabItem.Header>
        <TabItem.Content>
            <Grid Background="#FFE5E5E5" Height="Auto">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="1*" />
                    <ColumnDefinition Width="5" />
                    <ColumnDefinition Width="3*" />
                </Grid.ColumnDefinitions>
                ...
            </Grid>
        </TabItem.Content>
    </TabItem>

    <TabItem ContentTemplate="{StaticResource AttorneyTabContent}" HeaderTemplate="{StaticResource AttorneyTabHeader}" />
</TabControl>

Body:
It's not impossible unless I'm missing something about your request. I will say that it doesn't sound like a good UX, but you know your users and your use case better than I would.

I put together something that I think will do what you want. You'd need to adapt it to your data. I hope it helps regardless. Please keep in mind this is very much only proof of concept code.

First is the XAML for the MainWindow. There's nothing special here. It starts off as a simple TabControl hosting a TabItem with a Listbox.

<Window x:Class="WpfTabControl1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfTabControl1"
        mc:Ignorable="d"
        Title="TabControl Sample" Height="350" Width="525">
    <Window.Resources>
        <x:Array x:Key="Items" Type="{x:Type local:Item}">
            <local:Item Name="Item A" Value="1" />
            <local:Item Name="Item B" Value="2" />
            <local:Item Name="Item C" Value="3" />
        </x:Array>
    </Window.Resources>
    <Grid>
        <TabControl x:Name="ItemTabControl">
            <TabItem Header="Items">
                <ListBox x:Name="ItemListBox" ItemsSource="{StaticResource Items}"
                         SelectionChanged="ListBox_SelectionChanged" />
            </TabItem>
        </TabControl>
    </Grid>
</Window>

The code behind is where most of the interesting things happen. I do one of two things in the event handler based on whether the tab for the item already exists -- I create the tab or I select the tab.

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

    void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (ItemListBox.SelectedItem is Item item) {
            // select the tab if one was already created for the item;
            // otherwise, create a new tab for it
            if (TabExists(item.Name, out TabItem tab)) {
                ItemTabControl.SelectedItem = tab;
            }
            else {
                var newItem = new ItemTabItem() {
                    Item = (Item)ItemListBox.SelectedItem
                };

                int newIndex = ItemTabControl.Items.Add(newItem);
                ItemTabControl.SelectedIndex = newIndex;
            }
        }
    }

    bool TabExists(string name, out TabItem tab)
    {
        tab = (from object item in ItemTabControl.Items
               let t = item as ItemTabItem
               where t != null && t.Item.Name == name
               select t).FirstOrDefault();

        return (tab != null);
    }
}

My ItemTabItem (I know awesome name right) takes care of displaying the Item class instance. Here's the XAML followed by the code behind.

<TabItem x:Class="WpfTabControl1.ItemTabItem"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:WpfTabControl1"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <TextBlock Text="Name" />
        <TextBlock Grid.Row="1" Text="Value" />
        <TextBox Grid.Column="1" Text="{Binding Name, Mode=TwoWay}" />
        <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Value, Mode=TwoWay}" />
    </Grid>
</TabItem>

Now the code behind. We could just set the DataContext directly, but the property makes it more clear and allows me to set the header as well (probably could data bind it).

public partial class ItemTabItem : TabItem
{
    private Item item;

    public ItemTabItem() => InitializeComponent();

    public Item Item
    {
        get => item;
        set
        {
            item = value;
            DataContext = value;
            Header = item?.Name;
        }
    }
}

The Item class is nothing special.

public class Item
{
    public string Name { get; set; }
    public int Value { get; set; }

    public override string ToString() => Name;
}


来源: stackexchange

问:
one bug in my code, I used Classes in python and define some functions inside but the values that passed to functions are not accurate
I am beginner on python and OOP. This is my first class code.
I wrote below python code and it will run, The Code is about 3 string that user enter them and the code check if these strings are valid or invalid(string are valid if string's length are between 1 to 50) But there is an issue on my code. I got always default values when I run my code. I think there is a problem on set_string functions. But I am not sure.
I would be appreciate for any help

Code:

```<code>class TripleString:
  string1=""
  string2=""
  string3=""
  Max_Len=50
  Min_Len=1
  def __init__(self,string1="Undefined1",string2="Undefined2",string3="Undefined3"):
    if(TripleString.get_string1_from_user()):
      self.string1=string1
    if(TripleString.get_string2_from_user()):
      self.string2=string2
    if(TripleString.get_string3_from_user()):
      self.string3=string3

  def valid_string(str):
    if(len(str)<TripleString.Min_Len or len(str)>TripleString.Max_Len):
      return False
    else:
      return True

  def set_string1(str1):
    if(TripleString.valid_string(str1)):
      TripleString.string1=str1
      print("String set")
      return True
    else:
      print("string not set since the len is not valid")
      return False

  def get_string1_from_user():
    str=input("STR1:")
    if(TripleString.set_string1(str)):
      return True
    else:
      return False

  def set_string2(str2):
    if(TripleString.valid_string(str2)):
      TripleString.string2=str2
      print("String set")
      return True
    else:
      print("string not set since the len is not valid")
      return False

  def get_string2_from_user():
    str=input("STR2:")
    if(TripleString.set_string2(str)):
      return True
    else:
      return False

  def set_string3(str3):
    if(TripleString.valid_string(str3)):
      TripleString.string3=str3
      print("String set")
      return True
    else:
      print("string not set since the len is not valid")
      return False

  def get_string3_from_user():
    str=input("STR3:")
    if(TripleString.set_string3(str)):
      return True
    else:
      return False

x=TripleString()

print(x.string1,x.string2,x.string3)
</code>```

Output1:

```<code>STR1: String1
String set
STR2: String2
String set
STR3: String3
String set
Undefined1 Undefined2 Undefined3
</code>```

output2:

```<code>STR1: strin1stringstringstringstringstringstringstringstringstringstringstringstringstringstring
string not set since the len is not valid
STR2: string2
String set
STR3: string3
String set
 Undefined2 Undefined3
</code>```

But I expect the output for

```<code>                        1st one : string1 string2 string3

                        2nd one: undefined1  string2 string3
</code>```

Appreciated!

Updated code for set_string1:

```<code>  def set_string1(self,str1):
    if(TripleString.valid_string(str1)):
      self.string1=str1
      print("String set")
      return True
    else:
      print("string not set since the len is not valid")
      return False

  def get_string1_from_user():
    str=input("STR1:")
    if(TripleString.set_string1(str)):
      return True
    else:
      return False
</code>```

output:

```<code>> STR1: kiarash Traceback (most recent call last):   File "python", line
> 71, in <module>   File "python", line 8, in __init__   File "python",
> line 32, in get_string1_from_user TypeError: set_string1() missing 1
> required positional argument: 'str1'
</code>```

答:
You are mixing up class bound variables and function calls (those starting with TripleString.) with object bound variables and calls (starting with self.) and local variables (starting with nothing).

If possible you should use object bound vars and calls. This first needs to prepend the parameter list of each method (including __init__) with a self parameter, like e.g.

```<code>def set_string1(self, str1):
</code>```

You can then set an object bound variable like e.g.

```<code>self.string1 = str1
</code>```

and refer to it in another function to e.g. print it:

```<code>print(self.string1)
</code>```

A legitimate use for class bound variables are TripleString.Min_Len and TripleString.Max_Len (assuming they are the same for all objects of this class).

So valid_string(str) doesn't need to know the particular object and can be a class bound (static) method. To declare this, write the function as:

```<code>@staticmethod
def valid_string(str):
</code>```

The method can then be called either as TripleString.valid_string(...) or even as self.valid_string(...) although it doesn't care about the particular object.

ContentLicense: CC BY-SA 3.0

Body:
I am beginner on python and OOP. This is my first class code.
I wrote below python code and it will run, The Code is about 3 string that user enter them and the code check if these strings are valid or invalid(string are valid if string's length are between 1 to 50) But there is an issue on my code. I got always default values when I run my code. I think there is a problem on set_string functions. But I am not sure.
I would be appreciate for any help

Code:

class TripleString:
  string1=""
  string2=""
  string3=""
  Max_Len=50
  Min_Len=1
  def __init__(self,string1="Undefined1",string2="Undefined2",string3="Undefined3"):
    if(TripleString.get_string1_from_user()):
      self.string1=string1
    if(TripleString.get_string2_from_user()):
      self.string2=string2
    if(TripleString.get_string3_from_user()):
      self.string3=string3

  def valid_string(str):
    if(len(str)<TripleString.Min_Len or len(str)>TripleString.Max_Len):
      return False
    else:
      return True

  def set_string1(str1):
    if(TripleString.valid_string(str1)):
      TripleString.string1=str1
      print("String set")
      return True
    else:
      print("string not set since the len is not valid")
      return False

  def get_string1_from_user():
    str=input("STR1:")
    if(TripleString.set_string1(str)):
      return True
    else:
      return False

  def set_string2(str2):
    if(TripleString.valid_string(str2)):
      TripleString.string2=str2
      print("String set")
      return True
    else:
      print("string not set since the len is not valid")
      return False

  def get_string2_from_user():
    str=input("STR2:")
    if(TripleString.set_string2(str)):
      return True
    else:
      return False

  def set_string3(str3):
    if(TripleString.valid_string(str3)):
      TripleString.string3=str3
      print("String set")
      return True
    else:
      print("string not set since the len is not valid")
      return False

  def get_string3_from_user():
    str=input("STR3:")
    if(TripleString.set_string3(str)):
      return True
    else:
      return False

x=TripleString()

print(x.string1,x.string2,x.string3)

Output1:

STR1: String1
String set
STR2: String2
String set
STR3: String3
String set
Undefined1 Undefined2 Undefined3

output2:

STR1: strin1stringstringstringstringstringstringstringstringstringstringstringstringstringstring
string not set since the len is not valid
STR2: string2
String set
STR3: string3
String set
 Undefined2 Undefined3

But I expect the output for

                        1st one : string1 string2 string3

                        2nd one: undefined1  string2 string3

Appreciated!

Updated code for set_string1:

  def set_string1(self,str1):
    if(TripleString.valid_string(str1)):
      self.string1=str1
      print("String set")
      return True
    else:
      print("string not set since the len is not valid")
      return False

  def get_string1_from_user():
    str=input("STR1:")
    if(TripleString.set_string1(str)):
      return True
    else:
      return False

output:

> STR1: kiarash Traceback (most recent call last):   File "python", line
> 71, in <module>   File "python", line 8, in __init__   File "python",
> line 32, in get_string1_from_user TypeError: set_string1() missing 1
> required positional argument: 'str1'

Body:
You are mixing up class bound variables and function calls (those starting with TripleString.) with object bound variables and calls (starting with self.) and local variables (starting with nothing).

If possible you should use object bound vars and calls. This first needs to prepend the parameter list of each method (including __init__) with a self parameter, like e.g.

def set_string1(self, str1):

You can then set an object bound variable like e.g.

self.string1 = str1

and refer to it in another function to e.g. print it:

print(self.string1)

A legitimate use for class bound variables are TripleString.Min_Len and TripleString.Max_Len (assuming they are the same for all objects of this class).

So valid_string(str) doesn't need to know the particular object and can be a class bound (static) method. To declare this, write the function as:

@staticmethod
def valid_string(str):

The method can then be called either as TripleString.valid_string(...) or even as self.valid_string(...) although it doesn't care about the particular object.


问:
Force an element to be 100% height when the parent is shimmed taller by another child
Here I have a parent div containing two children. Child 1 is set to 100% height, but it does not display at the actual height of parent, because child 2 is forcing the parent div taller.

```<code><div style="height: 50px; width:106px">
  <div style="border: 1px solid red; display: flex">

    <span style="border: 1px solid blue; height: 100%;">Child 1</span>

    <span style="border: 1px solid green; height: 100px;">Child 2</span>

  </div>
</div>
</code>```

How can I get child 1 to match the actual height of the parent div in this scenario? I want to do this with pure HTML/CSS.

答:
Another answer to this question is correct in terms of the solution, but the explanation is incorrect.

You have a flex container.

The container has two span children: span1 and span2.

span1 is set to height: 100%

span2 is set to height: 100px.

Because span1 is set to height: 100% and the flex container has no defined height, this element computes to height: auto (the height of the content).

Here is a more complete explanation of how this works:

Working with the CSS height property and percentage values

However, a default setting on a flex container is align-items: stretch. This means that flex items will expand to cover the length of the container's cross axis, which would be the height in this case.

But this default setting is overridden by the height property on flex items.

Therefore, remove height: 100% so align-items: stretch can work.

Now you have two equal height columns.

    Child 1
    Child 2

```

Body:
Here I have a parent div containing two children. Child 1 is set to 100% height, but it does not display at the actual height of parent, because child 2 is forcing the parent div taller.

    Child 1

    Child 2

How can I get child 1 to match the actual height of the parent div in this scenario? I want to do this with pure HTML/CSS.

Body:
Another answer to this question is correct in terms of the solution, but the explanation is incorrect.

You have a flex container.

The container has two span children: span1 and span2.

span1 is set to height: 100%

span2 is set to height: 100px.

Because span1 is set to height: 100% and the flex container has no defined height, this element computes to height: auto (the height of the content).

Here is a more complete explanation of how this works:

Working with the CSS height property and percentage values

However, a default setting on a flex container is align-items: stretch. This means that flex items will expand to cover the length of the container's cross axis, which would be the height in this case.

But this default setting is overridden by the height property on flex items.

Therefore, remove height: 100% so align-items: stretch can work.

Now you have two equal height columns.

<div style="height: 50px;">
  <div style="border: 1px solid red; display: inline-flex; padding: 5px;">
    <span style="border: 1px solid blue;">Child 1</span>
    <span style="border: 1px solid green; height: 100px; margin-left: 5px;">Child 2</span>
  </div>
</div>


问:
foreign key not updated in one to many hibernate mapping

User class

```<code>@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="PK_USER_ID")
    private Integer userId;

    @Column(name="FIRST_NAME")
    private String firstName;

    @Column(name="LAST_NAME")
    private String lastName;

    @OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
    @JoinColumn(name="FK_USER_ID",referencedColumnName="PK_USER_ID")
    private Set<DeviceInfo> deviceInfos;
}
</code>```

DeviceInfo

```<code>@Entity
@Table(name="device_info")
public class DeviceInfo {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="DEVICE_ID")
    private Integer deviceId;

    @Column(name="DEVICE_KEY")
    private String deviceKey;
    @Column(name="FK_USER_ID")
    private Integer userId;
}
</code>```

When i try to insert data into user table and device_info table, data is inserted but foreign key column of device_info table not updated with primary key of user table.

Hibernate version:4.3.6.Final
Spring version :4.3.1

答:
I think @ManyToOne mapping is missing in your entity DeviceInfo

User.java

```<code>@Entity
@Table(name="user")
public class User {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="PK_USER_ID")
    private Integer userId;

    @Column(name="FIRST_NAME")
    private String firstName;

    @Column(name="LAST_NAME")
    private String lastName;

    @OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY, mappedBy = "user")
    private Set<DeviceInfo> deviceInfos;
}
</code>```

DeviceInfo.java

```<code>@Entity
@Table(name="device_info")
public class DeviceInfo {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="DEVICE_ID")
    private Integer deviceId;

    @Column(name="DEVICE_KEY")
    private String deviceKey;

  @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "PK_USER_ID", nullable = false)
    private User user;
}
</code>```

Body:
User class

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="PK_USER_ID")
    private Integer userId;

    @Column(name="FIRST_NAME")
    private String firstName;

    @Column(name="LAST_NAME")
    private String lastName;

    @OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
    @JoinColumn(name="FK_USER_ID",referencedColumnName="PK_USER_ID")
    private Set<DeviceInfo> deviceInfos;
}

DeviceInfo

@Entity
@Table(name="device_info")
public class DeviceInfo {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="DEVICE_ID")
    private Integer deviceId;

    @Column(name="DEVICE_KEY")
    private String deviceKey;
    @Column(name="FK_USER_ID")
    private Integer userId;
}

When i try to insert data into user table and device_info table, data is inserted but foreign key column of device_info table not updated with primary key of user table.

Hibernate version:4.3.6.Final
Spring version :4.3.1

Body:
I think @ManyToOne mapping is missing in your entity DeviceInfo

User.java

@Entity
@Table(name="user")
public class User {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="PK_USER_ID")
    private Integer userId;

    @Column(name="FIRST_NAME")
    private String firstName;

    @Column(name="LAST_NAME")
    private String lastName;

    @OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY, mappedBy = "user")
    private Set<DeviceInfo> deviceInfos;
}

DeviceInfo.java

@Entity
@Table(name="device_info")
public class DeviceInfo {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="DEVICE_ID")
    private Integer deviceId;

    @Column(name="DEVICE_KEY")
    private String deviceKey;

  @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "PK_USER_ID", nullable = false)
    private User user;
}


问:
How can I access a property of an html element?
I'm trying to get the "validacion" property of an HTML element.

```<code>console.log (element[0]);
</code>```

This returns me:

```<code><input class="estilo_input_text ng-pristine ng-untouched ng-valid ng-empty" id="asunto" name="asunto" ng-model="asunto" placeholder="Asunto" type="text" validacion="required">
</code>```

How can I access the "validacion" property?

答: Use the element[0].getAttribute("attribute_name"); method.

Body:
I'm trying to get the "validacion" property of an HTML element.

console.log (element[0]);

This returns me:

<input class="estilo_input_text ng-pristine ng-untouched ng-valid ng-empty" id="asunto" name="asunto" ng-model="asunto" placeholder="Asunto" type="text" validacion="required">

How can I access the "validacion" property?


答:
Try element[0].attributes['validacion'].value

Have a good day!

Title: How can I access a property of an html element?


问:
In React, Is it possible to get access to Redux action creators from inside a utility function?
I have a form input validation function that just returns an empty errors object or a populated errors object.

```<code>const validate = function validateSomeInput({ field1, field2 }) {
  const errors = {}
  // some logic
  return errors
}

export default validate
</code>```

Is there a way to hook an action creator into this function?

This is what I am trying to achieve:

```<code>const validate = function validateSomeInput({ field1, field2 }) {
  const errors = {}
  // some logic
  props.onErrorEvent('do something')
  return errors
}

export default connect(null, { onErrorEvent })(validate)
</code>```

My issue is that since it's not a class, I don't have access to this.props, and I have never tried to make a container before that doesn't render any JSX.

I also can't create a callback into the parent because the validate function is controlled by Redux-Form.

It's used like this in the parent container:

```<code>export default compose(
  connect(mapStateToProps, {
    onErrorEvent,      // this is the action creator I want to access from validate
    onLoginSuccess,
  }),
  graphql(LOGIN_MUTATION),
  reduxForm({
    validate,           // how do I get an action creator into this function?
    form: 'LoginForm',
  }),
)(LoginForm)
</code>```

Is it possible to wire an action creator into a utility function that doesn't render JSX and can't callback to parent?

I'd also like to know if this is bordering into any kind of horrendous anti-pattern territory because I can't find any information about allowing random utility functions to call action creators.

I didn't see a solution with bindActionCreators, but maybe I just didn't see how it relates to this scenario.

Is there a way I can create a HOC in this scenario?

答:
The validate function receives a second argument, which are the component props.  This makes it trivial to pass in the dispatch-bound action creators.  See the docs for details, but your code example should work if you examine the 2nd argument:

```<code>function validate({ field1, field2 }, {onErrorEvent}) {
  // ...
}

export default compose(
  connect(mapStateToProps, {
    onErrorEvent,      // this is the action creator I want to access from validate
    onLoginSuccess,
  }),
  graphql(LOGIN_MUTATION),
  reduxForm({
    validate,           // how do I get an action creator into this function?
    form: 'LoginForm',
  }),
)(LoginForm)
</code>```

If you want to insulate the validation function from the action, then use this pattern:

```<code>function sendOnError(validate, fields, props) {
  const result = validate(fields, props);
  if (!_.isEmpty(result)) {
    props.onErrorAction(...);
  }
  return result;
}

const myValidator = ({field1, field2}) => ...;

export default compose(
  connect(mapStateToProps, {
    onErrorEvent,      // this is the action creator I want to access from validate
    onLoginSuccess,
  }),
  graphql(LOGIN_MUTATION),
  reduxForm({
    validate: sendOnError.bind(null, myValidator),
    form: 'LoginForm',
  }),
)(LoginForm)
</code>```

Body:
I have a form input validation function that just returns an empty errors object or a populated errors object.

const validate = function validateSomeInput({ field1, field2 }) {
  const errors = {}
  // some logic
  return errors
}

export default validate

Is there a way to hook an action creator into this function?

This is what I am trying to achieve:

const validate = function validateSomeInput({ field1, field2 }) {
  const errors = {}
  // some logic
  props.onErrorEvent('do something')
  return errors
}

export default connect(null, { onErrorEvent })(validate)

My issue is that since it's not a class, I don't have access to this.props, and I have never tried to make a container before that doesn't render any JSX.

I also can't create a callback into the parent because the validate function is controlled by Redux-Form.

It's used like this in the parent container:

export default compose(
  connect(mapStateToProps, {
    onErrorEvent,      // this is the action creator I want to access from validate
    onLoginSuccess,
  }),
  graphql(LOGIN_MUTATION),
  reduxForm({
    validate,           // how do I get an action creator into this function?
    form: 'LoginForm',
  }),
)(LoginForm)

Is it possible to wire an action creator into a utility function that doesn't render JSX and can't callback to parent?

I'd also like to know if this is bordering into any kind of horrendous anti-pattern territory because I can't find any information about allowing random utility functions to call action creators.

I didn't see a solution with bindActionCreators, but maybe I just didn't see how it relates to this scenario.

Is there a way I can create a HOC in this scenario?

Body:
The validate function receives a second argument, which are the component props.  This makes it trivial to pass in the dispatch-bound action creators.  See the docs for details, but your code example should work if you examine the 2nd argument:

function validate({ field1, field2 }, {onErrorEvent}) {
  // ...
}

export default compose(
  connect(mapStateToProps, {
    onErrorEvent,      // this is the action creator I want to access from validate
    onLoginSuccess,
  }),
  graphql(LOGIN_MUTATION),
  reduxForm({
    validate,           // how do I get an action creator into this function?
    form: 'LoginForm',
  }),
)(LoginForm)

If you want to insulate the validation function from the action, then use this pattern:

function sendOnError(validate, fields, props) {
  const result = validate(fields, props);
  if (!_.isEmpty(result)) {
    props.onErrorAction(...);
  }
  return result;
}

const myValidator = ({field1, field2}) => ...;

export default compose(
  connect(mapStateToProps, {
    onErrorEvent,      // this is the action creator I want to access from validate
    onLoginSuccess,
  }),
  graphql(LOGIN_MUTATION),
  reduxForm({
    validate: sendOnError.bind(null, myValidator),
    form: 'LoginForm',
  }),
)(LoginForm)


问:
Angular Use page generated HTML for component template
So, I'm upgrading from AngularJS to Angular 2. We had to not upgrade directly to 4 for some internal reasons.

Anyway. We have some parts of the HTML that needs to be generated by the backend before being presented. So, this obviously means that I can't go the route of static HTML or HTML files. I've attempted to use my best Googling skills to find a solution but have come up empty.

For example (PHP):

```<code><div id="appRoot">
    <div id="mainView">
<?php
if ($user->isActive()) :
    ?>
        <p>Welcome, <?php print $user->getName(); ?>!</p>
<?php
else:
    ?>
        <p>Hello newbie!</p>
<?php
endif; ?>
        <... begin main Angular Template ... >
    </div>
    <div id="sideContent">
        <... begin side Angular Template ... >
    </div>
</div>
</code>```

It gets a little more complicated than that in places, but that's the gist. There are parts of the template that won't get rendered or will get rendered with different values that aren't dependent on the Angular app but the backend.

I'm hoping that there's a way to do this, but my search thus far has yielded goose-egg. If this is true and it can't be done, I really don't get why one of the most versatile parts of the AngularJS approach was removed.

Anyway, any help will be appreciated.

Edit: Fleshed-out the example a little more.

答:
In the end, what we wanted to do wasn't really possible. The particular case that we needed to solve was having multiple possible root elements for the user to interact with, but we didn't want to expose the logic for determining whether the elements should be shown or not to the end user.

We had to go with a, slightly, hack-ish solution that utilized generating new root components with specific selectors for each element (i.e. selector: "div#element1"). This was the most widely available and, apparently, used solution for this specific issue. It's apparently known by the Angular team, and it's unclear whether they will be addressing it in the future.

The end solution was to find all the elements on the page that needed the root elements, iterate over them and assign a unique selector (using utilizing the ID selector), then adding a new component class with that selector to the list of components to bootstrap.

i.e.

```<code>const BOOTSTRAP_ELEMENTS: any[] = [];
const DECLARATION_COMPONENTS: any[] = [];
let elements = document.getElementsByClassName('.custom-elements');
elements.map(
    (index: number, element: Element) => {
        let selector = 'custom-element#' + element.getAttribute('id');
        let component = getCustomComponentForSelector('.selector');
        BOOTSTRAP_ELEMENT.push(component);
        DELCARATION_COMPONENTS.push(component);
        element.className += selector;
    }
);

@NgModule({
    ...
    declarations: DECLARATION_COMPONENTS,
    bootstrap: BOOTSTRAP_COMPONENTS,
    ...
})
export class MyModule {}
</code>```

Body:
So, I'm upgrading from AngularJS to Angular 2. We had to not upgrade directly to 4 for some internal reasons.

Anyway. We have some parts of the HTML that needs to be generated by the backend before being presented. So, this obviously means that I can't go the route of static HTML or HTML files. I've attempted to use my best Googling skills to find a solution but have come up empty.

For example (PHP):

<?php
if ($user->isActive()) :
    ?>

Welcome, <?php print $user->getName(); ?>!

<?php
else:
    ?>

Hello newbie!

<?php
endif; ?>
        <... begin main Angular Template ... >

        <... begin side Angular Template ... >

It gets a little more complicated than that in places, but that's the gist. There are parts of the template that won't get rendered or will get rendered with different values that aren't dependent on the Angular app but the backend.

I'm hoping that there's a way to do this, but my search thus far has yielded goose-egg. If this is true and it can't be done, I really don't get why one of the most versatile parts of the AngularJS approach was removed.

Anyway, any help will be appreciated.

Edit: Fleshed-out the example a little more.

Body:
In the end, what we wanted to do wasn't really possible. The particular case that we needed to solve was having multiple possible root elements for the user to interact with, but we didn't want to expose the logic for determining whether the elements should be shown or not to the end user.

We had to go with a, slightly, hack-ish solution that utilized generating new root components with specific selectors for each element (i.e. selector: "div#element1"). This was the most widely available and, apparently, used solution for this specific issue. It's apparently known by the Angular team, and it's unclear whether they will be addressing it in the future.

The end solution was to find all the elements on the page that needed the root elements, iterate over them and assign a unique selector (using utilizing the ID selector), then adding a new component class with that selector to the list of components to bootstrap.

i.e.

const BOOTSTRAP_ELEMENTS: any[] = [];
const DECLARATION_COMPONENTS: any[] = [];
let elements = document.getElementsByClassName('.custom-elements');
elements.map(
    (index: number, element: Element) => {
        let selector = 'custom-element#' + element.getAttribute('id');
        let component = getCustomComponentForSelector('.selector');
        BOOTSTRAP_ELEMENT.push(component);
        DELCARATION_COMPONENTS.push(component);
        element.className += selector;
    }
);

@NgModule({
    ...
    declarations: DECLARATION_COMPONENTS,
    bootstrap: BOOTSTRAP_COMPONENTS,
    ...
})
export class MyModule {}


问:
Accessing Python instance variables with __dict__- Is it wrong?
If I want to access the list of instance variables of an object, I can call myObject.__dict__.keys().  I want to use this attribute to print out all instance variables of an object.  I am hesitant to do this because __dict__ is a "secret" attribute, and I do not understand what this footnote means.

So is it wrong to use myObject.__dict__?

答:
What the footnote means is that you shouldn't try to access __dict__ directly but instead check if the feature/behavior you want is available.

So instead of doing something like:

```<code>if "__some_attribute__" in obj.__dict__:
    # do stuff
</code>```

you should instead do:

```<code>try:
    obj.some_action_i_want_to_do(...)
except AttributeError:
    # doesn't provide the functionality I want
</code>```

The reasons for this are because different objects might provide different internal references to a certain action but still provide the desired output.

If you want to list the "internals" for the sake of debugging and inspecting the current object, then dir() is the right way to do it.

ContentLicense: CC BY-SA 2.5

Body:
What the footnote means is that you shouldn't try to access __dict__ directly but instead check if the feature/behavior you want is available.

So instead of doing something like:

if "__some_attribute__" in obj.__dict__:
    # do stuff

you should instead do:

try:
    obj.some_action_i_want_to_do(...)
except AttributeError:
    # doesn't provide the functionality I want

The reasons for this are because different objects might provide different internal references to a certain action but still provide the desired output.

If you want to list the "internals" for the sake of debugging and inspecting the current object, then dir() is the right way to do it.


问:
Python - recursive function call with changing variable value
I'm trying to create a function that uses the Monte Carlo approximation method to calculate the value of pi to the given precision (number of decimal places). I was trying to do this by comparing the approximated value to the literal value of pi and if they don't match, recursively calling the function on itself to try again with a greater number of trials.
This is what I have so far:

```<code>def estimate_pi(precision):

     x = 1

     N_tot = 0
     N_hits = 0

     for i in range(0,trials*10**x):
         if(inside_circle(random.random(),random.random())==True):
             N_hits = N_hits+1
             N_tot = N_tot+1
         else:
             N_tot = N_tot+1

     result = 4.0*N_hits/N_tot

     if compare_to_pi(result,precision)==True:
         print(result)
     else:
         x++
         estimate_pi(precision)

         if trials>999999:
             raise Error('approximation not converging to given precision')
             print(result)
</code>```

I'm having trouble because the variable x, which is supposed to control the number of trials for approximation, gets initialised to 1 every time the function is called. I have no idea what to do, please help!

答:
you can solve this by wrapping your function in a class and have the class instance store the value of x over time.</p>

```<code>class foo():
   def __init__(self, precision, trials):
       self.x = 1
       self.precision = precision
       self.trials = trials
       ....

   def compare_to_pi(self, ...):
       ....

   def inside_circle(self, ...):
       ....

   def estimate_pi(self, precision):
       N_tot = 0
       N_hits = 0

       for i in range(0, self.trials*10**self.x):
           if(inside_circle(random.random(),random.random())==True):
               N_hits = N_hits+1
               N_tot = N_tot+1
          else:
               N_tot = N_tot+1

      result = 4.0*N_hits/N_tot

      if compare_to_pi(result, self.precision)==True:
          print(result)
      else:
          self.x += 1
          self.estimate_pi(self.precision)

      if self.trials > 999999:
         raise Error('approximation not converging to given precision')
         print(result)
</code>```

Body:
I'm trying to create a function that uses the Monte Carlo approximation method to calculate the value of pi to the given precision (number of decimal places). I was trying to do this by comparing the approximated value to the literal value of pi and if they don't match, recursively calling the function on itself to try again with a greater number of trials.
This is what I have so far:

def estimate_pi(precision):

     x = 1

     N_tot = 0
     N_hits = 0

     for i in range(0,trials*10**x):
         if(inside_circle(random.random(),random.random())==True):
             N_hits = N_hits+1
             N_tot = N_tot+1
         else:
             N_tot = N_tot+1

     result = 4.0*N_hits/N_tot

     if compare_to_pi(result,precision)==True:
         print(result)
     else:
         x++
         estimate_pi(precision)

         if trials>999999:
             raise Error('approximation not converging to given precision')
             print(result)

I'm having trouble because the variable x, which is supposed to control the number of trials for approximation, gets initialised to 1 every time the function is called. I have no idea what to do, please help!

Body:
you can solve this by wrapping your function in a class and have the class instance store the value of x over time.

class foo():
   def __init__(self, precision, trials):
       self.x = 1
       self.precision = precision
       self.trials = trials
       ....

   def compare_to_pi(self, ...):
       ....

   def inside_circle(self, ...):
       ....

   def estimate_pi(self, precision):
       N_tot = 0
       N_hits = 0

       for i in range(0, self.trials*10**self.x):
           if(inside_circle(random.random(),random.random())==True):
               N_hits = N_hits+1
               N_tot = N_tot+1
          else:
               N_tot = N_tot+1

      result = 4.0*N_hits/N_tot

      if compare_to_pi(result, self.precision)==True:
          print(result)
      else:
          self.x += 1
          self.estimate_pi(self.precision)

      if self.trials > 999999:
         raise Error('approximation not converging to given precision')
         print(result)


答:
You need the javascript  Element.getAttribute() method:

```<code>console.log(element[0].getAttribute("validacion"));
</code>```

Body:
You need the javascript  Element.getAttribute() method:

console.log(element[0].getAttribute("validacion"));


问:
SpeechSynthesis stops working after first utterance in FireFox, but works in Chrome
The problem is very simple, see JSfiddle.

SpeechSynthesis works fine in Chrome, but mysteriously stops after the first utterance in FireFox. (Works for me in Safari as well.) Any ideas welcome, as I don't have much to go by.

The code:

```<code>var u = new SpeechSynthesisUtterance();
var synth = window.speechSynthesis;
u.text = "hello";
synth.speak(u);
synth.speak(u);
synth.speak(u);
</code>```

答:
This is actually a known bug in Firefox.

The specs drafts are still not very clear about the re-usability of an utterance, but you can see this issue on w3c's github, where they agreed on the fact it should be.

For the time being, one workaround is to create a new utterance every time...

var synth = window.speechSynthesis;

synth.speak(new SpeechSynthesisUtterance('hello'));
synth.speak(new SpeechSynthesisUtterance('hello'));
synth.speak(new SpeechSynthesisUtterance('hello'));```

Body:
The problem is very simple, see JSfiddle.

SpeechSynthesis works fine in Chrome, but mysteriously stops after the first utterance in FireFox. (Works for me in Safari as well.) Any ideas welcome, as I don't have much to go by.

The code:

var u = new SpeechSynthesisUtterance();
var synth = window.speechSynthesis;
u.text = "hello";
synth.speak(u);
synth.speak(u);
synth.speak(u);


问:
How to check whether input value is integer or float?
How to check whether input value is integer or float?

Suppose 312/100=3.12
Here i need check whether 3.12 is a float value or integer value, i.e., without any decimal place value.

答:
How about this. using the modulo operator</p>

```<code>if(a%b==0)
{
    System.out.println("b is a factor of a. i.e. the result of a/b is going to be an integer");
}
else
{
    System.out.println("b is NOT a factor of a");
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How about this. using the modulo operator

if(a%b==0)
{
    System.out.println("b is a factor of a. i.e. the result of a/b is going to be an integer");
}
else
{
    System.out.println("b is NOT a factor of a");
}


问:
Cross-validation for Sklearn 0.20+?
I am trying to do cross validation and I am running into an error that says: 'Found input variables with inconsistent numbers of samples: [18, 1]'

I am using different columns in a pandas data frame (df) as the features, with the last column as the label. This is derived from the machine learning repository for UC Irvine. When importing the cross-validation package that I have used in the past, I am getting an error that it may have depreciated. I am going to be running a decision tree, SVM, and K-NN.

My code is as such:

```<code>feature = [df['age'], df['job'], df['marital'], df['education'], df['default'], df['housing'], df['loan'], df['contact'],
       df['month'], df['day_of_week'], df['campaign'], df['pdays'], df['previous'], df['emp.var.rate'], df['cons.price.idx'],
       df['cons.conf.idx'], df['euribor3m'], df['nr.employed']]
label = [df['y']]

from sklearn.cross_validation import train_test_split
from sklearn.model_selection import cross_val_score
# Model Training
x = feature[:]
y = label
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.5)
</code>```

Any help would be great!

答:
cross_validation module is deprecated. The new module model_selection has taken its place. So everything you did with cross_validation. is now available in model_selection. Then your above code becomes:

```<code>feature = [df['age'], df['job'], df['marital'], df['education'], df['default'], df['housing'], df['loan'], df['contact'],
       df['month'], df['day_of_week'], df['campaign'], df['pdays'], df['previous'], df['emp.var.rate'], df['cons.price.idx'],
       df['cons.conf.idx'], df['euribor3m'], df['nr.employed']]
label = [df['y']]

from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
</code>```

Now as far as declaring the X and y is concerned, why are you wrapping them in a list. Just use them like this:

```<code>feature = df[['age', 'job', 'marital', 'education', 'default', 'housing',
              'loan', 'contact', 'month', 'day_of_week', 'campaign',
              'pdays', 'previous', 'emp.var.rate', 'cons.price.idx',
              'cons.conf.idx', 'euribor3m', 'nr.employed']]
label = df['y']
</code>```

And then you can simply use your code, without changing anything.

```<code># Model Training
x = feature[:]
y = label
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.5)
</code>```

And for your last question about folds in cross-validation, there are multiple classes in sklearn which does this (depending upon task). Please have a look at:

http://scikit-learn.org/stable/modules/classes.html#splitter-classes

Which contains fold iterators. And remember, all this is present in model_selection package.

Title: Cross-validation for Sklearn 0.20+?

Body:
I am trying to do cross validation and I am running into an error that says: 'Found input variables with inconsistent numbers of samples: [18, 1]'

I am using different columns in a pandas data frame (df) as the features, with the last column as the label. This is derived from the machine learning repository for UC Irvine. When importing the cross-validation package that I have used in the past, I am getting an error that it may have depreciated. I am going to be running a decision tree, SVM, and K-NN.

My code is as such:

feature = [df['age'], df['job'], df['marital'], df['education'], df['default'], df['housing'], df['loan'], df['contact'],
       df['month'], df['day_of_week'], df['campaign'], df['pdays'], df['previous'], df['emp.var.rate'], df['cons.price.idx'],
       df['cons.conf.idx'], df['euribor3m'], df['nr.employed']]
label = [df['y']]

from sklearn.cross_validation import train_test_split
from sklearn.model_selection import cross_val_score
# Model Training
x = feature[:]
y = label
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.5)

Any help would be great!

Body:
cross_validation module is deprecated. The new module model_selection has taken its place. So everything you did with cross_validation. is now available in model_selection. Then your above code becomes:

feature = [df['age'], df['job'], df['marital'], df['education'], df['default'], df['housing'], df['loan'], df['contact'],
       df['month'], df['day_of_week'], df['campaign'], df['pdays'], df['previous'], df['emp.var.rate'], df['cons.price.idx'],
       df['cons.conf.idx'], df['euribor3m'], df['nr.employed']]
label = [df['y']]

from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score

Now as far as declaring the X and y is concerned, why are you wrapping them in a list. Just use them like this:

feature = df[['age', 'job', 'marital', 'education', 'default', 'housing',
              'loan', 'contact', 'month', 'day_of_week', 'campaign',
              'pdays', 'previous', 'emp.var.rate', 'cons.price.idx',
              'cons.conf.idx', 'euribor3m', 'nr.employed']]
label = df['y']

And then you can simply use your code, without changing anything.

# Model Training
x = feature[:]
y = label
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.5)

And for your last question about folds in cross-validation, there are multiple classes in sklearn which does this (depending upon task). Please have a look at:

http://scikit-learn.org/stable/modules/classes.html#splitter-classes

Which contains fold iterators. And remember, all this is present in model_selection package.


问:
Appending characters to each line in a txt file with python
I wrote the following python code snippet to append a lower p character to each line of a txt file:

```<code>f = open('helloworld.txt','r')
for line in f:
    line+='p'
print(f.read())
f.close()
</code>```

However, when I execute this python program, it returns nothing but an empty blank:

```<code>zhiwei@zhiwei-Lenovo-Rescuer-15ISK:~/Documents/1001/ass5$ python3 helloworld.py
</code>```

Can anyone tell me what's wrong with my codes?

答:
Currently, you are only reading each line and not writing to the file. reopen the file in write mode and write your full string to it, like so:</p>

```<code>newf=""
with open('helloworld.txt','r') as f:
    for line in f:
        newf+=line.strip()+"p\n"
    f.close()
with open('helloworld.txt','w') as f:
    f.write(newf)
    f.close()
</code>```

Body:
I wrote the following python code snippet to append a lower p character to each line of a txt file:

f = open('helloworld.txt','r')
for line in f:
    line+='p'
print(f.read())
f.close()

However, when I execute this python program, it returns nothing but an empty blank:

zhiwei@zhiwei-Lenovo-Rescuer-15ISK:~/Documents/1001/ass5$ python3 helloworld.py

Can anyone tell me what's wrong with my codes?

Body:
Currently, you are only reading each line and not writing to the file. reopen the file in write mode and write your full string to it, like so:

newf=""
with open('helloworld.txt','r') as f:
    for line in f:
        newf+=line.strip()+"p\n"
    f.close()
with open('helloworld.txt','w') as f:
    f.write(newf)
    f.close()


答:
open(filePath, openMode) takes two arguments, the first one is the path to your file, the second one is the mode it will be opened it. When you use 'r' as second argument, you are actually telling Python to open it as an only reading file.

If you want to write on it, you need to open it in writing mode, using 'w' as second argument. You can find more about how to read/write files in Python in its official documentation.

If you want to read and write at the same time, you have to open the file in both reading and writing modes. You can do this simply by using 'r+' mode.

Title: Appending characters to each line in a txt file with python


问:
How do I verify the order of MANIFEST.MF within jar?
I've run into interesting problem which is absolutely new to me. As I've suddenly discovered, Jar specification says that, being included, META-INF and MANIFEST.MF must be first and second entries of *.jar package and not just directory and file within archive.

I'm working with Java framework being very watchful about this requirement and not as much verbose. How do I check that META-INF and MANIFEST.MF are properly ordered within jar?

UPDATE:
Many of jars are third-party, and there are many of them. I'm not able to open these jars in notepad, excel, hexeditor, photoshop or whatever looking for byte sequences. I need command-line tool. Thanks!

UPDATE 2:
Here is the reason why I'm asking this question:
http://www.mail-archive.com/dev@felix.apache.org/msg17097.html

答: The jar tool with the JDK automatically adds them first, so there shouldn't be anything you have to do. If you really want to check, get a hex editor and look for the strings 'META-INF' and 'MANIFEST.MF' before any other file names.</p>


问:
IT Hit WebDAV Sample App not running with tomcat
I have downloaded the sample app [ITHitWebDAVServerLibJava.tar.gz] trying to understand how this IT Hit Webdav work.

I started the demo app with Tomcat 8, running on JDK 1.8. From the tomcat console / log, it seems everything just fine, however when I access the main page, it doesn't list out the sample folders & files as how it suppose to (referring to the online demo).
screen : main page is render without listing out the folders & files

I downloaded the sample app and unzip it, without changing the folder structure of it. I have just edited the WEB-INF\web.xml so that it point to the correct trial license file. Please advise if I have missed out some configuration? Should I move out certain files from the WEB-INF folder? Is there any step by step setup guide this demo?
screen : unzipped sample app folder without changing the folder structure

Also, I have downloaded the trial version of AJAX library as well [ITHitWebDAVAJAXLibraryTrial.tar.gz], please advise how should I put this library into the main sample app? As in I should put this library files under which folder of the main sample app?

Please advise.

答:
The default HTML page supplied with IT Hit WebDAV Server Library for Java sample servers use IT Hit WebDAV Ajax Library to list and browse WebDAV server content as well as to open documents for editing.

You can install IT Hit WebDAV Ajax Library from NPM using NPM command-line tool.

Install the Node.js, it installs NPM command-line tool.

Navigate to '\sample_folder\WEB-INF\wwwroot\' folder.

Execute:

```<code>npm install webdav.client
</code>```

This will download IT Hit WebDAV Ajax Library library into the wwwroot folder.

Body:
The default HTML page supplied with IT Hit WebDAV Server Library for Java sample servers use IT Hit WebDAV Ajax Library to list and browse WebDAV server content as well as to open documents for editing.

You can install IT Hit WebDAV Ajax Library from NPM using NPM command-line tool.

Install the Node.js, it installs NPM command-line tool.

Navigate to '\sample_folder\WEB-INF\wwwroot\' folder.

Execute:

npm install webdav.client

This will download IT Hit WebDAV Ajax Library library into the wwwroot folder.


答:
Don't know why you need to do this:

You'd better use the directive way to get the element.

Or you can use Angular jqLite API:

```<code>angular.element('#asunto').attr('validacion')
</code>```

Body:
Don't know why you need to do this:

You'd better use the directive way to get the element.

Or you can use Angular jqLite API:

angular.element('#asunto').attr('validacion')


问:
Segment fault when using Rcpp/Armadillo and openMP prarallel with user-defined function
I was trying to use rcpp/armadillo with openmp to speed up a loop in R. The loop takes a matrix with each row containing indices of a location vector(or matrix if it's 2D locations) as input(and other matrix/vec to be used). Inside the loop, I extracted each row of input indices matrix and find the corresponding locations, calculate distance matrix, and covariance matrix, do cholesky and backsolve, save the backsolve results to a new matrix. Here is the rcpp code:

```<code>`#include <iostream>
#include <RcppArmadillo.h>
#include <omp.h>
#include <Rcpp.h>

// [[Rcpp::plugins(openmp)]]
using namespace Rcpp;
using namespace arma;
using namespace std;

// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
mat NZentries_new2 (int m, int nnp, const mat& locs, const umat& revNNarray, const mat& revCondOnLatent, const vec& nuggets, const vec covparms){
// initialized the output matrix
mat Lentries=zeros(nnp,m+1);
// initialized objects in parallel part
int n0; //number of !is_na elements
uvec inds;//
vec revCon_row;//
uvec inds00;//
vec nug;//
mat covmat;//
vec onevec;//
vec M;//
mat dist;//
int k;//
omp_set_num_threads(2);// selects the number of cores to use.
#pragma omp parallel for shared(locs,revNNarray,revCondOnLatent,nuggets,nnp,m,Lentries) private(k,M,dist,onevec,covmat,nug,n0,inds,revCon_row,inds00) default(none) schedule(static)
for (k = 0; k < nnp; k++) {
// extract a row to work with
inds=revNNarray.row(k).t();
revCon_row=revCondOnLatent.row(k).t();

if (k < m){
  n0=k+1;
} else {
  n0=m+1;
}
// extract locations
inds00=inds(span(m+1-n0,m))-ones<uvec>(n0);

nug=nuggets.elem(inds00) % (ones(n0)-revCon_row(span(m+1-n0,m))); // vec is vec, cannot convert to mat
dist=calcPWD2(locs.rows(inds00));

#pragma omp critical
{
  //calculate covariance matrix
  covmat= MaternFun(dist,covparms) + diagmat(nug) ; // summation from arma
}

// get last row of inverse Cholesky
onevec = zeros(n0);
onevec[n0-1] = 1;
M=solve(chol(covmat,"upper"),onevec);
// save the entries to matrix
Lentries(k,span(0,n0-1)) = M.t();
}
return Lentries;
}`
</code>```

The current version works fine but speed is slow(almost the same as no parallel version), if I take the line in omp critical bracket out, it cause segment fault and R will be crashed. This MaterFun is a function I defined as below with several other small functions. So my question is that why MaternFun has to stay in the critical part.

```<code>// [[Rcpp::export]]
    mat MaternFun( mat distmat, vec covparms ){

      int d1 = distmat.n_rows;
      int d2 = distmat.n_cols;
      int j1;
      int j2;
      mat covmat(d1,d2);
      double scaledist;

      double normcon = covparms(0)/(pow(2.0,covparms(2)-1)*Rf_gammafn(covparms(2)));

      for (j1 = 0; j1 < d1; j1++){
        for (j2 = 0; j2 < d2; j2++){
          if ( distmat(j1,j2) == 0 ){
            covmat(j1,j2) = covparms(0);
          } else {
            scaledist = distmat(j1,j2)/covparms(1);
            covmat(j1,j2) = normcon*pow( scaledist, covparms(2) )*
              Rf_bessel_k(scaledist,covparms(2),1.0);
          }
        }
      }
      return covmat;
    }

    // [[Rcpp::export]]
    double dist2(double lat1,double long1,double lat2,double long2) {
      double dist = sqrt(pow(lat1 - lat2, 2) + pow(long1 - long2, 2)) ;
      return (dist) ;
    }
   // [[Rcpp::export]]
    mat calcPWD2( mat x) {//Rcpp::NumericMatrix
      int outrows = x.n_rows ;

      int outcols = x.n_rows ;
      mat out(outrows, outcols) ;
      for (int arow = 0 ; arow < outrows ; arow++) {
        for (int acol = 0 ; acol < outcols ; acol++) {
          out(arow, acol) = dist2(x(arow, 0),x(arow, 1),
                                  x(acol, 0),x(acol, 1)) ; //extract element from mat
        }
      }
      return (out) ;
    }
</code>```

Here is some sample inputs for testing the MaterFun in R:
    library(fields)
    distmat=rdist(1:5) # distance matrix
    covparms=c(1,0.2,1.5)

答:
The issue is there are two calls to R math functions (Rf_bessel_k and Rf_gammafn) that require the access to be single threaded instead of parallel.

To get around this, let's add a dependency on boost via BH to obtain the cyl_bessel_k and tgamma functions. Alternatively, there is always the option of reimplementing R's besselK and gamma in C++ so it doesn't use the single-threaded R variant.

This gives:

```<code>#include <Rcpp.h>
#include <boost/math/special_functions/bessel.hpp>
#include <boost/math/special_functions/gamma.hpp>

// [[Rcpp::depends(BH)]]

// [[Rcpp::export]]
double besselK_boost(double x, double v) {
  return boost::math::cyl_bessel_k(v, x);
}

// [[Rcpp::export]]
double gamma_fn_boost(double x) {
  return boost::math::tgamma(x);
}
</code>```

Test Code

```<code>x0 = 9.536743e-07
nu = -10
all.equal(besselK(x0, nu), besselK_boost(x0, nu))
# [1] TRUE

x = 2
all.equal(gamma(x), gamma_fn_boost(x))
# [1] TRUE
</code>```

Note: The order of parameters for boost's variant differs from R's:

```<code>cyl_bessel_k(v, x)
Rf_bessel_k(x, v, expon.scaled = FALSE)
</code>```

From here, we can modify the MaternFun. Unfortunately, because calcPWD2 is missing, the furthest we can go is switching to use boost and incorporating in OpenMP protections.

```<code>#include <RcppArmadillo.h>
#include <boost/math/special_functions/bessel.hpp>
#include <boost/math/special_functions/gamma.hpp>

#ifdef _OPENMP
#include <omp.h>
#endif

// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::depends(BH)]]
// [[Rcpp::plugins(openmp)]]

// [[Rcpp::export]]
arma::mat MaternFun(arma::mat distmat, arma::vec covparms) {

  int d1 = distmat.n_rows;
  int d2 = distmat.n_cols;
  int j1;
  int j2;
  arma::mat covmat(d1,d2);
  double scaledist;

  double normcon = covparms(0) /
    (pow(2.0, covparms(2) - 1) * boost::math::tgamma(covparms(2)));

  for (j1 = 0; j1 < d1; ++j1){
    for (j2 = 0; j2 < d2; ++j2){
      if ( distmat(j1, j2) == 0 ){
        covmat(j1, j2) = covparms(0);
      } else {
        scaledist = distmat(j1, j2)/covparms(1);
        covmat(j1, j2) = normcon * pow( scaledist, covparms(2) ) *
          boost::math::cyl_bessel_k(covparms(2), scaledist);
      }
    }
  }
  return covmat;
}
</code>```

Body:
I was trying to use rcpp/armadillo with openmp to speed up a loop in R. The loop takes a matrix with each row containing indices of a location vector(or matrix if it's 2D locations) as input(and other matrix/vec to be used). Inside the loop, I extracted each row of input indices matrix and find the corresponding locations, calculate distance matrix, and covariance matrix, do cholesky and backsolve, save the backsolve results to a new matrix. Here is the rcpp code:

`#include <iostream>
#include <RcppArmadillo.h>
#include <omp.h>
#include <Rcpp.h>

// [[Rcpp::plugins(openmp)]]
using namespace Rcpp;
using namespace arma;
using namespace std;

// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
mat NZentries_new2 (int m, int nnp, const mat& locs, const umat& revNNarray, const mat& revCondOnLatent, const vec& nuggets, const vec covparms){
// initialized the output matrix
mat Lentries=zeros(nnp,m+1);
// initialized objects in parallel part
int n0; //number of !is_na elements
uvec inds;//
vec revCon_row;//
uvec inds00;//
vec nug;//
mat covmat;//
vec onevec;//
vec M;//
mat dist;//
int k;//
omp_set_num_threads(2);// selects the number of cores to use.
#pragma omp parallel for shared(locs,revNNarray,revCondOnLatent,nuggets,nnp,m,Lentries) private(k,M,dist,onevec,covmat,nug,n0,inds,revCon_row,inds00) default(none) schedule(static)
for (k = 0; k < nnp; k++) {
// extract a row to work with
inds=revNNarray.row(k).t();
revCon_row=revCondOnLatent.row(k).t();

if (k < m){
  n0=k+1;
} else {
  n0=m+1;
}
// extract locations
inds00=inds(span(m+1-n0,m))-ones<uvec>(n0);

nug=nuggets.elem(inds00) % (ones(n0)-revCon_row(span(m+1-n0,m))); // vec is vec, cannot convert to mat
dist=calcPWD2(locs.rows(inds00));

#pragma omp critical
{
  //calculate covariance matrix
  covmat= MaternFun(dist,covparms) + diagmat(nug) ; // summation from arma
}

// get last row of inverse Cholesky
onevec = zeros(n0);
onevec[n0-1] = 1;
M=solve(chol(covmat,"upper"),onevec);
// save the entries to matrix
Lentries(k,span(0,n0-1)) = M.t();
}
return Lentries;
}`

The current version works fine but speed is slow(almost the same as no parallel version), if I take the line in omp critical bracket out, it cause segment fault and R will be crashed. This MaterFun is a function I defined as below with several other small functions. So my question is that why MaternFun has to stay in the critical part.

// [[Rcpp::export]]
    mat MaternFun( mat distmat, vec covparms ){

      int d1 = distmat.n_rows;
      int d2 = distmat.n_cols;
      int j1;
      int j2;
      mat covmat(d1,d2);
      double scaledist;

      double normcon = covparms(0)/(pow(2.0,covparms(2)-1)*Rf_gammafn(covparms(2)));

      for (j1 = 0; j1 < d1; j1++){
        for (j2 = 0; j2 < d2; j2++){
          if ( distmat(j1,j2) == 0 ){
            covmat(j1,j2) = covparms(0);
          } else {
            scaledist = distmat(j1,j2)/covparms(1);
            covmat(j1,j2) = normcon*pow( scaledist, covparms(2) )*
              Rf_bessel_k(scaledist,covparms(2),1.0);
          }
        }
      }
      return covmat;
    }

    // [[Rcpp::export]]
    double dist2(double lat1,double long1,double lat2,double long2) {
      double dist = sqrt(pow(lat1 - lat2, 2) + pow(long1 - long2, 2)) ;
      return (dist) ;
    }
   // [[Rcpp::export]]
    mat calcPWD2( mat x) {//Rcpp::NumericMatrix
      int outrows = x.n_rows ;

      int outcols = x.n_rows ;
      mat out(outrows, outcols) ;
      for (int arow = 0 ; arow < outrows ; arow++) {
        for (int acol = 0 ; acol < outcols ; acol++) {
          out(arow, acol) = dist2(x(arow, 0),x(arow, 1),
                                  x(acol, 0),x(acol, 1)) ; //extract element from mat
        }
      }
      return (out) ;
    }

Here is some sample inputs for testing the MaterFun in R:
    library(fields)
    distmat=rdist(1:5) # distance matrix
    covparms=c(1,0.2,1.5)

Body:
The issue is there are two calls to R math functions (Rf_bessel_k and Rf_gammafn) that require the access to be single threaded instead of parallel.

To get around this, let's add a dependency on boost via BH to obtain the cyl_bessel_k and tgamma functions. Alternatively, there is always the option of reimplementing R's besselK and gamma in C++ so it doesn't use the single-threaded R variant.

This gives:

#include <Rcpp.h>
#include <boost/math/special_functions/bessel.hpp>
#include <boost/math/special_functions/gamma.hpp>

// [[Rcpp::depends(BH)]]

// [[Rcpp::export]]
double besselK_boost(double x, double v) {
  return boost::math::cyl_bessel_k(v, x);
}

// [[Rcpp::export]]
double gamma_fn_boost(double x) {
  return boost::math::tgamma(x);
}

Test Code

x0 = 9.536743e-07
nu = -10
all.equal(besselK(x0, nu), besselK_boost(x0, nu))
# [1] TRUE

x = 2
all.equal(gamma(x), gamma_fn_boost(x))
# [1] TRUE

Note: The order of parameters for boost's variant differs from R's:

cyl_bessel_k(v, x)
Rf_bessel_k(x, v, expon.scaled = FALSE)

From here, we can modify the MaternFun. Unfortunately, because calcPWD2 is missing, the furthest we can go is switching to use boost and incorporating in OpenMP protections.

#include <RcppArmadillo.h>
#include <boost/math/special_functions/bessel.hpp>
#include <boost/math/special_functions/gamma.hpp>

#ifdef _OPENMP
#include <omp.h>
#endif

// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::depends(BH)]]
// [[Rcpp::plugins(openmp)]]

// [[Rcpp::export]]
arma::mat MaternFun(arma::mat distmat, arma::vec covparms) {

  int d1 = distmat.n_rows;
  int d2 = distmat.n_cols;
  int j1;
  int j2;
  arma::mat covmat(d1,d2);
  double scaledist;

  double normcon = covparms(0) /
    (pow(2.0, covparms(2) - 1) * boost::math::tgamma(covparms(2)));

  for (j1 = 0; j1 < d1; ++j1){
    for (j2 = 0; j2 < d2; ++j2){
      if ( distmat(j1, j2) == 0 ){
        covmat(j1, j2) = covparms(0);
      } else {
        scaledist = distmat(j1, j2)/covparms(1);
        covmat(j1, j2) = normcon * pow( scaledist, covparms(2) ) *
          boost::math::cyl_bessel_k(covparms(2), scaledist);
      }
    }
  }
  return covmat;
}


问:
Expanding a list to include all possible pairwise combinations within a group
I am currently running a randomization where individuals of a given population are sampled and placed into groups of defined size. The result is a data frame seen below:

```<code>Ind Group
Sally   1
Bob 1
Sue 1
Joe 2
Jeff    2
Jess    2
Mary    2
Jim 3
James   3
</code>```

Is there a function which will allow me to expand the data set to show every possible within group pairing? (Desired output below). The pairings do not need to be reciprocal.

```<code>Group   Ind1    Ind2
1   Sally   Bob
1   Sally   Sue
1   Sue Bob
2   Joe Jeff
2   Joe Jess
2   Joe Mary
2   Jeff    Jess
2   Jess    Mary
2   Jeff    Mary
3   Jim James
</code>```

I feel like there must be a way to do this in dplyr, but for the life of me I can't seem to sort it out.

答:
A solution using dplyr. We can use group_by and do to apply the combn function to each group and combine the results to form a data frame.

```<code>library(dplyr)
dt2 <- dt %>%
  group_by(Group) %>%
  do(as_data_frame(t(combn(.$Ind, m = 2)))) %>%
  ungroup() %>%
  setNames(sub("V", "Ind", colnames(.)))
dt2

# # A tibble: 10 x 3
#    Group  Ind1  Ind2
#    <int> <chr> <chr>
#  1     1 Sally   Bob
#  2     1 Sally   Sue
#  3     1   Bob   Sue
#  4     2   Joe  Jeff
#  5     2   Joe  Jess
#  6     2   Joe  Mary
#  7     2  Jeff  Jess
#  8     2  Jeff  Mary
#  9     2  Jess  Mary
# 10     3   Jim James
</code>```

DATA

```<code>dt <- read.table(text = "Ind Group
Sally   1
Bob 1
Sue 1
Joe 2
Jeff    2
Jess    2
Mary    2
Jim 3
James   3",
                 header = TRUE, stringsAsFactors = FALSE)
</code>```

Body:
I am currently running a randomization where individuals of a given population are sampled and placed into groups of defined size. The result is a data frame seen below:

Ind Group
Sally   1
Bob 1
Sue 1
Joe 2
Jeff    2
Jess    2
Mary    2
Jim 3
James   3

Is there a function which will allow me to expand the data set to show every possible within group pairing? (Desired output below). The pairings do not need to be reciprocal.

Group   Ind1    Ind2
1   Sally   Bob
1   Sally   Sue
1   Sue Bob
2   Joe Jeff
2   Joe Jess
2   Joe Mary
2   Jeff    Jess
2   Jess    Mary
2   Jeff    Mary
3   Jim James

I feel like there must be a way to do this in dplyr, but for the life of me I can't seem to sort it out.

Body:
A solution using dplyr. We can use group_by and do to apply the combn function to each group and combine the results to form a data frame.

library(dplyr)
dt2 <- dt %>%
  group_by(Group) %>%
  do(as_data_frame(t(combn(.$Ind, m = 2)))) %>%
  ungroup() %>%
  setNames(sub("V", "Ind", colnames(.)))
dt2

# # A tibble: 10 x 3
#    Group  Ind1  Ind2
#    <int> <chr> <chr>
#  1     1 Sally   Bob
#  2     1 Sally   Sue
#  3     1   Bob   Sue
#  4     2   Joe  Jeff
#  5     2   Joe  Jess
#  6     2   Joe  Mary
#  7     2  Jeff  Jess
#  8     2  Jeff  Mary
#  9     2  Jess  Mary
# 10     3   Jim James

DATA

dt <- read.table(text = "Ind Group
Sally   1
Bob 1
Sue 1
Joe 2
Jeff    2
Jess    2
Mary    2
Jim 3
James   3",
                 header = TRUE, stringsAsFactors = FALSE)


问:
WordPress How to sort by a custom meta key using a key inside it?
On my WordPress site, each user has a custom meta key named 'user_details' which is an array and has the following structure:

```<code>$user_details = array('age'=>10,'gender'=>'male');
</code>```

in the following example, how can I sort users in an ASC order according to each user 'age'?

```<code><?php
//get all users above 10 years
$args = array(
    'meta_query'    => array(
        'meta_key' => array(
            'key'       => 'user_details',
            'value'     => '',
            'type'      => 'CHAR',
            'compare'   => '!=',
        ),
    ),
    'orderby'       => array( 'meta_key' => 'ASC' ),
);
$users = get_users( $args );
?>
</code>```

SO, the line
array( 'meta_key' => 'ASC' ) does not sort the retrieved users according to 'age', how can I sort the retrieved users according to the age?

Thanks.

答:
Power,

there are 2 options:

1) IF you store an array into the user meta VALUE (not the key) as you appear to have done, THEN you will have to query the records and then sort the array retrieved AFTER the query - lookup php array sorting functions.

2) AN alternative is to store the user details more cleanly in separate meta records eg:
meta-key: user-age
meta-key: user-gender

THEN you can query and sort at the same time.

If you look at how the data is stored in phpmyadmin and try to write a MYSQL query to extract that data, you will gain a better appreciation of the situation.

Body:
On my WordPress site, each user has a custom meta key named 'user_details' which is an array and has the following structure:

$user_details = array('age'=>10,'gender'=>'male');

in the following example, how can I sort users in an ASC order according to each user 'age'?

<?php
//get all users above 10 years
$args = array(
    'meta_query'    => array(
        'meta_key' => array(
            'key'       => 'user_details',
            'value'     => '',
            'type'      => 'CHAR',
            'compare'   => '!=',
        ),
    ),
    'orderby'       => array( 'meta_key' => 'ASC' ),
);
$users = get_users( $args );
?>

SO, the line
array( 'meta_key' => 'ASC' ) does not sort the retrieved users according to 'age', how can I sort the retrieved users according to the age?

Thanks.


问:
.net SQL Server stored procs wrapper class structure
I'm looking to write a C# SQL Server wrapper to call some stored procedures.  If I was writing a single function I'd do something like the following (which I think is correct/proper):

```<code>void RunStoredProc1(object arg1)
{
  using(SqlConnection conn = new SqlConnection(connStr)){
    try{
      SqlCommand cmd = new SqlCommand("storedProc1", conn);
      cmd.CommandType = CommandType.StoredProcedure;
      cmd.Parameters.AddWithValue("@input1", arg1);

      conn.Open();
      cmd.ExecuteNonQuery();
    } catch (Exception ex){
      //handle the exception appropriately.
    }
  }
}
</code>```

The problem I'm having is that it seems like a lot of repeated code... every function will have the same using/try(open/execute)/catch code, and it'd be nice to have it all in only one place.  Is there a clean way of doing this?  How about for queries that I'd want to use a data reader on?

答:
I'm a big fan of letting computers do the rote, repetitive work. They're very good at it. I only have to teach them to do it once. So I wrote a code generator that uses a reference database to generate strongly typed access code. The advantage of this technique is that if you change the stored procedure's signatures, all you have to do it re-gen your data access layer. Any breaking changes will cause compile errors.

The code generate I wrote reads an XML file identifying the stored procedures of interest and retrieves their metadata from the specified reference database(s).

The XML file contains flags identifying whether each stored procedure returns

multiple result sets (dataset)

a single result set (datatable)

a single row (datarow)

a single row with a single column (a scalar value)

a DataReader

an XmlReader

or nothing (nonquery)

From that it generates appropriate code, 1 class per stored procedure. The generated code provides access to the stored procedure's return code as well as the returned value for any output parameters.

It also parses the declaration for the stored procedure in the stored procedure's source code to identify any optional arguments (those with default values): the generated code allows those to be omitted in the call to execute the stored procedure.

Invoking the generated code goes like this:

```<code>    public DataTable GetRiskFactorsForPatient( int patientID )
    {
        dbo_GetRiskbyPatient sp = new dbo_GetRiskbyPatient( CONNECT_STRING_ID ) ;
        int                  rc = sp.Exec( patientID ) ;
        DataTable            dt = sp.ResultSet ;

        if ( dt == null ) throw new InvalidOperationException( "nothing returned from stored procedure" ) ;
        return dt ;
    }
</code>```

Body:
I'm looking to write a C# SQL Server wrapper to call some stored procedures.  If I was writing a single function I'd do something like the following (which I think is correct/proper):

void RunStoredProc1(object arg1)
{
  using(SqlConnection conn = new SqlConnection(connStr)){
    try{
      SqlCommand cmd = new SqlCommand("storedProc1", conn);
      cmd.CommandType = CommandType.StoredProcedure;
      cmd.Parameters.AddWithValue("@input1", arg1);

      conn.Open();
      cmd.ExecuteNonQuery();
    } catch (Exception ex){
      //handle the exception appropriately.
    }
  }
}

The problem I'm having is that it seems like a lot of repeated code... every function will have the same using/try(open/execute)/catch code, and it'd be nice to have it all in only one place.  Is there a clean way of doing this?  How about for queries that I'd want to use a data reader on?

Body:
I'm a big fan of letting computers do the rote, repetitive work. They're very good at it. I only have to teach them to do it once. So I wrote a code generator that uses a reference database to generate strongly typed access code. The advantage of this technique is that if you change the stored procedure's signatures, all you have to do it re-gen your data access layer. Any breaking changes will cause compile errors.

The code generate I wrote reads an XML file identifying the stored procedures of interest and retrieves their metadata from the specified reference database(s).

The XML file contains flags identifying whether each stored procedure returns

multiple result sets (dataset)

a single result set (datatable)

a single row (datarow)

a single row with a single column (a scalar value)

a DataReader

an XmlReader

or nothing (nonquery)

From that it generates appropriate code, 1 class per stored procedure. The generated code provides access to the stored procedure's return code as well as the returned value for any output parameters.

It also parses the declaration for the stored procedure in the stored procedure's source code to identify any optional arguments (those with default values): the generated code allows those to be omitted in the call to execute the stored procedure.

Invoking the generated code goes like this:

    public DataTable GetRiskFactorsForPatient( int patientID )
    {
        dbo_GetRiskbyPatient sp = new dbo_GetRiskbyPatient( CONNECT_STRING_ID ) ;
        int                  rc = sp.Exec( patientID ) ;
        DataTable            dt = sp.ResultSet ;

        if ( dt == null ) throw new InvalidOperationException( "nothing returned from stored procedure" ) ;
        return dt ;
    }


问:
Data Structures - Randomized Queues
I am currently working on the Queues assignment from Princeton's Algorithms Part I. One of the assignments is to implement a randomized queue. This is a question regarding the implementation and tradeoffs of using different data structures.

Question:

A randomized queue is similar to a stack or queue, except that the item removed is chosen uniformly at random from items in the data structure. Create a generic data type RandomizedQueue that implements the following API:

```<code>public class RandomizedQueue<Item> implements Iterable<Item> {
    public RandomizedQueue() // construct an empty randomized queue
    public boolean isEmpty() // is the queue empty?
    public int size() // return the number of items on the queue
    public void enqueue(Item item) // add the item
    public Item dequeue() // remove and return a random item
    public Item sample() // return (but do not remove) a random item
    public Iterator<Item> iterator() // return an independent iterator over items in random order
    public static void main(String[] args)   // unit testing
}
</code>```

The catch here is to implement the dequeue operation and the iterator since the dequeue removes and returns a random element and the iterator iterates over the queue in a random order.

1. Array Implementation:

The primary implementation I was considering is an array implementation. This will be identical to the implementation of an an array queue except the randomness.

Query 1.1: For the dequeue operation, I simply select a number randomly from the size of the array and return that item, and then move the last item in the array to the position of the returned item.

However, this approach changes the order of the queue. In this case it does not matter since I am dequeuing in random order. However, I was wondering if there was an time/memory efficient way to dequeue a random element from the array while preserving the order of the queue without having to create a new array and transfer all the data to it.

```<code>// Current code for dequeue - changes the order of the array after dequeue
private int[] queue; // array queue
private int N; // number of items in the queue

public Item dequeue() {
    if (isEmpty()) throw NoSuchElementException("Queue is empty");
    int randomIndex = StdRandom.uniform(N);
    Item temp = queue[randomIndex]

    if (randomIndex == N - 1) {
        queue[randomIndex] = null; // to avoid loitering
    } else {
        queue[randomIndex] = queue[N - 1];
        queue[randomIndex] = null;
    }

    // code to resize array

    N--;
    return temp;
}
</code>```

Query 1.2: For the iterator to meet the requirement of returning elements randomly, I create a new array with all the indices of the queue, then shuffle the array with a Knuth shuffle operation and return the elements at those particular indices in the queue. However, this involves creating a new array equal to the length of the queue. Again, I am sure I am missing a more efficient method.

2. Inner Class Implementation

The second implementation involves an inner node class.

```<code>public class RandomizedQueue<Item> {
    private static class Node<Item> {
        Item item;
        Node<Item> next;
        Node<Item> previous;
    }
}
</code>```

Query 2.1. In this case I understand how to perform the dequeue operation efficiently: Return a random node and change the references for the adjacent nodes.

However, I am confounded by how to return a iterator that returns the nodes in random order without having to create a whole new queue with nodes attached in random order.

Further, what are the benefits of using such a data structure over an array, other than readability and ease of implementation?

This post is kind of long. I appreciate that you guys have taken the time to read my question and help me out. Thanks!

答:
For your Query 1.1: Here you can indeed remove a random element in constant time.
The idea is simply as follows:

pick a random element to return

swap it with the last element in your queue

delete the last element in your queue

This way you keep having a continuous array without 'holes'

Title: Data Structures - Randomized Queues

Body:
I am currently working on the Queues assignment from Princeton's Algorithms Part I. One of the assignments is to implement a randomized queue. This is a question regarding the implementation and tradeoffs of using different data structures.

Question:

A randomized queue is similar to a stack or queue, except that the item removed is chosen uniformly at random from items in the data structure. Create a generic data type RandomizedQueue that implements the following API:

public class RandomizedQueue<Item> implements Iterable<Item> {
    public RandomizedQueue() // construct an empty randomized queue
    public boolean isEmpty() // is the queue empty?
    public int size() // return the number of items on the queue
    public void enqueue(Item item) // add the item
    public Item dequeue() // remove and return a random item
    public Item sample() // return (but do not remove) a random item
    public Iterator<Item> iterator() // return an independent iterator over items in random order
    public static void main(String[] args)   // unit testing
}

The catch here is to implement the dequeue operation and the iterator since the dequeue removes and returns a random element and the iterator iterates over the queue in a random order.

1. Array Implementation:

The primary implementation I was considering is an array implementation. This will be identical to the implementation of an an array queue except the randomness.

Query 1.1: For the dequeue operation, I simply select a number randomly from the size of the array and return that item, and then move the last item in the array to the position of the returned item.

However, this approach changes the order of the queue. In this case it does not matter since I am dequeuing in random order. However, I was wondering if there was an time/memory efficient way to dequeue a random element from the array while preserving the order of the queue without having to create a new array and transfer all the data to it.

// Current code for dequeue - changes the order of the array after dequeue
private int[] queue; // array queue
private int N; // number of items in the queue

public Item dequeue() {
    if (isEmpty()) throw NoSuchElementException("Queue is empty");
    int randomIndex = StdRandom.uniform(N);
    Item temp = queue[randomIndex]

    if (randomIndex == N - 1) {
        queue[randomIndex] = null; // to avoid loitering
    } else {
        queue[randomIndex] = queue[N - 1];
        queue[randomIndex] = null;
    }

    // code to resize array

    N--;
    return temp;
}

Query 1.2: For the iterator to meet the requirement of returning elements randomly, I create a new array with all the indices of the queue, then shuffle the array with a Knuth shuffle operation and return the elements at those particular indices in the queue. However, this involves creating a new array equal to the length of the queue. Again, I am sure I am missing a more efficient method.

2. Inner Class Implementation

The second implementation involves an inner node class.

public class RandomizedQueue<Item> {
    private static class Node<Item> {
        Item item;
        Node<Item> next;
        Node<Item> previous;
    }
}

Query 2.1. In this case I understand how to perform the dequeue operation efficiently: Return a random node and change the references for the adjacent nodes.

However, I am confounded by how to return a iterator that returns the nodes in random order without having to create a whole new queue with nodes attached in random order.

Further, what are the benefits of using such a data structure over an array, other than readability and ease of implementation?

This post is kind of long. I appreciate that you guys have taken the time to read my question and help me out. Thanks!


问:
Selecting one row based on the values in a group
Novice SQL coder here. My data looks like this:

```<code>Case          Allegation          Result
1             1                   Supported
1             2                   Not Supported
2             1                   Not Supported
3             1                   Not Supported
3             2                   Supported
3             3                   Not Supported
4             1                   Not Supported
4             2                   Supported
</code>```

For my purposes, a case is considered "supported" if any allegations within it are supported. What I need to do is to return one row per unique Case which reads "Supported" if that condition is met, and otherwise reads "Not Supported":

```<code>Case          Result
1             Supported
2             Not Supported
3             Supported
4             Supported
</code>```

In the past I'd have "over-selected" what I needed and done the display work through Reporting Services expressions, but this time I'm delivering a query. I'd imagine I need a subselect with groups for this but haven't the first idea of how to do it.

答:
```<code>SELECT DISTINCT a.[case],
            CASE
              WHEN c.result IS NULL THEN 'Not Supported'
              ELSE 'Supported'
            END AS result
FROM   t AS a
   LEFT JOIN (SELECT b.[case],
                     b.result
              FROM   t AS b
              WHERE  b.result = 'Supported') AS c
          ON a.[case] = c.[case];
</code>```

Result:

```<code>case    result
1   Supported
2   Not Supported
3   Supported
4   Supported
</code>```

You can see it here:

http://sqlfiddle.com/#!6/9c217/47

Body:
Novice SQL coder here. My data looks like this:

Case          Allegation          Result
1             1                   Supported
1             2                   Not Supported
2             1                   Not Supported
3             1                   Not Supported
3             2                   Supported
3             3                   Not Supported
4             1                   Not Supported
4             2                   Supported

For my purposes, a case is considered "supported" if any allegations within it are supported. What I need to do is to return one row per unique Case which reads "Supported" if that condition is met, and otherwise reads "Not Supported":

Case          Result
1             Supported
2             Not Supported
3             Supported
4             Supported

In the past I'd have "over-selected" what I needed and done the display work through Reporting Services expressions, but this time I'm delivering a query. I'd imagine I need a subselect with groups for this but haven't the first idea of how to do it.

Body:
SELECT DISTINCT a.[case],
            CASE
              WHEN c.result IS NULL THEN 'Not Supported'
              ELSE 'Supported'
            END AS result
FROM   t AS a
   LEFT JOIN (SELECT b.[case],
                     b.result
              FROM   t AS b
              WHERE  b.result = 'Supported') AS c
          ON a.[case] = c.[case];

Result:

case    result
1   Supported
2   Not Supported
3   Supported
4   Supported

You can see it here:

http://sqlfiddle.com/#!6/9c217/47