问:
How to Display Working Keyboard Shortcut for Menu Items?
I am trying to create a localizable WPF menu bar with menu items that have keyboard shortcuts - not accelerator keys/mnemonics (usually shown as underlined characters that can be pressed to directly select a menu item when the menu is already open), but keyboard shortcuts (usually combinations of Ctrl + another key) that are displayed right-aligned next to the menu item header.

I am using the MVVM pattern for my application, meaning that I avoid placing any code in code-behind wherever possible and have my view-models (that I assign to the DataContext properties) provide implementations of the ICommand interface that are used by controls in my views.

As a base for reproducing the issue, here is some minimal source code for an application as described:

Window1.xaml

```<code><Window x:Class="MenuShortcutTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MenuShortcutTest" Height="300" Width="300">
    <Menu>
        <MenuItem Header="{Binding MenuHeader}">
            <MenuItem Header="{Binding DoSomethingHeader}" Command="{Binding DoSomething}"/>
        </MenuItem>
    </Menu>
</Window>
</code>```

Window1.xaml.cs

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

namespace MenuShortcutTest
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            this.DataContext = new MainViewModel();
        }
    }
}
</code>```

MainViewModel.cs

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

namespace MenuShortcutTest
{
    public class MainViewModel
    {
        public string MenuHeader {
            get {
                // in real code: load this string from localization
                return "Menu";
            }
        }

        public string DoSomethingHeader {
            get {
                // in real code: load this string from localization
                return "Do Something";
            }
        }

        private class DoSomethingCommand : ICommand
        {
            public DoSomethingCommand(MainViewModel owner)
            {
                if (owner == null) {
                    throw new ArgumentNullException("owner");
                }

                this.owner = owner;
            }

            private readonly MainViewModel owner;

            public event EventHandler CanExecuteChanged;

            public void Execute(object parameter)
            {
                // in real code: do something meaningful with the view-model
                MessageBox.Show(owner.GetType().FullName);
            }

            public bool CanExecute(object parameter)
            {
                return true;
            }
        }

        private ICommand doSomething;

        public ICommand DoSomething {
            get {
                if (doSomething == null) {
                    doSomething = new DoSomethingCommand(this);
                }

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

The WPF MenuItem class has an InputGestureText property, but as described in SO questions such as this, this, this and this, that is purely cosmetic and has no effect whatsoever on what shortcuts are actually processed by the application.

SO questions like this and this point out that the command should be linked with a KeyBinding in the InputBindings list of the window. While that enables the functionality, it does not automatically display the shortcut with the menu item. Window1.xaml changes as follows:

```<code><Window x:Class="MenuShortcutTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MenuShortcutTest" Height="300" Width="300">
    <Window.InputBindings>
        <KeyBinding Key="D" Modifiers="Control" Command="{Binding DoSomething}"/>
    </Window.InputBindings>
    <Menu>
        <MenuItem Header="{Binding MenuHeader}">
            <MenuItem Header="{Binding DoSomethingHeader}" Command="{Binding DoSomething}"/>
        </MenuItem>
    </Menu>
</Window>
</code>```

I have tried manually setting the InputGestureText property in addition, making Window1.xaml look like this:

```<code><Window x:Class="MenuShortcutTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MenuShortcutTest" Height="300" Width="300">
    <Window.InputBindings>
        <KeyBinding Key="D" Modifiers="Control" Command="{Binding DoSomething}"/>
    </Window.InputBindings>
    <Menu>
        <MenuItem Header="{Binding MenuHeader}">
            <MenuItem Header="{Binding DoSomethingHeader}" Command="{Binding DoSomething}" InputGestureText="Ctrl+D"/>
        </MenuItem>
    </Menu>
</Window>
</code>```

This does display the shortcut, but is not a viable solution for obvious reasons:

It does not update when the actual shortcut binding changes, so even if the shortcuts are not configurable by users, this solution is a maintenance nightmare.

The text needs to be localized (as e.g. the Ctrl key has different names in some languages), so if any of the shortcuts is ever changed, all translations would need to be updated individually.

I have looked into creating an IValueConverter to use for binding the InputGestureText property to the InputBindings list of the window (there might be more than one KeyBinding in the InputBindings list, or none at all, so there is no specific KeyBinding instance that I could bind to (if KeyBinding even lends itself to being a binding target)). This appears to me like the most desirable solution, because it is very flexible and at the same time very clean (it does not require a plethora of declarations in various places), but on the one hand, InputBindingCollection does not implement INotifyCollectionChanged, thus the binding would not be updated when shortcuts are replaced, and on the other hand, I did not manage to provide the converter with a reference to my view-model in a tidy manner (which it would need to access the localization data). What is more, InputBindings is not a dependency property, so I cannot bind that to a common source (such as a list of input bindings located in the view-model) that the ItemGestureText property could be bound to, as well.

Now, many resources (this question, that question, this thread, that question and that thread point out that RoutedCommand and RoutedUICommand contain a built-in InputGestures property and imply that key bindings from that property are automatically displayed in menu items.

However, using either of those ICommand implementations seems to open a new can of worms, as their Execute and CanExecute methods are not virtual and thus cannot be overridden in subclasses to fill in the desired functionality. The only way to provide that seems to be declaring a CommandBinding in XAML (shown e.g. here or here) that connects a command with an event handler - however, that event handler would then be located in the code-behind, thus violating the MVVM architecture described above.

Trying nonetheless, this means turning most of the aforementioned structure inside-out (which also kind of implies that I need to make my mind up on how to eventually solve the issue in my current, comparably early stage of development):

Window1.xaml

```<code><Window x:Class="MenuShortcutTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:local="clr-namespace:MenuShortcutTest"
    Title="MenuShortcutTest" Height="300" Width="300">
    <Window.CommandBindings>
        <CommandBinding Command="{x:Static local:DoSomethingCommand.Instance}" Executed="CommandBinding_Executed"/>
    </Window.CommandBindings>
    <Menu>
        <MenuItem Header="{Binding MenuHeader}">
            <MenuItem Header="{Binding DoSomethingHeader}" Command="{x:Static local:DoSomethingCommand.Instance}"/>
        </MenuItem>
    </Menu>
</Window>
</code>```

Window1.xaml.cs

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

namespace MenuShortcutTest
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            this.DataContext = new MainViewModel();
        }

        void CommandBinding_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
        {
            ((MainViewModel)DataContext).DoSomething();
        }
    }
}
</code>```

MainViewModel.cs

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

namespace MenuShortcutTest
{
    public class MainViewModel
    {
        public string MenuHeader {
            get {
                // in real code: load this string from localization
                return "Menu";
            }
        }

        public string DoSomethingHeader {
            get {
                // in real code: load this string from localization
                return "Do Something";
            }
        }

        public void DoSomething()
        {
            // in real code: do something meaningful with the view-model
            MessageBox.Show(this.GetType().FullName);
        }
    }
}
</code>```

DoSomethingCommand.cs

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

namespace MenuShortcutTest
{
    public class DoSomethingCommand : RoutedCommand
    {
        public DoSomethingCommand()
        {
            this.InputGestures.Add(new KeyGesture(Key.D, ModifierKeys.Control));
        }

        private static Lazy<DoSomethingCommand> instance = new Lazy<DoSomethingCommand>();

        public static DoSomethingCommand Instance {
            get {
                return instance.Value;
            }
        }
    }
}
</code>```

For the same reason (RoutedCommand.Execute and such being non-virtual), I do not know how to subclass RoutedCommand in a way to create a RelayCommand like the one used in an answer to this question based on RoutedCommand, so I do not have to make the detour over the InputBindings of the window - while explicitly reimplementing the methods from ICommand in a RoutedCommand subclass feels like I might be breaking something.

What is more, while the shortcut is automatically displayed with this method as configured in the RoutedCommand, it does not seem to get automatically localized. My understanding is that adding

```<code>System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-de");
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture;
</code>```

to the MainWindow constructor should make sure that localizable strings supplied by the framework should be taken from the German CultureInfo - however, Ctrl does not change to Strg, so unless I am mistaken about how to set the CultureInfo for framework-supplied strings, this method is not viable anyway if I expect the displayed shortcut to be correctly localized.

Now, I am aware that KeyGesture allows me to specify a custom display string for the keyboard shortcut, but not only is the RoutedCommand-derived DoSomethingCommand class disjoint from all of my instances (from where I could get in touch with the loaded localization) due to the way CommandBinding has to be linked with a command in XAML, the respective DisplayString property is read-only, so there would be no way to change it when another localization is loaded at runtime.

This leaves me with the option to manually dig through the menu tree (EDIT: for the sake of clarification, no code here because I am not asking for this and I know how to do this) and the InputBindings list of the window to check which commands have any KeyBinding instances associated with them, and which menu items are linked to any of those commands, so that I can manually set the InputGestureText of each of the respective menu items to reflect the first (or preferred, by whichever metric I want to use here) keyboard shortcut. And this procedure would have to be repeated every time I think the key bindings may have changed. However, this seems like an extremely tedious workaround for something that is essentially a basic feature of a menu bar GUI, so I'm convinced it cannot be the "correct" way to do this.

What is the right way to automatically display a keyboard shortcut that is configured to work for WPF MenuItem instances?

EDIT: All of the other questions I found dealt with how a KeyBinding/KeyGesture could be used to actually enable the functionality visually implied by InputGestureText, without explaining how to automatically link the two aspects in the described situation. The only somewhat promising question that I found was this, but it has not received any answers in over two years.

答:
Based on Pavel Voronin's answer, I created the following. Actually I just created two new UserControls which automatically set Gesture on the command and read it.

```<code>class HotMenuItem : MenuItem
{
    public HotMenuItem()
    {
        SetBinding(InputGestureTextProperty, new Binding("Command.GestureText")
        {
            Source = this
        });
    }
}

class HotKeyBinding : KeyBinding
{

    protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        base.OnPropertyChanged(e);
        if (e.Property.Name == "Command" || e.Property.Name == "Gesture")
        {
            if (Command is IHotkeyCommand hotkeyCommand)
                hotkeyCommand.Gesture = Gesture as KeyGesture;
        }
    }
}
</code>```

The used interface

```<code>public interface IHotkeyCommand
{
    KeyGesture Gesture { get; set; }
}
</code>```

The Command is pretty much the same, it just implements INotifyPropertyChanged.

So the usage gets a bit cleaner in my opinion:

```<code><Window.InputBindings>
    <viewModels:HotKeyBinding Command="{Binding ExitCommand}" Gesture="Alt+F4" />
</Window.InputBindings>

<Menu>
    <MenuItem Header="File" >
        <viewModels:HotMenuItem Header="Exit"  Command="{Binding ExitCommand}" />
    </MenuItem>
</Menu>
</code>```

Body:
I am trying to create a localizable WPF menu bar with menu items that have keyboard shortcuts - not accelerator keys/mnemonics (usually shown as underlined characters that can be pressed to directly select a menu item when the menu is already open), but keyboard shortcuts (usually combinations of Ctrl + another key) that are displayed right-aligned next to the menu item header.

I am using the MVVM pattern for my application, meaning that I avoid placing any code in code-behind wherever possible and have my view-models (that I assign to the DataContext properties) provide implementations of the ICommand interface that are used by controls in my views.

As a base for reproducing the issue, here is some minimal source code for an application as described:

Window1.xaml

<Window x:Class="MenuShortcutTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MenuShortcutTest" Height="300" Width="300">
    <Menu>
        <MenuItem Header="{Binding MenuHeader}">
            <MenuItem Header="{Binding DoSomethingHeader}" Command="{Binding DoSomething}"/>
        </MenuItem>
    </Menu>
</Window>

Window1.xaml.cs

using System;
using System.Windows;

namespace MenuShortcutTest
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            this.DataContext = new MainViewModel();
        }
    }
}

MainViewModel.cs

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

namespace MenuShortcutTest
{
    public class MainViewModel
    {
        public string MenuHeader {
            get {
                // in real code: load this string from localization
                return "Menu";
            }
        }

        public string DoSomethingHeader {
            get {
                // in real code: load this string from localization
                return "Do Something";
            }
        }

        private class DoSomethingCommand : ICommand
        {
            public DoSomethingCommand(MainViewModel owner)
            {
                if (owner == null) {
                    throw new ArgumentNullException("owner");
                }

                this.owner = owner;
            }

            private readonly MainViewModel owner;

            public event EventHandler CanExecuteChanged;

            public void Execute(object parameter)
            {
                // in real code: do something meaningful with the view-model
                MessageBox.Show(owner.GetType().FullName);
            }

            public bool CanExecute(object parameter)
            {
                return true;
            }
        }

        private ICommand doSomething;

        public ICommand DoSomething {
            get {
                if (doSomething == null) {
                    doSomething = new DoSomethingCommand(this);
                }

                return doSomething;
            }
        }
    }
}

The WPF MenuItem class has an InputGestureText property, but as described in SO questions such as this, this, this and this, that is purely cosmetic and has no effect whatsoever on what shortcuts are actually processed by the application.

SO questions like this and this point out that the command should be linked with a KeyBinding in the InputBindings list of the window. While that enables the functionality, it does not automatically display the shortcut with the menu item. Window1.xaml changes as follows:

<Window x:Class="MenuShortcutTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MenuShortcutTest" Height="300" Width="300">
    <Window.InputBindings>
        <KeyBinding Key="D" Modifiers="Control" Command="{Binding DoSomething}"/>
    </Window.InputBindings>
    <Menu>
        <MenuItem Header="{Binding MenuHeader}">
            <MenuItem Header="{Binding DoSomethingHeader}" Command="{Binding DoSomething}"/>
        </MenuItem>
    </Menu>
</Window>

I have tried manually setting the InputGestureText property in addition, making Window1.xaml look like this:

<Window x:Class="MenuShortcutTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MenuShortcutTest" Height="300" Width="300">
    <Window.InputBindings>
        <KeyBinding Key="D" Modifiers="Control" Command="{Binding DoSomething}"/>
    </Window.InputBindings>
    <Menu>
        <MenuItem Header="{Binding MenuHeader}">
            <MenuItem Header="{Binding DoSomethingHeader}" Command="{Binding DoSomething}" InputGestureText="Ctrl+D"/>
        </MenuItem>
    </Menu>
</Window>

This does display the shortcut, but is not a viable solution for obvious reasons:

It does not update when the actual shortcut binding changes, so even if the shortcuts are not configurable by users, this solution is a maintenance nightmare.

The text needs to be localized (as e.g. the Ctrl key has different names in some languages), so if any of the shortcuts is ever changed, all translations would need to be updated individually.

I have looked into creating an IValueConverter to use for binding the InputGestureText property to the InputBindings list of the window (there might be more than one KeyBinding in the InputBindings list, or none at all, so there is no specific KeyBinding instance that I could bind to (if KeyBinding even lends itself to being a binding target)). This appears to me like the most desirable solution, because it is very flexible and at the same time very clean (it does not require a plethora of declarations in various places), but on the one hand, InputBindingCollection does not implement INotifyCollectionChanged, thus the binding would not be updated when shortcuts are replaced, and on the other hand, I did not manage to provide the converter with a reference to my view-model in a tidy manner (which it would need to access the localization data). What is more, InputBindings is not a dependency property, so I cannot bind that to a common source (such as a list of input bindings located in the view-model) that the ItemGestureText property could be bound to, as well.

Now, many resources (this question, that question, this thread, that question and that thread point out that RoutedCommand and RoutedUICommand contain a built-in InputGestures property and imply that key bindings from that property are automatically displayed in menu items.

However, using either of those ICommand implementations seems to open a new can of worms, as their Execute and CanExecute methods are not virtual and thus cannot be overridden in subclasses to fill in the desired functionality. The only way to provide that seems to be declaring a CommandBinding in XAML (shown e.g. here or here) that connects a command with an event handler - however, that event handler would then be located in the code-behind, thus violating the MVVM architecture described above.

Trying nonetheless, this means turning most of the aforementioned structure inside-out (which also kind of implies that I need to make my mind up on how to eventually solve the issue in my current, comparably early stage of development):

Window1.xaml

<Window x:Class="MenuShortcutTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:local="clr-namespace:MenuShortcutTest"
    Title="MenuShortcutTest" Height="300" Width="300">
    <Window.CommandBindings>
        <CommandBinding Command="{x:Static local:DoSomethingCommand.Instance}" Executed="CommandBinding_Executed"/>
    </Window.CommandBindings>
    <Menu>
        <MenuItem Header="{Binding MenuHeader}">
            <MenuItem Header="{Binding DoSomethingHeader}" Command="{x:Static local:DoSomethingCommand.Instance}"/>
        </MenuItem>
    </Menu>
</Window>

Window1.xaml.cs

using System;
using System.Windows;

namespace MenuShortcutTest
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            this.DataContext = new MainViewModel();
        }

        void CommandBinding_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
        {
            ((MainViewModel)DataContext).DoSomething();
        }
    }
}

MainViewModel.cs

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

namespace MenuShortcutTest
{
    public class MainViewModel
    {
        public string MenuHeader {
            get {
                // in real code: load this string from localization
                return "Menu";
            }
        }

        public string DoSomethingHeader {
            get {
                // in real code: load this string from localization
                return "Do Something";
            }
        }

        public void DoSomething()
        {
            // in real code: do something meaningful with the view-model
            MessageBox.Show(this.GetType().FullName);
        }
    }
}

DoSomethingCommand.cs

using System;
using System.Windows.Input;

namespace MenuShortcutTest
{
    public class DoSomethingCommand : RoutedCommand
    {
        public DoSomethingCommand()
        {
            this.InputGestures.Add(new KeyGesture(Key.D, ModifierKeys.Control));
        }

        private static Lazy<DoSomethingCommand> instance = new Lazy<DoSomethingCommand>();

        public static DoSomethingCommand Instance {
            get {
                return instance.Value;
            }
        }
    }
}

For the same reason (RoutedCommand.Execute and such being non-virtual), I do not know how to subclass RoutedCommand in a way to create a RelayCommand like the one used in an answer to this question based on RoutedCommand, so I do not have to make the detour over the InputBindings of the window - while explicitly reimplementing the methods from ICommand in a RoutedCommand subclass feels like I might be breaking something.

What is more, while the shortcut is automatically displayed with this method as configured in the RoutedCommand, it does not seem to get automatically localized. My understanding is that adding

System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-de");
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture;

to the MainWindow constructor should make sure that localizable strings supplied by the framework should be taken from the German CultureInfo - however, Ctrl does not change to Strg, so unless I am mistaken about how to set the CultureInfo for framework-supplied strings, this method is not viable anyway if I expect the displayed shortcut to be correctly localized.

Now, I am aware that KeyGesture allows me to specify a custom display string for the keyboard shortcut, but not only is the RoutedCommand-derived DoSomethingCommand class disjoint from all of my instances (from where I could get in touch with the loaded localization) due to the way CommandBinding has to be linked with a command in XAML, the respective DisplayString property is read-only, so there would be no way to change it when another localization is loaded at runtime.

This leaves me with the option to manually dig through the menu tree (EDIT: for the sake of clarification, no code here because I am not asking for this and I know how to do this) and the InputBindings list of the window to check which commands have any KeyBinding instances associated with them, and which menu items are linked to any of those commands, so that I can manually set the InputGestureText of each of the respective menu items to reflect the first (or preferred, by whichever metric I want to use here) keyboard shortcut. And this procedure would have to be repeated every time I think the key bindings may have changed. However, this seems like an extremely tedious workaround for something that is essentially a basic feature of a menu bar GUI, so I'm convinced it cannot be the "correct" way to do this.

What is the right way to automatically display a keyboard shortcut that is configured to work for WPF MenuItem instances?

EDIT: All of the other questions I found dealt with how a KeyBinding/KeyGesture could be used to actually enable the functionality visually implied by InputGestureText, without explaining how to automatically link the two aspects in the described situation. The only somewhat promising question that I found was this, but it has not received any answers in over two years.

Body:
Based on Pavel Voronin's answer, I created the following. Actually I just created two new UserControls which automatically set Gesture on the command and read it.

class HotMenuItem : MenuItem
{
    public HotMenuItem()
    {
        SetBinding(InputGestureTextProperty, new Binding("Command.GestureText")
        {
            Source = this
        });
    }
}

class HotKeyBinding : KeyBinding
{

    protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        base.OnPropertyChanged(e);
        if (e.Property.Name == "Command" || e.Property.Name == "Gesture")
        {
            if (Command is IHotkeyCommand hotkeyCommand)
                hotkeyCommand.Gesture = Gesture as KeyGesture;
        }
    }
}

The used interface

public interface IHotkeyCommand
{
    KeyGesture Gesture { get; set; }
}

The Command is pretty much the same, it just implements INotifyPropertyChanged.

So the usage gets a bit cleaner in my opinion:

<Window.InputBindings>
    <viewModels:HotKeyBinding Command="{Binding ExitCommand}" Gesture="Alt+F4" />
</Window.InputBindings>

<Menu>
    <MenuItem Header="File" >
        <viewModels:HotMenuItem Header="Exit"  Command="{Binding ExitCommand}" />
    </MenuItem>
</Menu>


来源: stackexchange

问:
How can i use ttf font in winform designer without installation?
I want to use custom ttf Font in winform designer.
I tried to search but, there is only add with programmatic way.
But the programmatic way does not be reflected in designer.
The wpf project can do this with blend for visual studio but winform can not set ttf font which i add the project with designer.
How sould i gonna do?</p>

答:
try this

```<code>// specify embedded resource name
string resource = "embedded_font.PAGAP___.TTF";

// receive resource stream
Stream fontStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);

// create an unsafe memory block for the font data
System.IntPtr data = Marshal.AllocCoTaskMem((int)fontStream.Length);

// create a buffer to read in to
byte[] fontdata = new byte[fontStream.Length];

// read the font data from the resource
fontStream.Read(fontdata, 0, (int)fontStream.Length);

// copy the bytes to the unsafe memory block
Marshal.Copy(fontdata, 0, data, (int)fontStream.Length);

// pass the font to the font collection
private_fonts.AddMemoryFont(data, (int)fontStream.Length);

// close the resource stream
fontStream.Close();

// free up the unsafe memory
Marshal.FreeCoTaskMem(data);
</code>```

How to quickly and easily embed fonts in winforms app in C#

ContentLicense: CC BY-SA 3.0

Body:
try this

// specify embedded resource name
string resource = "embedded_font.PAGAP___.TTF";

// receive resource stream
Stream fontStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);

// create an unsafe memory block for the font data
System.IntPtr data = Marshal.AllocCoTaskMem((int)fontStream.Length);

// create a buffer to read in to
byte[] fontdata = new byte[fontStream.Length];

// read the font data from the resource
fontStream.Read(fontdata, 0, (int)fontStream.Length);

// copy the bytes to the unsafe memory block
Marshal.Copy(fontdata, 0, data, (int)fontStream.Length);

// pass the font to the font collection
private_fonts.AddMemoryFont(data, (int)fontStream.Length);

// close the resource stream
fontStream.Close();

// free up the unsafe memory
Marshal.FreeCoTaskMem(data);

How to quickly and easily embed fonts in winforms app in C#


问:
ipython notebook server behind VPN
Hi I am trying to set up a ipython notebook server at a machine at my school and access from outside the network

I can ssh to the machine after connecting to the school VPN.

I set up the ipython notebook to listen to all the ip address. I can open chrome/firefox to connect to it within the network.

```<code>The IPython Notebook is running at: http://[all ip addresses on your system]:9999/
</code>```

But I can't access the notebook from outside the network (even with VPN)?

答: Try adding [all ip addresses on your system] to your VPN whitelist, typically is 127.0.0.1 or localhost. If this still does not work, check if you are using global mode of your VPN which might overlook the whitelist config.

Title: ipython notebook server behind VPN

Body:
Hi I am trying to set up a ipython notebook server at a machine at my school and access from outside the network

I can ssh to the machine after connecting to the school VPN.

I set up the ipython notebook to listen to all the ip address. I can open chrome/firefox to connect to it within the network.

The IPython Notebook is running at: http://[all ip addresses on your system]:9999/

But I can't access the notebook from outside the network (even with VPN)?


问:
How to clear ListView on Fragment when back button pressed?
All data from that ListView is provided by a CursorAdapter.
Whenever I pressed back button and return to activity, then click on the activity to start my fragment, all previous data still there stacking on top of each other.

答:
you can try</p>

```<code>      try {
           arraylist.clear();
           listView.removeAllViews();
        }catch (Exception e){

        }
</code>```

Body:
you can try

      try {
           arraylist.clear();
           listView.removeAllViews();
        }catch (Exception e){

        }


问:
URLSession doesn't pass 'Authorization' key in header swift 4
I am trying to pass authorization key in header of a URLRequest. But at the server end the key is not received. The same API when called from postman working fine. Any other key in the header is working fine, even authorizations key is visible at server end.

Here is my code:

```<code>let headers = [
    "authorization": "token abcd"
]

var request = URLRequest.init(url: NSURL(string:
    "http://127.0.0.1:7000/api/channels?filter=contributed")! as URL)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = headers
let session = URLSession.init(configuration: config)

let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
    if (error != nil) {
        print(error ?? "")
    } else {
        let httpResponse = response as? HTTPURLResponse
        print(httpResponse ?? "")
    }
})
</code>```

As you can see, I tried to set the token in both session config and request but none is working.

答:
Looks like the problem is that you are modifying Authorization header using httpAdditionalHeaders which is something you should not do.

From the Doc

An NSURLSession object is designed to handle various aspects of the HTTP protocol for you. As a result, you should not modify the following headers:
  Authorization,
  Connection,
  Host,
  Proxy-Authenticate,
  Proxy-Authorization,
  WWW-Authenticate

Removing the line config.httpAdditionalHeaders = headers
 should fix the issue.

Body:
I am trying to pass authorization key in header of a URLRequest. But at the server end the key is not received. The same API when called from postman working fine. Any other key in the header is working fine, even authorizations key is visible at server end.

Here is my code:

let headers = [
    "authorization": "token abcd"
]

var request = URLRequest.init(url: NSURL(string:
    "http://127.0.0.1:7000/api/channels?filter=contributed")! as URL)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = headers
let session = URLSession.init(configuration: config)

let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
    if (error != nil) {
        print(error ?? "")
    } else {
        let httpResponse = response as? HTTPURLResponse
        print(httpResponse ?? "")
    }
})

As you can see, I tried to set the token in both session config and request but none is working.


问:
Predicate Logic A cup is above a book
Am a right or not.
The predicate logic for the following Sentences.

A cup is above a book.

```<code>\x exists \y exists cup(x) and book(y) and above(x,y)
</code>```

A cup is touching a book.

```<code>\x exists \y exists cup(x) and book(y) and touches(x,y).
</code>```

if x is on top of y then y supports x.

```<code>for all x For all y on(x,y) implies support(y,x).
</code>```

If x is above y and they are touching each other then  x is on top of y.

```<code>for all x for all y above(x,y) and touches(x,y)  implies on(x,y).
</code>```

Am i right?

答:
All your formulae seem reasonable representations to me.

I would add extra brackets around above(x,y) and touches(x,y) to ensure that both together form the antecedent of the implication. Otherwise it could be incorrectly interpretted as above(x,y) and (touches(x,y) implies on(x,y))

Title: Predicate Logic A cup is above a book

Body:
Am a right or not.
The predicate logic for the following Sentences.

A cup is above a book.

\x exists \y exists cup(x) and book(y) and above(x,y)

A cup is touching a book.

\x exists \y exists cup(x) and book(y) and touches(x,y).

if x is on top of y then y supports x.

for all x For all y on(x,y) implies support(y,x).

If x is above y and they are touching each other then  x is on top of y.

for all x for all y above(x,y) and touches(x,y)  implies on(x,y).

Am i right?


问:
Suppressing LINQ to SQL DBML warnings
I've generated LINQ to SQL classes from a database not under my control which has a lot of Decimal(38, 5) fields. Apparently the range of the .NET Decimal type is smaller than this, so the LINQ to SQL code generator is throwing a lot of warnings:

DBML1008: Mapping between DbType 'Decimal(38,5)' and Type 'System.Decimal' in Column 'StructGable24InchOCStuds' of Type 'AddersAndMultiplier' may cause data loss when loading from the database

It's extremely unlikely that any of these fields will ever have a value big enough to cause data loss in practice so I'd like to suppress these warnings. However, apparently setting warning suppression through the dialog in VS doesn't work with LINQ to SQL code generator warnings - is there another method?

答:
I am not sure how to suppress the warning but since I have control of the stored procedure that was causing the problem on my system I cast the return value to a smaller decimal which removed the warning.</p>

```<code>SELECT CAST(SUM(AdFee) AS DECIMAL(19, 3))
</code>```

ContentLicense: CC BY-SA 2.5

Title: Suppressing LINQ to SQL DBML warnings

Body:
I am not sure how to suppress the warning but since I have control of the stored procedure that was causing the problem on my system I cast the return value to a smaller decimal which removed the warning.

SELECT CAST(SUM(AdFee) AS DECIMAL(19, 3))


问:
SHA256 giving different result for same string input
I have simple code to generate hash code using SHA256, however, it gives different result for the same input. However, if I declare the same string value in quotes for example <code>_input= "test"</code> then it returns the same result. </p>

```<code>public static System.String generateKey(System.String _input)
{
     System.Byte[] convertedArr;
     SHA256Managed sh = new System.Security.Cryptography.SHA256Managed();
        convertedArr = sh.ComputeHash(System.Text.Encoding::UTF8.GetBytes(_inputString),0, System.Text.Encoding::UTF8.GetByteCount(_input));
        hashCode = System.Convert::ToBase64String(convertedArr);
    return hashCode;
    }
</code>```

答:
Note:

convertedArr = sh.ComputeHash(System.Text.Encoding::UTF8.GetBytes(_inputString),0, System.Text.Encoding::UTF8.GetByteCount(_input));

The input to the hash is _inputString but the length is taken from _input, they are not the same. _inputString != _input.

The function defintion:

```<code>public static System.String generateKey(System.String _input)
</code>```

Current code:

```<code>convertedArr = sh.ComputeHash(System.Text.Encoding::UTF8.GetBytes(_inputString),0, System.Text.Encoding::UTF8.GetByteCount(_input));
</code>```

Debuggable (semio-pseudo) code:

```<code>inputBytes  = System.Text.Encoding::UTF8.GetBytes(_input)
inputLength = System.Text.Encoding::UTF8.GetByteCount(_input)
hashBytes   = convertedArr = sh.ComputeHash(inputBytes, 0, inputLength);
</code>```

With this the input and length can easily be verified. The chance of the error is less because _input is only used once.

Note: In practice I would get the length from inputBytes but I am not fluent in X++ so I did not make that change.

Body:
I have simple code to generate hash code using SHA256, however, it gives different result for the same input. However, if I declare the same string value in quotes for example _input= "test" then it returns the same result.

public static System.String generateKey(System.String _input)
{
     System.Byte[] convertedArr;
     SHA256Managed sh = new System.Security.Cryptography.SHA256Managed();
        convertedArr = sh.ComputeHash(System.Text.Encoding::UTF8.GetBytes(_inputString),0, System.Text.Encoding::UTF8.GetByteCount(_input));
        hashCode = System.Convert::ToBase64String(convertedArr);
    return hashCode;
    }

Body:
Note:

convertedArr = sh.ComputeHash(System.Text.Encoding::UTF8.GetBytes(_inputString),0, System.Text.Encoding::UTF8.GetByteCount(_input));

The input to the hash is _inputString but the length is taken from _input, they are not the same. _inputString != _input.

The function defintion:

public static System.String generateKey(System.String _input)

Current code:

convertedArr = sh.ComputeHash(System.Text.Encoding::UTF8.GetBytes(_inputString),0, System.Text.Encoding::UTF8.GetByteCount(_input));

Debuggable (semio-pseudo) code:

inputBytes  = System.Text.Encoding::UTF8.GetBytes(_input)
inputLength = System.Text.Encoding::UTF8.GetByteCount(_input)
hashBytes   = convertedArr = sh.ComputeHash(inputBytes, 0, inputLength);

With this the input and length can easily be verified. The chance of the error is less because _input is only used once.

Note: In practice I would get the length from inputBytes but I am not fluent in X++ so I did not make that change.


问:
Injected bean reset to NULL in the Aspect
I am new Spring AOP and Aspectj. I have seen various posts related to injected bean in an aspect being null and I have run into a similar problem. I am still not clear how I should proceed to get past the problem I am currently encountering.

Issue: Currently we are using Spring 3.2.3 and all injection is through Annotation. In my case, the dependent bean is injected properly by Spring but at the point of execution the injected bean is NULL. BTW, this doesn't happen all the time but what I  can say is the stack trace when it fails and when it succeeds is slightly different. When the injected bean is not null (I can successfully use the injected bean service), the call to the before advice (in the aspect) always happens before the target method is called as it should.When the injected bean is NULL, the call to the aspect is from the first statement of the target method. At this point, I think another aspect is instantiated and has no reference to the injected bean. Here is the aspect I have created:

```<code>@Component
@Aspect
public class Enable{

       private NameService nameService;

       @Autowired
       public void SetNameService(NameSerice service){
            // service is injected properly
            this.nameSerice = service;
       }

       @Before("* *.*(..)")
       public void callBefore(JoinPoint jp){
            //sometimes nameService is null and sometimes it not not
            this.nameService.lookup(...);
       }
}
</code>```

Examining the various posts, one way to get around this (as suggested in the post) is to configure the aspect in the XML configuration file and use the factory-method ="aspectOf" and in the configuration inject the reference to the NameService bean as a property. Our whole project uses Annotation based injection (as stated earlier). Assuming I can still configure the above aspect in an XML configuration file, how can I get the reference NameService bean Id so that I can add it to the configuration. I also saw a post related to using Configurable annotation but I assume that is for objects created outside the Spring IOC.

Currently, the aspects are woven using Aspectj compile option in pom.xml. Our root-context.xml contains the entry context:annotation-config and the aspect is injected into Spring IOC because component-scan is turned on for the folder where the aspect resides. Any help will be appreciated

答:
It might be too late to answer this question. But i have come across the same situation and i fixed it as below.

1) Have a setter and getter for "NameService" in your aspect class.
2) Mark "NameService" with @Component ("nameService")
3) Configure "nameService" in xml configuration using setter injection.
4) Re-Start your server after making changes.

This should resolve the problem of getting null for "NameService" in aspect.

Body:
I am new Spring AOP and Aspectj. I have seen various posts related to injected bean in an aspect being null and I have run into a similar problem. I am still not clear how I should proceed to get past the problem I am currently encountering.

Issue: Currently we are using Spring 3.2.3 and all injection is through Annotation. In my case, the dependent bean is injected properly by Spring but at the point of execution the injected bean is NULL. BTW, this doesn't happen all the time but what I  can say is the stack trace when it fails and when it succeeds is slightly different. When the injected bean is not null (I can successfully use the injected bean service), the call to the before advice (in the aspect) always happens before the target method is called as it should.When the injected bean is NULL, the call to the aspect is from the first statement of the target method. At this point, I think another aspect is instantiated and has no reference to the injected bean. Here is the aspect I have created:

@Component
@Aspect
public class Enable{

       private NameService nameService;

       @Autowired
       public void SetNameService(NameSerice service){
            // service is injected properly
            this.nameSerice = service;
       }

       @Before("* *.*(..)")
       public void callBefore(JoinPoint jp){
            //sometimes nameService is null and sometimes it not not
            this.nameService.lookup(...);
       }
}

Examining the various posts, one way to get around this (as suggested in the post) is to configure the aspect in the XML configuration file and use the factory-method ="aspectOf" and in the configuration inject the reference to the NameService bean as a property. Our whole project uses Annotation based injection (as stated earlier). Assuming I can still configure the above aspect in an XML configuration file, how can I get the reference NameService bean Id so that I can add it to the configuration. I also saw a post related to using Configurable annotation but I assume that is for objects created outside the Spring IOC.

Currently, the aspects are woven using Aspectj compile option in pom.xml. Our root-context.xml contains the entry context:annotation-config and the aspect is injected into Spring IOC because component-scan is turned on for the folder where the aspect resides. Any help will be appreciated


问:
Palindrome checker not giving all correct values when looped
I'm trying to check if the product of a series of numbers (from 100 to 999) are palindromes. I have my palindrome checker working, but when I try to incorporate it into my loop I don't get all the possible answers.

```<code>def pali_check(n):
  n = str(n)
  pali = n[::-1]
  if pali == n:
   print(pali)

for x in range(999,99,-1):
  product = x*(x+1)
  pali_check(product)
</code>```

I should be getting all palindromes in this range (ex. one is 906609)

However, the only value I get is 289982. How can I fix my code so that it gives me all possible results?

答:
```<code>906609 = 913 * 993
</code>```

Since you are only checking n*(n+1), you wont find that one

On the other hand,

```<code>289982 = 538 * 539
</code>```

so that is why you are finding it

You should try using a nested loop and multiply the two loop variables together

```<code>for x in range(999, 99, -1):
    for y in range(999, 99, -1):
        product = x * y
        pali_check(product)
</code>```

You can easily optimise the above to prevent duplicates

Body:
I'm trying to check if the product of a series of numbers (from 100 to 999) are palindromes. I have my palindrome checker working, but when I try to incorporate it into my loop I don't get all the possible answers.

def pali_check(n):
  n = str(n)
  pali = n[::-1]
  if pali == n:
   print(pali)

for x in range(999,99,-1):
  product = x*(x+1)
  pali_check(product)

I should be getting all palindromes in this range (ex. one is 906609)

However, the only value I get is 289982. How can I fix my code so that it gives me all possible results?

Body:
906609 = 913 * 993

Since you are only checking n*(n+1), you wont find that one

On the other hand,

289982 = 538 * 539

so that is why you are finding it

You should try using a nested loop and multiply the two loop variables together

for x in range(999, 99, -1):
    for y in range(999, 99, -1):
        product = x * y
        pali_check(product)

You can easily optimise the above to prevent duplicates


问:
Internal Server Error .htaccess -
I have migrated my web page to a own hosting created with xubuntu. I have moved everything but at the time of publishing new content, I have the error of "'LimitInternalRecursion' in my log,
I have tried to uninstall the plugins (all), change the theme and it does not work for me. in my .htaccess I have the following configuration:

ERROR LOG:

any ideas?

答:
You should charter "#" from the line 5. The .htaccess should looks as this:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code>```

More information about the WordPress' htaccess file you can find on the link below:
https://codex.wordpress.org/htaccess

Title: Internal Server Error .htaccess -

Body:
You should charter "#" from the line 5. The .htaccess should looks as this:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

More information about the WordPress' htaccess file you can find on the link below:
https://codex.wordpress.org/htaccess


问:
PyAudio and Decibel change and panning
I have a pretty basic pyaudio code that plays a wav file.

```<code>    open_wave = wave.open("tone_silence/l0r1d0_500.wavc",'rb')

    pyAudio_session = pyaudio.PyAudio()

    def callback(in_data, frame_count, time_info, status):
        data = open_wave.readframes(frame_count)
        return (data, pyaudio.paContinue)
    pyAudio_stream = pyAudio_session.open(
        format = pyAudio_session.get_format_from_width(open_wave.getsampwidth()),
        channels = open_wave.getnchannels(),
        rate = open_wave.getframerate(),
        output = True,
        stream_callback=callback)

    while pyAudio_stream.is_active():
        time.sleep(0.1)

    pyAudio_stream.stop_stream()
    pyAudio_stream.close()
    print("Stopped")
    pyAudio_session.terminate()
</code>```

I have searched every corner of the internet to find a way such that I can change the Decibel level of the stream and pan the stereo output to a specific channel (left speaker only/right speaker only) as per need. But I could not find any method.

I cannot shift to pydub (which actually has this features) because it does not let me close the stream at any time; it plays the full audio and cannot be closed abruptly.

答:
While pydub does not have a direct way to stop audioSegment play, According to this documentation, it breaks the audio in to half-second chunks to facilitate keyboard interrupts.

Thus if we take audio and run through a while loop within a try-except block, we should be able to break the play using "Ctrl + c"

Here is a working sample code that pans audio to left or right channel as per documentation from here and then uses above logic to stop playing upon "Ctrl + c"

```<code>from pydub import AudioSegment
from pydub.playback import play

song = AudioSegment.from_wav("music.wav")

# pan the sound 15% to the right
panned_right = song.pan(+0.15)

# pan the sound 50% to the left
panned_left = song.pan(-0.50)

#Play panned left audio
while True:
    try:
        play(panned_left)
    except KeyboardInterrupt:
        print "Stopping playing"
        break
</code>```

We get IDLE session prompt back upon breaking from play loop. You can tailor that your needs.

```<code>Output:
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Stopping playing
>>>
</code>```

This gives you ease of using built-in panning methods within pydub and also a hack to interrupt play-back mid-stream. Hope this help you with your problem.

EDIT-1

Above solution may run into problem that while loop will play indefinitely (if you don't break it.). It's may be good for testing only.

Another option is to use python multiprocess module to spawn a process that plays an audio segment and terminate it when not needed. This gives more control during playback.

Here is an example.

```<code>from multiprocessing import Process

def play_audio(seg):
    play(seg)

if __name__ == '__main__':
    p = Process(target=play_audio, args=(panned_left,))
    p.start()
</code>```

When you need audio to be stopped, simply invoke p.terminate() either in IDE  or in program.

```<code>Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
>>> p.terminate()
>>>
</code>```

Title: PyAudio and Decibel change and panning

Body:
I have a pretty basic pyaudio code that plays a wav file.

    open_wave = wave.open("tone_silence/l0r1d0_500.wavc",'rb')

    pyAudio_session = pyaudio.PyAudio()

    def callback(in_data, frame_count, time_info, status):
        data = open_wave.readframes(frame_count)
        return (data, pyaudio.paContinue)
    pyAudio_stream = pyAudio_session.open(
        format = pyAudio_session.get_format_from_width(open_wave.getsampwidth()),
        channels = open_wave.getnchannels(),
        rate = open_wave.getframerate(),
        output = True,
        stream_callback=callback)

    while pyAudio_stream.is_active():
        time.sleep(0.1)

    pyAudio_stream.stop_stream()
    pyAudio_stream.close()
    print("Stopped")
    pyAudio_session.terminate()

I have searched every corner of the internet to find a way such that I can change the Decibel level of the stream and pan the stereo output to a specific channel (left speaker only/right speaker only) as per need. But I could not find any method.

I cannot shift to pydub (which actually has this features) because it does not let me close the stream at any time; it plays the full audio and cannot be closed abruptly.

Body:
While pydub does not have a direct way to stop audioSegment play, According to this documentation, it breaks the audio in to half-second chunks to facilitate keyboard interrupts.

Thus if we take audio and run through a while loop within a try-except block, we should be able to break the play using "Ctrl + c"

Here is a working sample code that pans audio to left or right channel as per documentation from here and then uses above logic to stop playing upon "Ctrl + c"

from pydub import AudioSegment
from pydub.playback import play

song = AudioSegment.from_wav("music.wav")

# pan the sound 15% to the right
panned_right = song.pan(+0.15)

# pan the sound 50% to the left
panned_left = song.pan(-0.50)

#Play panned left audio
while True:
    try:
        play(panned_left)
    except KeyboardInterrupt:
        print "Stopping playing"
        break

We get IDLE session prompt back upon breaking from play loop. You can tailor that your needs.

Output:
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Stopping playing
>>>

This gives you ease of using built-in panning methods within pydub and also a hack to interrupt play-back mid-stream. Hope this help you with your problem.

EDIT-1

Above solution may run into problem that while loop will play indefinitely (if you don't break it.). It's may be good for testing only.

Another option is to use python multiprocess module to spawn a process that plays an audio segment and terminate it when not needed. This gives more control during playback.

Here is an example.

from multiprocessing import Process

def play_audio(seg):
    play(seg)

if __name__ == '__main__':
    p = Process(target=play_audio, args=(panned_left,))
    p.start()

When you need audio to be stopped, simply invoke p.terminate() either in IDE  or in program.

Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
>>> p.terminate()
>>>


问:
Python condensing tuple's to first value
I have a list of tuples that output </p>

```<code>[('city 1', '#' ), ('city 1', '#' ), ('city 2', '#' ), ('city 2', '#'), etc...]
</code>```

<p>What I need to do is to add up all of each city's # value and output a list such that: </p>

```<code>[('city 1', 'sumof#' ), ('city 2', 'sumof#' ), ('city 3', 'sumof#' ), ('city 4', 'sumof#'), etc...]
</code>```

答:
You can do without importing any external module, just create some logic here :

```<code>data=[('city 1', 1), ('city 1', 3), ('city 2', 5 ), ('city 2', 9)]

def sum_tuples(data):
    track={}
    for i in data:
        if i[0] not in track:
            track[i[0]]=i[1]
        else:
            track[i[0]]+=i[1]

    return [(key,value) for key,value in track.items()]
print(sum_tuples(data))
</code>```

output:

```<code>[('city 1', 4), ('city 2', 14)]
</code>```

Body:
I have a list of tuples that output

[('city 1', '#' ), ('city 1', '#' ), ('city 2', '#' ), ('city 2', '#'), etc...]

What I need to do is to add up all of each city's # value and output a list such that:

[('city 1', 'sumof#' ), ('city 2', 'sumof#' ), ('city 3', 'sumof#' ), ('city 4', 'sumof#'), etc...]

Body:
You can do without importing any external module, just create some logic here :

data=[('city 1', 1), ('city 1', 3), ('city 2', 5 ), ('city 2', 9)]

def sum_tuples(data):
    track={}
    for i in data:
        if i[0] not in track:
            track[i[0]]=i[1]
        else:
            track[i[0]]+=i[1]

    return [(key,value) for key,value in track.items()]
print(sum_tuples(data))

output:

[('city 1', 4), ('city 2', 14)]


问:
UITableView problem with asynchronous image loading
So this is my problem:
I have an UITableView with custom UITableViewCells. Each one of the cells have one UIImageView which downloads an remote image using asynchronous image loading.

It's working ALMOST perfectly, but I have this weird issue.

When the view is loaded I can see the 5 or 6 first cells without scrolling (iPhone's display height).

The problem is: the image of each cell doesn't appear at this moment. Scrolling the table to the bottom, the cells #7~end loads perfectly.

The WEIRD fact is: when I scroll back to the top, now the 5 or 6 cells loads perfectly.

My first thought was: when the view is loaded, the cellForRowAtIndexPath method was not calling loadimage method automatically for the first cells, just after user interaction.

But using NSLog (step by step) to find where is the problem, the thing is:

cellForRowAtIndexPath calls the loadimage method

inside loadimage method, the NSURLConnection is created

NSURLConnection didReceiveData's method is not being called

So, the loadimage method is being called, indeed. But not receiving data.

Scrolling to the bottom and then going back to the top cells, it's all ok.
The word is WEIRD.

答: Check out HJCache, which is made to make this problem easy, it provides full management of asynchrounous image download, UIImage object sharing, and a file cache that you can configure and can clean itself up: HJCache: iPhone cache library for asynchronous image loading and caching</p>


问:
CngKey.Import on azure
```<code>var rawData = Convert.FromBase64String(_signingKey);
var cng = CngKey.Import(rawData, CngKeyBlobFormat.Pkcs8PrivateBlob);
</code>```

I use this code to extract key, from embedded base64 string.
It works fine when I test it locally but when I publish on azure I get following exception:

```<code>WindowsCryptographicException: The system cannot find the file specified
</code>```

(once again I'm not reading from any file)
I need this to communicate with apple apns for push notifications, is there any workaround?
And this happens only on free service plan, if I switch to basic plan it's working.

答:
I've had a similar error trying to construct a X509Certificate2 from a byte array - worked fine locally but once I deploy to Azure Web App, I got the same and VERY misleading file not found exception.

The real issue turned out to be that there was no user store associated with the web service account. You can also get a similar error if there are permission-related errors with accessing the certificate store on Windows.

In any case - In my scenario I fixed the problem by using MachineKeySet:
new X509Certificate2(certRawBytes, default(string), X509KeyStorageFlags.MachineKeySet);

So, in your scenario, try something like:

```<code>var keyParams = new CngKeyCreationParameters
{
  KeyCreationOptions = CngKeyCreationOptions.MachineKey,
};
CngKey.Create(CngAlgorithm.Rsa, keyName, keyParams);
</code>```

Note: You may have to set a few parameters to get the above working. The Import method doesn't seem to support MachineKey - but you should be able to achieve similar outcome by using the Create method.

Title: CngKey.Import on azure

Body:
var rawData = Convert.FromBase64String(_signingKey);
var cng = CngKey.Import(rawData, CngKeyBlobFormat.Pkcs8PrivateBlob);

I use this code to extract key, from embedded base64 string.
It works fine when I test it locally but when I publish on azure I get following exception:

WindowsCryptographicException: The system cannot find the file specified

(once again I'm not reading from any file)
I need this to communicate with apple apns for push notifications, is there any workaround?
And this happens only on free service plan, if I switch to basic plan it's working.

Body:
I've had a similar error trying to construct a X509Certificate2 from a byte array - worked fine locally but once I deploy to Azure Web App, I got the same and VERY misleading file not found exception.

The real issue turned out to be that there was no user store associated with the web service account. You can also get a similar error if there are permission-related errors with accessing the certificate store on Windows.

In any case - In my scenario I fixed the problem by using MachineKeySet:
new X509Certificate2(certRawBytes, default(string), X509KeyStorageFlags.MachineKeySet);

So, in your scenario, try something like:

var keyParams = new CngKeyCreationParameters
{
  KeyCreationOptions = CngKeyCreationOptions.MachineKey,
};
CngKey.Create(CngAlgorithm.Rsa, keyName, keyParams);

Note: You may have to set a few parameters to get the above working. The Import method doesn't seem to support MachineKey - but you should be able to achieve similar outcome by using the Create method.


问:
Weird RNG behavior in C++11 when defined and called in different places
I'm trying to write a multi-file program including the following code related to random number generation:

in help.h file:

```<code>extern random_device rand_dev;
extern ranlux48 rand_eng;
extern uniform_real_distribution<> zero2one_dist;
</code>```

in help.cpp file:

```<code>#include "help.h"
random_device rand_dev;
ranlux48 rand_eng{ rand_dev() };
uniform_real_distribution<> zero2one_dist(0, 1);
</code>```

in main.cpp file

```<code>#include "help.h"
//identical as help.cpp, just for illustration of the problem
random_device rand_dev1;
ranlux48 rand_eng1{ rand_dev1() };
uniform_real_distribution<> zero2one_dist1(0, 1);
//random number generation
float rnd1 = zero2one_dist1(rand_eng1);
float rnd2 = zero2one_dist(rand_eng);
//main function
int main()
{
    //another random number generation.
    float rnd3 = zero2one_dist(rand_eng);
    //output
    cout << rnd1 << endl << rnd2 << endl << rnd3 << endl;
    return 0;
}
</code>```

The desired result is outputting three random number between 0 and 1, however, rnd1 and rnd3 generates proper result but rnd2 keeps 0?!

I'm totally confused here, what's the difference between definitions in external file help.h and in main.cpp and what's the difference between a call inside and outside main()?

In my real work, I would need to write the code in the form of rnd2, but now it won't work and I don't know why.

Can anyone illustrate the difference between rnd1, rnd2 and rnd3 and get rnd2 to work? Thanks!

答:
There is no guarantee for the initialization order across translation units. rnd2 may be initialized before or after zero2one_dist. Use form rnd3 if you really want an external distribution object, or a helper function, for instance:

```<code>float rand_zero2one()
{
   static random_device rand_dev;
   static ranlux48 rand_eng{ rand_dev() };
   static uniform_real_distribution<> zero2one_dist(0, 1);
   return zero2one_dist(rand_eng);
}
</code>```

This guarantees the static variables are initialized before the function is first called. Put it in your help file and make that available instead of the extern variables.

Or even better, if your intent is to make it a singleton, do so. Put those into a singleton class and then use MySingletonGenerator::instance().nextValue().

Body:
I'm trying to write a multi-file program including the following code related to random number generation:

in help.h file:

extern random_device rand_dev;
extern ranlux48 rand_eng;
extern uniform_real_distribution<> zero2one_dist;

in help.cpp file:

#include "help.h"
random_device rand_dev;
ranlux48 rand_eng{ rand_dev() };
uniform_real_distribution<> zero2one_dist(0, 1);

in main.cpp file

#include "help.h"
//identical as help.cpp, just for illustration of the problem
random_device rand_dev1;
ranlux48 rand_eng1{ rand_dev1() };
uniform_real_distribution<> zero2one_dist1(0, 1);
//random number generation
float rnd1 = zero2one_dist1(rand_eng1);
float rnd2 = zero2one_dist(rand_eng);
//main function
int main()
{
    //another random number generation.
    float rnd3 = zero2one_dist(rand_eng);
    //output
    cout << rnd1 << endl << rnd2 << endl << rnd3 << endl;
    return 0;
}

The desired result is outputting three random number between 0 and 1, however, rnd1 and rnd3 generates proper result but rnd2 keeps 0?!

I'm totally confused here, what's the difference between definitions in external file help.h and in main.cpp and what's the difference between a call inside and outside main()?

In my real work, I would need to write the code in the form of rnd2, but now it won't work and I don't know why.

Can anyone illustrate the difference between rnd1, rnd2 and rnd3 and get rnd2 to work? Thanks!

Body:
There is no guarantee for the initialization order across translation units. rnd2 may be initialized before or after zero2one_dist. Use form rnd3 if you really want an external distribution object, or a helper function, for instance:

float rand_zero2one()
{
   static random_device rand_dev;
   static ranlux48 rand_eng{ rand_dev() };
   static uniform_real_distribution<> zero2one_dist(0, 1);
   return zero2one_dist(rand_eng);
}

This guarantees the static variables are initialized before the function is first called. Put it in your help file and make that available instead of the extern variables.

Or even better, if your intent is to make it a singleton, do so. Put those into a singleton class and then use MySingletonGenerator::instance().nextValue().


问:
Github release vs actual software version
Does anyone know what is the difference between a GitHub release and the actual release that software company announces?

I'm trying to find the different versions of vue.js, on the vue.js official website there are only two versions but on the GitHub repository many releases I was wondered if the two concepts are different?

答:
Release(may be downloadable link) version is just file which is uploaded.

Just they decide to provide only two version(may be latest) on official site.

It is all. If same version, (should be) same file. It is just like top selling tag on a store.


问:
Create functions in Python NLTK to get information retrieval
I am a beginner in using Python NLTK to create inverted index to get information retrieval.

The function makeInvertedIndex which I successfully created is to take a dict variable rdes_list as input, the output is an inverted index dictionary.
For example:

input rdes_list = {1:'hello world',2:'hello',3:'hello cat',4:'hellolot of cats'}

output index_dict = {'hello': [0, 1, 2], 'cat': [2], 'of': [3], 'world': [0], 'cats': [3], 'hellolot': [3]}

Based on the above function, I meet the problem to create other two functions:
The first one is to create a orSearch (invertedIndex, query)function, which takes an inverted index (i.e., index_dict) and query (i.e., a list of words), then returns the set of document numbers specifying all documents that contain any of the words in query.

The second one is to create a andSearch (invertedIndex, query)function, which takes an inverted index (i.e., index_dict) and query (i.e., a list of words), then returns the set of document numbers specifying all documents that contain all of the words in query.

答:
I offer the following solution:

```<code>output_index_dict = {'hello': [0, 1, 2], 'cat': [2], 'of': [3], 'world': [0], 'cats': [3], 'hellolot': [3]}

def orSearch (invertedIndex, query):
    result = []
    for key, value in invertedIndex.items():
        if key in query:
            result.append(value)
    relevant_documents = [index for indexes in result for index in indexes]
    return set(relevant_documents)

>>> orSearch(output_index_dict, ['of', 'hello', 'cat'])
output : {0, 1, 2, 3}

def andSearch (invertedIndex, query):
    result = []
    for key, value in invertedIndex.items():
        if key in query:
            result.append(value)
    common_indexes = set.intersection(*map(set,result))
    return common_indexes

>>> andSearch(output_index_dict, ['hellolot', 'of', 'cats'])
output : {3}
</code>```

Hope I did not miss something in your request.

Body:
I offer the following solution:

output_index_dict = {'hello': [0, 1, 2], 'cat': [2], 'of': [3], 'world': [0], 'cats': [3], 'hellolot': [3]}

def orSearch (invertedIndex, query):
    result = []
    for key, value in invertedIndex.items():
        if key in query:
            result.append(value)
    relevant_documents = [index for indexes in result for index in indexes]
    return set(relevant_documents)

>>> orSearch(output_index_dict, ['of', 'hello', 'cat'])
output : {0, 1, 2, 3}

def andSearch (invertedIndex, query):
    result = []
    for key, value in invertedIndex.items():
        if key in query:
            result.append(value)
    common_indexes = set.intersection(*map(set,result))
    return common_indexes

>>> andSearch(output_index_dict, ['hellolot', 'of', 'cats'])
output : {3}

Hope I did not miss something in your request.


问:
Java Ragged Array, trying to display multiple Arrays
I am having trouble finding out what is the issue with my code,  Everything is fine till I get to the Jagged array. I want it to display the code as a jagged array but I dont know</p>
```<code>package ajk;

public class Test2
{

    public static void main(String[] args)
        int[][] twoD = {
            {1, 2},
            {3, 4, 5},
            {6},
            {7, 8, 9},
        };
        printArray(twoD);
    }
    public static void printArray(int[][] arr) {
        System.out.println("[");

        int r = 4;
        int c = 3;
        int i, j;

        for (i=0; i < r; i++ );
            System.out.print("[");
            for (j=0; j < c; j++ ) {
                System.out.print( arr[i][j]  + " " );
            }
        }
    }
}
</code>```

答:
You are making some mistakes in your code

1.Always put the code of for loop in curly braces like this for(){}

2.You are making a general mistake by making the array index out of bounds for that you should use array[i].length to make sure column size are not different from each other

3.your code should look like this so change and try the code below

```<code> public class Test2
 {

public static void main(String[] args){
int[][] twoD = {
        {1, 2},
        {3, 4, 5},
        {6},
        {7, 8, 9}
};
Test2.printArray(twoD);
}
public static void printArray(int[][] arr) {
System.out.println("[");

int r = 4;
int c = 3;
int i, j,a=0;

for(i=0; i<r; i++ ){
System.out.print("[");
for (j=0; j<arr[i].length; j++ ) {
    System.out.print( arr[i][j]  + " " );

}
System.out.println("]");
 }
 }
}
</code>```

And

I have also added another square bracket for better understanding

ContentLicense: CC BY-SA 4.0

Body:
I am having trouble finding out what is the issue with my code,  Everything is fine till I get to the Jagged array. I want it to display the code as a jagged array but I dont know

package ajk;

public class Test2
{

    public static void main(String[] args)
        int[][] twoD = {
            {1, 2},
            {3, 4, 5},
            {6},
            {7, 8, 9},
        };
        printArray(twoD);
    }
    public static void printArray(int[][] arr) {
        System.out.println("[");

        int r = 4;
        int c = 3;
        int i, j;

        for (i=0; i < r; i++ );
            System.out.print("[");
            for (j=0; j < c; j++ ) {
                System.out.print( arr[i][j]  + " " );
            }
        }
    }
}

Body:
You are making some mistakes in your code

1.Always put the code of for loop in curly braces like this for(){}

2.You are making a general mistake by making the array index out of bounds for that you should use array[i].length to make sure column size are not different from each other

3.your code should look like this so change and try the code below

 public class Test2
 {

public static void main(String[] args){
int[][] twoD = {
        {1, 2},
        {3, 4, 5},
        {6},
        {7, 8, 9}
};
Test2.printArray(twoD);
}
public static void printArray(int[][] arr) {
System.out.println("[");

int r = 4;
int c = 3;
int i, j,a=0;

for(i=0; i<r; i++ ){
System.out.print("[");
for (j=0; j<arr[i].length; j++ ) {
    System.out.print( arr[i][j]  + " " );

}
System.out.println("]");
 }
 }
}

And

I have also added another square bracket for better understanding


问:
How do I get the directory where a Bash script is located from within the script itself?
How do I get the path of the directory in which a Bash script is located, inside that script?

I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:

```<code>$ ./application
</code>```

答:
I usually do:</p>

```<code>LIBDIR=$(dirname "$(readlink -f "$(type -P $0 || echo $0)")")
source $LIBDIR/lib.sh
</code>```

OwnerDisplayName: Jim Robert

Body:
How do I get the path of the directory in which a Bash script is located, inside that script?

I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:

$ ./application

Body:
I usually do:

LIBDIR=$(dirname "$(readlink -f "$(type -P $0 || echo $0)")")
source $LIBDIR/lib.sh

OwnerDisplayName: Tokland

LastEditorDisplayName: Tokland


问:
WPF combine two collections in one DataGrid
I have two collections that I want to display together in one table. I intend to use a horizontal DataGrid for this, and I'm trying to figure out what the best way is to expose the collections to the DataGrid.
(a horizontal DataGrid solution is described here: WPF horizontal DataGrid )

A bit of a nonsensical example with chairs and tables. In my application I have a list of tables and a list of chairs (both Table and a Chair have a Date and NumberOfItems property):

```<code>public List<Table> TableList { get; set; }
public List<Table> ChairList { get; set; }
</code>```

In xaml I want to DataBind to a combined list so that I would get something like:

```<code>Date             | 01-Jan-2011 | 02-Jan-2011 | 03-Jan-2011 | 04-Jan-2011
Number of tables |     5       |     6       |             |     7
Number of chairs |     3       |             |     2       |
</code>```

The TableList and ChairList do not have the same number of items.
What would be the best approach to expose a bindable combined collection?

答: Try the CompositeCollection class.  There's a good example here, including showing how to template for multiple item types in the composite list.  Once nice thing here is that you can either create the collection in code and expose it for binding, or build it in Xaml from two separately-bound collections.

Body:
I have two collections that I want to display together in one table. I intend to use a horizontal DataGrid for this, and I'm trying to figure out what the best way is to expose the collections to the DataGrid.
(a horizontal DataGrid solution is described here: WPF horizontal DataGrid )

A bit of a nonsensical example with chairs and tables. In my application I have a list of tables and a list of chairs (both Table and a Chair have a Date and NumberOfItems property):

public List
 TableList { get; set; }
public List
 ChairList { get; set; }

In xaml I want to DataBind to a combined list so that I would get something like:

Date             | 01-Jan-2011 | 02-Jan-2011 | 03-Jan-2011 | 04-Jan-2011
Number of tables |     5       |     6       |             |     7
Number of chairs |     3       |             |     2       |

The TableList and ChairList do not have the same number of items.
What would be the best approach to expose a bindable combined collection?


问:
Creating new column with letters v from beginning to last row
How do I add a new empty column with the letters 'v' from beginning to the last row.

df1:

```<code>    AM
0   MA
1   Ming
2   Mo
</code>```

Desired output for df1:

```<code>    AM    C
0   MA    v
1   Ming  v
2   Mo    v
</code>```

I get error: AttributeError: 'DataFrame' object has no attribute 'Sample'

When  I try this:

```<code>df1["C"] = np.nan
df1
df1["C"] = df1.Sample.str['v']
</code>```

答:
I think you are looking for this.</p>

```<code>df1['C'] = 'V'
</code>```

Body:
How do I add a new empty column with the letters 'v' from beginning to the last row.

df1:

    AM
0   MA
1   Ming
2   Mo

Desired output for df1:

    AM    C
0   MA    v
1   Ming  v
2   Mo    v

I get error: AttributeError: 'DataFrame' object has no attribute 'Sample'

When  I try this:

df1["C"] = np.nan
df1
df1["C"] = df1.Sample.str['v']

Body:
I think you are looking for this.

df1['C'] = 'V'


问:
Laravel - Composer Autoload Error
I have created a file in App\Helpers\Common.php. Inside this file I have defined some constants. In local it works great but when I uploaded it in a shared host, it returns an error saying:

```<code>[04-Dec-2017 03:39:00 UTC] PHP Warning:  require(/home/bibbibco/public_html/main/vendor/composer/../../App/Helpers/common.php): failed to open stream: No such file or directory in /home/bibbibco/public_html/main/vendor/composer/autoload_real.php on line 66
[04-Dec-2017 03:39:00 UTC] PHP Fatal error:  require(): Failed opening required '/home/bibbibco/public_html/main/vendor/composer/../../App/Helpers/common.php' (include_path='.:/opt/alt/php71/usr/share/pear') in /home/bibbibco/public_html/main/vendor/composer/autoload_real.php on line 66
</code>```

I have added in composer.json:

```<code>"autoload": {
"files": [
    "App/Helpers/Common.php"
]
}
</code>```

to load the files, but it returns the error mentioned above.

How can I fix it?

答:
By default, the application directory in Laravel is app not App.

If you're using Windows either App/Helpers/Common.php or app/Helpers/Common.php will work because paths are not case-sensitive. Using Linux, app and App are distinct so only app/Helpers/Common.php will work.

Title: Laravel - Composer Autoload Error

Body:
I have created a file in App\Helpers\Common.php. Inside this file I have defined some constants. In local it works great but when I uploaded it in a shared host, it returns an error saying:

[04-Dec-2017 03:39:00 UTC] PHP Warning:  require(/home/bibbibco/public_html/main/vendor/composer/../../App/Helpers/common.php): failed to open stream: No such file or directory in /home/bibbibco/public_html/main/vendor/composer/autoload_real.php on line 66
[04-Dec-2017 03:39:00 UTC] PHP Fatal error:  require(): Failed opening required '/home/bibbibco/public_html/main/vendor/composer/../../App/Helpers/common.php' (include_path='.:/opt/alt/php71/usr/share/pear') in /home/bibbibco/public_html/main/vendor/composer/autoload_real.php on line 66

I have added in composer.json:

"autoload": {
"files": [
    "App/Helpers/Common.php"
]
}

to load the files, but it returns the error mentioned above.

How can I fix it?


问:
Why are the compile dependencies of my library leaking through?
I'm working with Gradle 3.4.1.

I have a library (let's call it utils) built with the Gradle java-library plugin which results in a nice JAR file. This is the dependencies section:

```<code>dependencies {
// public API
api group: "org.postgresql", name: "postgresql", version: "9.2-1004-jdbc4"
api group: "log4j", name: "log4j", version: "1.2.17"

// implementation specific
implementation group: "commons-configuration", name: "commons-configuration" , version: "1.10"
implementation group: "commons-lang", name: "commons-lang" , version: "2.6"
}
</code>```

Now my project includes this library as well as some other Apache Commons libraries:

```<code>dependencies {
compile group: "com.foo", name: "utils", version: "6.+", changing: true
compile group: "org.apache.commons", name: "commons-lang3", version: "3.5"
compile group: "commons-io", name: "commons-io" , version: "2.5"
}
</code>```

In my classpath for the project I have now the commons-lang library as well as the commons-lang3 library although I specified the appropriate dependencies as implementation! According to the docs https://docs.gradle.org/3.4.1/userguide/java_library_plugin.html this should be the correct way.

Here's the dependencies listing of my project:

```<code>default - Configuration for default artifacts.
+--- com.foo:utils:6.+ -> 6.0.0
|    +--- org.postgresql:postgresql:9.2-1004-jdbc4
|    +--- log4j:log4j:1.2.17
|    +--- commons-configuration:commons-configuration:1.10
|    |    +--- commons-lang:commons-lang:2.6
|    |    \--- commons-logging:commons-logging:1.1.1
|    \--- commons-lang:commons-lang:2.6
+--- org.apache.commons:commons-lang3:3.5
\--- commons-io:commons-io:2.5
</code>```

What am I doing wrong? How can I get rid of the external dependencies commons-lang and commons-configuration?

答:
There are several ways to exclude transitive dependencies, covered in several questions and in gradle documentation.

```<code>configurations {
    compile.transitive = false
}
</code>```

or

```<code>configurations.all {
    exclude group:"ch.qos.logback", module:"logback-core"
}
</code>```

or

```<code>dependencies {
    compile ('foo:bar:0.1') {
        exclude group: "org.slf4j", module: "slf4j-log4j12"
    }
}
</code>```

Body:
I'm working with Gradle 3.4.1.

I have a library (let's call it utils) built with the Gradle java-library plugin which results in a nice JAR file. This is the dependencies section:

dependencies {
// public API
api group: "org.postgresql", name: "postgresql", version: "9.2-1004-jdbc4"
api group: "log4j", name: "log4j", version: "1.2.17"

// implementation specific
implementation group: "commons-configuration", name: "commons-configuration" , version: "1.10"
implementation group: "commons-lang", name: "commons-lang" , version: "2.6"
}

Now my project includes this library as well as some other Apache Commons libraries:

dependencies {
compile group: "com.foo", name: "utils", version: "6.+", changing: true
compile group: "org.apache.commons", name: "commons-lang3", version: "3.5"
compile group: "commons-io", name: "commons-io" , version: "2.5"
}

In my classpath for the project I have now the commons-lang library as well as the commons-lang3 library although I specified the appropriate dependencies as implementation! According to the docs https://docs.gradle.org/3.4.1/userguide/java_library_plugin.html this should be the correct way.

Here's the dependencies listing of my project:

default - Configuration for default artifacts.
+--- com.foo:utils:6.+ -> 6.0.0
|    +--- org.postgresql:postgresql:9.2-1004-jdbc4
|    +--- log4j:log4j:1.2.17
|    +--- commons-configuration:commons-configuration:1.10
|    |    +--- commons-lang:commons-lang:2.6
|    |    \--- commons-logging:commons-logging:1.1.1
|    \--- commons-lang:commons-lang:2.6
+--- org.apache.commons:commons-lang3:3.5
\--- commons-io:commons-io:2.5

What am I doing wrong? How can I get rid of the external dependencies commons-lang and commons-configuration?

Body:
There are several ways to exclude transitive dependencies, covered in several questions and in gradle documentation.

configurations {
    compile.transitive = false
}

or

configurations.all {
    exclude group:"ch.qos.logback", module:"logback-core"
}

or

dependencies {
    compile ('foo:bar:0.1') {
        exclude group: "org.slf4j", module: "slf4j-log4j12"
    }
}


问:
Java cast ArrayList to C#
Need to cast a Java ArrayList to C# ArrayList.

It does not work.

```<code>//code in C#
public void DoSomething(Java.Lang.Object obj){
    Java.Util.ArrayList list = (Java.Util.ArrayList) obj;
}
</code>```

The Exception:

Unhandled Exception:

System.InvalidCastException: Specified cast is not valid.

When I print out obj.Class, it returns class java.util.ArrayList

How to fix it?

答:
I think you need this amazing library: https://www.ikvm.net/ by Jeroen Frijters & contributors.

IKVM.NET is an implementation of Java for Mono and the Microsoft .NET Framework. It includes the following components:

A Java Virtual Machine implemented in .NET

A .NET implementation of the Java class libraries

Tools that enable Java and .NET interoperability

This is such a massive subject, you'll have to do a few tutorials, eg Convert a Java Application to .NET. Good luck!

Title: Java cast ArrayList to C#

Body:
Need to cast a Java ArrayList to C# ArrayList.

It does not work.

//code in C#
public void DoSomething(Java.Lang.Object obj){
    Java.Util.ArrayList list = (Java.Util.ArrayList) obj;
}

The Exception:

Unhandled Exception:

System.InvalidCastException: Specified cast is not valid.

When I print out obj.Class, it returns class java.util.ArrayList

How to fix it?


问:
pass default value from graphql query in apollo to child
I am trying to pass graphql query value to my React component from the parent component's state. My method isn't work working because it's loading and isn't called again after it is done loading. Any recommendations on how to do this?</p>

```<code>class Parent extends Component {
   constructor(props) {
     super(props)
     const defaultSelectedId = (this.props.query && !this.props.query.loading) ?
           this.props.query.defaultId : ''
     this.state = {
         id: defaultSelectedId
     }
   render() {
      return(
<Child selectedId={this.state.id} />
)}}
</code>```

答:
Add </p>

```<code>componentWillReceiveProps(nextProps) {
const defaultSelectedId = (nextProps.query && !nextProps.query.loading) ?
           nextProps.query.defaultId : ''
     this.setState ({
         id: defaultSelectedId
     })

}
</code>```

Body:
I am trying to pass graphql query value to my React component from the parent component's state. My method isn't work working because it's loading and isn't called again after it is done loading. Any recommendations on how to do this?

class Parent extends Component {
   constructor(props) {
     super(props)
     const defaultSelectedId = (this.props.query && !this.props.query.loading) ?
           this.props.query.defaultId : ''
     this.state = {
         id: defaultSelectedId
     }
   render() {
      return(
<Child selectedId={this.state.id} />
)}}

Body:
Add

componentWillReceiveProps(nextProps) {
const defaultSelectedId = (nextProps.query && !nextProps.query.loading) ?
           nextProps.query.defaultId : ''
     this.setState ({
         id: defaultSelectedId
     })

}


问:
How to Search a String with spaces in between
i am new to VB. so when i run my program and search for the name . i want to search with any spaces in between. For example i want to search "    Brian    Tracy" like that

i am quite confused on the string function that would do that. Thank you for your help

This is the code am working on

```<code>Dim search As String = txtAuthorsName.Text

'Search Sql For Authors Data
Dim conn As New
OleDb.OleDbConnection("Provider=Microsoft.ACE.OleDb.12.0;Data Source=" +
                                          Server.MapPath("~/Access/bookstore.accdb"))
conn.Open()

Dim sql As String = "SELECT AID, authorName, authorSex FROM Authors"

Dim cmd As Object
If searchAuthor.SelectedValue.Equals("Name") Then
    If search.Length > 0 Then
       Dim keywords As String() = search.Split(" ")
       sql = "SELECT * FROM Authors where authorName like '%" & keywords(0) & "%'"
       For k As Integer = 1 To keywords.Length - 1
          sql += " or authorName Like '%" & keywords(k) & "%'"
       Next
    End If
    cmd = New OleDb.OleDbCommand(sql, conn)
    cmd.Parameters.AddWithValue("@authorName", "%" + txtAuthorsName.Text + "%")
Else
   sql += "WHERE authorSex LIKE @authorSex"
   cmd = New OleDb.OleDbCommand(sql, conn)
   cmd.Parameters.AddWithValue("@authorSex", "%" + txtAuthorSex.Text + "%")
End If

Dim dbread = cmd.ExecuteReader()
GridView2.DataSource = dbread
GridView2.DataBind()
dbread.Close()
conn.Close()
</code>```

答:
This is an example on how to filter/search data :

```<code>  Public Sub FilterData(valueToSearch As String)
    '
    Dim searchQuery As String = "SELECT * From Users WHERE CONCAT(fname, lname, age) like '%" & valueToSearch & "%'"

    Dim command As New SqlCommand(searchQuery, connection)
    Dim adapter As New SqlDataAdapter(command)
    Dim table As New DataTable()

    adapter.Fill(table)

    DataGridView1.DataSource = table

End Sub

Private Sub BTN_FILTER_Click(sender As Object, e As EventArgs) Handles BTN_FILTER.Click

    FilterData(TextBox1.Text)
</code>```

Make necessary changes, hope it works

Body:
i am new to VB. so when i run my program and search for the name . i want to search with any spaces in between. For example i want to search "    Brian    Tracy" like that

i am quite confused on the string function that would do that. Thank you for your help

This is the code am working on

Dim search As String = txtAuthorsName.Text

'Search Sql For Authors Data
Dim conn As New
OleDb.OleDbConnection("Provider=Microsoft.ACE.OleDb.12.0;Data Source=" +
                                          Server.MapPath("~/Access/bookstore.accdb"))
conn.Open()

Dim sql As String = "SELECT AID, authorName, authorSex FROM Authors"

Dim cmd As Object
If searchAuthor.SelectedValue.Equals("Name") Then
    If search.Length > 0 Then
       Dim keywords As String() = search.Split(" ")
       sql = "SELECT * FROM Authors where authorName like '%" & keywords(0) & "%'"
       For k As Integer = 1 To keywords.Length - 1
          sql += " or authorName Like '%" & keywords(k) & "%'"
       Next
    End If
    cmd = New OleDb.OleDbCommand(sql, conn)
    cmd.Parameters.AddWithValue("@authorName", "%" + txtAuthorsName.Text + "%")
Else
   sql += "WHERE authorSex LIKE @authorSex"
   cmd = New OleDb.OleDbCommand(sql, conn)
   cmd.Parameters.AddWithValue("@authorSex", "%" + txtAuthorSex.Text + "%")
End If

Dim dbread = cmd.ExecuteReader()
GridView2.DataSource = dbread
GridView2.DataBind()
dbread.Close()
conn.Close()

Body:
This is an example on how to filter/search data :

  Public Sub FilterData(valueToSearch As String)
    '
    Dim searchQuery As String = "SELECT * From Users WHERE CONCAT(fname, lname, age) like '%" & valueToSearch & "%'"

    Dim command As New SqlCommand(searchQuery, connection)
    Dim adapter As New SqlDataAdapter(command)
    Dim table As New DataTable()

    adapter.Fill(table)

    DataGridView1.DataSource = table

End Sub

Private Sub BTN_FILTER_Click(sender As Object, e As EventArgs) Handles BTN_FILTER.Click

    FilterData(TextBox1.Text)

Make necessary changes, hope it works


问:
Conflicting changes detected. This may happen when trying to insert multiple entities with the same key
I'm trying to have Auto Generated ID with EF6. The table in the Database has Identity set to yes on the PK. I keep getting the error "Conflicting changes detected. This may happen when trying to insert multiple entities with the same key.". I'm using Code First.
Model:

```<code> public partial class CurrentEquipmentOrderStatu
{

    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]

    public long CurrentEquipmentOrderStatusId { get; set; }

    public long? GPSInsightRowId { get; set; }

    [StringLength(50)]
    public string Status { get; set; }

    [StringLength(50)]
    public string TimeToJob { get; set; }

    public long? OrderEquipAssignmentId { get; set; }

    [StringLength(50)]
    public string DistanceToJob { get; set; }

    public long? EquipmentId { get; set; }

    public virtual Equipment Equipment { get; set; }

    public virtual GPSInsight GPSInsight { get; set; }

    public virtual OrderEquipAssignment OrderEquipAssignment { get; set; }
}
</code>```

Create and save method:

```<code> public static void CreateCurrentOrderStatus()
    {
        var Status = new List<CurrentEquipmentOrderStatu>();
        using (FFAELDB db = new FFAELDB())
        {
            db.Configuration.AutoDetectChangesEnabled = false;
            var EquipAssignments = db.OrderEquipAssignments;
            foreach(OrderEquipAssignment assign in EquipAssignments)
            {

                 db.CurrentEquipmentOrderStatus.Add(new CurrentEquipmentOrderStatu()
                {
                    EquipmentId = assign.EquipmentId,
                    OrderEquipAssignmentId = assign.OrderEquipAssignmentId,

                });

            }
            db.SaveChanges();

            db.Dispose();
        }

    }
</code>```

Any Help would be greatly appreciated.

答: There could be a problem with a foreign key. I had mapped my foreign key wrongly so I was getting this error. By correcting the FK and updating it in my Entity Framework it worked.</p>

Body:
I'm trying to have Auto Generated ID with EF6. The table in the Database has Identity set to yes on the PK. I keep getting the error "Conflicting changes detected. This may happen when trying to insert multiple entities with the same key.". I'm using Code First.
Model:

 public partial class CurrentEquipmentOrderStatu
{

    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]

    public long CurrentEquipmentOrderStatusId { get; set; }

    public long? GPSInsightRowId { get; set; }

    [StringLength(50)]
    public string Status { get; set; }

    [StringLength(50)]
    public string TimeToJob { get; set; }

    public long? OrderEquipAssignmentId { get; set; }

    [StringLength(50)]
    public string DistanceToJob { get; set; }

    public long? EquipmentId { get; set; }

    public virtual Equipment Equipment { get; set; }

    public virtual GPSInsight GPSInsight { get; set; }

    public virtual OrderEquipAssignment OrderEquipAssignment { get; set; }
}

Create and save method:

 public static void CreateCurrentOrderStatus()
    {
        var Status = new List<CurrentEquipmentOrderStatu>();
        using (FFAELDB db = new FFAELDB())
        {
            db.Configuration.AutoDetectChangesEnabled = false;
            var EquipAssignments = db.OrderEquipAssignments;
            foreach(OrderEquipAssignment assign in EquipAssignments)
            {

                 db.CurrentEquipmentOrderStatus.Add(new CurrentEquipmentOrderStatu()
                {
                    EquipmentId = assign.EquipmentId,
                    OrderEquipAssignmentId = assign.OrderEquipAssignmentId,

                });

            }
            db.SaveChanges();

            db.Dispose();
        }

    }

Any Help would be greatly appreciated.