问:
osx conda install boost compiled with gcc
I'm trying to install boost using anaconda on osx. Specifically, I must have it be compioled with gcc (instead of the osx default clang). Does anyone know how to do this or if this is even possible with conda? Ideally, I would like two separate boost libraries, one compiled with gcc and one with clang.

答:
Edited:

Assuming that anaconda is installed in

```<code>/Users/you/anaconda
</code>```

the following steps should allow you to compile boost with python using gcc compiler bindings for anaconda:

fix anaconda lib:

```<code>install_name_tool -id /Users/you/anaconda/lib/libpython2.7.dylib /Users/you/anaconda/lib/libpython2.7.dylib
</code>```

(re-)compile boost python

```<code>mkdir /Users/you/tmp
cd /Users/you/tmp
wget http://sourceforge.net/projects/boost/files/boost/1.57.0/boost_1_57_0.tar.bz2/download
mv download boost_1_57_0.tar.bz2
tar xvjf boost_1_57_0.tar.bz2
mkdir /Users/you/anaconda_boost_install
cd boost_1_57_0
# export PATH=/usr/bin:/bin:/usr/sbin:/sbin:  # might be necessary to prevent custom compilers be used
./bootstrap.sh --prefix=/Users/you/anaconda_boost_install/ --with-python=/Users/you/anaconda/bin/python2.7
./b2 link=shared
./b2 link=shared install
# source ~/.bashrc  # get back $PATH
</code>```

fix libboost-python against anaconda:

```<code>install_name_tool -id /Users/you/anaconda_boost_install/lib/libboost_python.dylib /Users/you/anaconda_boost_install/lib/libboost_python.dylib
</code>```

Note: gcc compiler is at /usr/bin/gcc.
Uncomment below line to use gcc compiler as default compiler:

```<code># export PATH=/usr/bin:/bin:/usr/sbin:/sbin:  # might be necessary to prevent custom compilers be used
</code>```

You can find the complete tutorial here.

Body:
Edited:

Assuming that anaconda is installed in

/Users/you/anaconda

the following steps should allow you to compile boost with python using gcc compiler bindings for anaconda:

fix anaconda lib:

install_name_tool -id /Users/you/anaconda/lib/libpython2.7.dylib /Users/you/anaconda/lib/libpython2.7.dylib

(re-)compile boost python

mkdir /Users/you/tmp
cd /Users/you/tmp
wget http://sourceforge.net/projects/boost/files/boost/1.57.0/boost_1_57_0.tar.bz2/download
mv download boost_1_57_0.tar.bz2
tar xvjf boost_1_57_0.tar.bz2
mkdir /Users/you/anaconda_boost_install
cd boost_1_57_0
# export PATH=/usr/bin:/bin:/usr/sbin:/sbin:  # might be necessary to prevent custom compilers be used
./bootstrap.sh --prefix=/Users/you/anaconda_boost_install/ --with-python=/Users/you/anaconda/bin/python2.7
./b2 link=shared
./b2 link=shared install
# source ~/.bashrc  # get back $PATH

fix libboost-python against anaconda:

install_name_tool -id /Users/you/anaconda_boost_install/lib/libboost_python.dylib /Users/you/anaconda_boost_install/lib/libboost_python.dylib

Note: gcc compiler is at /usr/bin/gcc.
Uncomment below line to use gcc compiler as default compiler:

# export PATH=/usr/bin:/bin:/usr/sbin:/sbin:  # might be necessary to prevent custom compilers be used

You can find the complete tutorial here.


来源: stackexchange

问:
How to access a pointer's value that is a char array
I have a function that saves a char with length 64 to a pointer but I am unsure of how to translate the char to an output later on in the program.

So my question is how do I access the entire char[] from the pointer?

char intToAscii(unsigned long x, char* output){
    int i;
    unsigned long n;
    char str[64];
    for(i =0; i<64;i++){
        n=x>>63;
        if(n==0){
            str[i]='0';
        }
        else{
            str[i]='1';
        }
        x=x<<1;

    }
    str[64]='\0';

    printf("Value of x is %s \n",str);
    *output = str;
}
```

答:
You can't use the pointer to a local array outside the scope where that array was defined because it's stored in the stack frame of the function and will be popped out when the function finishes and returns, so it will no longer be valid to use it (read it). Instead, you could pass the array from the caller function.

```<code>// In the caller function
char data[64];
intToAscii(1234, data);
</code>```

And the intToAscii() function, simply

```<code>void intToAscii(unsigned long x, char *str)
{
    int i;
    unsigned long n;
    for (i = 0; i < 63; i++) {
        n = x >> 63;
        if (n == 0) {
            str[i] = '0';
        } else {
            str[i] = '1';
        }
        x = x << 1;
    }
    str[i] = '\0';
    printf("Value of x is %s \n", str);
}
</code>```

Another mistake, is that you are accessing index 64 of str, but arrays are 0-indexed so 64 is out of bounds besides, the '\0' terminator must be the character right after the last, you can achieve that by using the index i which will have the correct value at the end of the loop and this way it doesn't matter if it's 63 or 64, it's the right value as long as the loop is ending before the last element of the array.

One more thing, functions like this are very dangerous, instead you can pass another parameter to tell the function how many bytes are available in the destination array like this,

```<code>void intToAscii(unsigned long x, char *str, size_t size)
{
    int i;
    unsigned long n;
    for (i = 0; i < size - 1; i++) {
        n = x >> 63;
        if (n == 0) {
            str[i] = '0';
        } else {
            str[i] = '1';
        }
        x = x << 1;
    }
    str[i] = '\0';
    printf("Value of x is %s \n", str);
}
</code>```

And finally, as was commented by @David C. Rankin your function returns char but it's body does not return anywhere, that will cause undefined behavior. You don't need your function to return anything because it modifies the array in place.

ContentLicense: CC BY-SA 3.0

Body:
You can't use the pointer to a local array outside the scope where that array was defined because it's stored in the stack frame of the function and will be popped out when the function finishes and returns, so it will no longer be valid to use it (read it). Instead, you could pass the array from the caller function.

// In the caller function
char data[64];
intToAscii(1234, data);

And the intToAscii() function, simply

void intToAscii(unsigned long x, char *str)
{
    int i;
    unsigned long n;
    for (i = 0; i < 63; i++) {
        n = x >> 63;
        if (n == 0) {
            str[i] = '0';
        } else {
            str[i] = '1';
        }
        x = x << 1;
    }
    str[i] = '\0';
    printf("Value of x is %s \n", str);
}

Another mistake, is that you are accessing index 64 of str, but arrays are 0-indexed so 64 is out of bounds besides, the '\0' terminator must be the character right after the last, you can achieve that by using the index i which will have the correct value at the end of the loop and this way it doesn't matter if it's 63 or 64, it's the right value as long as the loop is ending before the last element of the array.

One more thing, functions like this are very dangerous, instead you can pass another parameter to tell the function how many bytes are available in the destination array like this,

void intToAscii(unsigned long x, char *str, size_t size)
{
    int i;
    unsigned long n;
    for (i = 0; i < size - 1; i++) {
        n = x >> 63;
        if (n == 0) {
            str[i] = '0';
        } else {
            str[i] = '1';
        }
        x = x << 1;
    }
    str[i] = '\0';
    printf("Value of x is %s \n", str);
}

And finally, as was commented by @David C. Rankin your function returns char but it's body does not return anywhere, that will cause undefined behavior. You don't need your function to return anything because it modifies the array in place.


问:
Why can't I insert a row at index 0 in MySQL?
I have a simple table with an id column as the primary key (int). When I run this statement, it creates a new row, but with an auto incremented id value:

```<code>INSERT INTO `test_table` (`id`,`id_user`,`someString`) VALUES (0, 0, 'Hello World')
</code>```

Produces:

```<code>id (pk) | id_user | someString
1       | 0       | Hello World
2       | 0       | Hello World
3       | 0       | Hello World
</code>```

Why does this happen? Shouldn't I be able to have an index of 0?

答: Don't ever try to write to an auto-increment field. MySql indexes always start with 1. If you have some operational need for an index of 0, you'll have to create your own index with each new record.</p>

Body:
I have a simple table with an id column as the primary key (int). When I run this statement, it creates a new row, but with an auto incremented id value:

INSERT INTO `test_table` (`id`,`id_user`,`someString`) VALUES (0, 0, 'Hello World')

Produces:

id (pk) | id_user | someString
1       | 0       | Hello World
2       | 0       | Hello World
3       | 0       | Hello World

Why does this happen? Shouldn't I be able to have an index of 0?


问:
Why is Array.IndexOf not checking for IEquatable like List<T> does?
Consider this code:

```<code>public static void Main()
{
    var item = new Item { Id = 1 };

    IList list = new List<Item> { item };
    IList array = new[] { item };

    var newItem = new Item { Id = 1 };

    var lIndex = list.IndexOf(newItem);
    var aIndex = array.IndexOf(newItem);

    Console.WriteLine(lIndex);
    Console.WriteLine(aIndex);
}

public class Item : IEquatable<Item>
{
    public int Id { get; set; }

    public bool Equals(Item other) => other != null && other.Id == Id;

}
</code>```

Results:

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

Why are the results different between List<T> and Array? I guess this is by design, but why?

Looking at the code of List<T>.IndexOf makes me wonder even more, since it's porting to Array.IndexOf.

答:
Implementation of IndexOf in array class calls method:

public static int IndexOf(Array array, object value, int startIndex, int count)

As you see, it uses object as value parameter. In this method there is code:

```<code>object obj = objArray[index];
if (obj != null && obj.Equals(value))
    return index;
</code>```

Classs works with objects, so it calls public virtual bool Equals(object obj) method, not generic one.

In List class IndexOf uses generic implementation:

```<code>public static int IndexOf<T>(T[] array, T value, int startIndex, int count)
</code>```

So, it uses generic quality comparer:

```<code>EqualityComparer<T>.Default.IndexOf(array, value, startIndex, count);
</code>```

UPD: I wrote a little post about this problem: http://blog.rogatnev.net/2017/07/14/IndexOf-with-IEquatable.html

Body:
Consider this code:

public static void Main()
{
    var item = new Item { Id = 1 };

    IList list = new List<Item> { item };
    IList array = new[] { item };

    var newItem = new Item { Id = 1 };

    var lIndex = list.IndexOf(newItem);
    var aIndex = array.IndexOf(newItem);

    Console.WriteLine(lIndex);
    Console.WriteLine(aIndex);
}

public class Item : IEquatable<Item>
{
    public int Id { get; set; }

    public bool Equals(Item other) => other != null && other.Id == Id;

}

Results:

0
-1

Why are the results different between List<T> and Array? I guess this is by design, but why?

Looking at the code of List<T>.IndexOf makes me wonder even more, since it's porting to Array.IndexOf.

Body:
Implementation of IndexOf in array class calls method:

public static int IndexOf(Array array, object value, int startIndex, int count)

As you see, it uses object as value parameter. In this method there is code:

object obj = objArray[index];
if (obj != null && obj.Equals(value))
    return index;

Classs works with objects, so it calls public virtual bool Equals(object obj) method, not generic one.

In List class IndexOf uses generic implementation:

public static int IndexOf<T>(T[] array, T value, int startIndex, int count)

So, it uses generic quality comparer:

EqualityComparer<T>.Default.IndexOf(array, value, startIndex, count);

UPD: I wrote a little post about this problem: http://blog.rogatnev.net/2017/07/14/IndexOf-with-IEquatable.html


问:
Java, sum range of numbers in a for loop
Sorry I have been trying to figure this out and it's driving me crazy.

I need to write a java program that sums a range of numbers entered by the user and by the count of numbers entered by a user.  So if a user enters 5, 25 with count of 5.  It should sum 5+10+15+20+25=75  I have gotten it to work with a while loop, but not a for loop.  Sorry if I am asking for help for something that should be simple.  I left school almost 15 years ago involuntarily and struggling to get back into in.

Do I need to nest the loop?

```<code>import java.util.Scanner;
public class example1

{
  public static void main(String[] args) {
    int s, e, c = 0, sum = 0;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a starting number:  ");
    s = sc.nextInt();
    System.out.print("Enter an end number:  ");
    e = sc.nextInt();
    System.out.print("Enter a count by number:  ");
    c = sc.nextInt();

    {

      for (; s <= e; s++)
        sum += c;
      System.out.println("Sum of your numbers  " + sum);
    }

  }
}
</code>```

答:
Try this code:</p>

```<code>import java.util.Scanner;
public class count

{
  public static void main(String[] args) {
    int s, e, c = 0, sum = 0,i=1;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a starting number:  ");
    s = sc.nextInt();
    System.out.print("Enter an end number:  ");
    e = sc.nextInt();
    System.out.print("Enter a count by number:  ");
    c = sc.nextInt();

    {
      for (i=s; i <= e; i+=c)
        sum += i;
      System.out.println("Sum of your numbers  " + sum);

    }

  }
}
</code>```

Body:
Sorry I have been trying to figure this out and it's driving me crazy.

I need to write a java program that sums a range of numbers entered by the user and by the count of numbers entered by a user.  So if a user enters 5, 25 with count of 5.  It should sum 5+10+15+20+25=75  I have gotten it to work with a while loop, but not a for loop.  Sorry if I am asking for help for something that should be simple.  I left school almost 15 years ago involuntarily and struggling to get back into in.

Do I need to nest the loop?

import java.util.Scanner;
public class example1

{
  public static void main(String[] args) {
    int s, e, c = 0, sum = 0;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a starting number:  ");
    s = sc.nextInt();
    System.out.print("Enter an end number:  ");
    e = sc.nextInt();
    System.out.print("Enter a count by number:  ");
    c = sc.nextInt();

    {

      for (; s <= e; s++)
        sum += c;
      System.out.println("Sum of your numbers  " + sum);
    }

  }
}

Body:
Try this code:

import java.util.Scanner;
public class count

{
  public static void main(String[] args) {
    int s, e, c = 0, sum = 0,i=1;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a starting number:  ");
    s = sc.nextInt();
    System.out.print("Enter an end number:  ");
    e = sc.nextInt();
    System.out.print("Enter a count by number:  ");
    c = sc.nextInt();

    {
      for (i=s; i <= e; i+=c)
        sum += i;
      System.out.println("Sum of your numbers  " + sum);

    }

  }
}


问:
Which of these two numpy slices are better to use?
I am learning Python through an online course. We were asked to slice a 6x6 numpy array and get the diagonal. As a group we developed two methods, shown below. Is one better than the other?

```<code>import numpy as n
six = n.arange(1, 73, 2)
six.reshape(6,6)
</code>```

Solutions found

```<code>six[::7]
six.reshape(36)[::7]
</code>```

My answers both return array([ 1, 15, 29, 43, 57, 71])

I like the first, my partner likes the second. Any help would be very appreciated.

Thank you!

答:
```<code>six.reshape(6,6)
</code>```

does not modify six itself: it just returns a new 2D array but leaves six unchanged. So, your two methods are in effect one and the same method.

You can verify this by doing:

```<code>>>> six = np.arange(1, 73, 2)
>>> six.reshape(6,6)
>>> print(six)
</code>```

You will get a 1D array like:

```<code>[ 1  3  5  7  9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39
 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71]
</code>```

Therefore, I declare that the answer that does not use the unnecessary reshape call (assuming six is a flat array created with np.arange(1, 73, 2)) is the best answer :)

Body:
I am learning Python through an online course. We were asked to slice a 6x6 numpy array and get the diagonal. As a group we developed two methods, shown below. Is one better than the other?

import numpy as n
six = n.arange(1, 73, 2)
six.reshape(6,6)

Solutions found

six[::7]
six.reshape(36)[::7]

My answers both return array([ 1, 15, 29, 43, 57, 71])

I like the first, my partner likes the second. Any help would be very appreciated.

Thank you!

Body:
six.reshape(6,6)

does not modify six itself: it just returns a new 2D array but leaves six unchanged. So, your two methods are in effect one and the same method.

You can verify this by doing:

>>> six = np.arange(1, 73, 2)
>>> six.reshape(6,6)
>>> print(six)

You will get a 1D array like:

[ 1  3  5  7  9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39
 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71]

Therefore, I declare that the answer that does not use the unnecessary reshape call (assuming six is a flat array created with np.arange(1, 73, 2)) is the best answer :)


问:
How can I make this javascript stop when the last slide is shown
I want to make this javascript stop when the last slide is shown, so that the next button won't work, but same with the previous button when the first slide is shown. For the previous button, when I press it and the slider is at the first slide I want it to stay to the current slide.

Javascript code:

```<code>var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
    showDivs(slideIndex += n);
}

function showDivs(n) {
    var i;
    var x = document.getElementsByClassName('slide');
    if (n < 1) {slideIndex = 1;}
    for (i = 0; i < x.length; i++) {
        x[i].style.display = 'none';
    }
    x[slideIndex-1].style.display = 'block';
    }
</code>```

HTML code:

```<code><div class="links-to-wbp">
                    <div class="slide">
                        <a href="/physics/index.html"><img class="wbp" alt="thumb1" src="img/thumb1.png"/></a><a href="/francais/index.html"><img class="wbp" alt="thumb2" src="img/thumb2.png"/></a><a href="/strict/index.html"><img class="wbp" alt="thumb3" src="img/thumb3.png"/></a></div>
                <div class="slide">
                        <img class="wbp" alt="thumb4" src="img/thumb4.png"/><img class="wbp" alt="thumb5" src="img/thumb5.png"/><img class="wbp" alt="thumb6" src="img/thumb6.png"/></div>
                <div class="slide">
                        <img class="wbp" alt="thumb7" src="img/thumb7.png"/><img class="wbp" alt="thumb8" src="img/thumb8.png"/><img class="wbp" alt="thumb9" src="img/thumb9.png"/></div>
                     <div onclick="plusDivs(-1)" class="button previous_button"><</div>
                    <div onclick="plusDivs(+1)" class="button next_button">></div>
                </div>
</code>```

答:
you must check if value of slideIndex greater than length array of slides then assign this length to slideIndex. The same if value of slide index smaller than 1 then assign 1 to it.

Simple code like bellow:

```<code>function plusDivs(n) {
    slideIndex += n;
    if(slideIndex >= x.length){slideIndex = x.length;}
    if(slideIndex <=1){slideIndex=1}
    showDivs(slideIndex += n);
}
</code>```

Body:
I want to make this javascript stop when the last slide is shown, so that the next button won't work, but same with the previous button when the first slide is shown. For the previous button, when I press it and the slider is at the first slide I want it to stay to the current slide.

Javascript code:

var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
    showDivs(slideIndex += n);
}

function showDivs(n) {
    var i;
    var x = document.getElementsByClassName('slide');
    if (n < 1) {slideIndex = 1;}
    for (i = 0; i < x.length; i++) {
        x[i].style.display = 'none';
    }
    x[slideIndex-1].style.display = 'block';
    }

HTML code:

<

>

Body:
you must check if value of slideIndex greater than length array of slides then assign this length to slideIndex. The same if value of slide index smaller than 1 then assign 1 to it.

Simple code like bellow:

function plusDivs(n) {
    slideIndex += n;
    if(slideIndex >= x.length){slideIndex = x.length;}
    if(slideIndex <=1){slideIndex=1}
    showDivs(slideIndex += n);
}


问:
Bind and update ObservableCollection<T> to MenuFlyoutSubItem
I am developing a UWP (Universal Windows Platform) app in Visual Studio 2015. I am currently facing this problem that I want to add items to a MenuFlyoutSubItem. Basically, the items are a collection of Playlists.

My question is this:
How can I bind an ObservableCollection or a List to a MenuFlyoutSubItem and update the items when a new item is added? I already tried this from here: Bind Obserable Collection to MenuFlyoutSubItem in UWP

```<code>public static class MenuExtension
{
public static List<MenuFlyoutItem> GetMyItems(DependencyObject obj)
{ return (List<MenuFlyoutItem>)obj.GetValue(MyItemsProperty); }

public static void SetMyItems(DependencyObject obj, List<MenuFlyoutItem> value)
{ obj.SetValue(MyItemsProperty, value); }

public static readonly DependencyProperty MyItemsProperty =
    DependencyProperty.Register("MyItems", typeof(List<MenuFlyoutItem>), typeof(MenuExtension),
    new PropertyMetadata(new List<MenuFlyoutItem>(), (sender, e) =>
    {
        Debug.WriteLine("Filling collection");
        var menu = sender as MenuFlyoutSubItem;
        menu.Items.Clear();
        foreach (var item in e.NewValue as List<MenuFlyoutItem>) menu.Items.Add(item);
    }));
</code>```

}

This is good as far as the items do not change but in my scenario Items will change. How can I add updating to this extension? If the Flyout is created again on each popup then it will update but I don't know how to implement this behaviour.

Any help will be highly appreciated, thank you.

答:
I've tried what @Elvis Xia - MSFT suggested, and although it didn't work for me, it showed me the way to the solution. I got a compilation error (using x:Bind) in one of the auto generated .cs files, saying that it couldn't convert from MenuFlyout to FrameworkElement. When I used 'Binding' instead, I managed to compile, but the menu did not update. So, what I did was simply to move the dependency property one level up (or 2 levels, if you consider <Button.Flyout>), to the button itself:

```<code><Button local:ButtonExtension.MenuFlyout="{x:Bind MainViewModel.Menu, Mode=OneWay}"/>
</code>```

Here's the ButtonExtension class:

```<code>public static class ButtonExtension
{
    public static readonly DependencyProperty MenuFlyoutProperty =
        DependencyProperty.Register("MenuFlyout",
            typeof(MenuFlyout), typeof(ButtonExtension),
            new PropertyMetadata(new MenuFlyout(), (sender, e) =>
            {
                var button = sender as Button;
                button.Flyout = e.NewValue as MenuFlyout;
            }));

    public static MenuFlyout GetMenuFlyout(DependencyObject obj)
    {
        return (MenuFlyout)obj.GetValue(MenuFlyoutProperty);
    }

    public static void SetMenuFlyout(DependencyObject obj, MenuFlyout value)
    {
        obj.SetValue(MenuFlyoutProperty, value);
    }
}
</code>```

Here's the property in the ViewModel:

```<code>public MenuFlyout Menu { get; private set; }
</code>```

Body:
I am developing a UWP (Universal Windows Platform) app in Visual Studio 2015. I am currently facing this problem that I want to add items to a MenuFlyoutSubItem. Basically, the items are a collection of Playlists.

My question is this:
How can I bind an ObservableCollection or a List to a MenuFlyoutSubItem and update the items when a new item is added? I already tried this from here: Bind Obserable Collection to MenuFlyoutSubItem in UWP

public static class MenuExtension
{
public static List<MenuFlyoutItem> GetMyItems(DependencyObject obj)
{ return (List<MenuFlyoutItem>)obj.GetValue(MyItemsProperty); }

public static void SetMyItems(DependencyObject obj, List<MenuFlyoutItem> value)
{ obj.SetValue(MyItemsProperty, value); }

public static readonly DependencyProperty MyItemsProperty =
    DependencyProperty.Register("MyItems", typeof(List<MenuFlyoutItem>), typeof(MenuExtension),
    new PropertyMetadata(new List<MenuFlyoutItem>(), (sender, e) =>
    {
        Debug.WriteLine("Filling collection");
        var menu = sender as MenuFlyoutSubItem;
        menu.Items.Clear();
        foreach (var item in e.NewValue as List<MenuFlyoutItem>) menu.Items.Add(item);
    }));

}

This is good as far as the items do not change but in my scenario Items will change. How can I add updating to this extension? If the Flyout is created again on each popup then it will update but I don't know how to implement this behaviour.

Any help will be highly appreciated, thank you.

Body:
I've tried what @Elvis Xia - MSFT suggested, and although it didn't work for me, it showed me the way to the solution. I got a compilation error (using x:Bind) in one of the auto generated .cs files, saying that it couldn't convert from MenuFlyout to FrameworkElement. When I used 'Binding' instead, I managed to compile, but the menu did not update. So, what I did was simply to move the dependency property one level up (or 2 levels, if you consider <Button.Flyout>), to the button itself:

<Button local:ButtonExtension.MenuFlyout="{x:Bind MainViewModel.Menu, Mode=OneWay}"/>

Here's the ButtonExtension class:

public static class ButtonExtension
{
    public static readonly DependencyProperty MenuFlyoutProperty =
        DependencyProperty.Register("MenuFlyout",
            typeof(MenuFlyout), typeof(ButtonExtension),
            new PropertyMetadata(new MenuFlyout(), (sender, e) =>
            {
                var button = sender as Button;
                button.Flyout = e.NewValue as MenuFlyout;
            }));

    public static MenuFlyout GetMenuFlyout(DependencyObject obj)
    {
        return (MenuFlyout)obj.GetValue(MenuFlyoutProperty);
    }

    public static void SetMenuFlyout(DependencyObject obj, MenuFlyout value)
    {
        obj.SetValue(MenuFlyoutProperty, value);
    }
}

Here's the property in the ViewModel:

public MenuFlyout Menu { get; private set; }


问:
For vDSP_fft_zropD the packed results seem to be wrong. Is this a bug or am I doing something wrong
I have the following code which does a DFT on a ramp using Swift and Accelerate

```<code>import Foundation
import Accelerate
let N = 16
var xdtar = UnsafeMutablePointer<Double>.allocate(capacity: N)
var xdtai = UnsafeMutablePointer<Double>.allocate(capacity: N)
xdtar.initialize(to: 0.0, count: N )
xdtai.initialize(to: 0.0, count: N )
var x = DSPDoubleSplitComplex(realp: xdtar, imagp: xdtai)
var ydtar = UnsafeMutablePointer<Double>.allocate(capacity: N)
var ydtai = UnsafeMutablePointer<Double>.allocate(capacity: N)
ydtar.initialize(to: 0.0, count: N )
ydtai.initialize(to: 0.0, count: N )
var y = DSPDoubleSplitComplex(realp: ydtar, imagp: ydtai)
for i in 0..<N {
    xdtar[i] = Double(i)
}
let setup = vDSP_DFT_zop_CreateSetupD(nil, vDSP_Length(N),
       vDSP_DFT_Direction.FORWARD)
vDSP_DFT_ExecuteD(setup!, x.realp, x.imagp, y.realp, y.imagp)
vDSP_DFT_DestroySetupD(setup)
for i in 0..<N {
    print(String(format: "%2d \t-> in \t(%5.4f, %5.4fi)\t out \t(%5.4f, %5.4fi)",
                i, xdtar[i], xdtai[i], ydtar[i], ydtai[i]))
}
xdtar.deinitialize(count: N); xdtar.deallocate(capacity: N)
xdtai.deinitialize(count: N); xdtai.deallocate(capacity: N)
ydtar.deinitialize(count: N); ydtar.deallocate(capacity: N)
ydtai.deinitialize(count: N); ydtai.deallocate(capacity: N)
</code>```

The output is

```<code>  0     -> in   (0.0000, 0.0000i)    out    (120.0000, 0.0000i)
  1     -> in   (1.0000, 0.0000i)    out    (-8.0000, 40.2187i)
  2     -> in   (2.0000, 0.0000i)    out    (-8.0000, 19.3137i)
  3     -> in   (3.0000, 0.0000i)    out    (-8.0000, 11.9728i)
  4     -> in   (4.0000, 0.0000i)    out    (-8.0000, 8.0000i)
  5     -> in   (5.0000, 0.0000i)    out    (-8.0000, 5.3454i)
  6     -> in   (6.0000, 0.0000i)    out    (-8.0000, 3.3137i)
  7     -> in   (7.0000, 0.0000i)    out    (-8.0000, 1.5913i)
  8     -> in   (8.0000, 0.0000i)    out    (-8.0000, 0.0000i)
  9     -> in   (9.0000, 0.0000i)    out    (-8.0000, -1.5913i)
 10     -> in   (10.0000, 0.0000i)   out    (-8.0000, -3.3137i)
 11     -> in   (11.0000, 0.0000i)   out    (-8.0000, -5.3454i)
 12     -> in   (12.0000, 0.0000i)   out    (-8.0000, -8.0000i)
 13     -> in   (13.0000, 0.0000i)   out    (-8.0000, -11.9728i)
 14     -> in   (14.0000, 0.0000i)   out    (-8.0000, -19.3137i)
 15     -> in   (15.0000, 0.0000i)   out    (-8.0000, -40.2187i)
</code>```

Which I believe to be correct.  The above was a complex to complex formulation.  Basically checking the code below which is a real to complex FFT.

```<code>import Foundation
import Accelerate
let N = 16
let log2N = vDSP_Length(4)
var xdtar = UnsafeMutablePointer<Double>.allocate(capacity: N)
xdtar.initialize(to: 0.0, count: N )
var x = DSPDoubleSplitComplex(realp: xdtar, imagp: xdtar + N/2)
var ydtar = UnsafeMutablePointer<Double>.allocate(capacity: N/2)
var ydtai = UnsafeMutablePointer<Double>.allocate(capacity: N/2)
ydtar.initialize(to: 0.0, count: N )
ydtai.initialize(to: 0.0, count: N )
var y = DSPDoubleSplitComplex(realp: ydtar, imagp: ydtai)
for i in 0..<N {
    xdtar[i] = Double(i)
}
let setup = vDSP_create_fftsetupD(log2N, Int32(2))
vDSP_fft_zropD(setup!, &x, vDSP_Stride(1), &y, vDSP_Stride(1), log2N, Int32(1))
vDSP_destroy_fftsetupD(setup)
for i in 0..<N/2 {
    print(String(format: "%2d \t-> in \t(%5.4f, %5.4fi)\t out \t(%5.4f, %5.4fi)",
                 i, x.realp[i], x.imagp[i], ydtar[i], ydtai[i]))
}
xdtar.deinitialize(count: N); xdtar.deallocate(capacity: N)
ydtar.deinitialize(count: N/2); ydtar.deallocate(capacity: N/2)
ydtai.deinitialize(count: N/2); ydtai.deallocate(capacity: N/2)
</code>```

It's output is

```<code> 0  -> in   (0.0000, 8.0000i)    out    (240.0000, -128.0000i)
 1  -> in   (1.0000, 9.0000i)    out    (-8.0000, 40.2187i)
 2  -> in   (2.0000, 10.0000i)   out    (-8.0000, 19.3137i)
 3  -> in   (3.0000, 11.0000i)   out    (-8.0000, 11.9728i)
 4  -> in   (4.0000, 12.0000i)   out    (-8.0000, 8.0000i)
 5  -> in   (5.0000, 13.0000i)   out    (-8.0000, 5.3454i)
 6  -> in   (6.0000, 14.0000i)   out    (-8.0000, 3.3137i)
 7  -> in   (7.0000, 15.0000i)   out    (-8.0000, 1.5913i)
</code>```

So it seems to me the packed output in entry zero should be 120, -8 but it is not.  Anybody have any suggestions as to what is going on here?  I am exploring these functions so I could easily have an error but enough of the output is correct that I don't understand the packed entries.

答:
Based on a very hasty reading, I see two probable bugs, both of which are discussed in the documentation.

Specifically, your input data layout is incorrect (see "Data packing for Real FFTs"); all the even terms should be in the "real" part of x and the odd terms in the "imaginary" part. After fixing that, I get:

```<code>0 -> in (0.0000, 1.0000i)    out (240.0000, -16.0000i)
1 -> in (2.0000, 3.0000i)    out (-16.0000, 80.4374i)
2 -> in (4.0000, 5.0000i)    out (-16.0000, 38.6274i)
3 -> in (6.0000, 7.0000i)    out (-16.0000, 23.9457i)
4 -> in (8.0000, 9.0000i)    out (-16.0000, 16.0000i)
5 -> in (10.0000, 11.0000i)  out (-16.0000, 10.6909i)
6 -> in (12.0000, 13.0000i)  out (-16.0000, 6.6274i)
7 -> in (14.0000, 15.0000i)  out (-16.0000, 3.1826i)
</code>```

Better, but that's off by a factor of two; if we look at "Scaling for Fourier Transforms", we see this note:

To provide the best possible execution speeds, the vDSP library's functions don't always adhere strictly to textbook formulas for Fourier transforms, and must be scaled accordingly. The following sections specify the scaling for each type of Fourier transform implemented by the vDSP Library. The scaling factors are also stated explicitly in the formulas that accompany the function definitions in the reference chapter.

...

Real forward transforms: RF_imp = RF_math * 2

So that's where the extra factor of two is coming from.

Body:
I have the following code which does a DFT on a ramp using Swift and Accelerate

import Foundation
import Accelerate
let N = 16
var xdtar = UnsafeMutablePointer<Double>.allocate(capacity: N)
var xdtai = UnsafeMutablePointer<Double>.allocate(capacity: N)
xdtar.initialize(to: 0.0, count: N )
xdtai.initialize(to: 0.0, count: N )
var x = DSPDoubleSplitComplex(realp: xdtar, imagp: xdtai)
var ydtar = UnsafeMutablePointer<Double>.allocate(capacity: N)
var ydtai = UnsafeMutablePointer<Double>.allocate(capacity: N)
ydtar.initialize(to: 0.0, count: N )
ydtai.initialize(to: 0.0, count: N )
var y = DSPDoubleSplitComplex(realp: ydtar, imagp: ydtai)
for i in 0..<N {
    xdtar[i] = Double(i)
}
let setup = vDSP_DFT_zop_CreateSetupD(nil, vDSP_Length(N),
       vDSP_DFT_Direction.FORWARD)
vDSP_DFT_ExecuteD(setup!, x.realp, x.imagp, y.realp, y.imagp)
vDSP_DFT_DestroySetupD(setup)
for i in 0..<N {
    print(String(format: "%2d \t-> in \t(%5.4f, %5.4fi)\t out \t(%5.4f, %5.4fi)",
                i, xdtar[i], xdtai[i], ydtar[i], ydtai[i]))
}
xdtar.deinitialize(count: N); xdtar.deallocate(capacity: N)
xdtai.deinitialize(count: N); xdtai.deallocate(capacity: N)
ydtar.deinitialize(count: N); ydtar.deallocate(capacity: N)
ydtai.deinitialize(count: N); ydtai.deallocate(capacity: N)

The output is

  0     -> in   (0.0000, 0.0000i)    out    (120.0000, 0.0000i)
  1     -> in   (1.0000, 0.0000i)    out    (-8.0000, 40.2187i)
  2     -> in   (2.0000, 0.0000i)    out    (-8.0000, 19.3137i)
  3     -> in   (3.0000, 0.0000i)    out    (-8.0000, 11.9728i)
  4     -> in   (4.0000, 0.0000i)    out    (-8.0000, 8.0000i)
  5     -> in   (5.0000, 0.0000i)    out    (-8.0000, 5.3454i)
  6     -> in   (6.0000, 0.0000i)    out    (-8.0000, 3.3137i)
  7     -> in   (7.0000, 0.0000i)    out    (-8.0000, 1.5913i)
  8     -> in   (8.0000, 0.0000i)    out    (-8.0000, 0.0000i)
  9     -> in   (9.0000, 0.0000i)    out    (-8.0000, -1.5913i)
 10     -> in   (10.0000, 0.0000i)   out    (-8.0000, -3.3137i)
 11     -> in   (11.0000, 0.0000i)   out    (-8.0000, -5.3454i)
 12     -> in   (12.0000, 0.0000i)   out    (-8.0000, -8.0000i)
 13     -> in   (13.0000, 0.0000i)   out    (-8.0000, -11.9728i)
 14     -> in   (14.0000, 0.0000i)   out    (-8.0000, -19.3137i)
 15     -> in   (15.0000, 0.0000i)   out    (-8.0000, -40.2187i)

Which I believe to be correct.  The above was a complex to complex formulation.  Basically checking the code below which is a real to complex FFT.

import Foundation
import Accelerate
let N = 16
let log2N = vDSP_Length(4)
var xdtar = UnsafeMutablePointer<Double>.allocate(capacity: N)
xdtar.initialize(to: 0.0, count: N )
var x = DSPDoubleSplitComplex(realp: xdtar, imagp: xdtar + N/2)
var ydtar = UnsafeMutablePointer<Double>.allocate(capacity: N/2)
var ydtai = UnsafeMutablePointer<Double>.allocate(capacity: N/2)
ydtar.initialize(to: 0.0, count: N )
ydtai.initialize(to: 0.0, count: N )
var y = DSPDoubleSplitComplex(realp: ydtar, imagp: ydtai)
for i in 0..<N {
    xdtar[i] = Double(i)
}
let setup = vDSP_create_fftsetupD(log2N, Int32(2))
vDSP_fft_zropD(setup!, &x, vDSP_Stride(1), &y, vDSP_Stride(1), log2N, Int32(1))
vDSP_destroy_fftsetupD(setup)
for i in 0..<N/2 {
    print(String(format: "%2d \t-> in \t(%5.4f, %5.4fi)\t out \t(%5.4f, %5.4fi)",
                 i, x.realp[i], x.imagp[i], ydtar[i], ydtai[i]))
}
xdtar.deinitialize(count: N); xdtar.deallocate(capacity: N)
ydtar.deinitialize(count: N/2); ydtar.deallocate(capacity: N/2)
ydtai.deinitialize(count: N/2); ydtai.deallocate(capacity: N/2)

It's output is

 0  -> in   (0.0000, 8.0000i)    out    (240.0000, -128.0000i)
 1  -> in   (1.0000, 9.0000i)    out    (-8.0000, 40.2187i)
 2  -> in   (2.0000, 10.0000i)   out    (-8.0000, 19.3137i)
 3  -> in   (3.0000, 11.0000i)   out    (-8.0000, 11.9728i)
 4  -> in   (4.0000, 12.0000i)   out    (-8.0000, 8.0000i)
 5  -> in   (5.0000, 13.0000i)   out    (-8.0000, 5.3454i)
 6  -> in   (6.0000, 14.0000i)   out    (-8.0000, 3.3137i)
 7  -> in   (7.0000, 15.0000i)   out    (-8.0000, 1.5913i)

So it seems to me the packed output in entry zero should be 120, -8 but it is not.  Anybody have any suggestions as to what is going on here?  I am exploring these functions so I could easily have an error but enough of the output is correct that I don't understand the packed entries.

Body:
Based on a very hasty reading, I see two probable bugs, both of which are discussed in the documentation.

Specifically, your input data layout is incorrect (see "Data packing for Real FFTs"); all the even terms should be in the "real" part of x and the odd terms in the "imaginary" part. After fixing that, I get:

0 -> in (0.0000, 1.0000i)    out (240.0000, -16.0000i)
1 -> in (2.0000, 3.0000i)    out (-16.0000, 80.4374i)
2 -> in (4.0000, 5.0000i)    out (-16.0000, 38.6274i)
3 -> in (6.0000, 7.0000i)    out (-16.0000, 23.9457i)
4 -> in (8.0000, 9.0000i)    out (-16.0000, 16.0000i)
5 -> in (10.0000, 11.0000i)  out (-16.0000, 10.6909i)
6 -> in (12.0000, 13.0000i)  out (-16.0000, 6.6274i)
7 -> in (14.0000, 15.0000i)  out (-16.0000, 3.1826i)

Better, but that's off by a factor of two; if we look at "Scaling for Fourier Transforms", we see this note:

To provide the best possible execution speeds, the vDSP library's functions don't always adhere strictly to textbook formulas for Fourier transforms, and must be scaled accordingly. The following sections specify the scaling for each type of Fourier transform implemented by the vDSP Library. The scaling factors are also stated explicitly in the formulas that accompany the function definitions in the reference chapter.

...

Real forward transforms: RF_imp = RF_math * 2

So that's where the extra factor of two is coming from.


答:
You can do this in a few ways, here's one using data.table functions:

```<code>library( data.table )
setDT( data2 )
setDT( data1 )
</code>```

Add a column to help casting to wide format, and to set the column names the way you want them.

```<code>data2[ , record := paste0( "unit1_", seq_len( .N ) ), by = match ]
</code>```

Convert from long to wide format.

```<code>data3 <- dcast( data2, match ~ record, value.var = "unit1", fill = NA_real_ )
</code>```

Now use the match column to merge that with your initial data1 set

```<code>data4 <- merge( data1, data3, by = "match", all = TRUE )

data4

#    match unit1_1 unit1_2 unit1_3 unit1_4 unit1_5 unit1_6 unit1_7 unit1_8 unit1_9
# 1:     a     300   200.0     300     600      NA      NA      NA      NA      NA
# 2:     a     300   200.0     300     600      NA      NA      NA      NA      NA
# 3:     a     300   200.0     300     600      NA      NA      NA      NA      NA
# 4:     a     300   200.0     300     600      NA      NA      NA      NA      NA
# 5:     a     300   200.0     300     600      NA      NA      NA      NA      NA
# 6:     a     300   200.0     300     600      NA      NA      NA      NA      NA
# 7:     a     300   200.0     300     600      NA      NA      NA      NA      NA
# 8:     b     250   100.0      90      50      10      NA      NA      NA      NA
# 9:     b     250   100.0      90      50      10      NA      NA      NA      NA
# 10:     b     250   100.0      90      50      10      NA      NA      NA      NA
# 11:     b     250   100.0      90      50      10      NA      NA      NA      NA
# 12:     b     250   100.0      90      50      10      NA      NA      NA      NA
# 13:     b     250   100.0      90      50      10      NA      NA      NA      NA
# 14:     b     250   100.0      90      50      10      NA      NA      NA      NA
# 15:     c       9     9.5      NA      NA      NA      NA      NA      NA      NA
# 16:     c       9     9.5      NA      NA      NA      NA      NA      NA      NA
# 17:     c       9     9.5      NA      NA      NA      NA      NA      NA      NA
# 18:     d      80    90.0      50      20      30      40      70      15     190
# 19:     d      80    90.0      50      20      30      40      70      15     190
</code>```

Title: data matching all cases in R

Body:
I have the following two datasets (data1 and data2) and would like to match based on the match variable across all possible cases.

data1 <- data.frame(

match = c(rep("a",7),rep("b",7),rep("c",3),rep("d",2))

)

data2 <- data.frame(

match = c(rep("a",4),rep("b",5),rep("c",2),rep("d",9)),
unit1 =
c(300,200,300,600,250,100,90,50,10,9,9.5,80,90,50,20,30,40,70,15,190)

)

in order to create a single dataset of the following format:
Also of note is that these datasets are large so will need an efficient way of doing such matching.

  match unit1_1 unit1_2 unit1_3 unit1_4 unit1_5 unit1_6 unit1_7 unit1_8 unit1_9
    a   300 200 300 600
    a   300 200 300 600
    a   300 200 300 600
    a   300 200 300 600
    a   300 200 300 600
    a   300 200 300 600
    a   300 200 300 600
    b   250 100 90  50  10
    b   250 100 90  50  10
    b   250 100 90  50  10
    b   250 100 90  50  10
    b   250 100 90  50  10
    b   250 100 90  50  10
    b   250 100 90  50  10
    c   9   9.5
    c   9   9.5
    c   9   9.5
    d   80  90  50  20  30  40  70  15  190
    d   80  90  50  20  30  40  70  15  190

Body:
You can do this in a few ways, here's one using data.table functions:

library( data.table )
setDT( data2 )
setDT( data1 )

Add a column to help casting to wide format, and to set the column names the way you want them.

data2[ , record := paste0( "unit1_", seq_len( .N ) ), by = match ]

Convert from long to wide format.

data3 <- dcast( data2, match ~ record, value.var = "unit1", fill = NA_real_ )

Now use the match column to merge that with your initial data1 set

data4 <- merge( data1, data3, by = "match", all = TRUE )

data4

#    match unit1_1 unit1_2 unit1_3 unit1_4 unit1_5 unit1_6 unit1_7 unit1_8 unit1_9
# 1:     a     300   200.0     300     600      NA      NA      NA      NA      NA
# 2:     a     300   200.0     300     600      NA      NA      NA      NA      NA
# 3:     a     300   200.0     300     600      NA      NA      NA      NA      NA
# 4:     a     300   200.0     300     600      NA      NA      NA      NA      NA
# 5:     a     300   200.0     300     600      NA      NA      NA      NA      NA
# 6:     a     300   200.0     300     600      NA      NA      NA      NA      NA
# 7:     a     300   200.0     300     600      NA      NA      NA      NA      NA
# 8:     b     250   100.0      90      50      10      NA      NA      NA      NA
# 9:     b     250   100.0      90      50      10      NA      NA      NA      NA
# 10:     b     250   100.0      90      50      10      NA      NA      NA      NA
# 11:     b     250   100.0      90      50      10      NA      NA      NA      NA
# 12:     b     250   100.0      90      50      10      NA      NA      NA      NA
# 13:     b     250   100.0      90      50      10      NA      NA      NA      NA
# 14:     b     250   100.0      90      50      10      NA      NA      NA      NA
# 15:     c       9     9.5      NA      NA      NA      NA      NA      NA      NA
# 16:     c       9     9.5      NA      NA      NA      NA      NA      NA      NA
# 17:     c       9     9.5      NA      NA      NA      NA      NA      NA      NA
# 18:     d      80    90.0      50      20      30      40      70      15     190
# 19:     d      80    90.0      50      20      30      40      70      15     190


问:
Programmatically configure ActiveRecordFacility for multiple databases
I'm trying to build a small application (ASP.NET MVC) that uses the plugin architecture. Along with Castle ActiveRecord Integration Facility. And I wish to let each plugin configure its own ActiveRecord behaviors. Like database connection string, proxy, etc..
However, I couldn't find a way to set multiple configurations without the use of web.config. The idea is to make this programmatically.

My goal is for each plugin in this system, if it defines its own ActiveRecord settings, the main application can set up next to ActiveRecordFacility these behaviors.

has someone do something like that?

P.S.: sorry, bad grammar...google translate...;P

答:
Ok...the example in Lostechies works great. (link text)

Mauricio, thanks for the tip!

ContentLicense: CC BY-SA 2.5


问:
How to create an edge list from pandas dataframe?
I have a pandas dataframe (df) of the form-

```<code>    Col1
A  [Green,Red,Purple]
B  [Red, Yellow, Blue]
C  [Brown, Green, Yellow, Blue]
</code>```

I need to convert this to an edge list i.e. a dataframe of the form:

```<code>Source    Target    Weight
  A         B         1
  A         C         1
  B         C         2
</code>```

EDIT
Note that the new dataframe has rows equal to the total number of possible pairwise combinations. Also, to compute the 'Weight' column, we simply find the intersection between the two lists. For instance, for B&C, the elements share two colors: Blue and Yellow. Therefore, the 'Weight' for the corresponding row is 2.

What is the fastest way to do this? The original dataframe contains about 28,000 elements.

答:
First, starting off with the dataframe:

```<code>from itertools import combinations

df = pd.DataFrame({
        'Col1': [['Green','Red','Purple'],
                 ['Red', 'Yellow', 'Blue'],
                 ['Brown', 'Green', 'Yellow', 'Blue']]
     }, index=['A', 'B', 'C'])

df['Col1'] = df['Col1'].apply(set)
df

                           Col1
A          {Purple, Red, Green}
B           {Red, Blue, Yellow}
C  {Green, Yellow, Blue, Brown}
</code>```

Each list in Col1 has been converted into a set to find the union efficiently. Next, we'll use itertools.combinations to create pairwise combinations of all rows in df:

```<code>df1 = pd.DataFrame(
    data=list(combinations(df.index.tolist(), 2)),
    columns=['Src', 'Dst'])

df1

  Src Dst
0   A   B
1   A   C
2   B   C
</code>```

Now, apply a function to take the union of the sets and find its length. The Src and Dst columns act as a lookup into df.

```<code>df1['Weights'] = df1.apply(lambda x: len(
    df.loc[x['Src']]['Col1'].intersection(df.loc[x['Dst']]['Col1'])), axis=1)
df1

  Src Dst  Weights
0   A   B        1
1   A   C        1
2   B   C        2
</code>```

I advice set conversion at the very beginning. Converting your lists to a set each time on the fly is expensive and wasteful.

For more speedup, you'd probably want to also copy the sets into two columns in the new dataframe because calling df.loc constantly will slow it down a notch.

Body:
I have a pandas dataframe (df) of the form-

    Col1
A  [Green,Red,Purple]
B  [Red, Yellow, Blue]
C  [Brown, Green, Yellow, Blue]

I need to convert this to an edge list i.e. a dataframe of the form:

Source    Target    Weight
  A         B         1
  A         C         1
  B         C         2

EDIT
Note that the new dataframe has rows equal to the total number of possible pairwise combinations. Also, to compute the 'Weight' column, we simply find the intersection between the two lists. For instance, for B&C, the elements share two colors: Blue and Yellow. Therefore, the 'Weight' for the corresponding row is 2.

What is the fastest way to do this? The original dataframe contains about 28,000 elements.

Body:
First, starting off with the dataframe:

from itertools import combinations

df = pd.DataFrame({
        'Col1': [['Green','Red','Purple'],
                 ['Red', 'Yellow', 'Blue'],
                 ['Brown', 'Green', 'Yellow', 'Blue']]
     }, index=['A', 'B', 'C'])

df['Col1'] = df['Col1'].apply(set)
df

                           Col1
A          {Purple, Red, Green}
B           {Red, Blue, Yellow}
C  {Green, Yellow, Blue, Brown}

Each list in Col1 has been converted into a set to find the union efficiently. Next, we'll use itertools.combinations to create pairwise combinations of all rows in df:

df1 = pd.DataFrame(
    data=list(combinations(df.index.tolist(), 2)),
    columns=['Src', 'Dst'])

df1

  Src Dst
0   A   B
1   A   C
2   B   C

Now, apply a function to take the union of the sets and find its length. The Src and Dst columns act as a lookup into df.

df1['Weights'] = df1.apply(lambda x: len(
    df.loc[x['Src']]['Col1'].intersection(df.loc[x['Dst']]['Col1'])), axis=1)
df1

  Src Dst  Weights
0   A   B        1
1   A   C        1
2   B   C        2

I advice set conversion at the very beginning. Converting your lists to a set each time on the fly is expensive and wasteful.

For more speedup, you'd probably want to also copy the sets into two columns in the new dataframe because calling df.loc constantly will slow it down a notch.

ContentLicense: CC BY-SA 4.0


问:
how to use context.Done() with nested http middleware
I would like to know how to properly implement/use context.Done() method when using it within an HTTP server and implementing middleware, my goal is to cancel subsequent events when a client disconnects across nested middleware.

For testing I created the following code, I don't know if is the correct way of doing it since I had to create a channel within the HandleFunc and a goroutine to handle the requests, putting all this together within a select wait statement.

```<code>package main

import (
    "fmt"
    "log"
    "net/http"
    "time"
)

func hello(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context()
    log.Println("handler started")
    defer log.Println("hander ended")

    ch := make(chan struct{})

    go func() {
        time.Sleep(5 * time.Second)
        fmt.Fprintln(w, "Hello")
        ch <- struct{}{}
    }()

    select {
    case <-ch:
    case <-ctx.Done():
        err := ctx.Err()
        log.Println(err)
        http.Error(w, err.Error(), http.StatusPartialContent)
    }
}

func main() {
    http.HandleFunc("/", hello)
    log.Fatal(http.ListenAndServe(":8080", nil))
}
</code>```

Basically here the request simulates load by sleeping 5 seconds, and then prints Hello, but if the client cancels the request, for example:

```<code>$ curl 0:8080
</code>```

And then pressing ctl +  c, this will be loged:

```<code>2017/07/07 22:22:40 handler started
2017/07/07 22:22:42 context canceled
2017/07/07 22:22:42 hander ended
</code>```

This works but wondering if this pattern (the goroutine and select) should be used in every nested handler or if there is a better way of implementing this.:

```<code>ch := make(chan struct{})
go func() {
    // some logic
    ch <- struct{}{}
}()

select {
case <-ch:
case <-ctx.Done():
    err := ctx.Err()
    log.Println(err)
    http.Error(w, err.Error(), http.StatusPartialContent)
}
</code>```

答:
At Google, we require that Go programmers pass a Context parameter as the first argument to every function on the call path between incoming and outgoing requests.

-- Go Concurrency Patterns: Context

Body:
I would like to know how to properly implement/use context.Done() method when using it within an HTTP server and implementing middleware, my goal is to cancel subsequent events when a client disconnects across nested middleware.

For testing I created the following code, I don't know if is the correct way of doing it since I had to create a channel within the HandleFunc and a goroutine to handle the requests, putting all this together within a select wait statement.

package main

import (
    "fmt"
    "log"
    "net/http"
    "time"
)

func hello(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context()
    log.Println("handler started")
    defer log.Println("hander ended")

    ch := make(chan struct{})

    go func() {
        time.Sleep(5 * time.Second)
        fmt.Fprintln(w, "Hello")
        ch <- struct{}{}
    }()

    select {
    case <-ch:
    case <-ctx.Done():
        err := ctx.Err()
        log.Println(err)
        http.Error(w, err.Error(), http.StatusPartialContent)
    }
}

func main() {
    http.HandleFunc("/", hello)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

Basically here the request simulates load by sleeping 5 seconds, and then prints Hello, but if the client cancels the request, for example:

$ curl 0:8080

And then pressing ctl +  c, this will be loged:

2017/07/07 22:22:40 handler started
2017/07/07 22:22:42 context canceled
2017/07/07 22:22:42 hander ended

This works but wondering if this pattern (the goroutine and select) should be used in every nested handler or if there is a better way of implementing this.:

ch := make(chan struct{})
go func() {
    // some logic
    ch <- struct{}{}
}()

select {
case <-ch:
case <-ctx.Done():
    err := ctx.Err()
    log.Println(err)
    http.Error(w, err.Error(), http.StatusPartialContent)
}


问:
Why does this method consume so much memory? Or rather, why isn't GC freeing the memory?
I'm building some software that requires image panning, zooming, and brightness controls. I set up a small project to to build a simple brightness control after finding a lot of examples online, so please ignore that I'm doing everything in the main form

When I start to use the trackbar controller, which fires the event below when the value (-100 to 100) is changed, memory usage stacks up into the Gigabytes in seconds. It'll then sit there and never free the memory. Moving the trackbar again eats up even more memory

```<code>private void trackBarBrightness_EditValueChanged(object sender, EventArgs e)
    {
        float value = trackBarBrightness.Value * 0.01f;
        float[][] colorMatrixElements =
        {
            new float[] {
                1,
                0,
                0,
                0,
                0
            },
            new float[] {
                0,
                1,
                0,
                0,
                0
            },
            new float[] {
                0,
                0,
                1,
                0,
                0
            },
            new float[] {
                0,
                0,
                0,
                1,
                0
            },
            new float[] {
                value,
                value,
                value,
                0,
                1
            }
        };

        ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
        ImageAttributes imageAttributes = new ImageAttributes();

        imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

        //Image img = this.pictureEdit.Image;
        Image img = originalImage;
        Graphics g = default(Graphics);
        Bitmap bm = new Bitmap(Convert.ToInt32(img.Width), Convert.ToInt32(img.Height));
        g = Graphics.FromImage(bm);
        g.DrawImage(img, new Rectangle(0, 0, bm.Width, bm.Height), 0, 0, bm.Width, bm.Height, GraphicsUnit.Pixel, imageAttributes);
        pictureEdit.Image = bm;
    }
</code>```

Any guidance would be much appreciated

答:
Bitmap is inheriting from Image and Image has a finalizer! That makes it automatically Gen1 when created and can take minutes to dispose and free if the GC does not feel memory pressure.

The fast pace of updating is actually creating many instances and they have to be collected by finalizer thread one by one. Sometimes it takes even 15 minutes, sometimes sooner.

The solution is to limit the number of Bitmaps at any moment and there is needed only one at any moment, latest one and when replaced, the previous can be disposed and the current presented until next update.

Then you should do something like this:

```<code>private void trackBarBrightness_EditValueChanged(object sender, EventArgs e)
{
    //your current code here up to (excluding): pictureEdit.Image = bm;
    IDisposable PreviousImage = pictureEdit.Image;
    pictureEdit.Image = bm;
    PreviousImage?.Dispose();
}
</code>```

or this, if the PictureBox is write only:

```<code>private IDisposable PreviousImage {get;set;}

private void trackBarBrightness_EditValueChanged(object sender, EventArgs e)
{
    //your current code here up to (excluding): pictureEdit.Image = bm;
    pictureEdit.Image = bm;
    PreviousImage?.Dispose();
    PreviousImage = bm;
}
</code>```

Body:
I'm building some software that requires image panning, zooming, and brightness controls. I set up a small project to to build a simple brightness control after finding a lot of examples online, so please ignore that I'm doing everything in the main form

When I start to use the trackbar controller, which fires the event below when the value (-100 to 100) is changed, memory usage stacks up into the Gigabytes in seconds. It'll then sit there and never free the memory. Moving the trackbar again eats up even more memory

private void trackBarBrightness_EditValueChanged(object sender, EventArgs e)
    {
        float value = trackBarBrightness.Value * 0.01f;
        float[][] colorMatrixElements =
        {
            new float[] {
                1,
                0,
                0,
                0,
                0
            },
            new float[] {
                0,
                1,
                0,
                0,
                0
            },
            new float[] {
                0,
                0,
                1,
                0,
                0
            },
            new float[] {
                0,
                0,
                0,
                1,
                0
            },
            new float[] {
                value,
                value,
                value,
                0,
                1
            }
        };

        ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
        ImageAttributes imageAttributes = new ImageAttributes();

        imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

        //Image img = this.pictureEdit.Image;
        Image img = originalImage;
        Graphics g = default(Graphics);
        Bitmap bm = new Bitmap(Convert.ToInt32(img.Width), Convert.ToInt32(img.Height));
        g = Graphics.FromImage(bm);
        g.DrawImage(img, new Rectangle(0, 0, bm.Width, bm.Height), 0, 0, bm.Width, bm.Height, GraphicsUnit.Pixel, imageAttributes);
        pictureEdit.Image = bm;
    }

Any guidance would be much appreciated

Body:
Bitmap is inheriting from Image and Image has a finalizer! That makes it automatically Gen1 when created and can take minutes to dispose and free if the GC does not feel memory pressure.

The fast pace of updating is actually creating many instances and they have to be collected by finalizer thread one by one. Sometimes it takes even 15 minutes, sometimes sooner.

The solution is to limit the number of Bitmaps at any moment and there is needed only one at any moment, latest one and when replaced, the previous can be disposed and the current presented until next update.

Then you should do something like this:

private void trackBarBrightness_EditValueChanged(object sender, EventArgs e)
{
    //your current code here up to (excluding): pictureEdit.Image = bm;
    IDisposable PreviousImage = pictureEdit.Image;
    pictureEdit.Image = bm;
    PreviousImage?.Dispose();
}

or this, if the PictureBox is write only:

private IDisposable PreviousImage {get;set;}

private void trackBarBrightness_EditValueChanged(object sender, EventArgs e)
{
    //your current code here up to (excluding): pictureEdit.Image = bm;
    pictureEdit.Image = bm;
    PreviousImage?.Dispose();
    PreviousImage = bm;
}


问:
PhantomJS 408 error "Socket operation timed out"
I'm getting this error when trying to open a webpage that is on the same server as the PhantomJS code. PhantomJS can open any other webpage (ssl or not) but won't open any webpage that is on my server. I always get this error and there is very little information, actually none, what "Socket operation timed out" means for PhantomJS.

I'm running CentOS 6.6 and PhantomJS 1.9.8. I tried a few PhantomJS versions already, including the latest 2.1.1 and I'm getting the same error.

The dev version of my app runs perfectly on Ubuntu 14.04 but doesn't seem to work on my production server.

I did have some luck opening webpages on this server working from another server (remote access, essentially).

Is there anything on my server (that is just running Wordpress) that can be blocking PhantomJS? The only thing I can think of is the fact I have SSL installed, but non-SSL pages also don't work.

I've tried command line and both php-phantomjs and wkhtmlpdf and always get a 408 error, unless I try another webpage that has a different IP address (google etc).

Any clue on what might be the problem?

答: Try changing the default user agent used by PhantomJS</p>


问:
Create a Map out of a List of String(s) with streams
I have a List of String(s), but I want to convert it into a Map<String, Boolean> from the List<String>, making all of the boolean mappings set to true. I have the following code.

```<code>import java.lang.*;
import java.util.*;
class Main {
  public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("ab");
    list.add("bc");
    list.add("cd");
    Map<String, Boolean> alphaToBoolMap = new HashMap<>();
    for (String item: list) {
      alphaToBoolMap.put(item, true);
    }
    //System.out.println(list); [ab, bc, cd]
    //System.out.println(alphaToBoolMap);  {ab=true, bc=true, cd=true}
  }
}
</code>```

Is there a way to reduce this using streams?

答:
If you are going to mutate an existing Map<..., Boolean>, you can use  Collections.newSetFromMap.  It lets you treat such a map as a Set:

```<code>Collections.newSetFromMap(alphaToBoolMap).addAll(list);
</code>```

Body:
I have a List of String(s), but I want to convert it into a Map<String, Boolean> from the List<String>, making all of the boolean mappings set to true. I have the following code.

import java.lang.*;
import java.util.*;
class Main {
  public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("ab");
    list.add("bc");
    list.add("cd");
    Map<String, Boolean> alphaToBoolMap = new HashMap<>();
    for (String item: list) {
      alphaToBoolMap.put(item, true);
    }
    //System.out.println(list); [ab, bc, cd]
    //System.out.println(alphaToBoolMap);  {ab=true, bc=true, cd=true}
  }
}

Is there a way to reduce this using streams?

Body:
If you are going to mutate an existing Map<..., Boolean>, you can use  Collections.newSetFromMap.  It lets you treat such a map as a Set:

Collections.newSetFromMap(alphaToBoolMap).addAll(list);


问:
Generate Graphql Type from mongoose schema with subfields
I'm starting to build a Graphql service to go alongside with a REST api already in production, using NodeJS and Mongoose, but I'm having some trouble in finding a way to translate my mongoose schema to a GraphQL type.

I have the following schema:

```<code>var userSchema = new mongoose.Schema({
    name: {type: String, required: true},
    email: {type: String},
    imageURL: {type: String, default:null},
    providerId: {type: String, required: true},
    token: {type: String, required: true},
    history: [{
        orders:[{type: mongoose.Types.ObjectId, ref:'Order'}],
        restaurant: {type: mongoose.Types.ObjectId, ref: 'Restaurant'}
    }]
}, { timestamps: true});
</code>```

So, basically, the trouble is the history field. This field is a list an object with 2 subfields: orders (list of Objects that reference another mongoose schema) and restaurant (that reference the mongoose schema for restaurant).

My main question is: when writing the corresponding GraphQL type for "User", is there a way to create subfields, as I did with mongoose on the history field, or I have to create a second Type and then reference this type (knowing that there's no need for the application to create another schema in mongoose, whould only create in GraphQL).

答:
Like you said, when you write your GraphQL schema, history will need to be a separate type, as will probably Order and Restaurant. Using Apollo, the schema type definitions would look something like:

```<code>type User {
  # additional fields
  history: [Record!]!
}

type Record {
  orders: [Order!]!
  restaurant: Restaurant
}
</code>```

In addition to the type definitions above, you would also provide a resolver for User. In this case, the resolver would simply return User.findOne() (or however you normally get the User object from your database).

Here's the neat part: you may not even need resolvers for Order, Restaurant or even History. When you don't specify a resolver, GraphQL will use a default resolver that happily uses the object it's passed (whatever chunk of the User object you would pass in your resolver for the User type). If it finds keys in that object that match the fields in you specified in your GraphQL schema's
type definition, it will populate those fields and ignore everything else.

Of course, if you need additional control (maybe your object keys and field names don't match), you can always still write the resolver yourself.

Body:
I'm starting to build a Graphql service to go alongside with a REST api already in production, using NodeJS and Mongoose, but I'm having some trouble in finding a way to translate my mongoose schema to a GraphQL type.

I have the following schema:

var userSchema = new mongoose.Schema({
    name: {type: String, required: true},
    email: {type: String},
    imageURL: {type: String, default:null},
    providerId: {type: String, required: true},
    token: {type: String, required: true},
    history: [{
        orders:[{type: mongoose.Types.ObjectId, ref:'Order'}],
        restaurant: {type: mongoose.Types.ObjectId, ref: 'Restaurant'}
    }]
}, { timestamps: true});

So, basically, the trouble is the history field. This field is a list an object with 2 subfields: orders (list of Objects that reference another mongoose schema) and restaurant (that reference the mongoose schema for restaurant).

My main question is: when writing the corresponding GraphQL type for "User", is there a way to create subfields, as I did with mongoose on the history field, or I have to create a second Type and then reference this type (knowing that there's no need for the application to create another schema in mongoose, whould only create in GraphQL).

Body:
Like you said, when you write your GraphQL schema, history will need to be a separate type, as will probably Order and Restaurant. Using Apollo, the schema type definitions would look something like:

type User {
  # additional fields
  history: [Record!]!
}

type Record {
  orders: [Order!]!
  restaurant: Restaurant
}

In addition to the type definitions above, you would also provide a resolver for User. In this case, the resolver would simply return User.findOne() (or however you normally get the User object from your database).

Here's the neat part: you may not even need resolvers for Order, Restaurant or even History. When you don't specify a resolver, GraphQL will use a default resolver that happily uses the object it's passed (whatever chunk of the User object you would pass in your resolver for the User type). If it finds keys in that object that match the fields in you specified in your GraphQL schema's
type definition, it will populate those fields and ignore everything else.

Of course, if you need additional control (maybe your object keys and field names don't match), you can always still write the resolver yourself.


问:
Univocity - Irregular csv parsing
I have irregular (albeit consistent) "csv" files I need to parse. Content looks like this:

```<code>Field1: Field1Text
Field2: Field2Text

Field3 (need to ignore)
Field4 (need to ignore)

Field5
Field5Text

// Cars - for example
#,Col1,Col2,Col3,Col4,Col5,Col6
#1,Col1Text,Col2Text,Col3Text,Col4Text,Col5Text,Col6Text
#2,Col1Text,Col2Text,Col3Text,Col4Text,Col5Text,Col6Text
#3,Col1Text,Col2Text,Col3Text,Col4Text,Col5Text,Col6Text
</code>```

Ideally I would like to use a similar approach as here.

I ultimately want to end up with an object like:

```<code>String field1;
String field2;
String field5;
List<Car> cars;
</code>```

I currently have the following problems:

After adding some exploratory tests, lines beginning with hash(#) are ignored. I don't want this, is there anyway to escape?

My intention was to use a BeanListProcessor for the cars section and process the other fields using separate row processors. Then combine the result in the object mentioned above. Am I missing any tricks here?

答:
Your first issue is with the # which by default is treated as a comment character. To prevent lines starting with # to be treated as a comment, do this:

```<code>parserSettings.getFormat().setComment('\0');
</code>```

As for the structure you are parsing, there's not a way to do it out of the box, but it's easy to leverage the API for it. The following will work:

```<code>    CsvParserSettings settings = new CsvParserSettings();
    settings.getFormat().setComment('\0'); //prevent lines starting with # to be parsed as comments

    //Creates a parser
    CsvParser parser = new CsvParser(settings);

    //Open the input
    parser.beginParsing(new File("/path/to/input.csv"), "UTF-8");

    //create BeanListProcessor for instances of Car, and initialize it.
    BeanListProcessor<Car> carProcessor = new BeanListProcessor<Car>(Car.class);
    carProcessor.processStarted(parser.getContext());

    String[] row;
    Parent parent = null;
    while ((row = parser.parseNext()) != null) { //read rows one by one.
        if (row[0].startsWith("Field1:")) {  // when Field1 is found, create your parent instance
            if (parent != null) { //if you already have a parent instance, cars have been read. Associate the list of cars to the instance
                parent.cars = new ArrayList<Car>(carProcessor.getBeans()); //copy the list of cars from the processor.
                carProcessor.getBeans().clear(); //clears the processor list
                //you probably want to do something with your parent bean here.
            }
            parent = new Parent(); //create a fresh parent instance
            parent.field1 = row[0]; //assign the fields as appropriate.
        } else if (row[0].startsWith("Field2:")) {
            parent.field2 = row[0]; //and so on
        } else if (row[0].startsWith("Field5:")) {
            parent.field5 = row[0];
        } else if (row[0].startsWith("#")){ //got a "Car" row, invoke the rowProcessed method of the carProcessor.
            carProcessor.rowProcessed(row, parser.getContext());
        }
    }

    //at the end, if there is a parent, get the cars parsed
    if (parent != null) {
        parent.cars = carProcessor.getBeans();
    }
</code>```

For the BeanListProcessor to work, you need to have your instance declared like this:

```<code>public static final class Car {
    @Parsed(index = 0)
    String id;
    @Parsed(index = 1)
    String col1;
    @Parsed(index = 2)
    String col2;
    @Parsed(index = 3)
    String col3;
    @Parsed(index = 4)
    String col4;
    @Parsed(index = 5)
    String col5;
    @Parsed(index = 6)
    String col6;
}
</code>```

You can use headers instead but it will make you write more code. If the headers are always the same then you can just assume the positions are fixed.

Hope this helps

Title: Univocity - Irregular csv parsing

Body:
I have irregular (albeit consistent) "csv" files I need to parse. Content looks like this:

Field1: Field1Text
Field2: Field2Text

Field3 (need to ignore)
Field4 (need to ignore)

Field5
Field5Text

// Cars - for example
#,Col1,Col2,Col3,Col4,Col5,Col6
#1,Col1Text,Col2Text,Col3Text,Col4Text,Col5Text,Col6Text
#2,Col1Text,Col2Text,Col3Text,Col4Text,Col5Text,Col6Text
#3,Col1Text,Col2Text,Col3Text,Col4Text,Col5Text,Col6Text

Ideally I would like to use a similar approach as here.

I ultimately want to end up with an object like:

String field1;
String field2;
String field5;
List<Car> cars;

I currently have the following problems:

After adding some exploratory tests, lines beginning with hash(#) are ignored. I don't want this, is there anyway to escape?

My intention was to use a BeanListProcessor for the cars section and process the other fields using separate row processors. Then combine the result in the object mentioned above. Am I missing any tricks here?

Body:
Your first issue is with the # which by default is treated as a comment character. To prevent lines starting with # to be treated as a comment, do this:

parserSettings.getFormat().setComment('\0');

As for the structure you are parsing, there's not a way to do it out of the box, but it's easy to leverage the API for it. The following will work:

    CsvParserSettings settings = new CsvParserSettings();
    settings.getFormat().setComment('\0'); //prevent lines starting with # to be parsed as comments

    //Creates a parser
    CsvParser parser = new CsvParser(settings);

    //Open the input
    parser.beginParsing(new File("/path/to/input.csv"), "UTF-8");

    //create BeanListProcessor for instances of Car, and initialize it.
    BeanListProcessor<Car> carProcessor = new BeanListProcessor<Car>(Car.class);
    carProcessor.processStarted(parser.getContext());

    String[] row;
    Parent parent = null;
    while ((row = parser.parseNext()) != null) { //read rows one by one.
        if (row[0].startsWith("Field1:")) {  // when Field1 is found, create your parent instance
            if (parent != null) { //if you already have a parent instance, cars have been read. Associate the list of cars to the instance
                parent.cars = new ArrayList<Car>(carProcessor.getBeans()); //copy the list of cars from the processor.
                carProcessor.getBeans().clear(); //clears the processor list
                //you probably want to do something with your parent bean here.
            }
            parent = new Parent(); //create a fresh parent instance
            parent.field1 = row[0]; //assign the fields as appropriate.
        } else if (row[0].startsWith("Field2:")) {
            parent.field2 = row[0]; //and so on
        } else if (row[0].startsWith("Field5:")) {
            parent.field5 = row[0];
        } else if (row[0].startsWith("#")){ //got a "Car" row, invoke the rowProcessed method of the carProcessor.
            carProcessor.rowProcessed(row, parser.getContext());
        }
    }

    //at the end, if there is a parent, get the cars parsed
    if (parent != null) {
        parent.cars = carProcessor.getBeans();
    }

For the BeanListProcessor to work, you need to have your instance declared like this:

public static final class Car {
    @Parsed(index = 0)
    String id;
    @Parsed(index = 1)
    String col1;
    @Parsed(index = 2)
    String col2;
    @Parsed(index = 3)
    String col3;
    @Parsed(index = 4)
    String col4;
    @Parsed(index = 5)
    String col5;
    @Parsed(index = 6)
    String col6;
}

You can use headers instead but it will make you write more code. If the headers are always the same then you can just assume the positions are fixed.

Hope this helps


问:
Getting maxlength from array
I'm trying to get the longest description from $productDetail array, but it returns empty array elements:

```<code>$desc = array_map(function($a) {
            return (!!$desc && strlen($desc) < strlen($a["desc"])) ?
                $a["desc"] : $desc;
        }, $productDetail);
</code>```

答: You're using $desc inside of your assignment of $desc before it's completed.

Title: Getting maxlength from array

Body:
I'm trying to get the longest description from $productDetail array, but it returns empty array elements:

$desc = array_map(function($a) {
            return (!!$desc && strlen($desc) < strlen($a["desc"])) ?
                $a["desc"] : $desc;
        }, $productDetail);


问:
count the number of zero group bits in a number
How do you count the number of zero group bits in a number? group bits
is any consecutive zero or one bits, for example, 2 is represented
as ....0000000000000000010 has two zero bits groups the least
significant bit and the group starts after one.
Also, I am in a bad need for algorithms on bits manipulation if any
one has a reference, please share</p>

答:
Here are some hints for you:

if (x & 1) {...} checks if the least-significant bit of x is set;

x >>= 1 shifts the value of x one bit to the right;

mind the negative numbers when you do bit manipulation.


问:
SQL Where clause use if value greater than
I try create optional query.I have in sql proc 4 param.

```<code>ALTER PROCEDURE [dbo].[sp_OdevTümBilgiler]
@ogretmenUserId int,

@ogrenciUserId int,
@odevAdi nvarchar(50) = null,
@odevId int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
 SELECT
  s.*,
  o.*,
  ko.*,
  ogretmenUser.UserID AS OgretmenUserId,
  ogrenciUser.UserID AS OgrenciId,
  (ogretmenUser.Name + ' ' + ogretmenUser.Surname) AS OgretmenFullName,
  (ogrenciUser.Name + ' ' + ogrenciUser.Surname) AS OgrenciFullName
FROM KullaniciOdev AS ko
INNER JOIN Odev o
  ON ko.OdevId = o.OdevId
INNER JOIN FrUser ogrenciUser
  ON ogrenciUser.UserID = ko.UserId
INNER JOIN Sinif s
  ON s.SinifId = o.ClassId
INNER JOIN FrUser ogretmenUser
  ON ogretmenUser.UserID = s.OlusturanKullaniciId
WHERE 1=1 and (@ogrenciUserId > 0 and ko.UserId = @ogrenciUserId) and
((@ogretmenUserId > 0) and s.OlusturanKullaniciId = @ogretmenUserId) and
(@odevAdi IS NOT NULL and LEN(@odevAdi) > 0 and o.OdevAdi = @odevAdi) and
(@odevId > 0 and ko.OdevId=@odevId)
  END
</code>```

In my application @ogretmenUserId default value is -1,

@ogrenciUserId default value is -1,

@odevAdi null,

@odevId -1

but nothing is returning with right values  is the query false ?

Example I try :

odevId=1  and ogretmenUserId=1027  but nothing is returning

答:
Given the following WHERE clause:

```<code>WHERE 1=1 and
      (@ogrenciUserId > 0 and ko.UserId = @ogrenciUserId) and
      ((@ogretmenUserId > 0) and s.OlusturanKullaniciId = @ogretmenUserId) and
      (@odevAdi IS NOT NULL and LEN(@odevAdi) > 0 and o.OdevAdi = @odevAdi) and
      (@odevId > 0 and ko.OdevId=@odevId)
</code>```

Plug the following values in

```<code>@odevId=1
@ogretmenUserId=1027
@ogrenciUserId default value is -1,
@odevAdi null,
</code>```

The WHERE clause becomes:

```<code>WHERE 1=1 and
      (-1 > 0 and ko.UserId = -1) and
      ((1027 > 0) and s.OlusturanKullaniciId = 1027) and
      (null IS NOT NULL and LEN(null) > 0 and o.OdevAdi = null) and
      (1 > 0 and ko.OdevId=1)
</code>```

which is equivalent to

```<code>WHERE true and
      false and
      ((1027 > 0) and s.OlusturanKullaniciId = 1027) and
      false and
      (1 > 0 and ko.OdevId=1)
</code>```

which is always false

Since it's always false based on your input parameters, regardless the content of the table rows you are scanning through, the WHERE clause always returns false and therefore no row will be selected.

Body:
I try create optional query.I have in sql proc 4 param.

ALTER PROCEDURE [dbo].[sp_OdevTümBilgiler]
@ogretmenUserId int,

@ogrenciUserId int,
@odevAdi nvarchar(50) = null,
@odevId int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
 SELECT
  s.*,
  o.*,
  ko.*,
  ogretmenUser.UserID AS OgretmenUserId,
  ogrenciUser.UserID AS OgrenciId,
  (ogretmenUser.Name + ' ' + ogretmenUser.Surname) AS OgretmenFullName,
  (ogrenciUser.Name + ' ' + ogrenciUser.Surname) AS OgrenciFullName
FROM KullaniciOdev AS ko
INNER JOIN Odev o
  ON ko.OdevId = o.OdevId
INNER JOIN FrUser ogrenciUser
  ON ogrenciUser.UserID = ko.UserId
INNER JOIN Sinif s
  ON s.SinifId = o.ClassId
INNER JOIN FrUser ogretmenUser
  ON ogretmenUser.UserID = s.OlusturanKullaniciId
WHERE 1=1 and (@ogrenciUserId > 0 and ko.UserId = @ogrenciUserId) and
((@ogretmenUserId > 0) and s.OlusturanKullaniciId = @ogretmenUserId) and
(@odevAdi IS NOT NULL and LEN(@odevAdi) > 0 and o.OdevAdi = @odevAdi) and
(@odevId > 0 and ko.OdevId=@odevId)
  END

In my application @ogretmenUserId default value is -1,

@ogrenciUserId default value is -1,

@odevAdi null,

@odevId -1

but nothing is returning with right values  is the query false ?

Example I try :

odevId=1  and ogretmenUserId=1027  but nothing is returning

Body:
Given the following WHERE clause:

WHERE 1=1 and
      (@ogrenciUserId > 0 and ko.UserId = @ogrenciUserId) and
      ((@ogretmenUserId > 0) and s.OlusturanKullaniciId = @ogretmenUserId) and
      (@odevAdi IS NOT NULL and LEN(@odevAdi) > 0 and o.OdevAdi = @odevAdi) and
      (@odevId > 0 and ko.OdevId=@odevId)

Plug the following values in

@odevId=1
@ogretmenUserId=1027
@ogrenciUserId default value is -1,
@odevAdi null,

The WHERE clause becomes:

WHERE 1=1 and
      (-1 > 0 and ko.UserId = -1) and
      ((1027 > 0) and s.OlusturanKullaniciId = 1027) and
      (null IS NOT NULL and LEN(null) > 0 and o.OdevAdi = null) and
      (1 > 0 and ko.OdevId=1)

which is equivalent to

WHERE true and
      false and
      ((1027 > 0) and s.OlusturanKullaniciId = 1027) and
      false and
      (1 > 0 and ko.OdevId=1)

which is always false

Since it's always false based on your input parameters, regardless the content of the table rows you are scanning through, the WHERE clause always returns false and therefore no row will be selected.


问:
C# type inference ("var") assignment from '??' null-coalescing operator
I've read many of the  SO questions on the null coalescing ?? operator but none of them seem to address the following specific issue, which concerns neither nullability (here), operator precedence (here and here) nor especially implicit conversion (here, here, here and here). I've also read the .NET docs (more here) and tried to read the offical spec, but sadly all to no avail.

So here goes. The only difference between the following two lines is the use of var for type inference in the second, versus explicit type Random in the first, yet the second line gives the error as shown, whereas the first is just fine.

```<code>Random x = new Random() ?? (x = new Random());        // ok

var    y = new Random() ?? (y = new Random());        // CS0841
                        //  ^-------- error here
</code>```

CS0841: Cannot use local variable 'y' before it is declared

What is it precisely about the second line that makes the outcome uncertain?

From the hubub I cited above, I learned that the possibility of the left-side of the ?? operator being null introduces a dependency on the runtime determination of the actual instantiated type of its right-side. Hmm, ok, I guess,... whatever that means? Maybe the amount of alarm generally wafting about the ?? operator on this site should have been some kind of dire warning...

Zeroing-in now, I thought that the whole point of the var keyword (as very specifically opposed to dynamic) was that it was not suscceptible to runtime considerations like that, by definition.

In other words, even if we adopt the conservative but perfectly defensible rule of "never peering beyond any assignment = operator", such that we therefore get no helpful information whatsoever from the right-side of the ??, then based on the left-side alone, the overall result must be "compatible with" Random. That is, the result must be Random or a more specific (derived) type; it cannot be more general. By definition, therefore, shouldn't Random be the inferred type, for this compile-time use of var?

As far as I can understand, corrupting var with runtime considerations summarily defeats its purpose. Isn't that precisely what dynamic is for? So I guess the questions are:

Is the null-coalescing operator a lone and/or rare exception to my understanding of C# static (i.e., compile-time) typing philosophy?

If yes, then what are the benefits or tradeoffs between this design vs. what seems to be going on here, namely, deliberately introducing non-determinism to a system of static type inference, and which it did not previously exhibit? Couldn't dynamic have been implemented without corrupting the purity of static typing?

Isn't one of the main points of strong-typing to enable compile-time design rigor via actionable feedback to the developer? Why can't var just maintain a policy of strict conservatism--always inferring the most-specific type that can be statically inferred--at the same time as the null-coalescing operator is doing whatever it wants to do based on information from the future?

答:
It's not a runtime consideration.

The compile time type of a variable declared using var is the static type of its initializer.  The static type of a ?? expression is the common type of the static type of both operands.  But the static type of the second operand is the static type of y, which isn't known.  Therefore the static type of the whole initializer is unknown, and deduction fails.

It's true that there exist types for which the initialization would be consistent, but they can't be found using the C# inference rules.

Body:
I've read many of the  SO questions on the null coalescing ?? operator but none of them seem to address the following specific issue, which concerns neither nullability (here), operator precedence (here and here) nor especially implicit conversion (here, here, here and here). I've also read the .NET docs (more here) and tried to read the offical spec, but sadly all to no avail.

So here goes. The only difference between the following two lines is the use of var for type inference in the second, versus explicit type Random in the first, yet the second line gives the error as shown, whereas the first is just fine.

Random x = new Random() ?? (x = new Random());        // ok

var    y = new Random() ?? (y = new Random());        // CS0841
                        //  ^-------- error here

CS0841: Cannot use local variable 'y' before it is declared

What is it precisely about the second line that makes the outcome uncertain?

From the hubub I cited above, I learned that the possibility of the left-side of the ?? operator being null introduces a dependency on the runtime determination of the actual instantiated type of its right-side. Hmm, ok, I guess,... whatever that means? Maybe the amount of alarm generally wafting about the ?? operator on this site should have been some kind of dire warning...

Zeroing-in now, I thought that the whole point of the var keyword (as very specifically opposed to dynamic) was that it was not suscceptible to runtime considerations like that, by definition.

In other words, even if we adopt the conservative but perfectly defensible rule of "never peering beyond any assignment = operator", such that we therefore get no helpful information whatsoever from the right-side of the ??, then based on the left-side alone, the overall result must be "compatible with" Random. That is, the result must be Random or a more specific (derived) type; it cannot be more general. By definition, therefore, shouldn't Random be the inferred type, for this compile-time use of var?

As far as I can understand, corrupting var with runtime considerations summarily defeats its purpose. Isn't that precisely what dynamic is for? So I guess the questions are:

Is the null-coalescing operator a lone and/or rare exception to my understanding of C# static (i.e., compile-time) typing philosophy?

If yes, then what are the benefits or tradeoffs between this design vs. what seems to be going on here, namely, deliberately introducing non-determinism to a system of static type inference, and which it did not previously exhibit? Couldn't dynamic have been implemented without corrupting the purity of static typing?

Isn't one of the main points of strong-typing to enable compile-time design rigor via actionable feedback to the developer? Why can't var just maintain a policy of strict conservatism--always inferring the most-specific type that can be statically inferred--at the same time as the null-coalescing operator is doing whatever it wants to do based on information from the future?


问:
How to disable the event that is executed before leaving the page?
I'm building a plugin for wordpress, I have a custom post type and several meta-boxes. In a meta-box I have a button to publish or update custom.

This is something of my code:

```<code>add_meta_box(
    'my_meta_boz'
    ,__( 'My title meta box', 'my-plugin' )
    ,array( $this, 'render_my_meta_box' )
    ,'my-screen'
    ,'normal'
    ,'high'
);
</code>```

In my 'render_my_meta_box' function I have my custom button:

```<code><p>
    <input type="submit" name="publish" id="publish" value="Save changes" />
</p>
</code>```

And I have no problem with that, except that saving or updating shows a confirmation dialog.

I want to remove this dialog box because the original button does not show any confirmation. How can I delete this dialog?

Try the following, but it did not work:

```<code><input type="submit" name="publish" id="publish" value="Save changes" onclick="javascript:window.onbeforeunload = null;"/>
</code>```

I have also used the 'submit_button ()' function, but it also shows the confirmation dialog.

答:
You can try this solution, it is not very clean but it works. Call the event click on the original button.</p>

```<code><input type="submit" value="Save changes" onclick="window.document.getElementById('publish').click();"/>
</code>```

Body:
I'm building a plugin for wordpress, I have a custom post type and several meta-boxes. In a meta-box I have a button to publish or update custom.

This is something of my code:

add_meta_box(
    'my_meta_boz'
    ,__( 'My title meta box', 'my-plugin' )
    ,array( $this, 'render_my_meta_box' )
    ,'my-screen'
    ,'normal'
    ,'high'
);

In my 'render_my_meta_box' function I have my custom button:

    <input type="submit" name="publish" id="publish" value="Save changes" />

And I have no problem with that, except that saving or updating shows a confirmation dialog.

I want to remove this dialog box because the original button does not show any confirmation. How can I delete this dialog?

Try the following, but it did not work:

<input type="submit" name="publish" id="publish" value="Save changes" onclick="javascript:window.onbeforeunload = null;"/>

I have also used the 'submit_button ()' function, but it also shows the confirmation dialog.

Body:
You can try this solution, it is not very clean but it works. Call the event click on the original button.

<input type="submit" value="Save changes" onclick="window.document.getElementById('publish').click();"/>


问:
rating bar becomes to large and is cut-off when adding custom images in android
I followed an answer on stack overflow to adding a custom rating bar to an android project, here it is: https://stackoverflow.com/a/32828726/5909396

Just in case I am posting my code.

First I created ratingBar.xml in drawable folder:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background"
          android:drawable="@drawable/ratingbar_empty" />
    <item android:id="@android:id/secondaryProgress"
          android:drawable="@drawable/ratingbar_empty" />
    <item android:id="@android:id/progress"
          android:drawable="@drawable/ratingbar_filled" />
</code>```

Then I created ratingbar_empty.xml and ratingbar_filled.xml also in drawable folder:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true"
    android:state_window_focused="true"
    android:drawable="@drawable/ic_emptyStar" />

<item android:state_focused="true"
    android:state_window_focused="true"
    android:drawable="@drawable/ic_emptyStar" />

<item android:state_selected="true"
    android:state_window_focused="true"
    android:drawable="@drawable/ic_emptyStar" />

<item android:drawable="@drawable/ic_emptyStar" />
</code>```

```<code><?xml version="1.0" encoding="UTF-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true"
    android:state_window_focused="true"
    android:drawable="@drawable/ic_fullStar" />

<item android:state_focused="true"
    android:state_window_focused="true"
    android:drawable="@drawable/ic_fullStar" />

<item android:state_selected="true"
    android:state_window_focused="true"
    android:drawable="@drawable/ic_fullStar" />

<item android:drawable="@drawable/ic_fullStar" />
</code>```

And then I created the custom style in styles.xml

```<code><style name="CustomRatingBar" parent="@android:style/Widget.RatingBar">
    <item name="android:progressDrawable">@drawable/ratingbar</item>
    <item name="android:minHeight">50dp</item>
    <item name="android:maxHeight">50dp</item>
</style>
</code>```

And finally I added a ratingBar to layout. The way I structured it is the rating bar is inside a relative layout and there is a textview inside the relative layout as well that is on top of the rating bar (The text view shows if there is no rating);

```<code> <RelativeLayout
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="0.4"
            android:orientation="vertical"
            android:layout_gravity="center">
            <RatingBar
                android:id="@+id/ratingRestaurant"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                style="@style/CustomRatingBar"
                android:numStars="5"
                android:stepSize="0.1"
                android:isIndicator="true"
                android:max="5"
                android:progress="3"
                android:layout_centerVertical="true"
                android:progressTint="#ffe4b331" />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="No rating available"
                android:textColor="@android:color/white"
                android:textSize="11dp"
                android:id="@+id/textViewNoRatingAvailable" />
 </RelativeLayout>
</code>```

When I run the application on the simulator, the stars are really large and are cut-off like below:

There are supposed to be five stars. How can i fix this problem?

答:
set</p>

```<code>android:layout_width="wrap_content"
android:layout_height="0dp"
</code>```

Body:
I followed an answer on stack overflow to adding a custom rating bar to an android project, here it is: https://stackoverflow.com/a/32828726/5909396

Just in case I am posting my code.

First I created ratingBar.xml in drawable folder:

<?xml version="1.0" encoding="UTF-8" ?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background"
          android:drawable="@drawable/ratingbar_empty" />
    <item android:id="@android:id/secondaryProgress"
          android:drawable="@drawable/ratingbar_empty" />
    <item android:id="@android:id/progress"
          android:drawable="@drawable/ratingbar_filled" />

Then I created ratingbar_empty.xml and ratingbar_filled.xml also in drawable folder:

<?xml version="1.0" encoding="UTF-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true"
    android:state_window_focused="true"
    android:drawable="@drawable/ic_emptyStar" />

<item android:state_focused="true"
    android:state_window_focused="true"
    android:drawable="@drawable/ic_emptyStar" />

<item android:state_selected="true"
    android:state_window_focused="true"
    android:drawable="@drawable/ic_emptyStar" />

<item android:drawable="@drawable/ic_emptyStar" />

<?xml version="1.0" encoding="UTF-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true"
    android:state_window_focused="true"
    android:drawable="@drawable/ic_fullStar" />

<item android:state_focused="true"
    android:state_window_focused="true"
    android:drawable="@drawable/ic_fullStar" />

<item android:state_selected="true"
    android:state_window_focused="true"
    android:drawable="@drawable/ic_fullStar" />

<item android:drawable="@drawable/ic_fullStar" />

And then I created the custom style in styles.xml

And finally I added a ratingBar to layout. The way I structured it is the rating bar is inside a relative layout and there is a textview inside the relative layout as well that is on top of the rating bar (The text view shows if there is no rating);

 <RelativeLayout
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="0.4"
            android:orientation="vertical"
            android:layout_gravity="center">
            <RatingBar
                android:id="@+id/ratingRestaurant"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                style="@style/CustomRatingBar"
                android:numStars="5"
                android:stepSize="0.1"
                android:isIndicator="true"
                android:max="5"
                android:progress="3"
                android:layout_centerVertical="true"
                android:progressTint="#ffe4b331" />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="No rating available"
                android:textColor="@android:color/white"
                android:textSize="11dp"
                android:id="@+id/textViewNoRatingAvailable" />
 </RelativeLayout>

When I run the application on the simulator, the stars are really large and are cut-off like below:

There are supposed to be five stars. How can i fix this problem?

Body:
set

android:layout_width="wrap_content"
android:layout_height="0dp"