问:
Getting Paypal access token from a refresh token
When I try to get access_token from refresh token via cURL or postman getting response successfully,

REQUEST

```<code>POST /v1/oauth2/token HTTP/1.1
Host: api.sandbox.paypal.com
Content-Type: application/x-www-form-urlencoded
Authorization: Basic QVZZeWdRa2dSX3pScmtJT25PZXVz.....
Cache-Control: no-cache

grant_type=refresh_token&refresh_token=-Q1_6fEwUDQ0ci0CJIA......
</code>```

RESULT

```<code>{
"scope":"phone https://uri.paypal.com/services/subscriptions https://api.paypal.com/v1/payments/.* address email https://api.paypal.com/v1/vault/credit-card https://uri.paypal.com/services/applications/webhooks https://uri.paypal.com/services/payments/futurepayments openid https://api.paypal.com/v1/vault/credit-card/.*","nonce":"2016-11-08T13:58:45Zm5eDiRGyJIDC9EwX7DRl6aB7IPlRl-cjoS_E3Ro8sCo",
"access_token":"A103.CfI6WQaDmEqrQ.....",
"token_type":"Bearer",
"app_id":"APP-80W28448....",
"expires_in":28796
}
</code>```

But when I do the same thing with paypal-net sdk like this,

```<code>var apiContext = PaypalConfiguration.GetAPIContext();
var tokenInfo = new Tokeninfo();
tokenInfo.refresh_token = "-Q1_6fEwUDQ0ci0CJIA7BtG_Ey4i....";
var refreshTokenParams = new CreateFromRefreshTokenParameters();
var token = tokenInfo.CreateFromRefreshToken(apiContext, refreshTokenParams);
</code>```

I keep getting this response,

```<code>{
"error_description":"POST /v1/oauth2/token returned a response status of 400 Bad Request",
"error":"400",
"correlation_id":"46ecefc761f3f",
"information_link":"https://developer.paypal.com/docs/api/#errors"
}
</code>```

my mode is set as sandbox, client id and client secret are right for sandbox.

Could you please tell me where I am wrong or are there something wrong with Paypal-NET-SDK?

答:
Try it for .Net SDK</p>

```<code> byte[] bytes = Encoding.UTF8.GetBytes("ClientId:ClientSecret");
            string base64 = Convert.ToBase64String(bytes);
            var client = new RestClient("https://api.sandbox.paypal.com/v1/identity/openidconnect/tokenservice");
            var request = new RestRequest(Method.POST);
            request.AddHeader("postman-token", "3c08eb6d-d6fb-a622-5d21-e9f1a6daa3ce");
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("content-type", "application/x-www-form-urlencoded");
            request.AddHeader("authorization", "Basic " + base64);
            request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&refresh_token=" + dataFilter.RefreshToken, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
</code>```

Body:
When I try to get access_token from refresh token via cURL or postman getting response successfully,

REQUEST

POST /v1/oauth2/token HTTP/1.1
Host: api.sandbox.paypal.com
Content-Type: application/x-www-form-urlencoded
Authorization: Basic QVZZeWdRa2dSX3pScmtJT25PZXVz.....
Cache-Control: no-cache

grant_type=refresh_token&refresh_token=-Q1_6fEwUDQ0ci0CJIA......

RESULT

{
"scope":"phone https://uri.paypal.com/services/subscriptions https://api.paypal.com/v1/payments/.* address email https://api.paypal.com/v1/vault/credit-card https://uri.paypal.com/services/applications/webhooks https://uri.paypal.com/services/payments/futurepayments openid https://api.paypal.com/v1/vault/credit-card/.*","nonce":"2016-11-08T13:58:45Zm5eDiRGyJIDC9EwX7DRl6aB7IPlRl-cjoS_E3Ro8sCo",
"access_token":"A103.CfI6WQaDmEqrQ.....",
"token_type":"Bearer",
"app_id":"APP-80W28448....",
"expires_in":28796
}

But when I do the same thing with paypal-net sdk like this,

var apiContext = PaypalConfiguration.GetAPIContext();
var tokenInfo = new Tokeninfo();
tokenInfo.refresh_token = "-Q1_6fEwUDQ0ci0CJIA7BtG_Ey4i....";
var refreshTokenParams = new CreateFromRefreshTokenParameters();
var token = tokenInfo.CreateFromRefreshToken(apiContext, refreshTokenParams);

I keep getting this response,

{
"error_description":"POST /v1/oauth2/token returned a response status of 400 Bad Request",
"error":"400",
"correlation_id":"46ecefc761f3f",
"information_link":"https://developer.paypal.com/docs/api/#errors"
}

my mode is set as sandbox, client id and client secret are right for sandbox.

Could you please tell me where I am wrong or are there something wrong with Paypal-NET-SDK?

Body:
Try it for .Net SDK

 byte[] bytes = Encoding.UTF8.GetBytes("ClientId:ClientSecret");
            string base64 = Convert.ToBase64String(bytes);
            var client = new RestClient("https://api.sandbox.paypal.com/v1/identity/openidconnect/tokenservice");
            var request = new RestRequest(Method.POST);
            request.AddHeader("postman-token", "3c08eb6d-d6fb-a622-5d21-e9f1a6daa3ce");
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("content-type", "application/x-www-form-urlencoded");
            request.AddHeader("authorization", "Basic " + base64);
            request.AddParameter("application/x-www-form-urlencoded", "grant_type=refresh_token&refresh_token=" + dataFilter.RefreshToken, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);


来源: stackexchange

问:
how can read text data from excel in matlab?
i want to read text and numbers from an excel file. when i write the code as below it can not read the text data from excel file. how can i fix it? thank for taking your time.

```<code>data = xlsread('normalize.xlsx');
</code>```

the picture of excel file is here:

    and the picture of data that created from the code is hear:

答:
'xlsread' and 'csvread' are both for reading numeric data in MATLAB.  If you are on a Windows platform and have Microsoft Excel installed, you can use the following syntax with 'xlsread' to read your data into two cell arrays:

```<code>[num_data string_data] = xlsread('normalize.xlsx');
</code>```

You will have the text column in your data in the string_data array. The corresponding column in num_data will still have NAN.

ContentLicense: CC BY-SA 3.0

Body:
i want to read text and numbers from an excel file. when i write the code as below it can not read the text data from excel file. how can i fix it? thank for taking your time.

data = xlsread('normalize.xlsx');

the picture of excel file is here:

    and the picture of data that created from the code is hear:

Body:
'xlsread' and 'csvread' are both for reading numeric data in MATLAB.  If you are on a Windows platform and have Microsoft Excel installed, you can use the following syntax with 'xlsread' to read your data into two cell arrays:

[num_data string_data] = xlsread('normalize.xlsx');

You will have the text column in your data in the string_data array. The corresponding column in num_data will still have NAN.


问:
Android ListView width keeps changing
Firstly, I am new to android so if I have missed something basic I apologise.

I have a page which has two ListViews side by side, both with varying amounts of content. I also have a TextView above the ListViews and another TextView below the listviews. These text view boxes change based on items selected in either of the two ListViews.

These two ListViews sit side by side, taking up half of the screen each, while a Textview sits directly above and directly below, both centred to the page. An image is shown below.

This is the page looking normal on load.

The problem is when I select an item from either list. I have a feeling I am missing some XML properties, but I am not sure which properties or if this is even the case. When an item is selected, let's say from the ListView on the right, the TextView at the bottom is updated with text taken from an array. The ListView also decides to change the width and I am not sure why this is.... I don't want the ListView to change width. I want it to remain taking up half of the page and half of the page only.

This is the page after an item from the right ListView has been selected.

I would also like to keep things in RelativeLayout. I also believe it is only an XML issue and not to do with the adapter or any other code so I will not include that for now. I can include it if required.

Any help would be great. Thanks in advance.

content_titles.xml my activity xml file

```<code><?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TitlesActivity">

<ListView
    android:id="@+id/unlocked_titles_list"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:longClickable="true"
    android:layout_below="@+id/current_title"
    android:layout_alignEnd="@+id/requirements"
    android:layout_marginEnd="26dp"
    android:layout_above="@+id/requirements">
</ListView>

<TextView
    android:id="@+id/current_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="65dp"
    android:text="Current Title: Novice"
    android:textSize="24sp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"/>

<ListView
    android:id="@+id/locked_titles_list"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_alignStart="@+id/requirements"
    android:layout_marginStart="28dp"
    android:layout_above="@+id/requirements"
    android:layout_below="@+id/current_title"/>

<TextView
    android:id="@+id/requirements"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="34dp"
    android:text="temp"
    android:textAlignment="center"
    android:textSize="24sp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"/>

</RelativeLayout>
</code>```

activity_listview.xml used as the individual rows of the ListViews

```<code><TextView xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/label"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:padding="10dip"
      android:textSize="16dip"
      android:textStyle="bold" >
</TextView>
</code>```

答: You have your layout_width properties set to wrap_content. This means that they could change as the data changes. I would recommend putting your ListViews in a LinearLayout with orientation:horizontal and set the amount of space that each element takes up with layout_weight. Here is a relevant SO question What does android:layout_weight mean?

Title: Android ListView width keeps changing

Body:
Firstly, I am new to android so if I have missed something basic I apologise.

I have a page which has two ListViews side by side, both with varying amounts of content. I also have a TextView above the ListViews and another TextView below the listviews. These text view boxes change based on items selected in either of the two ListViews.

These two ListViews sit side by side, taking up half of the screen each, while a Textview sits directly above and directly below, both centred to the page. An image is shown below.

This is the page looking normal on load.

The problem is when I select an item from either list. I have a feeling I am missing some XML properties, but I am not sure which properties or if this is even the case. When an item is selected, let's say from the ListView on the right, the TextView at the bottom is updated with text taken from an array. The ListView also decides to change the width and I am not sure why this is.... I don't want the ListView to change width. I want it to remain taking up half of the page and half of the page only.

This is the page after an item from the right ListView has been selected.

I would also like to keep things in RelativeLayout. I also believe it is only an XML issue and not to do with the adapter or any other code so I will not include that for now. I can include it if required.

Any help would be great. Thanks in advance.

content_titles.xml my activity xml file

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TitlesActivity">

<ListView
    android:id="@+id/unlocked_titles_list"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:longClickable="true"
    android:layout_below="@+id/current_title"
    android:layout_alignEnd="@+id/requirements"
    android:layout_marginEnd="26dp"
    android:layout_above="@+id/requirements">
</ListView>

<TextView
    android:id="@+id/current_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="65dp"
    android:text="Current Title: Novice"
    android:textSize="24sp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"/>

<ListView
    android:id="@+id/locked_titles_list"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_alignStart="@+id/requirements"
    android:layout_marginStart="28dp"
    android:layout_above="@+id/requirements"
    android:layout_below="@+id/current_title"/>

<TextView
    android:id="@+id/requirements"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="34dp"
    android:text="temp"
    android:textAlignment="center"
    android:textSize="24sp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"/>

</RelativeLayout>

activity_listview.xml used as the individual rows of the ListViews

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/label"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:padding="10dip"
      android:textSize="16dip"
      android:textStyle="bold" >
</TextView>


问:
Why is toggleClass not working here?
I'm trying to add / remove a class on click here, but toggleClass is not working as I'm expecting it to. On the contrary, addClass works fine, but I need it to remove the class on the second click.

```<code>$('.label1').on('click', function() {
    var $checkItem = $(this).find('input[type=checkbox]');
    $(this).toggleClass('checked');
    $checkItem.prop("checked", !$checkItem.prop("checked"));
})

$('.label2').on('click', function() {
    var $checkItem = $(this).find('input[type=checkbox]');
    $(this).addClass('checked');
    $checkItem.prop("checked", !$checkItem.prop("checked"));
})
</code>```

Can you tell me what am I doing wrong?

See it in action here: Test jquery.

Thanks!

答:
Here you can do it like this.

Try this example hope it will helps you.

$('.label1').on('click', function() {
    var $checkItem = $(this).find('input[type=checkbox]');

    $(this).toggleClass('checked');
    if($(this).hasClass('checked')) {
       $checkItem.prop("checked", true);
    } else {
        $checkItem.prop("checked", false);
    }
  })

  $('.label2').on('click', function() {
    var $checkItem = $(this).find('input[type=checkbox]');

    if($(this).hasClass('checked')) {
       $checkItem.prop("checked", false);
        $(this).removeClass('checked');
    } else {
       $(this).addClass('checked');
        $checkItem.prop("checked", true);
    }
  })```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.checked {
  border: 2px solid red;
}</code>```

<form>

      <input type="checkbox">
      Check me out

      <input type="checkbox">
      Check me out

</form>```

Title: Why is toggleClass not working here?

Body:
I'm trying to add / remove a class on click here, but toggleClass is not working as I'm expecting it to. On the contrary, addClass works fine, but I need it to remove the class on the second click.

$('.label1').on('click', function() {
    var $checkItem = $(this).find('input[type=checkbox]');
    $(this).toggleClass('checked');
    $checkItem.prop("checked", !$checkItem.prop("checked"));
})

$('.label2').on('click', function() {
    var $checkItem = $(this).find('input[type=checkbox]');
    $(this).addClass('checked');
    $checkItem.prop("checked", !$checkItem.prop("checked"));
})

Can you tell me what am I doing wrong?

See it in action here: Test jquery.

Thanks!

Body:
Here you can do it like this.

Try this example hope it will helps you.

$('.label1').on('click', function() {
    var $checkItem = $(this).find('input[type=checkbox]');

    $(this).toggleClass('checked');
    if($(this).hasClass('checked')) {
       $checkItem.prop("checked", true);
    } else {
        $checkItem.prop("checked", false);
    }
  })

  $('.label2').on('click', function() {
    var $checkItem = $(this).find('input[type=checkbox]');

    if($(this).hasClass('checked')) {
       $checkItem.prop("checked", false);
        $(this).removeClass('checked');
    } else {
       $(this).addClass('checked');
        $checkItem.prop("checked", true);
    }
  })

.checked {
  border: 2px solid red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <div class="checkbox">
    <label class="label1">
      <input type="checkbox">
      Check me out
    </label>
  </div>
  <div class="checkbox">
    <label class="label2">
      <input type="checkbox">
      Check me out
    </label>
  </div>
</form>


问:
Add children to UserControl
I created a user control and now I would like to be able to set it up so I can add children to each instance of it.

This is how it's laid out:

The red boxes are panels that I'd like to be able to add children to. The idea is that I use this control in my winforms app, and from there drag and drop new controls into the red parent container.

How do I do this?

答:
I just want to know if it's possible to drag items from the toolbox into one of the red areas to have it become a child of the user control.

Yes, it is possible:

```<code>[Designer(typeof(MyUserControlDesigner))]
public partial class MyUserControl : UserControl
{
}
</code>```

And you have to implement a designer class. This is how you can add controls to the inner Content panel at design time (assuming that the panel is exposed as a public PanelContent property):

```<code>internal sealed class MyUserControlDesigner : ParentControlDesigner
{
    IDesignerHost designerHost;

    public override void Initialize(IComponent component)
    {
        base.Initialize(component);
        base.AutoResizeHandles = true;
        base.EnableDesignMode(((MyUserControl)component).PanelContent, "ContentPanel");
        designerHost = (IDesignerHost)component.Site.GetService(typeof(IDesignerHost));
    }

    public override bool CanParent(Control control)
    {
        return false;
    }

    public override System.Collections.ICollection AssociatedComponents
    {
        get
        {
            List<Control> list = new List<Control>();
            foreach (Control control in ((MyUserControl)Control).PanelContent.Controls)
            {
                list.Add(control);
            }
            return list;
        }
    }

    protected override Control GetParentForComponent(IComponent component)
    {
        return ((MyUserControl)Control).PanelContent;
    }

    public override int NumberOfInternalControlDesigners()
    {
        return 1;
    }

    public override ControlDesigner InternalControlDesigner(int internalControlIndex)
    {
        Control panel = ((MyUserControl)Control).PanelContent;
        switch (internalControlIndex)
        {
            case 0:
                return this.designerHost.GetDesigner(panel) as ControlDesigner;
            default:
                return null;
        }
    }

    protected override IComponent[] CreateToolCore(ToolboxItem tool, int x, int y, int width, int height, bool hasLocation, bool hasSize)
    {
        ParentControlDesigner panelDesigner = this.designerHost.GetDesigner(((MyUserControl)Control).PanelContent) as ParentControlDesigner;
        InvokeCreateTool(panelDesigner, tool);
        return null;
    }
}
</code>```

If you want to expose multiple hosts you can modify NumberOfInternalControlDesigners and InternalControlDesigner methods. However, it never really worked for me. You can decide by the component to add, which parent should be used (see GetParentForComponent) but it means for example that buttons are always added to the buttons panel. I suggest to offer the content panel only as parent and use some public properties for manipulating the buttons panel instead.

Title: Add children to UserControl

Body:
I just want to know if it's possible to drag items from the toolbox into one of the red areas to have it become a child of the user control.

Yes, it is possible:

[Designer(typeof(MyUserControlDesigner))]
public partial class MyUserControl : UserControl
{
}

And you have to implement a designer class. This is how you can add controls to the inner Content panel at design time (assuming that the panel is exposed as a public PanelContent property):

internal sealed class MyUserControlDesigner : ParentControlDesigner
{
    IDesignerHost designerHost;

    public override void Initialize(IComponent component)
    {
        base.Initialize(component);
        base.AutoResizeHandles = true;
        base.EnableDesignMode(((MyUserControl)component).PanelContent, "ContentPanel");
        designerHost = (IDesignerHost)component.Site.GetService(typeof(IDesignerHost));
    }

    public override bool CanParent(Control control)
    {
        return false;
    }

    public override System.Collections.ICollection AssociatedComponents
    {
        get
        {
            List<Control> list = new List<Control>();
            foreach (Control control in ((MyUserControl)Control).PanelContent.Controls)
            {
                list.Add(control);
            }
            return list;
        }
    }

    protected override Control GetParentForComponent(IComponent component)
    {
        return ((MyUserControl)Control).PanelContent;
    }

    public override int NumberOfInternalControlDesigners()
    {
        return 1;
    }

    public override ControlDesigner InternalControlDesigner(int internalControlIndex)
    {
        Control panel = ((MyUserControl)Control).PanelContent;
        switch (internalControlIndex)
        {
            case 0:
                return this.designerHost.GetDesigner(panel) as ControlDesigner;
            default:
                return null;
        }
    }

    protected override IComponent[] CreateToolCore(ToolboxItem tool, int x, int y, int width, int height, bool hasLocation, bool hasSize)
    {
        ParentControlDesigner panelDesigner = this.designerHost.GetDesigner(((MyUserControl)Control).PanelContent) as ParentControlDesigner;
        InvokeCreateTool(panelDesigner, tool);
        return null;
    }
}

If you want to expose multiple hosts you can modify NumberOfInternalControlDesigners and InternalControlDesigner methods. However, it never really worked for me. You can decide by the component to add, which parent should be used (see GetParentForComponent) but it means for example that buttons are always added to the buttons panel. I suggest to offer the content panel only as parent and use some public properties for manipulating the buttons panel instead.


问:
Canvas causes contentcontrol children to spill out over control
I have the following XAML:

```<code><Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="2*"/>
        <ColumnDefinition Width="11" />
        <ColumnDefinition Width="3*"/>
    </Grid.ColumnDefinitions>
    <ListView ... Grid.Column="2"/>
    <controls:GridSplitter
    Grid.Column="1"
        Width="11"
    ResizeBehavior="BasedOnAlignment"
    ResizeDirection="Auto"
        Background="Gray"
        Foreground="White"
        FontSize="13">
        <controls:GridSplitter.Element>
            <Grid>
                <TextBlock HorizontalAlignment="Center"
                           IsHitTestVisible="False"
                           VerticalAlignment="Center"
                            Text=""
                           Foreground="Black"
                           FontFamily="Segoe MDL2 Assets">
                </TextBlock>
            </Grid>
        </controls:GridSplitter.Element>
    </controls:GridSplitter>
    <Canvas Canvas.ZIndex="1">
        <ContentControl MaxWidth="750" Content="{Binding CAV, Mode=TwoWay}" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" />
    </Canvas>
</Grid>
</code>```

Without the Canvas wrapped around the ContentControl in the first column, the children of the ContentControl properly stay within the content control and I can make it wider to see more of the children horizontally.

When I add the Canvas and set the ZIndex, the children of the content control spill out over the gridsplitter and the ListView without respecting the width of the contentcontrol.

The effect I'm trying to get it to allow expanding the width of the content control with the grid splitter and having that content control expand "over" the listview (instead of reducing the width of the listview).

What am I missing? I'm confused as to why the width of the contentcontrol isn't being respected suddenly just because I wrap it in a Canvas. Or should I not be using Canvas to get the "overlay" effect I want?

答:
Canvas doesn't stretch its children. It only gives them the space they need. In fact, you don't have to wrap your ContentControl inside a Canvas to set the Canvas.ZIndex; it is an attached property that can be attached to the ContentControl directly. If you want a panel that allows its children/child to stretch, try a Border(single child only) or a Grid.

However, setting the ZIndex here seems to be unnecessary to me. Since the GridSplitter simply resizes the width of the columns, there won't be any overlay happening here.

If you want the overlay effect, you need to create another Grid with the same column layout and place your ListView there, something like the following -

```<code><Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="2*" />
            <ColumnDefinition Width="11" />
            <ColumnDefinition Width="3*" />
        </Grid.ColumnDefinitions>
        <Grid x:Name="ListView" Background="LightGreen" Grid.Column="2" />
    </Grid>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="2*" />
            <ColumnDefinition Width="11" />
            <ColumnDefinition Width="3*" />
        </Grid.ColumnDefinitions>
        <controls:GridSplitter Grid.Column="1" Background="LightBlue">
        </controls:GridSplitter>
        <Grid x:Name="ContentControl" Background="LightPink" Opacity="0.5" />
    </Grid>
</Grid>
</code>```

Body:
I have the following XAML:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="2*"/>
        <ColumnDefinition Width="11" />
        <ColumnDefinition Width="3*"/>
    </Grid.ColumnDefinitions>
    <ListView ... Grid.Column="2"/>
    <controls:GridSplitter
    Grid.Column="1"
        Width="11"
    ResizeBehavior="BasedOnAlignment"
    ResizeDirection="Auto"
        Background="Gray"
        Foreground="White"
        FontSize="13">
        <controls:GridSplitter.Element>
            <Grid>
                <TextBlock HorizontalAlignment="Center"
                           IsHitTestVisible="False"
                           VerticalAlignment="Center"
                            Text=""
                           Foreground="Black"
                           FontFamily="Segoe MDL2 Assets">
                </TextBlock>
            </Grid>
        </controls:GridSplitter.Element>
    </controls:GridSplitter>
    <Canvas Canvas.ZIndex="1">
        <ContentControl MaxWidth="750" Content="{Binding CAV, Mode=TwoWay}" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" />
    </Canvas>
</Grid>

Without the Canvas wrapped around the ContentControl in the first column, the children of the ContentControl properly stay within the content control and I can make it wider to see more of the children horizontally.

When I add the Canvas and set the ZIndex, the children of the content control spill out over the gridsplitter and the ListView without respecting the width of the contentcontrol.

The effect I'm trying to get it to allow expanding the width of the content control with the grid splitter and having that content control expand "over" the listview (instead of reducing the width of the listview).

What am I missing? I'm confused as to why the width of the contentcontrol isn't being respected suddenly just because I wrap it in a Canvas. Or should I not be using Canvas to get the "overlay" effect I want?

Body:
Canvas doesn't stretch its children. It only gives them the space they need. In fact, you don't have to wrap your ContentControl inside a Canvas to set the Canvas.ZIndex; it is an attached property that can be attached to the ContentControl directly. If you want a panel that allows its children/child to stretch, try a Border(single child only) or a Grid.

However, setting the ZIndex here seems to be unnecessary to me. Since the GridSplitter simply resizes the width of the columns, there won't be any overlay happening here.

If you want the overlay effect, you need to create another Grid with the same column layout and place your ListView there, something like the following -

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="2*" />
            <ColumnDefinition Width="11" />
            <ColumnDefinition Width="3*" />
        </Grid.ColumnDefinitions>
        <Grid x:Name="ListView" Background="LightGreen" Grid.Column="2" />
    </Grid>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="2*" />
            <ColumnDefinition Width="11" />
            <ColumnDefinition Width="3*" />
        </Grid.ColumnDefinitions>
        <controls:GridSplitter Grid.Column="1" Background="LightBlue">
        </controls:GridSplitter>
        <Grid x:Name="ContentControl" Background="LightPink" Opacity="0.5" />
    </Grid>
</Grid>


答:
You can use np.lib.stride_tricks.as_strided:

```<code># a smaller example
import numpy.random as npr
npr.seed(123)
arr = npr.randn(10)
arr[:4] = np.nan

windows = np.lib.stride_tricks.as_strided(arr, shape=(8, 3), strides=(8, 8))

print(windows.max(axis=1))
print(windows.sum(axis=1))
[        nan         nan         nan         nan  1.65143654  1.65143654
  1.26593626  1.26593626]
[        nan         nan         nan         nan -1.35384296 -1.20415534
 -1.58965561 -0.02971677]
</code>```

Title: How to get the rolling(window = 3).max() on a numpy.ndarray?

Body:
I have a numpy.ndarray as follow. It's the output from talib.RSI. It's the type of numpy.ndarray. I want to get the list of rolling(windows=3).max() and the rolling(window=3).min

How to do that?

[         nan          nan          nan          nan          nan
          nan          nan          nan          nan          nan
          nan          nan          nan          nan  56.50118203
  60.05461743  56.99068148  55.70899949  59.2299361   64.19044898
  60.62186599  53.96346826  44.06538636  52.04519976  51.32884016
  58.65240379  60.44789401  58.94743634  59.75308787  53.56534397
  54.22091468  47.22502341  51.5425848   50.0923126   49.80608264
  45.69087847  50.07778871  54.21701441  58.79268406  63.59307774
  66.08195696  65.49255218  65.11035657  68.47403716  70.70530564
  73.21955929  76.57474822  65.89852612  66.51497688  72.42658468
  73.80944844  69.56561001]

Body:
You can use np.lib.stride_tricks.as_strided:

# a smaller example
import numpy.random as npr
npr.seed(123)
arr = npr.randn(10)
arr[:4] = np.nan

windows = np.lib.stride_tricks.as_strided(arr, shape=(8, 3), strides=(8, 8))

print(windows.max(axis=1))
print(windows.sum(axis=1))
[        nan         nan         nan         nan  1.65143654  1.65143654
  1.26593626  1.26593626]
[        nan         nan         nan         nan -1.35384296 -1.20415534
 -1.58965561 -0.02971677]


问:
Oracle SQL WITH clause correct use case and performance
I have to perform relatively complicated query involving multiple deep joins and complex predicates, where the result (and criteria) depends of suitable entries available meeting the criteria. There are kinda primary and secondary criteria involved, primary is applied always, and secondary strikes in if the the result is not satisfying. In a nutshell

Return N (pseudo) random  distinct customers and their newest document

The result should contain equal amount of documents of two different type

But if there's not enough different document types or different customers with a document, try to still satisfy the amount of N documents

Compensate the lack of other document type by choosing more another

Compensate the lack of overall document count by using multiple documents of the same customers, when necessary

I choose declarative (query) approach over imperative (cursors and counters). And this is where the WITH clause comes in. Roughly, by using multiple WITH blocks (CTE's) I declare queries (I like to think them as ad-hoc views) to declare two distinct target set for both document types. In the end, I UNION subsets of different CTE's for the final result, performing some COUNT checks to limit the amount.

Multiple CTE's are referencing each other and are referenced from multiple places in the context of COUNT and NOT EXISTS for example. I'm novice with SQL and happened to encounter WITH by a coincidence, and chose to use it intuitively. Is this the correct use case for WITH, or an anti pattern? How does this solution compares in performance to implementing the same functionality with cursors and counters in an imperative style? Have I chosen the wrong approach? We are talking about tables with million entries.

Here is the the query as a whole. Pardon me, I had to obscure the fields due confidentiality.

```<code>    WITH target_documents AS (
        SELECT
            <Necessary fields>
        FROM documents l
        WHERE
            <Suitable document criteria>
    ),
    target_documents_type_1 AS (
        SELECT * FROM target_documents WHERE type = 1
    ),
    target_documents_type_2 AS (
        SELECT * FROM target_documents WHERE type = 2
    ),
    target_customers AS (
        SELECT
            <Necessary fields>
        FROM customers a
        WHERE
            <Suitable customer criteria>
            AND
            EXISTS(
                SELECT 1 FROM target_documents l WHERE l.customer_id = a.customer_id
            )
    ),
    target_customers_type_1 AS (
        SELECT * FROM target_customers a WHERE EXISTS(
            SELECT 1 FROM target_documents_type_1 l WHERE l.customer_id = a.customer_id
        )
        AND ROWNUM <= (<N> / 2)
    ),
    target_customers_type_2 AS (
        SELECT * FROM target_customers a WHERE EXISTS(
            SELECT 1 FROM target_documents_type_2 l WHERE l.customer_id = a.customer_id
        )
        AND a.customer_id NOT IN (
            SELECT customer_id FROM target_customers_type_1
        )
        AND ROWNUM <= <N>
    ),
    -- This is the set, which meets the the primary criteria:
    -- Contains only distinct customers
    -- The amount of different document types is balanced as much as possible
    different_customers_set AS (
        SELECT
            <Necessary fields>
        FROM target_customers_type_1 a -- rows 0--(<N>/2) amount
        JOIN target_documents_type_1 l ON (l.customer_id = a.customer_id)
        WHERE
            l.create_dt = (SELECT MAX(create_dt) FROM target_documents_type_1 WHERE customer_id = l.customer_id)
        UNION ALL
        SELECT
            <Necessary fields>
        FROM target_customers_type_2 a -- rows 0--<N> amount
        JOIN target_documents_type_2 l ON (l.customer_id = a.customer_id)
        WHERE
            l.create_dt = (SELECT MAX(create_dt) FROM target_documents_type_2 WHERE customer_id = l.customer_id) AND
            ROWNUM <= <N> - (SELECT COUNT(*) FROM target_customers_type_1) -- Limit the total to max N rows
    )

    -- Final result: primary criteria result filled with the result of secondary criteria
    SELECT * FROM different_customers_set
    UNION ALL
    SELECT
        <Necessary fields>
    FROM target_customers a
    JOIN target_documents l ON (l.customer_id = a.customer_id AND l.document_id NOT IN (SELECT document_id FROM different_customers_set))
    WHERE
        ROWNUM <= <N> - (SELECT COUNT(1) FROM different_customers_set);
</code>```

Is this the correct usage of WITH clause? Are there some obvious performance issues, where I should refactor? Or should I have done all this imperatively? Also, this query itself defines a cursor, which is used opened repeatedly in a loop (the loop defines certain criteria for customers).

I'm especially concerned, how the optimizer handles those WITH blocks. Is the most efficiently plan always used (so there's not performance penalty compared to using cursors)?

答:
The only true way to evaluate the performance of a query against some other approach is to benchmark both and see which is the best fit for your data and your application/environment. Everything else is just grimacing and guessing.

Having said which :-)

SQL is generally faster than PL/SQL, especially for large amounts of data because set operations scale better than row-by-row processing.

The temptation with the WITH clause is to build a procedural query rather than a set-based one. It looks like you've dodged that bullet: you're using subquery factoring properly, to reduce the number of times you execute the query to get the same result set.

However, that's just my guess. You could try writing the query the long way, without the WITH clause and see which is better (faster)

Body:
I have to perform relatively complicated query involving multiple deep joins and complex predicates, where the result (and criteria) depends of suitable entries available meeting the criteria. There are kinda primary and secondary criteria involved, primary is applied always, and secondary strikes in if the the result is not satisfying. In a nutshell

Return N (pseudo) random  distinct customers and their newest document

The result should contain equal amount of documents of two different type

But if there's not enough different document types or different customers with a document, try to still satisfy the amount of N documents

Compensate the lack of other document type by choosing more another

Compensate the lack of overall document count by using multiple documents of the same customers, when necessary

I choose declarative (query) approach over imperative (cursors and counters). And this is where the WITH clause comes in. Roughly, by using multiple WITH blocks (CTE's) I declare queries (I like to think them as ad-hoc views) to declare two distinct target set for both document types. In the end, I UNION subsets of different CTE's for the final result, performing some COUNT checks to limit the amount.

Multiple CTE's are referencing each other and are referenced from multiple places in the context of COUNT and NOT EXISTS for example. I'm novice with SQL and happened to encounter WITH by a coincidence, and chose to use it intuitively. Is this the correct use case for WITH, or an anti pattern? How does this solution compares in performance to implementing the same functionality with cursors and counters in an imperative style? Have I chosen the wrong approach? We are talking about tables with million entries.

Here is the the query as a whole. Pardon me, I had to obscure the fields due confidentiality.

    WITH target_documents AS (
        SELECT
            <Necessary fields>
        FROM documents l
        WHERE
            <Suitable document criteria>
    ),
    target_documents_type_1 AS (
        SELECT * FROM target_documents WHERE type = 1
    ),
    target_documents_type_2 AS (
        SELECT * FROM target_documents WHERE type = 2
    ),
    target_customers AS (
        SELECT
            <Necessary fields>
        FROM customers a
        WHERE
            <Suitable customer criteria>
            AND
            EXISTS(
                SELECT 1 FROM target_documents l WHERE l.customer_id = a.customer_id
            )
    ),
    target_customers_type_1 AS (
        SELECT * FROM target_customers a WHERE EXISTS(
            SELECT 1 FROM target_documents_type_1 l WHERE l.customer_id = a.customer_id
        )
        AND ROWNUM <= (<N> / 2)
    ),
    target_customers_type_2 AS (
        SELECT * FROM target_customers a WHERE EXISTS(
            SELECT 1 FROM target_documents_type_2 l WHERE l.customer_id = a.customer_id
        )
        AND a.customer_id NOT IN (
            SELECT customer_id FROM target_customers_type_1
        )
        AND ROWNUM <= <N>
    ),
    -- This is the set, which meets the the primary criteria:
    -- Contains only distinct customers
    -- The amount of different document types is balanced as much as possible
    different_customers_set AS (
        SELECT
            <Necessary fields>
        FROM target_customers_type_1 a -- rows 0--(<N>/2) amount
        JOIN target_documents_type_1 l ON (l.customer_id = a.customer_id)
        WHERE
            l.create_dt = (SELECT MAX(create_dt) FROM target_documents_type_1 WHERE customer_id = l.customer_id)
        UNION ALL
        SELECT
            <Necessary fields>
        FROM target_customers_type_2 a -- rows 0--<N> amount
        JOIN target_documents_type_2 l ON (l.customer_id = a.customer_id)
        WHERE
            l.create_dt = (SELECT MAX(create_dt) FROM target_documents_type_2 WHERE customer_id = l.customer_id) AND
            ROWNUM <= <N> - (SELECT COUNT(*) FROM target_customers_type_1) -- Limit the total to max N rows
    )

    -- Final result: primary criteria result filled with the result of secondary criteria
    SELECT * FROM different_customers_set
    UNION ALL
    SELECT
        <Necessary fields>
    FROM target_customers a
    JOIN target_documents l ON (l.customer_id = a.customer_id AND l.document_id NOT IN (SELECT document_id FROM different_customers_set))
    WHERE
        ROWNUM <= <N> - (SELECT COUNT(1) FROM different_customers_set);

Is this the correct usage of WITH clause? Are there some obvious performance issues, where I should refactor? Or should I have done all this imperatively? Also, this query itself defines a cursor, which is used opened repeatedly in a loop (the loop defines certain criteria for customers).

I'm especially concerned, how the optimizer handles those WITH blocks. Is the most efficiently plan always used (so there's not performance penalty compared to using cursors)?


问:
How to create a query dynamically for an array of elements?
I have a basic query as follows

```<code>$query = "SELECT * FROM files WHERE (subject_code = '".$subject_code."' )";
</code>```

I have to modify this query to create a query where we have multiple subject codes fetched from an array.

```<code>$query1="SELECT subject_code FROM subject WHERE (sbranch = '".$branch."' )";
$result = mysqli_query($bmysqli, $query1);
</code>```

Now result holds all the required subject_codes say result[0]=SC1,result[1]=SC2 etc....

Now I want to the original query to be modified something as follows

```<code>$query = "SELECT * FROM files WHERE (subject_code = SC1 OR subject_code = SC2 .....)";
</code>```

Note that i don't know what are the values of SC1 SC2 etc.It depends on the branch and is inside $result.

How can i accomplish this?

答:
You can use a subquery like this:</p>

```<code>$query = 'SELECT * FROM files
WHERE subject_code IN (
    SELECT subject_code FROM subject WHERE sbranch = "' . $branch . '"
)';
</code>```

Body:
I have a basic query as follows

$query = "SELECT * FROM files WHERE (subject_code = '".$subject_code."' )";

I have to modify this query to create a query where we have multiple subject codes fetched from an array.

$query1="SELECT subject_code FROM subject WHERE (sbranch = '".$branch."' )";
$result = mysqli_query($bmysqli, $query1);

Now result holds all the required subject_codes say result[0]=SC1,result[1]=SC2 etc....

Now I want to the original query to be modified something as follows

$query = "SELECT * FROM files WHERE (subject_code = SC1 OR subject_code = SC2 .....)";

Note that i don't know what are the values of SC1 SC2 etc.It depends on the branch and is inside $result.

How can i accomplish this?

Body:
You can use a subquery like this:

$query = 'SELECT * FROM files
WHERE subject_code IN (
    SELECT subject_code FROM subject WHERE sbranch = "' . $branch . '"
)';


问:
Flex Smooth Drag of Objects
I'm trying to create an object which can be moved in Flex 4.

I tried http://help.adobe.com/en_US/flex/using/WS2db454920e96a9e51e63e3d11c0bf64595-7fed.html but in this most examples actually leaves the actual object (at pause) until the drag is completed, but I'm looking for something where the update will be done/shown while the drag is still on ... in those lines I've tried: Problems replicating drag-and-drop with mouse events ... but here I dint understand 'what are MouseHelper & EventHelpers'.

Also tried this: Flash AS3 custome Dragging using MOUSE_MOVE event but the movement is not smooth, very jig-jag.

Any suggestions are most welcome.

Regards

答:
here's an example with 5 ways of dragging (four are commented out):

 *  MouseEvent.MOUSE_MOVE

 *  Event.ENTER_FRAME

 *   startDrag(true)

 *   Timer(10) which sets x = mouseX y = mouseY every 10ms

 *  Timer(100) which creates a tween to mouseX, mouseY instead of applying values

If i move the mouse fast enough all of those modes (at 30fps) look as if a sprite is chasing mouse cursor, not being dragged, and also the animation is not smooth at all. However the smoothest animation is provided by tweener, but that mode shows a bigger average distance between mouse cursor and the sprite being dragged.

and btw fast dragging e.g. windows explorer also makes it blink because it doesn't have enough time for rendering at every position

ContentLicense: CC BY-SA 2.5

Title: Flex Smooth Drag of Objects


问:
Error while joining two tables in laravel controller
Joining two tables showing error:

```<code>"SQLSTATE[42000]: Syntax error or access violation: 1103 Incorrect table name 'transaction_master ' "
</code>```

But in my database transaction_master is exists.

The following query:

```<code>$trans_results= DB::table('report_master as rm')->join('transaction_master ', 'transaction_master.id','=','rm.id')->select('transaction_master.name as transactionID')->get();
</code>```

答: You need to reverse the transaction_master.id and the rm.id in your join

Body:
Joining two tables showing error:

"SQLSTATE[42000]: Syntax error or access violation: 1103 Incorrect table name 'transaction_master ' "

But in my database transaction_master is exists.

The following query:

$trans_results= DB::table('report_master as rm')->join('transaction_master ', 'transaction_master.id','=','rm.id')->select('transaction_master.name as transactionID')->get();


答:
The problems with layout could be caused by ScrollView to be the wrapper

I stumbled upon some note in http://developer.android.com/reference/android/widget/ExpandableListView.html

"...Note: You cannot use the value wrap_content for the android:layout_height attribute of a ExpandableListView in XML if the parent's size is also not strictly specified (for example, if the parent were ScrollView you could not specify wrap_content since it also can be any length. However, you can use wrap_content if the ExpandableListView parent has a specific size, such as 100 pixels."

I removed wrapping ScrollView and linear layout started working properly. Now its only to understand how to wrap the stuff to ScrollView. God help me

But anyway this is really weird behavior. I think that fill_parent is not really correct wording. When using heirarchyviewer tool I always see WRAP_CONTENT and MATCH_PARENT values for layout_width and leayout_height. So probably fill_parent is actually means match_parent which puts me in cognitive dissonance.

Title: Android ListView width keeps changing


问:
How to prevent user from selecting the same value from more than one combobox in wpf
I have a simple class as such:

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

I have a List of this class in my Mainwindow.xaml.cs as such:

```<code>public List<Item> AllItems=GetAllItems();
</code>```

I have four properties of Item class in my Mainwindow.xaml.cs as such:

```<code>public Item Item1{get;set;}
public Item Item2{get;set;}
public Item Item3{get;set;}
public Item Item4{get;set;}
</code>```

This List:AllItems is databinded to four Comboboxes as under:

```<code> <ComboBox x:Name="cmbCode1" ItemsSource="{Binding AllItems}" DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
 <ComboBox x:Name="cmbCode2" ItemsSource="{Binding AllItems}"  DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
 <ComboBox x:Name="cmbCode3" ItemsSource="{Binding AllItems}" DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
 <ComboBox x:Name="cmbCode4" ItemsSource="{Binding AllItems}" DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
</code>```

I have four TextBoxes corresponding to these four Comboboxes as such:

```<code><TextBlock x:Name="txtName1" Text="{Binding Item1.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock x:Name="txtName2" Text="{Binding Item2.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock x:Name="txtName3" Text="{Binding Item3.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock x:Name="txtName4" Text="{Binding Item4.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
</code>```

What i want is that the user should never be able to select the same ID from more than one combobox.
Is there some simple way that could be done,especially using xaml only?How can i hide or show the items selected/unselected from other comboboxes so that the user can't select the same ID from more than one combobox ever?
So far i have tried to send the selected Item and the entire List to a MultivalueConverter and eliminating/adding items to the Lists there itself,but this seems too meesy.Any other better idea would be appreciated.

答:
You can use the code to hide the selected item in different combobox

```<code> for (int count = 0; count <= cmb1.Items.Count -1; count++)
    {

    if((ComboBoxItem)(cmb1.Items[count])).SelectedValue==TextBox1.Text)
 ((ComboBoxItem)(cmb1.Items[count])).Visibility = System.Windows.Visibility.Collapsed;
        }
</code>```

This code you can write in selected event of the comboxes.

I guess you can write the same logic using triggers in XAML

Body:
I have a simple class as such:

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

I have a List of this class in my Mainwindow.xaml.cs as such:

public List<Item> AllItems=GetAllItems();

I have four properties of Item class in my Mainwindow.xaml.cs as such:

public Item Item1{get;set;}
public Item Item2{get;set;}
public Item Item3{get;set;}
public Item Item4{get;set;}

This List:AllItems is databinded to four Comboboxes as under:

 <ComboBox x:Name="cmbCode1" ItemsSource="{Binding AllItems}" DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
 <ComboBox x:Name="cmbCode2" ItemsSource="{Binding AllItems}"  DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
 <ComboBox x:Name="cmbCode3" ItemsSource="{Binding AllItems}" DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
 <ComboBox x:Name="cmbCode4" ItemsSource="{Binding AllItems}" DisplayMemberPath="ID" SelectedValuePath="ID" SelectedValue="{Binding Item1.ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Item1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>

I have four TextBoxes corresponding to these four Comboboxes as such:

<TextBlock x:Name="txtName1" Text="{Binding Item1.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock x:Name="txtName2" Text="{Binding Item2.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock x:Name="txtName3" Text="{Binding Item3.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock x:Name="txtName4" Text="{Binding Item4.Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>

What i want is that the user should never be able to select the same ID from more than one combobox.
Is there some simple way that could be done,especially using xaml only?How can i hide or show the items selected/unselected from other comboboxes so that the user can't select the same ID from more than one combobox ever?
So far i have tried to send the selected Item and the entire List to a MultivalueConverter and eliminating/adding items to the Lists there itself,but this seems too meesy.Any other better idea would be appreciated.

Body:
You can use the code to hide the selected item in different combobox

 for (int count = 0; count <= cmb1.Items.Count -1; count++)
    {

    if((ComboBoxItem)(cmb1.Items[count])).SelectedValue==TextBox1.Text)
 ((ComboBoxItem)(cmb1.Items[count])).Visibility = System.Windows.Visibility.Collapsed;
        }

This code you can write in selected event of the comboxes.

I guess you can write the same logic using triggers in XAML


问:
No qualifying bean of type 'javax.persistence.EntityManager' available: expected single matching bean but found 2
I have two entity manager configurations for two separate databases but when I try to auto-wire an entity manager in to configure my GraphQLExecutor bean I get an exception stating that there are two beans that match the criteria even though I've specified a unit name in the PersistenceContext.

Exception

org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'graphQLExecutor': Injection of resource
  dependencies failed; nested exception is
  org.springframework.beans.factory.NoUniqueBeanDefinitionException: No
  qualifying bean of type 'javax.persistence.EntityManager' available:
  expected single matching bean but found 2:
  org.springframework.orm.jpa.SharedEntityManagerCreator#0,org.springframework.orm.jpa.SharedEntityManagerCreator#1
  at
  org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:321)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
  ~[spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  com.ogl.JpaDemoApplication.main(JpaDemoApplication.java:15)
  [classes/:na] Caused by:
  org.springframework.beans.factory.NoUniqueBeanDefinitionException: No
  qualifying bean of type 'javax.persistence.EntityManager' available:
  expected single matching bean but found 2:
  org.springframework.orm.jpa.SharedEntityManagerCreator#0,org.springframework.orm.jpa.SharedEntityManagerCreator#1
    at
  org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:173)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:518)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]     at
  org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:496)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]     at
  org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:627)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]     at
  org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:318)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]     ... 17 common
  frames omitted

Entity Manager 1

```<code>package com.ogl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
@EnableJpaRepositories(basePackages = "com.ogl.system", entityManagerFactoryRef = "companyEntityManagerFactory", transactionManagerRef = "companyTransactionManager")
public class SystemJpaConfig {

  private final Environment environment;

  @Autowired
  public SystemJpaConfig(Environment environment) {
    this.environment = environment;
  }

  @Bean("systemEntityManagerFactory")
  public LocalContainerEntityManagerFactoryBean systemEntityManagerFactory() {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setPackagesToScan("com.ogl.system");
    entityManagerFactoryBean.setPersistenceUnitName("system");
    entityManagerFactoryBean.setDataSource(systemDataSource());

    HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
    adapter.setDatabase(Database.POSTGRESQL);
    adapter.setShowSql(true);
    adapter.setGenerateDdl(false);

    entityManagerFactoryBean.setJpaVendorAdapter(adapter);

    return entityManagerFactoryBean;
  }

  @Bean
  DataSource systemDataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment.getProperty("p4.datasource.driver"));
    dataSource.setUrl(environment.getProperty("p4.system.url"));
    dataSource.setUsername(environment.getProperty("p4.system.user"));
    dataSource.setPassword(environment.getProperty("p4.system.password"));

    return dataSource;
  }

  @Bean
  public PlatformTransactionManager systemTransactionManager() {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory((systemEntityManagerFactory().getObject()));

    return transactionManager;
  }
}
</code>```

Entity Manager 2

```<code>package com.ogl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
@EnableJpaRepositories(basePackages = "com.ogl.company", entityManagerFactoryRef = "companyEntityManagerFactory", transactionManagerRef = "companyTransactionManager")
public class CompanyJpaConfig {

  private final Environment environment;

  @Autowired
  public CompanyJpaConfig(Environment environment) {
    this.environment = environment;
  }

  @Primary
  @Bean("companyEntityManagerFactory")
  public LocalContainerEntityManagerFactoryBean companyEntityManagerFactory() {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setPackagesToScan("com.ogl.company");
    entityManagerFactoryBean.setPersistenceUnitName("company");
    entityManagerFactoryBean.setDataSource(companyDataSource());

    HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
    adapter.setDatabase(Database.POSTGRESQL);
    adapter.setShowSql(true);
    adapter.setGenerateDdl(false);

    entityManagerFactoryBean.setJpaVendorAdapter(adapter);

    return entityManagerFactoryBean;
  }

  @Bean
  DataSource companyDataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment.getProperty("p4.datasource.driver"));
    dataSource.setUrl(environment.getProperty("p4.company.url"));
    dataSource.setUsername(environment.getProperty("p4.company.user"));
    dataSource.setPassword(environment.getProperty("p4.company.password"));

    return dataSource;
  }

  @Primary
  @Bean
  public PlatformTransactionManager companyTransactionManager() {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory((companyEntityManagerFactory().getObject()));

    return transactionManager;
  }
}
</code>```

Injection

```<code>package com.ogl;

import org.crygier.graphql.GraphQLExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Configuration
@ComponentScan
public class GraphQLJpaConfig {

  @PersistenceContext(unitName = "company")
  private EntityManager entityManager;

  @Bean
  public GraphQLExecutor graphQLExecutor() {
    return new GraphQLExecutor(entityManager);
  }
}
</code>```

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ogl</groupId>
    <artifactId>jpa-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jpa-demo</name>
    <description>Demo project for JPA</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.graphql-java</groupId>
            <artifactId>graphql-java</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.crygier</groupId>
            <artifactId>graphql-jpa</artifactId>
            <version>0.3</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

答: Can you try giving the annotation @Primary over entityManagerFactory and transactionManager in one of the configuration files once?</p>

Body:
I have two entity manager configurations for two separate databases but when I try to auto-wire an entity manager in to configure my GraphQLExecutor bean I get an exception stating that there are two beans that match the criteria even though I've specified a unit name in the PersistenceContext.

Exception

org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'graphQLExecutor': Injection of resource
  dependencies failed; nested exception is
  org.springframework.beans.factory.NoUniqueBeanDefinitionException: No
  qualifying bean of type 'javax.persistence.EntityManager' available:
  expected single matching bean but found 2:
  org.springframework.orm.jpa.SharedEntityManagerCreator#0,org.springframework.orm.jpa.SharedEntityManagerCreator#1
  at
  org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:321)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE] at
  org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
  ~[spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
  [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE] at
  com.ogl.JpaDemoApplication.main(JpaDemoApplication.java:15)
  [classes/:na] Caused by:
  org.springframework.beans.factory.NoUniqueBeanDefinitionException: No
  qualifying bean of type 'javax.persistence.EntityManager' available:
  expected single matching bean but found 2:
  org.springframework.orm.jpa.SharedEntityManagerCreator#0,org.springframework.orm.jpa.SharedEntityManagerCreator#1
    at
  org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:173)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:518)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]     at
  org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:496)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]     at
  org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:627)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]     at
  org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
  ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]   at
  org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:318)
  ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]     ... 17 common
  frames omitted

Entity Manager 1

package com.ogl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
@EnableJpaRepositories(basePackages = "com.ogl.system", entityManagerFactoryRef = "companyEntityManagerFactory", transactionManagerRef = "companyTransactionManager")
public class SystemJpaConfig {

  private final Environment environment;

  @Autowired
  public SystemJpaConfig(Environment environment) {
    this.environment = environment;
  }

  @Bean("systemEntityManagerFactory")
  public LocalContainerEntityManagerFactoryBean systemEntityManagerFactory() {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setPackagesToScan("com.ogl.system");
    entityManagerFactoryBean.setPersistenceUnitName("system");
    entityManagerFactoryBean.setDataSource(systemDataSource());

    HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
    adapter.setDatabase(Database.POSTGRESQL);
    adapter.setShowSql(true);
    adapter.setGenerateDdl(false);

    entityManagerFactoryBean.setJpaVendorAdapter(adapter);

    return entityManagerFactoryBean;
  }

  @Bean
  DataSource systemDataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment.getProperty("p4.datasource.driver"));
    dataSource.setUrl(environment.getProperty("p4.system.url"));
    dataSource.setUsername(environment.getProperty("p4.system.user"));
    dataSource.setPassword(environment.getProperty("p4.system.password"));

    return dataSource;
  }

  @Bean
  public PlatformTransactionManager systemTransactionManager() {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory((systemEntityManagerFactory().getObject()));

    return transactionManager;
  }
}

Entity Manager 2

package com.ogl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
@EnableJpaRepositories(basePackages = "com.ogl.company", entityManagerFactoryRef = "companyEntityManagerFactory", transactionManagerRef = "companyTransactionManager")
public class CompanyJpaConfig {

  private final Environment environment;

  @Autowired
  public CompanyJpaConfig(Environment environment) {
    this.environment = environment;
  }

  @Primary
  @Bean("companyEntityManagerFactory")
  public LocalContainerEntityManagerFactoryBean companyEntityManagerFactory() {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setPackagesToScan("com.ogl.company");
    entityManagerFactoryBean.setPersistenceUnitName("company");
    entityManagerFactoryBean.setDataSource(companyDataSource());

    HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
    adapter.setDatabase(Database.POSTGRESQL);
    adapter.setShowSql(true);
    adapter.setGenerateDdl(false);

    entityManagerFactoryBean.setJpaVendorAdapter(adapter);

    return entityManagerFactoryBean;
  }

  @Bean
  DataSource companyDataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment.getProperty("p4.datasource.driver"));
    dataSource.setUrl(environment.getProperty("p4.company.url"));
    dataSource.setUsername(environment.getProperty("p4.company.user"));
    dataSource.setPassword(environment.getProperty("p4.company.password"));

    return dataSource;
  }

  @Primary
  @Bean
  public PlatformTransactionManager companyTransactionManager() {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory((companyEntityManagerFactory().getObject()));

    return transactionManager;
  }
}

Injection

package com.ogl;

import org.crygier.graphql.GraphQLExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Configuration
@ComponentScan
public class GraphQLJpaConfig {

  @PersistenceContext(unitName = "company")
  private EntityManager entityManager;

  @Bean
  public GraphQLExecutor graphQLExecutor() {
    return new GraphQLExecutor(entityManager);
  }
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ogl</groupId>
    <artifactId>jpa-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jpa-demo</name>
    <description>Demo project for JPA</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.graphql-java</groupId>
            <artifactId>graphql-java</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.crygier</groupId>
            <artifactId>graphql-jpa</artifactId>
            <version>0.3</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>


问:
Get-content function for powershell svn
I would like to get access to file content from SVN. It's quite easy when the path is in local disc like C:\folder...\ then I can use function get-content -path $path.

However, when my source path is SVN URL then I can't do it. Is there any simple way to do it?

Thanks in advance.

答: The command you look for is svn cat. You can't use Get-Content PowerShell cmdlet to access remote URLs.

Title: Get-content function for powershell svn


问:
QQuickImageProvider loads only around 1% of raw images
I started to learn Qt and I wanted to make simple list of images in folder with thumbnail. I managed to get it kind of working, but it seems to randomly load only about 1 image in 500 and 1 image in 50 is black (screenshot below). Once scrolled away the thumbnail will probably not load again and some other might load this time. For the raw images I use libraw.

Few observations:

7.7.2017 - I tried to check if issue wasn't caused by broken files. Although libraw says thumbnails are jpg, they don't seem to be, because normal browsers are unable to browser neither success nor failed attemps, but better editors can open both the same. So it seems issue isn't with corrupted data being given to QImage

When I hardcoded few photos to load, when there were fewer photos they almost always loaded properly. With increasing amounts they suddenly could all go black or not load at all. Maybe a multithreading issue?

Libraw seems to always load files properly. I tested it by printing enough bytes in the middle of the file when it loaded and when it didn't

When image is black, it thinks everything is fine, when image doesn't load at all it is because QImage has null content.

When I add one image many times, all copies share the same fate (They all load or they all fail)

```<code>QImage RawImageProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize) {
LibRaw rawProc;
auto state = rawProc.open_file(id.toLatin1().data());
QImage thumbnail;
if(LIBRAW_SUCCESS == state) {
    if(LIBRAW_SUCCESS == rawProc.unpack_thumb()) {
        if (LIBRAW_THUMBNAIL_JPEG == rawProc.imgdata.thumbnail.tformat) {
            thumbnail.loadFromData((unsigned char*)rawProc.imgdata.thumbnail.thumb, rawProc.imgdata.thumbnail.tlength, "JPEG");
        }
    }
    rawProc.recycle();
}
return thumbnail;
}
</code>```

for displaying the images I use gridview and model-delegate

```<code>GridView {
    id: gridView
    anchors.rightMargin: 6
    anchors.leftMargin: 6
    anchors.bottomMargin: 6
    anchors.topMargin: 46
    anchors.fill: parent
    cellHeight: 200
    cellWidth: 185
    model: imageModel
    delegate: PhotoDelegate {}
}
</code>```

raw image provider and model are registered like this in main function

```<code>int main(int argc, char *argv[])
{
...
QQmlApplicationEngine engine;
engine.addImageProvider(QLatin1String("rawProvider"), new RawImageProvider);

AppData::setContext(engine.rootContext());
AppData::notifyContext();
...
}
</code>```

AppData is my "static" class which holds list from which the model is created and pointer to context so I can easily access and update these values from other class which is called from qml (File Browser). The updating of model is done as followed every time data are changed.

```<code>void AppData::notifyContext() {
     context->setContextProperty("imageModel", QVariant::fromValue(dataList));
}
</code>```

I have really ran out of ideas how I could solve this, any help would be... well... helpful

答:
The issue was very simple. Libraw's jpg thumbnail is actually the original image only as jpg (I was not aware of this, my bad) and QtQuick could not handle the size of images it was supplied. That's why it worked just fine with fewer images but failed terribly with more. The solution than was returning resized thumbnails to much smaller size, ideally exactly the size of the Image in qml.</p>

```<code> return thumbnail.scaled(320, 320).scaled(160, 160, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation);
</code>```

Body:
I started to learn Qt and I wanted to make simple list of images in folder with thumbnail. I managed to get it kind of working, but it seems to randomly load only about 1 image in 500 and 1 image in 50 is black (screenshot below). Once scrolled away the thumbnail will probably not load again and some other might load this time. For the raw images I use libraw.

Few observations:

7.7.2017 - I tried to check if issue wasn't caused by broken files. Although libraw says thumbnails are jpg, they don't seem to be, because normal browsers are unable to browser neither success nor failed attemps, but better editors can open both the same. So it seems issue isn't with corrupted data being given to QImage

When I hardcoded few photos to load, when there were fewer photos they almost always loaded properly. With increasing amounts they suddenly could all go black or not load at all. Maybe a multithreading issue?

Libraw seems to always load files properly. I tested it by printing enough bytes in the middle of the file when it loaded and when it didn't

When image is black, it thinks everything is fine, when image doesn't load at all it is because QImage has null content.

When I add one image many times, all copies share the same fate (They all load or they all fail)

QImage RawImageProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize) {
LibRaw rawProc;
auto state = rawProc.open_file(id.toLatin1().data());
QImage thumbnail;
if(LIBRAW_SUCCESS == state) {
    if(LIBRAW_SUCCESS == rawProc.unpack_thumb()) {
        if (LIBRAW_THUMBNAIL_JPEG == rawProc.imgdata.thumbnail.tformat) {
            thumbnail.loadFromData((unsigned char*)rawProc.imgdata.thumbnail.thumb, rawProc.imgdata.thumbnail.tlength, "JPEG");
        }
    }
    rawProc.recycle();
}
return thumbnail;
}

for displaying the images I use gridview and model-delegate

GridView {
    id: gridView
    anchors.rightMargin: 6
    anchors.leftMargin: 6
    anchors.bottomMargin: 6
    anchors.topMargin: 46
    anchors.fill: parent
    cellHeight: 200
    cellWidth: 185
    model: imageModel
    delegate: PhotoDelegate {}
}

raw image provider and model are registered like this in main function

int main(int argc, char *argv[])
{
...
QQmlApplicationEngine engine;
engine.addImageProvider(QLatin1String("rawProvider"), new RawImageProvider);

AppData::setContext(engine.rootContext());
AppData::notifyContext();
...
}

AppData is my "static" class which holds list from which the model is created and pointer to context so I can easily access and update these values from other class which is called from qml (File Browser). The updating of model is done as followed every time data are changed.

void AppData::notifyContext() {
     context->setContextProperty("imageModel", QVariant::fromValue(dataList));
}

I have really ran out of ideas how I could solve this, any help would be... well... helpful

Body:
The issue was very simple. Libraw's jpg thumbnail is actually the original image only as jpg (I was not aware of this, my bad) and QtQuick could not handle the size of images it was supplied. That's why it worked just fine with fewer images but failed terribly with more. The solution than was returning resized thumbnails to much smaller size, ideally exactly the size of the Image in qml.

 return thumbnail.scaled(320, 320).scaled(160, 160, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation);


问:
go concurrency all goroutines are asleep - deadlock
Sorry about the noob question but I'm having a hard time wrapping my head around the concurrency part of go. Basically this program below is a simplified version of a larger one I'm writing, thus I want to keep the structure similar to below.

Basically instead of waiting 4 seconds I want to run addCount(..) concurrent using the unbuffered channel and when all elements in the int_slice has been processed I want to do another operation on them. However this program ends with a "panic: close of closed channel" and if I remove the closing of the channel I'm getting the output I'm expecting but it panics with: "fatal error: all goroutines are asleep - deadlock"

How can I implement the concurrency part correctly in this scenario?

Thanks in advance!

```<code>package main

import (
    "fmt"
    "time"
)

func addCount(num int, counter chan<- int) {
    time.Sleep(time.Second * 2)
    counter <- num * 2
}

func main() {
    counter := make(chan int)
    int_slice := []int{2, 4}

    for _, item := range int_slice {
        go addCount(item, counter)
        close(counter)
    }

    for item := range counter {
        fmt.Println(item)
    }
}
</code>```

答:
```<code>package main

import (
    "fmt"
    "time"
)

func addCount(num int, counter chan <- int) {
    time.Sleep(time.Second * 2)
    counter <- num * 2
}

func main() {
    counter := make(chan int)
    int_slice := []int{2, 4}

    for _, item := range int_slice {
        go addCount(item, counter)

        fmt.Println(<-counter)
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Sorry about the noob question but I'm having a hard time wrapping my head around the concurrency part of go. Basically this program below is a simplified version of a larger one I'm writing, thus I want to keep the structure similar to below.

Basically instead of waiting 4 seconds I want to run addCount(..) concurrent using the unbuffered channel and when all elements in the int_slice has been processed I want to do another operation on them. However this program ends with a "panic: close of closed channel" and if I remove the closing of the channel I'm getting the output I'm expecting but it panics with: "fatal error: all goroutines are asleep - deadlock"

How can I implement the concurrency part correctly in this scenario?

Thanks in advance!

package main

import (
    "fmt"
    "time"
)

func addCount(num int, counter chan<- int) {
    time.Sleep(time.Second * 2)
    counter <- num * 2
}

func main() {
    counter := make(chan int)
    int_slice := []int{2, 4}

    for _, item := range int_slice {
        go addCount(item, counter)
        close(counter)
    }

    for item := range counter {
        fmt.Println(item)
    }
}


问:
Replace statement creating duplicate lines
I'm using the code below

```<code>$content | ForEach-Object {

$addresseeName = $_.Substring(11,50)
$example = 'X' * 50
if ($_.Substring(0,10) -eq 'ADDRESSEE0')
{
    $_ -replace $addresseeName, $example

}
else
{
  $_
}

$addresseeName2 = $_.Substring(62,50)
$example = 'Y' * 50
if ($_.Substring(0,10) -eq 'ADDRESSEE0')
{
    $_ -replace $addresseeName2, $example
}
else
{
  $_
}
</code>```

Text file before:

```<code>ABSINVEST2|Y|N|
ADDRESSEE0|Name Name Letters Letters & Financial             |                                                  |19 Greemount House            |
ADDRSDETAS|                                                  |                                                  |
</code>```

Text File After:

```<code>ABSINVEST2|Y|N|
ADDRESSEE0|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|                                                  |19 Greemount House
ADDRESSEE0|Samp less Independent Examples & Exampless s      |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|19 Greemount House
ADDRSDETAS|                                                  |                                                  |
</code>```

I am attempting to mask particular fields (positions). Can anyone help me as to why the line is being duplicated for every IF Else statement?

Updating code I got working:

```<code>$content |
  ForEach-Object {

  $addresseeName = $_.Substring(11,50)
  $addresseeName2 = $_.Substring(62,50)
  $example = 'X' * 50
    if ($_.Substring(0,10) -eq 'ADDRESSEE0')

    {
        $_.replace($addresseeName, $example).replace($addresseeName2, $example)
    }
</code>```

答:
The short answer is, because you are duplicating it (your current script outputs it twice). Try this instead:

```<code>$content | ForEach-Object {
    $addresseeName = $_.Substring(11,50)
    $example = 'X' * 50

    if ($_.Substring(0,10) -eq 'ADDRESSEE0')
    {
        $_ = $_ -replace $addresseeName, $example

    }

    $addresseeName2 = $_.Substring(62,50)
    $example = 'Y' * 50

    if ($_.Substring(0,10) -eq 'ADDRESSEE0')
    {
        $_ = $_ -replace $addresseeName2, $example
    }

    $_
}
</code>```

This modifies the current line variable $_ by setting it when performing the replace and then only outputting it once at the end (whether it has changed or not).

Body:
I'm using the code below

$content | ForEach-Object {

$addresseeName = $_.Substring(11,50)
$example = 'X' * 50
if ($_.Substring(0,10) -eq 'ADDRESSEE0')
{
    $_ -replace $addresseeName, $example

}
else
{
  $_
}

$addresseeName2 = $_.Substring(62,50)
$example = 'Y' * 50
if ($_.Substring(0,10) -eq 'ADDRESSEE0')
{
    $_ -replace $addresseeName2, $example
}
else
{
  $_
}

Text file before:

ABSINVEST2|Y|N|
ADDRESSEE0|Name Name Letters Letters & Financial             |                                                  |19 Greemount House            |
ADDRSDETAS|                                                  |                                                  |

Text File After:

ABSINVEST2|Y|N|
ADDRESSEE0|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|                                                  |19 Greemount House
ADDRESSEE0|Samp less Independent Examples & Exampless s      |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|19 Greemount House
ADDRSDETAS|                                                  |                                                  |

I am attempting to mask particular fields (positions). Can anyone help me as to why the line is being duplicated for every IF Else statement?

Updating code I got working:

$content |
  ForEach-Object {

  $addresseeName = $_.Substring(11,50)
  $addresseeName2 = $_.Substring(62,50)
  $example = 'X' * 50
    if ($_.Substring(0,10) -eq 'ADDRESSEE0')

    {
        $_.replace($addresseeName, $example).replace($addresseeName2, $example)
    }

Body:
The short answer is, because you are duplicating it (your current script outputs it twice). Try this instead:

$content | ForEach-Object {
    $addresseeName = $_.Substring(11,50)
    $example = 'X' * 50

    if ($_.Substring(0,10) -eq 'ADDRESSEE0')
    {
        $_ = $_ -replace $addresseeName, $example

    }

    $addresseeName2 = $_.Substring(62,50)
    $example = 'Y' * 50

    if ($_.Substring(0,10) -eq 'ADDRESSEE0')
    {
        $_ = $_ -replace $addresseeName2, $example
    }

    $_
}

This modifies the current line variable $_ by setting it when performing the replace and then only outputting it once at the end (whether it has changed or not).