问:
WPF - Inherit TabControl and customize the style
I want to inherit the default TabControl and handle the event double-click TabItem Header.

This is XAML file:

```<code><local:MyTabControl x:Class="MyTabControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:CustomizedTabControl"
    mc:Ignorable="d">
<local:MyTabControl.Style>
    <Style TargetType="{x:Type local:MyTabControl}" BasedOn="{StaticResource {x:Type TabControl}}">
        <Setter Property="ItemContainerStyle">
            <Setter.Value>
                <Style  TargetType="{x:Type TabItem}">
                    <Setter Property="HeaderTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <Label Content="{Binding}">
                                    <Label.Style>
                                        <Style TargetType="Label">
                                            <EventSetter Event="MouseDoubleClick" Handler="OnTabHeaderDoubleClick"/>
                                        </Style>
                                    </Label.Style>
                                </Label>
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </Setter.Value>
        </Setter>
    </Style>
</local:MyTabControl.Style>
</code>```

And this is the code-behind:

```<code>using System.Windows.Controls;
using System.Windows.Input;

namespace CustomizedTabControl
{
    public partial class MyTabControl : TabControl
    {
        public MyTabControl() : base()
        {
        }
        public void OnTabHeaderDoubleClick(object sender, MouseButtonEventArgs e)
        {
            // Never call
        }
    }
}
</code>```

But the event handler is never called. Do you have any idea?

P/S: This is the code I used the customized TabControl:

```<code><Window x:Class="CustomizedTabControl.MainWindow"
 ...
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <local:MyTabControl x:Name="tabControl">
            <TabItem Header="TabItem">
                <Grid Background="#FFE5E5E5"/>
            </TabItem>
            <TabItem Header="TabItem">
                <Grid Background="#FFE5E5E5"/>
            </TabItem>
        </local:MyTabControl>
    </Grid>
</Window>
</code>```

答:
I could not figure out why the style I define in XAML file of MyTabControl does not work. However this is the workaround I use. I have to use DictionaryResource to catch the event.

The xaml file:

```<code><ResourceDictionary x:Class="CustomizedTabControl.MyTabControlResourceDictionary"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:CustomizedTabControl"
        mc:Ignorable="d">
    <Style BasedOn="{StaticResource {x:Type TabControl}}" TargetType="{x:Type local:MyTabControl}" x:Key="MyTabControlStyle">
        <Setter Property="ItemContainerStyle">
            <Setter.Value>
                <Style  TargetType="{x:Type TabItem}">
                    <Setter Property="HeaderTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <Grid>
                                    <Label Content="{Binding}" Background="Blue" Tag="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:MyTabControl}}}">
                                        <Label.Style>
                                            <Style TargetType="Label">
                                                <EventSetter Event="MouseDoubleClick" Handler="OnTabHeaderDoubleClick"/>
                                            </Style>
                                        </Label.Style>
                                    </Label>
                                </Grid>

                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>
</code>```

The corresponding code-behind:

```<code>namespace CustomizedTabControl
{
    public partial class MyTabControlResourceDictionary : ResourceDictionary
    {
        public void OnTabHeaderDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var tabControl = (sender as FrameworkElement)?.Tag as MyTabControl;
            if(tabControl != null)
            {
                tabControl.OnTabHeaderDoubleClick();
            }
        }
    }

    public partial class MyTabControl : TabControl
    {
        public MyTabControl() : base()
        {
        }

        public void OnTabHeaderDoubleClick()
        {
             // Now I can handle the event here
        }

    }
}
</code>```

Add this is how I use it:

```<code><Grid>
    <local:MyTabControl x:Name="tabControl" Style="{StaticResource MyTabControlStyle}">
        <TabItem Header="TabItem">
            <Grid Background="#FFE5E5E5"/>
        </TabItem>
        <TabItem Header="TabItem">
            <Grid Background="#FFE5E5E5"/>
        </TabItem>
    </local:MyTabControl>
</Grid>
</code>```

Body:
I want to inherit the default TabControl and handle the event double-click TabItem Header.

This is XAML file:

<local:MyTabControl x:Class="MyTabControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:CustomizedTabControl"
    mc:Ignorable="d">
<local:MyTabControl.Style>

                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </Setter.Value>
        </Setter>
    </Style>
</local:MyTabControl.Style>

And this is the code-behind:

using System.Windows.Controls;
using System.Windows.Input;

namespace CustomizedTabControl
{
    public partial class MyTabControl : TabControl
    {
        public MyTabControl() : base()
        {
        }
        public void OnTabHeaderDoubleClick(object sender, MouseButtonEventArgs e)
        {
            // Never call
        }
    }
}

But the event handler is never called. Do you have any idea?

P/S: This is the code I used the customized TabControl:

<Window x:Class="CustomizedTabControl.MainWindow"
 ...
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <local:MyTabControl x:Name="tabControl">
            <TabItem Header="TabItem">
                <Grid Background="#FFE5E5E5"/>
            </TabItem>
            <TabItem Header="TabItem">
                <Grid Background="#FFE5E5E5"/>
            </TabItem>
        </local:MyTabControl>
    </Grid>
</Window>

Body:
I could not figure out why the style I define in XAML file of MyTabControl does not work. However this is the workaround I use. I have to use DictionaryResource to catch the event.

The xaml file:

<ResourceDictionary x:Class="CustomizedTabControl.MyTabControlResourceDictionary"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:CustomizedTabControl"
        mc:Ignorable="d">
    <Style BasedOn="{StaticResource {x:Type TabControl}}" TargetType="{x:Type local:MyTabControl}" x:Key="MyTabControlStyle">
        <Setter Property="ItemContainerStyle">
            <Setter.Value>
                <Style  TargetType="{x:Type TabItem}">
                    <Setter Property="HeaderTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <Grid>
                                    <Label Content="{Binding}" Background="Blue" Tag="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:MyTabControl}}}">
                                        <Label.Style>
                                            <Style TargetType="Label">
                                                <EventSetter Event="MouseDoubleClick" Handler="OnTabHeaderDoubleClick"/>
                                            </Style>
                                        </Label.Style>
                                    </Label>
                                </Grid>

                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

The corresponding code-behind:

namespace CustomizedTabControl
{
    public partial class MyTabControlResourceDictionary : ResourceDictionary
    {
        public void OnTabHeaderDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var tabControl = (sender as FrameworkElement)?.Tag as MyTabControl;
            if(tabControl != null)
            {
                tabControl.OnTabHeaderDoubleClick();
            }
        }
    }

    public partial class MyTabControl : TabControl
    {
        public MyTabControl() : base()
        {
        }

        public void OnTabHeaderDoubleClick()
        {
             // Now I can handle the event here
        }

    }
}

Add this is how I use it:

<Grid>
    <local:MyTabControl x:Name="tabControl" Style="{StaticResource MyTabControlStyle}">
        <TabItem Header="TabItem">
            <Grid Background="#FFE5E5E5"/>
        </TabItem>
        <TabItem Header="TabItem">
            <Grid Background="#FFE5E5E5"/>
        </TabItem>
    </local:MyTabControl>
</Grid>


来源: stackexchange

问:
time series Input for 1D convolution with tensorflow
i am trying to model time series data in to a convolution NN with tensorflow.
My time series data format is as follows

```<code>[timestamp, x, y, z]
</code>```

I want to create 300 time stamp windows for three channels (x, y, z). Therefore i have pre-processed the data as follows and when i feed this in to the tf.layers.conv1d i use the input of following reshapings

```<code>[1]
[x,y,z],[x,y,z],...[x,y,z] of size 3*300
#input shape is [-1, 3*300]
input = tf.reshape(input, shape = [-1, 300, 3])
#input shape is [-1, 300, 3]

[2]
[x,x,..x],[y,y,..y],[z,z...z] of size 300*3
#input shape is [-1, 300*3]
input = tf.reshape(input, shape = [-1, 300, 3])
#input shape is [-1, 300, 3]
</code>```

which of this versions is correct reshaping considering my original data set?
Or are both of them not right? In that case what is the correct way to feed this data in to the convolution layer?

I have tried both and the accuracy results are very low (less than 40%).

Thanks in advance!

答:
Method 2 is correct. You can verify it by running the following simple example code. Here, My bacth_size =2 and instead of 300 I just used 9.

```<code>#Method1
input1 = np.array([[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3],
                   [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]])
print(input1.shape)  # prints (2, 3*9)
out1 = tf.reshape(input1, shape=[-1, 9, 3])

#Method2
input2 = np.array([[1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 3, 3, 3],
                   [1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 3, 3, 3]])
print(input2.shape)  # prints (2, 3*9)
out2 = tf.reshape(input2, shape=[-1, 9, 3])

sess = tf.Session()
with sess.as_default():
    print(out1.eval())  # runs out1
    print(out2.eval())  # runs out2
</code>```

Therefore, the input (batch_size=2, width=9, num_channels=3) to the tf.layers.conv1d should have the following shape.

```<code>[[[x y z]
  [x y z]
  [x y z]
  [x y z]
  [x y z]
  [x y z]
  [x y z]
  [x y z]
  [x y z]]

 [[x y z]
  [x y z]
  [x y z]
  [x y z]
  [x y z]
  [x y z]
  [x y z]
  [x y z]
  [x y z]]]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i am trying to model time series data in to a convolution NN with tensorflow.
My time series data format is as follows

[timestamp, x, y, z]

I want to create 300 time stamp windows for three channels (x, y, z). Therefore i have pre-processed the data as follows and when i feed this in to the tf.layers.conv1d i use the input of following reshapings

[1]
[x,y,z],[x,y,z],...[x,y,z] of size 3*300
#input shape is [-1, 3*300]
input = tf.reshape(input, shape = [-1, 300, 3])
#input shape is [-1, 300, 3]

[2]
[x,x,..x],[y,y,..y],[z,z...z] of size 300*3
#input shape is [-1, 300*3]
input = tf.reshape(input, shape = [-1, 300, 3])
#input shape is [-1, 300, 3]

which of this versions is correct reshaping considering my original data set?
Or are both of them not right? In that case what is the correct way to feed this data in to the convolution layer?

I have tried both and the accuracy results are very low (less than 40%).

Thanks in advance!

Body:
Method 2 is correct. You can verify it by running the following simple example code. Here, My bacth_size =2 and instead of 300 I just used 9.

#Method1
input1 = np.array([[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3],
                   [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]])
print(input1.shape)  # prints (2, 3*9)
out1 = tf.reshape(input1, shape=[-1, 9, 3])

#Method2
input2 = np.array([[1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 3, 3, 3],
                   [1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 3, 3, 3]])
print(input2.shape)  # prints (2, 3*9)
out2 = tf.reshape(input2, shape=[-1, 9, 3])

sess = tf.Session()
with sess.as_default():
    print(out1.eval())  # runs out1
    print(out2.eval())  # runs out2

Therefore, the input (batch_size=2, width=9, num_channels=3) to the tf.layers.conv1d should have the following shape.

[[[x y z]
  [x y z]
  [x y z]
  [x y z]
  [x y z]
  [x y z]
  [x y z]
  [x y z]
  [x y z]]

 [[x y z]
  [x y z]
  [x y z]
  [x y z]
  [x y z]
  [x y z]
  [x y z]
  [x y z]
  [x y z]]]


问:
Send lat lng from variable to google maps
I´m trying to make a simple code using Google maps API (I'm new at this), the idea is to get the latitude and longitude from JSON variable direccion to the var uluru.
I have the following code:
Where am I wrong?

Thanks in advance.

<!DOCTYPE html>

My Google Maps Demo

```

答:
Your direction is json array, you need to access by index as below:

```<code>var uluru = {lat: direccion[0].lat, lng: direccion[0].lng};
</code>```

see my example below:

<!DOCTYPE html>

My Google Maps Demo

```

Body:
Your direction is json array, you need to access by index as below:

var uluru = {lat: direccion[0].lat, lng: direccion[0].lng};

see my example below:

<!DOCTYPE html>
<html>
  <head>
    <style>
       #map {
        height: 400px;
        width: 100%;
       }
    </style>
  </head>
  <body>
    <h3>My Google Maps Demo</h3>
    <div id="map"></div>
    <script>

      function initMap() {

      var direccion=[
        {
          lugar:'CICESE',
          lat:31.8675375,
          lng: -116.6686867
        },
        {
          lugar: 'Casa',
          lat:31.8915163,
          lng:-116.6879557
        }
      ];

        var uluru = {lat: direccion[0].lat, lng: direccion[0].lng};//{lat: -25.363, lng: 131.044};
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 4,
          center: uluru
        });
        var marker = new google.maps.Marker({
          position: uluru,
          map: map
        });
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDgMyVeh8DwebGfZHjiNjyle4xFe9pKSdc&callback=initMap">
    </script>
  </body>
</html>


问:
Comparing two char* and two char[ ] strings in C
```<code>#include <stdio.h>

int main(){
    char a[] = "bar";
    char b[] = "bar";
    printf("%d\n", (a==b));

    char* x = "bar";
    char* y = "bar";
    printf("%d\n", (x==y));
 }
</code>```

Output :

```<code>0
1
</code>```

I know we can't compare C char arrays using the == operator as it compares memory locations, but why does it work in the second case ?

答:
This is implementation-dependent

In the 1st case, a and b have separate storage space, so their address won't be equal.

However, the compiler may identify that the strings x and y are pointing to is identical, so it may optimize by making them point to the same location, since you can't modify it. However, as the standard does not require to do so, you can't rely on the result. It's an optional optimization. The compiler can still generate two identical strings and make x and y point to them separately.

Body:
#include <stdio.h>

int main(){
    char a[] = "bar";
    char b[] = "bar";
    printf("%d\n", (a==b));

    char* x = "bar";
    char* y = "bar";
    printf("%d\n", (x==y));
 }

Output :

0
1

I know we can't compare C char arrays using the == operator as it compares memory locations, but why does it work in the second case ?


问:
Marker Info-window not working using ngMap
I am trying to show an info window on google map using ng-map. Here's my code:

```<code><div id="map">
  <ng-map zoom="13" center="[{{latitude}}, {{longitude}}]" style="display: block; height: 100%;">
    <marker ng-repeat="pothole in potholeData" position="{{pothole.lat}},{{pothole.lng}}" on-click="showDetails(e, pothole)"></marker>
  </ng-map>
</div>
</code>```

I am giving an on-click function on each marker with a lat and long value. but in my controller I am getting undefined value.

Here's my controller:

```<code>$scope.showDetails = function(e, pothole) {
  var infowindow = new google.maps.InfoWindow();
  var center = new google.maps.LatLng(pothole.lat, pothole.lng);

  infowindow.setContent(
    '<h3>' + pothole + '</h3>');

  infowindow.setPosition(center);
  infowindow.open($scope.map);
}
</code>```

In showDetails function, I am getting pothole undefined.
Can someone help me out?

答:
The problem was in on-click="showDetails(e, pothole), change to on-click="showDetails(event, pothole).
I have produced snippet working.

angular.module('mapApp', ['ngMap'])
    .controller('mapController', function($scope, NgMap) {

        NgMap.getMap().then(function(map) {
            $scope.map = map;
        });
        $scope.potholeData = [
            { lat: 59.923043, lng: 10.752839 },
            { lat: 59.339025, lng: 18.065818 },
            { lat: 55.675507, lng: 12.574227 },
            { lat: 52.521248, lng: 13.399038 },
            { lat: 48.856127, lng: 2.346525 }
        ];
        $scope.showDetails = function(e, pothole) {
          console.log(pothole);
          var infowindow = new google.maps.InfoWindow();
          var center = new google.maps.LatLng(pothole.lat,pothole.lng);

          infowindow.setContent(
            '
' + pothole.lat + " " + pothole.lng + '
');

          infowindow.setPosition(center);
          infowindow.open($scope.map);
        };

    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://maps.google.com/maps/api/js"></script>
<script src="https://code.angularjs.org/1.3.15/angular.js"></script>
<script src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/scripts/ng-map.js"></script>
<div ng-app="mapApp" ng-controller="mapController">
    <ng-map default-style="true" zoom="5" center="59.339025, 18.065818">
        <marker ng-repeat="pothole in potholeData"
                position="{{pothole.lat}},{{pothole.lng}}" on-click="showDetails(event, pothole)">
        </marker>
    </ng-map>
</div></code>```

Body:
I am trying to show an info window on google map using ng-map. Here's my code:

  <ng-map zoom="13" center="[{{latitude}}, {{longitude}}]" style="display: block; height: 100%;">
    <marker ng-repeat="pothole in potholeData" position="{{pothole.lat}},{{pothole.lng}}" on-click="showDetails(e, pothole)"></marker>
  </ng-map>

I am giving an on-click function on each marker with a lat and long value. but in my controller I am getting undefined value.

Here's my controller:

$scope.showDetails = function(e, pothole) {
  var infowindow = new google.maps.InfoWindow();
  var center = new google.maps.LatLng(pothole.lat, pothole.lng);

  infowindow.setContent(
    '
' + pothole + '
');

  infowindow.setPosition(center);
  infowindow.open($scope.map);
}

In showDetails function, I am getting pothole undefined.
Can someone help me out?

Body:
The problem was in on-click="showDetails(e, pothole), change to on-click="showDetails(event, pothole).
I have produced snippet working.

angular.module('mapApp', ['ngMap'])
    .controller('mapController', function($scope, NgMap) {

        NgMap.getMap().then(function(map) {
            $scope.map = map;
        });
        $scope.potholeData = [
            { lat: 59.923043, lng: 10.752839 },
            { lat: 59.339025, lng: 18.065818 },
            { lat: 55.675507, lng: 12.574227 },
            { lat: 52.521248, lng: 13.399038 },
            { lat: 48.856127, lng: 2.346525 }
        ];
        $scope.showDetails = function(e, pothole) {
          console.log(pothole);
          var infowindow = new google.maps.InfoWindow();
          var center = new google.maps.LatLng(pothole.lat,pothole.lng);

          infowindow.setContent(
            '<h3>' + pothole.lat + " " + pothole.lng + '</h3>');

          infowindow.setPosition(center);
          infowindow.open($scope.map);
        };

    });

<script src="https://maps.google.com/maps/api/js"></script>
<script src="https://code.angularjs.org/1.3.15/angular.js"></script>
<script src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/scripts/ng-map.js"></script>
<div ng-app="mapApp" ng-controller="mapController">
    <ng-map default-style="true" zoom="5" center="59.339025, 18.065818">
        <marker ng-repeat="pothole in potholeData"
                position="{{pothole.lat}},{{pothole.lng}}" on-click="showDetails(event, pothole)">
        </marker>
    </ng-map>
</div>


问:
VBA if in text is in textbox then do something
I've written the following code so that if a certain text exists in my listbox and "ok" button is clicked a certain thing is done.

```<code>Private Sub CommandButton3_Click()

If (Me.ListBox2.Text) <> ("PA") Then

Call macro1

ElseIf (Me.ListBox2.Text) <> "menu" Then

Sheets("menu").Visible = xlSheetVisible

Worksheets("menu").Activate

Else
 MsgBox "Nothing is selected"

End If

End Sub
</code>```

The problem is that when "ok" is clicked all events are still carried out even if the specified text isn't in the textbox.

答:
You probably want to use = operator, and not <> operator. Also note that ListBox.List(i) is the correct way of getting selected item for single selection mode:

```<code>Private Sub CommandButton3_Click()
  Dim SelectedItem = ListBox1.List(ListBox1.ListIndex)

  If SelectedItem = "PA" Then
    Call macro1
  ElseIf SelectedItem = "menu" Then
    Sheets("menu").Visible = xlSheetVisible
    Worksheets("menu").Activate
  Else
    MsgBox "Nothing is selected"
  End If
End Sub
</code>```

Edit

Following your comment, you can create a function that looks for the existence of that item:

```<code>Private Function TextExists(text as String) as Boolean
  Dim i as Long
  For i = 0 To ListBox1.ListCount - 1
    If ListBox1.List(i) = text Then
      TextExists = True
      Exit Function
    End If
  Next

  TextExists = False
End Function
</code>```

And then use this function in the main code like this:

```<code>Private Sub CommandButton3_Click()
  If TextExists("PA") Then
    Call macro1
  ElseIf TextExists("menu") Then
    Sheets("menu").Visible = xlSheetVisible
    Worksheets("menu").Activate
  Else
    MsgBox "Nothing is selected"
  End If
End Sub
</code>```

N.B. I have written this manually here, without an IDE. Please check for indexes and other little things.

Body:
I've written the following code so that if a certain text exists in my listbox and "ok" button is clicked a certain thing is done.

Private Sub CommandButton3_Click()

If (Me.ListBox2.Text) <> ("PA") Then

Call macro1

ElseIf (Me.ListBox2.Text) <> "menu" Then

Sheets("menu").Visible = xlSheetVisible

Worksheets("menu").Activate

Else
 MsgBox "Nothing is selected"

End If

End Sub

The problem is that when "ok" is clicked all events are still carried out even if the specified text isn't in the textbox.

Body:
You probably want to use = operator, and not <> operator. Also note that ListBox.List(i) is the correct way of getting selected item for single selection mode:

Private Sub CommandButton3_Click()
  Dim SelectedItem = ListBox1.List(ListBox1.ListIndex)

  If SelectedItem = "PA" Then
    Call macro1
  ElseIf SelectedItem = "menu" Then
    Sheets("menu").Visible = xlSheetVisible
    Worksheets("menu").Activate
  Else
    MsgBox "Nothing is selected"
  End If
End Sub

Edit

Following your comment, you can create a function that looks for the existence of that item:

Private Function TextExists(text as String) as Boolean
  Dim i as Long
  For i = 0 To ListBox1.ListCount - 1
    If ListBox1.List(i) = text Then
      TextExists = True
      Exit Function
    End If
  Next

  TextExists = False
End Function

And then use this function in the main code like this:

Private Sub CommandButton3_Click()
  If TextExists("PA") Then
    Call macro1
  ElseIf TextExists("menu") Then
    Sheets("menu").Visible = xlSheetVisible
    Worksheets("menu").Activate
  Else
    MsgBox "Nothing is selected"
  End If
End Sub

N.B. I have written this manually here, without an IDE. Please check for indexes and other little things.


答:
The output makes sense because the memory storage for the arrays are not equal. For the char's, their literal characters are compared. Try running this example.

```<code>int main(void) {
    char a[] = "bar";
    char b[] = "bar";

    printf("Arrays Test: %x == %x ? %d\n",&a,&b,(a==b));

    char* x = "bar";
    char* y = "bar";

    printf("Literals Test: %x == %x ? %d, however x == y ? %d\n",&x,&y, (&x==&y),(x==y));

    return 0;
}
</code>```

This online runnable example shows that the char's memory references are not the same.

If you wanted to see if the array's content is equal, you would need to call every char in the array and compare it to the secondary array manually. You could potentially end execution faster by checking the sizes of the array against each other.

An additional point is that "pointerizing" the chars or arrays makes no difference in this scope of comparison.

Title: Comparing two char* and two char[ ] strings in C

Body:
The output makes sense because the memory storage for the arrays are not equal. For the char's, their literal characters are compared. Try running this example.

int main(void) {
    char a[] = "bar";
    char b[] = "bar";

    printf("Arrays Test: %x == %x ? %d\n",&a,&b,(a==b));

    char* x = "bar";
    char* y = "bar";

    printf("Literals Test: %x == %x ? %d, however x == y ? %d\n",&x,&y, (&x==&y),(x==y));

    return 0;
}

This online runnable example shows that the char's memory references are not the same.

If you wanted to see if the array's content is equal, you would need to call every char in the array and compare it to the secondary array manually. You could potentially end execution faster by checking the sizes of the array against each other.

An additional point is that "pointerizing" the chars or arrays makes no difference in this scope of comparison.


问:
C# instantiating class object & adding to List
How can I create new instance of Country which uses 3 variables firstParam, secondParam, thirdParam for its constructor and add to a List countryList?

The 3 variables are being read from .txt and split on the ,
Afghanistan,Kabul,30419928
Albania,Tirana,2821977

My 3 split variables firstParam, secondParam, thirdParam contain the right information. I think I am making a syntax mistake when I add to the countryList because debug mode stepping through the variables load the right info but when I try a foreach on the countryList I get the output "countries.country".

```<code>    List<Country> countryList = new List<Country>();

        foreach (string line in lines)
        {
            string[] criteria = line.Split(',');

            string firstParam = "";
            string secondParam = "";
            int thirdParam = 1;

            firstParam = criteria[0];
            secondParam = criteria[1];
            thirdParam = Convert.ToInt32(criteria[2]);

            countryList.Add(new Country(firstParam, secondParam, thirdParam));

        }
</code>```

I ran out of ideas and not sure what else to try I am trying to learn more about composition but hoping someone can nudge me along.
thank you.

答:
If you want to choose the value for debugging, you should use this way 'Override ToString()' or 'DebuggerDisplayAttribute'.</p>

```<code> //DebuggerDisplayAttribute
[DebuggerDisplay("Value = {Display}")]
public class Country
{
    public string Name { get; set; }
    public string City { get; set; }

    public string Display
    {
        get => $"{Name}, {City}";
    }

    //Override ToString()
    public override string ToString()
    {
        return $"{Name}, {City}";
    }
}
</code>```

Body:
How can I create new instance of Country which uses 3 variables firstParam, secondParam, thirdParam for its constructor and add to a List countryList?

The 3 variables are being read from .txt and split on the ,
Afghanistan,Kabul,30419928
Albania,Tirana,2821977

My 3 split variables firstParam, secondParam, thirdParam contain the right information. I think I am making a syntax mistake when I add to the countryList because debug mode stepping through the variables load the right info but when I try a foreach on the countryList I get the output "countries.country".

    List<Country> countryList = new List<Country>();

        foreach (string line in lines)
        {
            string[] criteria = line.Split(',');

            string firstParam = "";
            string secondParam = "";
            int thirdParam = 1;

            firstParam = criteria[0];
            secondParam = criteria[1];
            thirdParam = Convert.ToInt32(criteria[2]);

            countryList.Add(new Country(firstParam, secondParam, thirdParam));

        }

I ran out of ideas and not sure what else to try I am trying to learn more about composition but hoping someone can nudge me along.
thank you.

Body:
If you want to choose the value for debugging, you should use this way 'Override ToString()' or 'DebuggerDisplayAttribute'.

 //DebuggerDisplayAttribute
[DebuggerDisplay("Value = {Display}")]
public class Country
{
    public string Name { get; set; }
    public string City { get; set; }

    public string Display
    {
        get => $"{Name}, {City}";
    }

    //Override ToString()
    public override string ToString()
    {
        return $"{Name}, {City}";
    }
}


问:
how to populate a listview asynchronously?
I am wondering how I should implement a ListAdapter that loads its views asynchronously into a ListView?  I want to do this because I am populating the list with information from my database, which is making my activity a bit slow to load at times.

答:
With Kotlin and the Kotlin extension libraries, this task has gotten way easier.  You can use the doAsync/uiThread construct in a library called Anko with a fraction of the code. In the link tutorial below I use this library to populate a ListView with stock quotes calling a REST API Asynchronously with Kotlin. Kotlin is fully integrated into Android Studio:

http://www.todroid.com/creating-a-stock-pricing-application-with-kotlin-for-android/


答:
According to @artgb answer you need change on-click="showDetails(e, pothole) to on-click="showDetails(event, pothole). See the event parameter. That was the real issue.

In this full ng-mapversion works the same way.

According to https://ngmap.github.io/.

You need these scripts:

. AIzaSyCGsmJhDsK9HS2_kYtQXbiJqaAE2AT_Pw0 is my API KEY for this demo. You can get your own in: https://developers.google.com/maps/documentation/javascript/.

You need to identify your markers with an id. As you are using ngRepeat I'm using this data:

```<code>[{
  "id": "Location1",
  "text": "Some content 1...",
  "lat": -12.339223,
  "lng": -76.808624
}, {
  "id": "Location2",
  "text": "Some content 2...",
  "lat": -12.349423,
  "lng": -76.828824
}]
</code>```

The ng-map directive contains the original Google Maps V3 api to the user so you don't need to use new google.maps Object.

Something like this:

(function() {

  angular.module("app", ["ngMap"]).controller("Controller", ["$scope", "NgMap", function($scope, NgMap) {
    NgMap.getMap().then(function(map) {
      $scope.map = map;
    });

    $scope.latitude = -12.339223;
    $scope.longitude = -76.808624;
    $scope.potholeData = [{
      "id": "Location1",
      "text": "Some content 1...",
      "lat": -12.339223,
      "lng": -76.808624
    }, {
      "id": "Location2",
      "text": "Some content 2...",
      "lat": -12.349423,
      "lng": -76.828824
    }];
    $scope.pothole = {};

    $scope.showDetails = function(e, pothole) {
      $scope.pothole = pothole;
      $scope.map.showInfoWindow('foo-iw', pothole.id);
    };

    $scope.hideDetail = function() {
      $scope.map.hideInfoWindow('foo-iw');
    };
  }]);
})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCGsmJhDsK9HS2_kYtQXbiJqaAE2AT_Pw0"></script>
<script src="https://code.angularjs.org/1.3.15/angular.js"></script>
<script src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/scripts/ng-map.js"></script>

<div data-ng-app="app">
  <div data-ng-controller="Controller">
    <ng-map default-style="true" center="{{latitude}}, {{longitude}}" zoom="13">
      <marker id="{{pothole.id}}" ng-repeat="pothole in potholeData" position="{{pothole.lat}},{{pothole.lng}}" on-click="showDetails(event, pothole)"></marker>

      <info-window id="foo-iw">
        <div ng-non-bindable="">
          id: {{pothole.id}}<br/> Text: {{pothole.text}}<br/> Position: {{anchor.getPosition()}}
        </div>
      </info-window>
    </ng-map>
  </div>
</div></code>```

Title: Marker Info-window not working using ngMap

Body:
According to @artgb answer you need change on-click="showDetails(e, pothole) to on-click="showDetails(event, pothole). See the event parameter. That was the real issue.

In this full ng-mapversion works the same way.

According to https://ngmap.github.io/.

You need these scripts:

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCGsmJhDsK9HS2_kYtQXbiJqaAE2AT_Pw0"></script>. AIzaSyCGsmJhDsK9HS2_kYtQXbiJqaAE2AT_Pw0 is my API KEY for this demo. You can get your own in: https://developers.google.com/maps/documentation/javascript/.

<script src="https://code.angularjs.org/1.3.15/angular.js"></script>

<script src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/scripts/ng-map.js"></script>

You need to identify your markers with an id. As you are using ngRepeat I'm using this data:

[{
  "id": "Location1",
  "text": "Some content 1...",
  "lat": -12.339223,
  "lng": -76.808624
}, {
  "id": "Location2",
  "text": "Some content 2...",
  "lat": -12.349423,
  "lng": -76.828824
}]

The ng-map directive contains the original Google Maps V3 api to the user so you don't need to use new google.maps Object.

Something like this:

(function() {

  angular.module("app", ["ngMap"]).controller("Controller", ["$scope", "NgMap", function($scope, NgMap) {
    NgMap.getMap().then(function(map) {
      $scope.map = map;
    });

    $scope.latitude = -12.339223;
    $scope.longitude = -76.808624;
    $scope.potholeData = [{
      "id": "Location1",
      "text": "Some content 1...",
      "lat": -12.339223,
      "lng": -76.808624
    }, {
      "id": "Location2",
      "text": "Some content 2...",
      "lat": -12.349423,
      "lng": -76.828824
    }];
    $scope.pothole = {};

    $scope.showDetails = function(e, pothole) {
      $scope.pothole = pothole;
      $scope.map.showInfoWindow('foo-iw', pothole.id);
    };

    $scope.hideDetail = function() {
      $scope.map.hideInfoWindow('foo-iw');
    };
  }]);
})();

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCGsmJhDsK9HS2_kYtQXbiJqaAE2AT_Pw0"></script>
<script src="https://code.angularjs.org/1.3.15/angular.js"></script>
<script src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/scripts/ng-map.js"></script>

<div data-ng-app="app">
  <div data-ng-controller="Controller">
    <ng-map default-style="true" center="{{latitude}}, {{longitude}}" zoom="13">
      <marker id="{{pothole.id}}" ng-repeat="pothole in potholeData" position="{{pothole.lat}},{{pothole.lng}}" on-click="showDetails(event, pothole)"></marker>

      <info-window id="foo-iw">
        <div ng-non-bindable="">
          id: {{pothole.id}}<br/> Text: {{pothole.text}}<br/> Position: {{anchor.getPosition()}}
        </div>
      </info-window>
    </ng-map>
  </div>
</div>


问:
stop javascript loop, setTimeout
This animation should stop playing (stop snowing) after 10 seconds. I added a function to the bottom, but it actually starts the animation after 10 seconds, rather than stopping the animation after 10 seconds.

I only want it to play for 10 seconds total time, and start right-away, see my codePen to see what I mean.

```<code>setTimeout(function() {
createSnow(20);
loop();
}, 10000)
</code>```

here is a codePen to see what I mean:
https://codepen.io/celli/pen/XzzjRW

答:
Use cancelAnimationFrame.

Sample usage

Declare cancelAnimFrame:

```<code>var cancelAnimFrame =
  window.cancelAnimationFrame ||
  window.mozcancelAnimationFrame ||
  window.webkitcancelAnimationFrame ||
  window.mscancelAnimationFrame;
</code>```

Update loop function:

```<code>var animId;
function loop() {
  draw();
  update();
  animId = animFrame(loop);
}
</code>```

and use animId to stop animation.
(As already mentioned, starting snowing should be out of setTimeout.)

```<code>createSnow(20);
loop();
setTimeout(function() {
  cancelAnimFrame(animId)
}, 1000)
</code>```

Title: stop javascript loop, setTimeout

Body:
This animation should stop playing (stop snowing) after 10 seconds. I added a function to the bottom, but it actually starts the animation after 10 seconds, rather than stopping the animation after 10 seconds.

I only want it to play for 10 seconds total time, and start right-away, see my codePen to see what I mean.

setTimeout(function() {
createSnow(20);
loop();
}, 10000)

here is a codePen to see what I mean:
https://codepen.io/celli/pen/XzzjRW

Body:
Use cancelAnimationFrame.

Sample usage

Declare cancelAnimFrame:

var cancelAnimFrame =
  window.cancelAnimationFrame ||
  window.mozcancelAnimationFrame ||
  window.webkitcancelAnimationFrame ||
  window.mscancelAnimationFrame;

Update loop function:

var animId;
function loop() {
  draw();
  update();
  animId = animFrame(loop);
}

and use animId to stop animation.
(As already mentioned, starting snowing should be out of setTimeout.)

createSnow(20);
loop();
setTimeout(function() {
  cancelAnimFrame(animId)
}, 1000)


问:
Using did as boolean flag name
I named one of my boolean parameters didInfoChange.

Many people on my team tell me to change it to isInfoChanged, which I don't agree. It maybe because my team members aren't native English speaker (neither am I), but I feel that ifInfoChanged is just isn't right.

didInfoChange -> Did information change? -> True/False

is pretty understand in my oppinion

isInfoChanged -> is info changed?

just does not sound right.
It's probably not a big deal to fight about this, but I did some search and people do not really use did for flag name. I'm ok with hasInfoChanged but has and did is basically the same thing.

I'm wondering why is did not ok?

答:
There are two questions here:

1) Which is better, didInfoChange or isInfoChanged?

The English word "change" can be transitive or intransitive, but in this context it is clear that "the info is changed" and "the info did change" mean exactly the same thing. (There is a subtle difference in connotation, but it is of no importance here.) The two names have the same length. There seems to be no difference except style convention.

2) If your way is better than theirs, what should you do?

Consider the consequences of your actions.

If you have the power to persuade the rest of the team to use your variable name, at no cost, then do so. If doing so would cause stress (e.g. by commanding your subordinates to do something they consider a bad idea), then the improvement in style probably isn't the cost to the group dynamic.

If you cannot persuade them, but you can prolong the argument and prevent the team from doing constructive work, then... don't. Use their variable name.

If you cannot prolong the argument, but you can make yourself unpopular by being argumentative, then... don't. Use their variable name.

Title: Using did as boolean flag name


问:
How do I detect the inherited background-color of an element using jQuery/JS?
Using jQuery (or just JavaScript), how do I detect the inherited background-color of an element?

For example:

```<code><div style="background-color: red">
    <p id="target">I'd like to know that the background-color here is red</p>
</div>
</code>```

However:

```<code>$('#target').css('background-color') == rgba(0,0,0,0)
</code>```

and

```<code>$('#target').css('backgroundColor') == rgba(0,0,0,0)
</code>```

I'm asking for a general solution.  $('#target').parent().css('background-color') would work in this instance, but not all.

答:
You can make use of window.getComputedStyle() to get the inherited value.

Caveat: You must manually declare the inheritance in css or inline.

```<code>#target{
  background-color: inherit;
}
</code>```

Working example:

let bgc = window.getComputedStyle($('#target')[0],null).getPropertyValue("background-color");
console.log(bgc);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#target{
  background-color: inherit;
}</code>```

I'd like to know that the background-color here is red

```

Body:
Using jQuery (or just JavaScript), how do I detect the inherited background-color of an element?

For example:

I'd like to know that the background-color here is red

However:

$('#target').css('background-color') == rgba(0,0,0,0)

and

$('#target').css('backgroundColor') == rgba(0,0,0,0)

I'm asking for a general solution.  $('#target').parent().css('background-color') would work in this instance, but not all.

Body:
You can make use of window.getComputedStyle() to get the inherited value.

Caveat: You must manually declare the inheritance in css or inline.

#target{
  background-color: inherit;
}

Working example:

let bgc = window.getComputedStyle($('#target')[0],null).getPropertyValue("background-color");
console.log(bgc);

#target{
  background-color: inherit;
}

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

<div style="background-color: red">
    <p id="target">I'd like to know that the background-color here is red</p>
</div>


问:
Fetch API Download Progress Indicator?
I am trying to capture the download progress of a Fetch request and use that to change the width of a progress bar. I looked at ProgressEvent.lengthComputable as a potential solution but unsure if this can be used with the Fetch API.</p>

答:
you can use axios instead</p>

```<code>import axios from 'axios'
export async function uploadFile(file, cb) {
  const url = `//127.0.0.1:4000/profile`
  try {
    let formData = new FormData()
    formData.append("avatar", file)
    const data = await axios.post(url, formData, {
      onUploadProgress: (progressEvent) => {
        console.log(progressEvent)
        if (progressEvent.lengthComputable) {
          let percentComplete = progressEvent.loaded / progressEvent.total;
          if (cb) {
            cb(percentComplete)
          }
        }
      }
    })
    return data
  } catch (error) {
    console.error(error)
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Fetch API Download Progress Indicator?

Body:
you can use axios instead

import axios from 'axios'
export async function uploadFile(file, cb) {
  const url = `//127.0.0.1:4000/profile`
  try {
    let formData = new FormData()
    formData.append("avatar", file)
    const data = await axios.post(url, formData, {
      onUploadProgress: (progressEvent) => {
        console.log(progressEvent)
        if (progressEvent.lengthComputable) {
          let percentComplete = progressEvent.loaded / progressEvent.total;
          if (cb) {
            cb(percentComplete)
          }
        }
      }
    })
    return data
  } catch (error) {
    console.error(error)
  }
}


问:
Android Facebook Login get Email
I have a simple app with facebook login button and displaying the user info. I am trying to get the user email, used many ways but it gives back a null value. How to get the user email ?</p>

```<code>loginButton=(LoginButton)findViewById(R.id.loginButton);
loginButton.setReadPermissions(Arrays.asList("public_profile", "email"));
callbackManager= CallbackManager.Factory.create();
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {
        loginButton.setVisibility(View.GONE);
        //how to get user email here
        finish();
    }

    @Override
    public void onCancel() {
        Toast.makeText(PopUpFaceBook.this,"تم الغاء تسجيل الدخول",Toast.LENGTH_SHORT).show();
        finish();
    }

    @Override
    public void onError(FacebookException error) {
        Toast.makeText(PopUpFaceBook.this,"هناك مشكلة فى تسجيل الدخول حاول مجددا",Toast.LENGTH_SHORT).show();
        finish();
    }
});
</code>```

答:
Use below code in your onSuccess() callback method :

```<code>LoginResult loginR = loginResult;
// App code
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
    @Override
    public void onCompleted(JSONObject object, GraphResponse response) {
        Log.v("LoginActivity", response.toString());
        // Application code
        try {
            String email  = object.getString("email");
            String birthday = object.getString("birthday");
            String gender = object.getString("gender");
            String name = object.getString("name");
            // 01/31/1980 format
        } catch (JSONException ex) {
            Log.d("JSonExceptioin", ex.toString());
        }
    }
});
Bundle parameters = new Bundle();
parameters.putString("fields","id,name,email,gender,birthday,picture,timezone");
request.setParameters(parameters);
request.executeAsync();
</code>```

Title: Android Facebook Login get Email

Body:
I have a simple app with facebook login button and displaying the user info. I am trying to get the user email, used many ways but it gives back a null value. How to get the user email ?

loginButton=(LoginButton)findViewById(R.id.loginButton);
loginButton.setReadPermissions(Arrays.asList("public_profile", "email"));
callbackManager= CallbackManager.Factory.create();
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {
        loginButton.setVisibility(View.GONE);
        //how to get user email here
        finish();
    }

    @Override
    public void onCancel() {
        Toast.makeText(PopUpFaceBook.this,"تم الغاء تسجيل الدخول",Toast.LENGTH_SHORT).show();
        finish();
    }

    @Override
    public void onError(FacebookException error) {
        Toast.makeText(PopUpFaceBook.this,"هناك مشكلة فى تسجيل الدخول حاول مجددا",Toast.LENGTH_SHORT).show();
        finish();
    }
});

Body:
Use below code in your onSuccess() callback method :

LoginResult loginR = loginResult;
// App code
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
    @Override
    public void onCompleted(JSONObject object, GraphResponse response) {
        Log.v("LoginActivity", response.toString());
        // Application code
        try {
            String email  = object.getString("email");
            String birthday = object.getString("birthday");
            String gender = object.getString("gender");
            String name = object.getString("name");
            // 01/31/1980 format
        } catch (JSONException ex) {
            Log.d("JSonExceptioin", ex.toString());
        }
    }
});
Bundle parameters = new Bundle();
parameters.putString("fields","id,name,email,gender,birthday,picture,timezone");
request.setParameters(parameters);
request.executeAsync();


问:
JavaScript: Why does closure only happen if I assign the return function to a variable?
Even after reading You don't know JS and JavaScript: The Core I still couldn't understand the behavior of the following code.

Why, when I call counter()(), do I get no closure, but if I assign a variable to the result of counter(), like var getClosure = counter(), I then get a closure when calling getClosure()?

```<code>function counter() {

    var _counter = 0;

    function increase() { return _counter++ }

    return increase;
}

// Double ()() to call the returned function always return 0, so no closure.
counter()() // returns 0
counter()() // returns 0
counter()() // returns 0
counter()() // returns 0

var createClosure = counter();

createClosure() // returns 0
createClosure() // returns 1
createClosure() // returns 2
createClosure() // returns 3
</code>```

答:
_counter is the local variable within function counter(). Every time when you call counter() a new _counter will be created.

But var createClosure = counter() only called the function 1 time, that's why _counter is not newly created every time and 'remembered' there (that's where closure happens)

Body:
Even after reading You don't know JS and JavaScript: The Core I still couldn't understand the behavior of the following code.

Why, when I call counter()(), do I get no closure, but if I assign a variable to the result of counter(), like var getClosure = counter(), I then get a closure when calling getClosure()?

function counter() {

    var _counter = 0;

    function increase() { return _counter++ }

    return increase;
}

// Double ()() to call the returned function always return 0, so no closure.
counter()() // returns 0
counter()() // returns 0
counter()() // returns 0
counter()() // returns 0

var createClosure = counter();

createClosure() // returns 0
createClosure() // returns 1
createClosure() // returns 2
createClosure() // returns 3


问:
Does Pivotal Cloud Foundry (PCF) supports Jersey or RestEasy services?
I am developing a new application and I want that to be deployed on PCF(Cloud Foundry). I am thinking which flavor of REST services that I have to use. Should I use Jersey or RestEasy to expose services? or cloud foundry provides default rest implementations?</p>

答: Cloud Foundry does not provide any rest implementation, and can support almost any, if it's supported by a language with a buildpack. Jersey and RestEasy would both be supported as they can run in a JVM, as is Spring Boot (which is my personal favorite). You can also write REST services in ruby, python, go, php, and nodejs--and those are just the languages that are supported out of the box!</p>


问:
AudioKit - can't get AKClipRecorder working
I am trying to achieve the ability to record something (microphone or oscillator or any other input), I need it to be as accurate as it could be in terms of executing a callback right after recording finishes, so I thought ClipRecorder could help me here. this piece of code goes into a simple view controller's viewDidLoad function, and the code executed and get to the end but the callback of the clip recorder never executed.

Can you please advise me what did I do wrong? I am very new to AudioKit so it could be my miss-understanding of things. here is the code:

```<code>AKSettings.bufferLength = .shortest
AKSettings.defaultToSpeaker = true
try! AKSettings.setSession(category: .playAndRecord)

let oscillator = AKOscillator()
let oscMixer = AKMixer(oscillator)
AudioKit.output = oscMixer
AudioKit.start()

oscillator.start()

let clipRecorder = AKClipRecorder(node: oscMixer)

do{
    AKLog("1")
    try clipRecorder.recordClip(time: 0, duration: 2, tap: nil, completion: { url, something, err in
        AKLog("recorded clip")
        oscillator.stop()
    })
    AKLog("2")
} catch let error as ClipRecordingError {
    print("\(String(describing: error.errorDescription))")
} catch {
    print("something general")
}
</code>```

logs 1,2 are printed, 'recorded clip' is not printed.

many thanks!

答: You have to call clipRecorder.play() or clipRecorder.play(at:).</p>

Body:
I am trying to achieve the ability to record something (microphone or oscillator or any other input), I need it to be as accurate as it could be in terms of executing a callback right after recording finishes, so I thought ClipRecorder could help me here. this piece of code goes into a simple view controller's viewDidLoad function, and the code executed and get to the end but the callback of the clip recorder never executed.

Can you please advise me what did I do wrong? I am very new to AudioKit so it could be my miss-understanding of things. here is the code:

AKSettings.bufferLength = .shortest
AKSettings.defaultToSpeaker = true
try! AKSettings.setSession(category: .playAndRecord)

let oscillator = AKOscillator()
let oscMixer = AKMixer(oscillator)
AudioKit.output = oscMixer
AudioKit.start()

oscillator.start()

let clipRecorder = AKClipRecorder(node: oscMixer)

do{
    AKLog("1")
    try clipRecorder.recordClip(time: 0, duration: 2, tap: nil, completion: { url, something, err in
        AKLog("recorded clip")
        oscillator.stop()
    })
    AKLog("2")
} catch let error as ClipRecordingError {
    print("\(String(describing: error.errorDescription))")
} catch {
    print("something general")
}

logs 1,2 are printed, 'recorded clip' is not printed.

many thanks!


问:
BackgroundWorker vs background Thread
I have a stylistic question about the choice of background thread implementation I should use on a windows form app. Currently I have a BackgroundWorker on a form that has an infinite (while(true)) loop. In this loop I use WaitHandle.WaitAny to keep the thread snoozing until something of interest happens. One of the event handles I wait on is a "StopThread" event so that I can break out of the loop. This event is signaled when from my overridden Form.Dispose().

I read somewhere that BackgroundWorker is really intended for operations that you don't want to tie up the UI with and have an finite end - like downloading a file, or processing a sequence of items. In this case the "end" is unknown and only when the window is closed. Therefore would it be more appropriate for me to use a background Thread instead of BackgroundWorker for this purpose?

答:
What's perplexing to me is that the visual studio designer only allows you to use BackgroundWorkers and Timers that don't actually work with the service project.

It gives you neat drag and drop controls onto your service but... don't even try deploying it.   Won't work.

Services:
Only use System.Timers.Timer
System.Windows.Forms.Timer won't work even though it's available in the toolbox

Services:
BackgroundWorkers will not work when it's running as a service
Use System.Threading.ThreadPools instead or Async calls

Title: BackgroundWorker vs background Thread


问:
Pandas sampling every nth value, or closest matching value to nth value
I have a bit of a peculiar problem. I have a very large dataframe that I'm trying to sample.

My data looks something like this (two columns x and y):

```<code>x,y
1,'a'
1,'b'
1,'c'
3,'a'
3,'b'
3,'c'
6,'a'
6,'b'
6,'c'
</code>```

I want to sample based on the value of 'x'. I'd like one sample out of every 32 x values (based on the change in x, so I want to sample once between 1 and 32, even if there is only one value of x between 1 and 32).

I wanted to do something like: df[df['x'] % 32 == 0]. The problem is that the values of x are not necessarily evenly spaced (they are "approximately" though, but not always -- such as in the example given). For example, if all the values of x in a particular subproblem are odd, the above sampling will return an empty dataframe. Effectively, I want to sample once every 32 'x's, or take the closest value to the 32nd value (it is acceptable to approximate closest -- for example, taking the next available value is fine) if no such value exists.

So if I had a series of X's [0, 10, 32, 39, 64, 70, 73, 74, 97, 100, 110, 129], I'd like to sample the rows with x values matching [0, 32, 64, 97, 129].

Ideally, I could also vectorize this operation, as the dataframes are often quite large.

答:
You can dynamically create your bins with list comprehensions then use pd.cut to create groups and use groupby with sample(1) to get one records for every 32 values of 'X'.

```<code>df = pd.DataFrame({'X':np.random.randint(0, 100, 5000),'Y':np.random.choice(list('ABCDEF'),5000)})

bins = [i for i in np.arange(df.X.min(), df.X.max(), 32)] + [np.inf]

df.groupby(pd.cut(df.X,bins=bins), as_index=False).apply(lambda x: x.sample(1).values)
</code>```

Output:

```<code>[[15 'F']
 [51 'A']
 [90 'C']
 [98 'A']]
</code>```

Body:
I have a bit of a peculiar problem. I have a very large dataframe that I'm trying to sample.

My data looks something like this (two columns x and y):

x,y
1,'a'
1,'b'
1,'c'
3,'a'
3,'b'
3,'c'
6,'a'
6,'b'
6,'c'

I want to sample based on the value of 'x'. I'd like one sample out of every 32 x values (based on the change in x, so I want to sample once between 1 and 32, even if there is only one value of x between 1 and 32).

I wanted to do something like: df[df['x'] % 32 == 0]. The problem is that the values of x are not necessarily evenly spaced (they are "approximately" though, but not always -- such as in the example given). For example, if all the values of x in a particular subproblem are odd, the above sampling will return an empty dataframe. Effectively, I want to sample once every 32 'x's, or take the closest value to the 32nd value (it is acceptable to approximate closest -- for example, taking the next available value is fine) if no such value exists.

So if I had a series of X's [0, 10, 32, 39, 64, 70, 73, 74, 97, 100, 110, 129], I'd like to sample the rows with x values matching [0, 32, 64, 97, 129].

Ideally, I could also vectorize this operation, as the dataframes are often quite large.

Body:
You can dynamically create your bins with list comprehensions then use pd.cut to create groups and use groupby with sample(1) to get one records for every 32 values of 'X'.

df = pd.DataFrame({'X':np.random.randint(0, 100, 5000),'Y':np.random.choice(list('ABCDEF'),5000)})

bins = [i for i in np.arange(df.X.min(), df.X.max(), 32)] + [np.inf]

df.groupby(pd.cut(df.X,bins=bins), as_index=False).apply(lambda x: x.sample(1).values)

Output:

[[15 'F']
 [51 'A']
 [90 'C']
 [98 'A']]


问:
How to make a calendar

As a homework assignment, I need to recreate this screenshot with pure code. I currently got stuck with making the calendar. When I tried to make mine for some reason I can't get the numerical days under the day itself. As you can see there are seven days in a row but 8 numerical days in a row. How could I fix this

What changes do I need to make on my code to fix it
This is the HTML code:

```<code><h2>Calendar</h2>

<p class="october">October 2017</p>
<ul class="weekdays">
  <li>M</li>
  <li>T</li>
  <li>W</li>
  <li>T</li>
  <li>F</li>
  <li>S</li>
  <li>S</li>
</ul>

<ul class="days">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li><span class="active">10</span></li>
  <li>11</li>
  <li>12</li>
  <li>13</li>
  <li>14</li>
  <li>15</li>
  <li>16</li>
  <li>17</li>
  <li>18</li>
  <li>19</li>
  <li>20</li>
  <li>21</li>
  <li>22</li>
  <li>23</li>
  <li>24</li>
  <li>25</li>
  <li>26</li>
  <li>27</li>
  <li>28</li>
  <li>29</li>
  <li>30</li>
  <li>31</li>
</ul>
</code>```

And my CSS code:

```<code>/* Calendar */
.october{
  text-align: center;
}
.weekdays {
    margin: 0;
    padding: 10px 0;
    background-color: #cccccc;
    text-align: center;
}

.weekdays li {
    display: inline-block;
    color: #ffffff;
    width: 10%;
    text-align: center;
}

.days {
    text-align: center;
    padding: 10px 0;
    background: #eee;
    margin: 0;
}

.days li {
    list-style-type: none;
    display: inline-block;
    width: 10%;
    text-align: center;
    margin-bottom: 5px;
    font-size:12px;
    color: #777;
}

.days li .active {
    color: #3c8cd7 !important
}
</code>```

P.S. I'm not completely done with everything else that's why it still looks sloppy

答:
For your purposes you could use an html table like so:

See live: Codepen

This will solve the placement issues of the numbers and align them with the days. Ill leave the color styling to you since its not what you stated was your problem.

    M
    T
    W
    T
    F
    S
    S

    1
    2
    3
    4
    5
    6
    7

    8
    9
    10
    11
    12
    13
    14

    15
    16
    17
    18
    19
    20
    21

    22
    23
    24
    25
    26
    27

    28

    29
    30
    31

```

Title: How to make a calendar

Body:
As a homework assignment, I need to recreate this screenshot with pure code. I currently got stuck with making the calendar. When I tried to make mine for some reason I can't get the numerical days under the day itself. As you can see there are seven days in a row but 8 numerical days in a row. How could I fix this

What changes do I need to make on my code to fix it
This is the HTML code:

Calendar

October 2017

M

T

W

T

F

S

S

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

And my CSS code:

/* Calendar */
.october{
  text-align: center;
}
.weekdays {
    margin: 0;
    padding: 10px 0;
    background-color: #cccccc;
    text-align: center;
}

.weekdays li {
    display: inline-block;
    color: #ffffff;
    width: 10%;
    text-align: center;
}

.days {
    text-align: center;
    padding: 10px 0;
    background: #eee;
    margin: 0;
}

.days li {
    list-style-type: none;
    display: inline-block;
    width: 10%;
    text-align: center;
    margin-bottom: 5px;
    font-size:12px;
    color: #777;
}

.days li .active {
    color: #3c8cd7 !important
}

P.S. I'm not completely done with everything else that's why it still looks sloppy

Body:
For your purposes you could use an html table like so:

See live: Codepen

This will solve the placement issues of the numbers and align them with the days. Ill leave the color styling to you since its not what you stated was your problem.

 <table>
    <tr>
    <th>M</th>
    <th>T</th>
    <th>W</th>
    <th>T</th>
    <th>F</th>
    <th>S</th>
    <th>S</th>
    </tr>
    <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
    <td>5</td>
    <td>6</td>
    <td>7</td>
    </tr>
    <tr>
    <td>8</td>
    <td>9</td>
    <td>10</td>
    <td>11</td>
    <td>12</td>
    <td>13</td>
    <td>14<br></td>
    </tr>
    <tr>
    <td>15</td>
    <td>16</td>
    <td>17</td>
    <td>18</td>
    <td>19</td>
    <td>20</td>
    <td>21</td>
    </tr>
    <tr>
    <td>22</td>
    <td>23</td>
    <td>24</td>
    <td>25</td>
    <td>26</td>
    <td>27<br></td>
    <td>28</td>
    </tr>
    <tr>
    <td>29</td>
    <td>30</td>
    <td>31</td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table>


问:
Close screen / unmount screen
I am using react-navigation to navigate the screen in my react native app. I have one question, is it possible that when I close screen or unmount screen, the rendered content are kept and not destroyed. So the next time when I call the screen again, the rendered content should not be reloaded again. Or maybe there is another way to achieve this. Thanks a lot </p>

答: You should try redux and get your states from your reducers.</p>

Title: Close screen / unmount screen


问:
iOS unit test: How to unit test firstResponderStatus
I am writing a test to confirm the if a method shifts the focus to next textField. I tried the code from iOS unit test: How to set/update/examine firstResponder?. But it fails.

```<code>- (void)testFocusMovedToYearField {
  UIWindow *window = [[UIWindow alloc] init];
  [window addSubview:self.dateCell.txtDay];
  [window addSubview:self.dateCell.txtYear];
  [self.dateCell completionBlockHelper];
  [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:5.0]];
  XCTAssertTrue([self.kioskDateCell.txtYear isFirstResponder]);
}
</code>```

The function completionBlockHelper contains the code to make the txtYear become first responder.

Any suggestions will be helpful.

答: The window needs to become the key window. In Swift: window.makeKeyAndVisible()

Body:
I am writing a test to confirm the if a method shifts the focus to next textField. I tried the code from iOS unit test: How to set/update/examine firstResponder?. But it fails.

- (void)testFocusMovedToYearField {
  UIWindow *window = [[UIWindow alloc] init];
  [window addSubview:self.dateCell.txtDay];
  [window addSubview:self.dateCell.txtYear];
  [self.dateCell completionBlockHelper];
  [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:5.0]];
  XCTAssertTrue([self.kioskDateCell.txtYear isFirstResponder]);
}

The function completionBlockHelper contains the code to make the txtYear become first responder.

Any suggestions will be helpful.


问:
efficient filter rows by multi column patterns
I have a big data frame (104029 x 142).

I want to filter rows which value>0 by multi specific column names.

```<code>df
         word abrasive abrasives abrasivefree abrasion slurry solute solution ....
1 composition     -0.2       0.2         -0.3    -0.40    0.2      0.1         0.20 ....
2       ceria      0.1       0.2         -0.4    -0.20   -0.1     -0.2         0.20 ....
3     diamond      0.3      -0.5         -0.6    -0.10   -0.1     -0.2        -0.15 ....
4        acid     -0.1      -0.1         -0.2    -0.15    0.1      0.3         0.20 ....
....
</code>```

Now I have tried to use filter() function to do, and it's OK.

But I think this way is not efficient for me.

Because I need to define each column name, it makes hard work when I need to maintain my process.

```<code>column_names <- c("agent", "agents", "liquid", "liquids", "slurry",
                  "solute", "solutes", "solution", "solutions")

df_filter <- filter(df,  agents>0 | agents>0 | liquid>0 | liquids>0 | slurry>0 | solute>0 |
                    solutes>0 | solution>0 | solutions>0)

df_filter
         word abrasive abrasives abrasivefree abrasion  slurry solute solution ....
1 composition     -0.2       0.2         -0.3    -0.40    0.2      0.1         0.20 ....
2       ceria      0.1       0.2         -0.4    -0.20   -0.1     -0.2         0.20 ....
4        acid     -0.1      -0.1         -0.2    -0.15    0.1      0.3         0.20 ....
....
</code>```

Is there any more efficient way to do?

答:
Use dplyr::filter_at() which allows you to use select()-style helpers to select some functions:

```<code>library(dplyr)

df_filter <- df %>%
    filter_at(
        # select all the columns that are in your column_names vector
        vars(one_of(column_names))
        # if any of those variables are greater than zero, keep the row
        , any_vars( . > 0)
    )
</code>```

Body:
I have a big data frame (104029 x 142).

I want to filter rows which value>0 by multi specific column names.

df
         word abrasive abrasives abrasivefree abrasion slurry solute solution ....
1 composition     -0.2       0.2         -0.3    -0.40    0.2      0.1         0.20 ....
2       ceria      0.1       0.2         -0.4    -0.20   -0.1     -0.2         0.20 ....
3     diamond      0.3      -0.5         -0.6    -0.10   -0.1     -0.2        -0.15 ....
4        acid     -0.1      -0.1         -0.2    -0.15    0.1      0.3         0.20 ....
....

Now I have tried to use filter() function to do, and it's OK.

But I think this way is not efficient for me.

Because I need to define each column name, it makes hard work when I need to maintain my process.

column_names <- c("agent", "agents", "liquid", "liquids", "slurry",
                  "solute", "solutes", "solution", "solutions")

df_filter <- filter(df,  agents>0 | agents>0 | liquid>0 | liquids>0 | slurry>0 | solute>0 |
                    solutes>0 | solution>0 | solutions>0)

df_filter
         word abrasive abrasives abrasivefree abrasion  slurry solute solution ....
1 composition     -0.2       0.2         -0.3    -0.40    0.2      0.1         0.20 ....
2       ceria      0.1       0.2         -0.4    -0.20   -0.1     -0.2         0.20 ....
4        acid     -0.1      -0.1         -0.2    -0.15    0.1      0.3         0.20 ....
....

Is there any more efficient way to do?

Body:
Use dplyr::filter_at() which allows you to use select()-style helpers to select some functions:

library(dplyr)

df_filter <- df %>%
    filter_at(
        # select all the columns that are in your column_names vector
        vars(one_of(column_names))
        # if any of those variables are greater than zero, keep the row
        , any_vars( . > 0)
    )


问:
How to check whether a character comes before another character in a string in Python
I'm writing a program that determines whether a math equation input by user has matching parentheses. I have it to where it counts whether the amount of right parentheses are equal to the amount of left parentheses, but the user could input 2)(3+x)(4+x)(6. To avoid telling the user his parentheses match in this case, I want to check if a ')' comes before a '('.

```<code>left_parenth = math.count("(")
right_parenth = math.count(")")

total_parenth = right_parenth + left_parenth

if total_parenth % 2 != 0:
    if right_parenth > left_parenth:
        print("\nYou are missing a left parentheses '('")
    elif right_parenth < left_parenth:
        print("\nYou are missing a right parentheses ')'")

elif total_parenth % 2 == 0:
    print("\nYour equation has the correct amount of parentheses")
</code>```

答:
General idea here is to use stack.
When you encounter a opening parentheses, PUSH it on stack
When you encounter a closing parentheses, POP cooresponding opening parentheses from stack</p>

Body:
I'm writing a program that determines whether a math equation input by user has matching parentheses. I have it to where it counts whether the amount of right parentheses are equal to the amount of left parentheses, but the user could input 2)(3+x)(4+x)(6. To avoid telling the user his parentheses match in this case, I want to check if a ')' comes before a '('.

left_parenth = math.count("(")
right_parenth = math.count(")")

total_parenth = right_parenth + left_parenth

if total_parenth % 2 != 0:
    if right_parenth > left_parenth:
        print("\nYou are missing a left parentheses '('")
    elif right_parenth < left_parenth:
        print("\nYou are missing a right parentheses ')'")

elif total_parenth % 2 == 0:
    print("\nYour equation has the correct amount of parentheses")


问:
How to get method name automatically in Code Snippet in C# 4.0
I am developing an application in ASP.Net 4.0 with C# where I am doing logging and tracing using Microsoft's Enterprise Lib. My problem is that almost in every function , as per my company guidline, where there is interaction with database or some critical business rules , use tracing, in this format.

```<code>try
{
_traceLog.clear();
_traceLog.AppendLine("XYZ method started: XYZ()");

_traceLog.AppendLine("XYZ method completed: XYZ()");
}
catch(Exception ex)
{
 _userException.CreateExceptionLog(ex);
}
finally
{
 _userException.CreateTraceLog(_traceLog.ToString());
}
</code>```

So what i want is to convert it as a code snippet that will automatically detect the current method, say in above case we have XYZ().

Please help me. Also tell me the way to add this to intellisense. Right now i am able create .snippet file and uses insert snippet from context menu.

UPdate

I think i am not clear to you guys. Let me make more clear. i have an code snippet

```<code><CodeSnippets
    xmlns="http://schemas.microsoft.com/VisualStudio/2010/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>
                TL
            </Title>
        </Header>
        <Snippet>
            <Code Language="CSharp">
                <![CDATA[ try
            {
                _traceLog.Clear();
                _traceLog.AppendLine("");   // here in side the append line i want to get name of method under which i am placing code snippet.
                _traceLog.AppendLine("");
            }
            catch (Exception ex)
            {

                _userExceptionLog.CreateExceptionLog(ex);
            }
            finally
            {
                _userExceptionLog.CreateTraceLog(_traceLog.ToString());
            }]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>
</code>```

For example if my method is

```<code>void XYZ()
{
  // when i insert snippet here , the snippet will automatically detect
</code>```

that this snippet is going to be placed under XYZ function.

```<code>try
                {
                    _traceLog.Clear();
                    _traceLog.AppendLine("XYZ started: XYZ()");
</code>```

// here in side the append line i want to get name of method under
which i am placing code snippet.

```<code>                _traceLog.AppendLine("XYZ completed: XYZ()");
                }
                catch (Exception ex)
                {

                    _userExceptionLog.CreateExceptionLog(ex);
                }
                finally
                {
                    _userExceptionLog.CreateTraceLog(_traceLog.ToString());
                }

}
</code>```

Is this possible? or I have to enter it manually or any other short way?

答:
I use this:

```<code>try
{

}
catch ( Exception ex )
{
    My.API.ErrorHandler.Handler.HandleError( ex,
        System.Reflection.MethodBase.GetCurrentMethod().Name,
        System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName );
}
</code>```

Here is the code for the snippet:

```<code><?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Try Catch</Title>
      <Shortcut>try</Shortcut>
      <Description>Places a try catch block with My API error handling</Description>
      <Author>Nathan Freeman-Smith</Author>
    </Header>
    <Snippet>
      <Code Language="csharp"><![CDATA[            try
            {

            }
            catch ( Exception ex )
            {
                My.API.ErrorHandler.Handler.HandleError( ex, System.Reflection.MethodBase.GetCurrentMethod().Name, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName );
            }]]></Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>
</code>```

Note the Shortcut tag with "try" inside of it.

It means I can use the snippet by typing try in visual studio to insert the snippet, or, marking piece of code and surround it with this snippt by using Ctrl+k, Ctrl+S (Deafult Keyboard Shourtcut)

ContentLicense: CC BY-SA 2.5

Body:
I am developing an application in ASP.Net 4.0 with C# where I am doing logging and tracing using Microsoft's Enterprise Lib. My problem is that almost in every function , as per my company guidline, where there is interaction with database or some critical business rules , use tracing, in this format.

try
{
_traceLog.clear();
_traceLog.AppendLine("XYZ method started: XYZ()");

_traceLog.AppendLine("XYZ method completed: XYZ()");
}
catch(Exception ex)
{
 _userException.CreateExceptionLog(ex);
}
finally
{
 _userException.CreateTraceLog(_traceLog.ToString());
}

So what i want is to convert it as a code snippet that will automatically detect the current method, say in above case we have XYZ().

Please help me. Also tell me the way to add this to intellisense. Right now i am able create .snippet file and uses insert snippet from context menu.

UPdate

I think i am not clear to you guys. Let me make more clear. i have an code snippet

<CodeSnippets
    xmlns="http://schemas.microsoft.com/VisualStudio/2010/CodeSnippet">
    <CodeSnippet Format="1.0.0">

            <Title>
                TL
            </Title>

        <Snippet>

                <![CDATA[ try
            {
                _traceLog.Clear();
                _traceLog.AppendLine("");   // here in side the append line i want to get name of method under which i am placing code snippet.
                _traceLog.AppendLine("");
            }
            catch (Exception ex)
            {

                _userExceptionLog.CreateExceptionLog(ex);
            }
            finally
            {
                _userExceptionLog.CreateTraceLog(_traceLog.ToString());
            }]]>

        </Snippet>
    </CodeSnippet>
</CodeSnippets>

For example if my method is

void XYZ()
{
  // when i insert snippet here , the snippet will automatically detect

that this snippet is going to be placed under XYZ function.

try
                {
                    _traceLog.Clear();
                    _traceLog.AppendLine("XYZ started: XYZ()");

// here in side the append line i want to get name of method under
which i am placing code snippet.

                _traceLog.AppendLine("XYZ completed: XYZ()");
                }
                catch (Exception ex)
                {

                    _userExceptionLog.CreateExceptionLog(ex);
                }
                finally
                {
                    _userExceptionLog.CreateTraceLog(_traceLog.ToString());
                }

}

Is this possible? or I have to enter it manually or any other short way?

Body:
I use this:

try
{

}
catch ( Exception ex )
{
    My.API.ErrorHandler.Handler.HandleError( ex,
        System.Reflection.MethodBase.GetCurrentMethod().Name,
        System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName );
}

Here is the code for the snippet:

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Try Catch</Title>
      <Shortcut>try</Shortcut>
      <Description>Places a try catch block with My API error handling</Description>
      <Author>Nathan Freeman-Smith</Author>
    </Header>
    <Snippet>
      <Code Language="csharp"><![CDATA[            try
            {

            }
            catch ( Exception ex )
            {
                My.API.ErrorHandler.Handler.HandleError( ex, System.Reflection.MethodBase.GetCurrentMethod().Name, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName );
            }]]></Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Note the Shortcut tag with "try" inside of it.

It means I can use the snippet by typing try in visual studio to insert the snippet, or, marking piece of code and surround it with this snippt by using Ctrl+k, Ctrl+S (Deafult Keyboard Shourtcut)


问:
Desktop Bridge UWP Windows.Services.Store;
I have a windows store WPF desktop bridge app compiled to 4.6.1. I am going to give the app away free and allow for in app purchases. To do this I need to use the UWP API for the windows store service.

I am also using the new desktop bridge packaging app template.

I want to keep the UWP API separate from the WPF project, so I have created a serparate dll project for the UWP API. I reference System.Runtime.WindowsRuntime and Windows. Use basic code from the Store Sample.

I add a reference from the WPF app to the UWP dll.

As soon as I reference the UWP dll the desktop bridge packaging app will return 9805 Errors and 1 warning.

One of the errors (which is typical) is

The .winmd file 'Windows.winmd' contains type 'Windows.Gaming.Input.Gamepad'. The use of the Windows namespace is reserved.

The warning is

No implementation file was provided for the .winmd file 'OUTPUT DIRECTORY PATH\Windows.winmd'. To generate registration information in the app manifest, specify the 'Implementation' metadata on the .winmd reference item in the project file.

I get the same errors if I add the two references to the WPF directly (System.Runtime.WindowsRuntime and Windows) and remove the UWP dll.

Updated: Have confirmed this is a problem with Desktop Bridge by:

```<code>Creating a new WPF App project.
Creating a new Windows Application Packaging Project and configure it to include the WPF project.
Build the WPF project.
Create an appx package and perform WACK tests. All Okay.
Add a reference to the C:\Program Files (x86)\Windows Kits\10\UnionMetadata\winmd
Add a reference to the C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll
Build the WPF project.
Trying to build the Packaging Project results in 9805 errors.
</code>```

Here is the blog that I was following: https://blogs.windows.com/buildingapps/2017/01/25/calling-windows-10-apis-desktop-application/

Anyone know what is going on?

The error messages come from the WACK tests

```<code><TEST INDEX="54" NAME="Type name correctness" DESCRIPTION="Only system types can be in the Windows namespace and no types can be in the global namespace." EXECUTIONTIME="00h:00m:08s.46ms" OPTIONAL="FALSE">
    <MESSAGES>
      <MESSAGE TEXT="The Windows.ApplicationModel.StartupTaskState type in the Windows.winmd file is in the Windows namespace." />
      <MESSAGE TEXT="The Windows.ApplicationModel.PackageSignatureKind type in the Windows.winmd file is in the Windows namespace." />
      <MESSAGE TEXT="The Windows.ApplicationModel.PackageVersion type in the Windows.winmd file is in the Windows namespace." />
</code>```

Anyone know how to get around it?

答:
Visual studio updates were installed a few days ago.

I built a new wpf app project targetting 4.6.1
Add a new windows packaging project and configure it.
I no longer get a long list of errors and the references seem to work. Both applications compile.

So I am unsure of what was going wrong before or why it is fixed.

Body:
I have a windows store WPF desktop bridge app compiled to 4.6.1. I am going to give the app away free and allow for in app purchases. To do this I need to use the UWP API for the windows store service.

I am also using the new desktop bridge packaging app template.

I want to keep the UWP API separate from the WPF project, so I have created a serparate dll project for the UWP API. I reference System.Runtime.WindowsRuntime and Windows. Use basic code from the Store Sample.

I add a reference from the WPF app to the UWP dll.

As soon as I reference the UWP dll the desktop bridge packaging app will return 9805 Errors and 1 warning.

One of the errors (which is typical) is

The .winmd file 'Windows.winmd' contains type 'Windows.Gaming.Input.Gamepad'. The use of the Windows namespace is reserved.

The warning is

No implementation file was provided for the .winmd file 'OUTPUT DIRECTORY PATH\Windows.winmd'. To generate registration information in the app manifest, specify the 'Implementation' metadata on the .winmd reference item in the project file.

I get the same errors if I add the two references to the WPF directly (System.Runtime.WindowsRuntime and Windows) and remove the UWP dll.

Updated: Have confirmed this is a problem with Desktop Bridge by:

Creating a new WPF App project.
Creating a new Windows Application Packaging Project and configure it to include the WPF project.
Build the WPF project.
Create an appx package and perform WACK tests. All Okay.
Add a reference to the C:\Program Files (x86)\Windows Kits\10\UnionMetadata\winmd
Add a reference to the C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll
Build the WPF project.
Trying to build the Packaging Project results in 9805 errors.

Here is the blog that I was following: https://blogs.windows.com/buildingapps/2017/01/25/calling-windows-10-apis-desktop-application/

Anyone know what is going on?

The error messages come from the WACK tests

<TEST INDEX="54" NAME="Type name correctness" DESCRIPTION="Only system types can be in the Windows namespace and no types can be in the global namespace." EXECUTIONTIME="00h:00m:08s.46ms" OPTIONAL="FALSE">
    <MESSAGES>
      <MESSAGE TEXT="The Windows.ApplicationModel.StartupTaskState type in the Windows.winmd file is in the Windows namespace." />
      <MESSAGE TEXT="The Windows.ApplicationModel.PackageSignatureKind type in the Windows.winmd file is in the Windows namespace." />
      <MESSAGE TEXT="The Windows.ApplicationModel.PackageVersion type in the Windows.winmd file is in the Windows namespace." />

Anyone know how to get around it?


问:
Fastest Multithreading Sorting Method
Currently, I am creating a multi-threaded sorter that reads in a bunch of CSV files and outputs a single large sorted CSV file consisting of all the data in the CSV files. Right now, I am planning on sorting each of the CSV's in their individual thread using mergesort and then sorting it one last time when all the data from the threads are concatenated together. I am just curious whether only using mergesort would be considered "fast". After the threads concatenate the sorted data together, the data is sorted in their individual sections but overall, it is still unsorted. </p>

答:
I thought that merge sort would be memory bound due to relatively tight loops in the merge function until I made a multi-threaded bottom up merge sort. With 4 threads, it was about 3 times as fast as a single-threaded merge sort. In this example, the array is split up into 4 parts, each part is merge-sorted, then thread 0 merges quarter arrays 0 and 1, and thread 2 merges quarter arrays 2 and 3, then thread 0 merges the two half arrays.

https://codereview.stackexchange.com/questions/148025/multithreaded-bottom-up-merge-sort

gnu sort, which is a text file sort, does a multi-threaded merge sort on an array of pointers in the first pass used to create the initial temporary files (assuming the original file is larger than available memory). After the initial pass, it does a single threaded 16 way merge on the temporary files, since the bottleneck there is the disk I/O speed, not processor speed.

Title: Fastest Multithreading Sorting Method


问:
How to save print settings from a Windows Forms Program?
I have program that print labels and I have to allow user to save/remember settings for printer. So I have this code:

```<code>private void printerToolStripButton_Click(object sender, EventArgs e)
{
     PrintDialog dialog = new PrintDialog();
     dialog.ShowDialog();
}
</code>```

User selects printer and clicks properties button, do some changes (paper size, orientation, etc.) and then click 'OK' and then click 'OK' on PrintDialog.

My problem is that those changes are not remembered... When I click button again or restart application they disappear...

Does anyone know how to persist them in application scope? Or if application scope is impossible, then maybe how to save them in the system (so when I go to control panel -> printers -> right click on printer -> preferences they will be there)?

答:
Yu can use my own interface-driven serialization. ;)

You can extend interface-driven serialization using my xml serialization properties. By the way, interface-driven serialization is cool when you are using interface inheritance ;)

```<code>using System;
using System.IO;
using System.Windows.Forms;

// download at [http://xmlserialization.codeplex.com/]
using System.Xml.Serialization;
namespace test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        [XmlRootSerializer("PrinterSettings")]
        public interface IPrinterSettings
        {
            bool PrintToFile { get; set; }
        }

        private static readonly string PrinterConfigurationFullName = Path.Combine(Application.StartupPath, "PrinterSettings.xml");

        private void Form1_Load(object sender, EventArgs e)
        {
            if (File.Exists(PrinterConfigurationFullName))
            {
                XmlObjectSerializer.Load<IPrinterSettings>(File.ReadAllText(PrinterConfigurationFullName), printDialog1);
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            File.WriteAllText(PrinterConfigurationFullName, XmlObjectSerializer.Save<IPrinterSettings>(printDialog1));
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (printDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                // do required stuff here...
            }
        }
    }
}
</code>```

Body:
I have program that print labels and I have to allow user to save/remember settings for printer. So I have this code:

private void printerToolStripButton_Click(object sender, EventArgs e)
{
     PrintDialog dialog = new PrintDialog();
     dialog.ShowDialog();
}

User selects printer and clicks properties button, do some changes (paper size, orientation, etc.) and then click 'OK' and then click 'OK' on PrintDialog.

My problem is that those changes are not remembered... When I click button again or restart application they disappear...

Does anyone know how to persist them in application scope? Or if application scope is impossible, then maybe how to save them in the system (so when I go to control panel -> printers -> right click on printer -> preferences they will be there)?

Body:
Yu can use my own interface-driven serialization. ;)

You can extend interface-driven serialization using my xml serialization properties. By the way, interface-driven serialization is cool when you are using interface inheritance ;)

using System;
using System.IO;
using System.Windows.Forms;

// download at [http://xmlserialization.codeplex.com/]
using System.Xml.Serialization;
namespace test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        [XmlRootSerializer("PrinterSettings")]
        public interface IPrinterSettings
        {
            bool PrintToFile { get; set; }
        }

        private static readonly string PrinterConfigurationFullName = Path.Combine(Application.StartupPath, "PrinterSettings.xml");

        private void Form1_Load(object sender, EventArgs e)
        {
            if (File.Exists(PrinterConfigurationFullName))
            {
                XmlObjectSerializer.Load<IPrinterSettings>(File.ReadAllText(PrinterConfigurationFullName), printDialog1);
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            File.WriteAllText(PrinterConfigurationFullName, XmlObjectSerializer.Save<IPrinterSettings>(printDialog1));
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (printDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                // do required stuff here...
            }
        }
    }
}


问:
How do I get out of a >> prompt in powershell when I made a mistake?
I use powershell with git for the poshgit features and sometimes I'll make an error typing the git command like git commit -m 'something and for get to close the ' before hitting enter. It goes to the new line I type ' and hit enter and I still get the >> prompt. Is there any easy way to say give me back a new prompt and get out of the infinite >> loop with out closing powershell?  </p>

答:
I tried the various commands in the above answers as well.
Then I simply "backspaced" and deleted all my commands back to "C:\" !
Works just fine.</p>


问:
OpenCV 3.x - Use already allocated buffer (with Cuda or OpenCL) for UMat
I was looking for a way to initialize a cv::Umat with the data of an already allocated GPU-Buffer (from OpenCL, Cuda or OpenGL) without having to copy the data back to the CPU side.

Ideally, no copy operation is involved and the UMat would "wrap" around the already existing data on the GPU (which was previously allocated using CUDA/OpenCL/OpenGL). If that does not work, it would also be acceptable to copy an OpenCL/CUDA Buffer directly on the GPU into an UMat without transfering the data back to the host side (since the copy operation on the GPU device is much faster than on the CPU side).

The OpenCV API describes how to get an OpenCL handle to the data of an existing UMat, but not the other way round. Anybody who already did this or has an idea how to get it done? Thanks!

答:
I'm also looking for the same answer, I have something that might work, however setting them all up may prove challenging...
From (opencl-opencv-interop.cpp):

```<code>// this function is an example of interoperability between OpenCL buffer
// and OpenCV UMat objects. It converts (without copying data) OpenCL buffer
// to OpenCV UMat and then do blur on these data
int App::process_cl_buffer_with_opencv(cl_mem buffer, size_t step, int rows, int cols, int type, cv::UMat& u)
{
    cv::ocl::convertFromBuffer(buffer, step, rows, cols, type, u);

    // process right half of frame in OpenCV
    cv::Point pt(u.cols / 2, 0);
    cv::Size  sz(u.cols / 2, u.rows);
    cv::Rect roi(pt, sz);
    cv::UMat uroi(u, roi);
    cv::blur(uroi, uroi, cv::Size(7, 7), cv::Point(-3, -3));

    if (buffer)
        clReleaseMemObject(buffer);
    m_mem_obj = 0;

    return 0;
}
</code>```

You should be able to convert to a CL buffer from GL, or use a CL buffer directly and then use the function above or the convertFromBuffer().

Body:
I'm also looking for the same answer, I have something that might work, however setting them all up may prove challenging...
From (opencl-opencv-interop.cpp):

// this function is an example of interoperability between OpenCL buffer
// and OpenCV UMat objects. It converts (without copying data) OpenCL buffer
// to OpenCV UMat and then do blur on these data
int App::process_cl_buffer_with_opencv(cl_mem buffer, size_t step, int rows, int cols, int type, cv::UMat& u)
{
    cv::ocl::convertFromBuffer(buffer, step, rows, cols, type, u);

    // process right half of frame in OpenCV
    cv::Point pt(u.cols / 2, 0);
    cv::Size  sz(u.cols / 2, u.rows);
    cv::Rect roi(pt, sz);
    cv::UMat uroi(u, roi);
    cv::blur(uroi, uroi, cv::Size(7, 7), cv::Point(-3, -3));

    if (buffer)
        clReleaseMemObject(buffer);
    m_mem_obj = 0;

    return 0;
}

You should be able to convert to a CL buffer from GL, or use a CL buffer directly and then use the function above or the convertFromBuffer().


问:
Yii2 authorization via php and database?
Is it possible to split authorization such that items, item children, and rules use yii\rbac\PhpManager but assignments use yii\rbac\DbManager?

The use case for this is that items, item children, and rules (at least in my case) are controlled by the app and are essentially 100% static. The only time they will be updated is if new items are added to existing roles. Assignments, however, are tied to users and are very dynamic.

The idea is to keep the static items out of the database (thus not requiring migrations for updates) but still having dynamic items (assignments) stored in the database.

答:
You can caching queries to items, item children, and rules tables.
In components section of config:</p>

```<code>'authManager' => [
    'class' => 'yii\rbac\DbManager',
    'cache' => 'cache' //Here is your cache
],
'cache' => [
    'class' => 'yii\caching\FileCache',
],
</code>```

Body:
You can caching queries to items, item children, and rules tables.
In components section of config:

'authManager' => [
    'class' => 'yii\rbac\DbManager',
    'cache' => 'cache' //Here is your cache
],
'cache' => [
    'class' => 'yii\caching\FileCache',
],


问:
Spring SimpleFormController in 3.0
i notice that this controller has now been deprecated in the latest spring and was wondering what the alternative controller is?</p>

答: Annotated POJOs can act as controllers; see @Controller.

Title: Spring SimpleFormController in 3.0