问:
How to disable specific items of combobox programmatically by condition in wpf c#
I want to disable some specific items of combobox conditionally. For Example, I have two comboboxes (combobox1,combobox2), I want to disable some specific items of combobox2 (not to remove, just want to disable) according to selected item of combobox1.
My xaml codes are like that:

```<code>    <Grid>
    <ComboBox x:Name="combobox1" HorizontalAlignment="Left" Margin="142,99,0,0" VerticalAlignment="Top" Width="319">
        <ComboBoxItem>Choice1</ComboBoxItem>
        <ComboBoxItem>Choice2</ComboBoxItem>
        <ComboBoxItem>Choice3</ComboBoxItem>

    </ComboBox>
    <ComboBox x:Name="combobox2" HorizontalAlignment="Left" Margin="520,99,0,0" VerticalAlignment="Top" Width="358">
        <ComboBoxItem>Selection1</ComboBoxItem>
        <ComboBoxItem>Selection2</ComboBoxItem>
        <ComboBoxItem>Selection3</ComboBoxItem>
        <ComboBoxItem>Selection4</ComboBoxItem>
        <ComboBoxItem>Selection5</ComboBoxItem>
        <ComboBoxItem>Selection6</ComboBoxItem>
    </ComboBox>
</Grid>
</code>```

and C#  codes are like that:

```<code>    public partial class UC_Servis : UserControl
{
    public UC_Servis()
    {
        InitializeComponent();
    }
    private void combobox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        switch (combobox1.SelectedIndex)
        {
            case 0:
                combobox2.SelectedIndex = 0;
                break;
            case 1:
                combobox2.SelectedIndex = 1;
                break;
            case 2:
                combobox2.SelectedIndex = 2;
                break;
            default:
                break;
        }
        combobox2.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged);
    }
    private void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
    {
        if (combobox2.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
        {
            foreach (var a in combobox2.Items)
            {
                int currentPosition = combobox2.Items.IndexOf(a);
                ComboBoxItem cbi = (ComboBoxItem)combobox2.ItemContainerGenerator.ContainerFromIndex(currentPosition);

                switch (combobox1.SelectedIndex)
                {
                    case 0:
                        switch (a.ToString())
                        {
                            case "Selection4":
                            case "Selection5":
                                cbi.IsEnabled = false;
                                break;
                            default:
                                cbi.IsEnabled = true;
                                break;
                        }
                        break;
                    case 1:
                        switch (a.ToString())
                        {
                            case "Selection1":
                            case "Selection3":
                                cbi.IsEnabled = false;
                                break;
                            default:
                                cbi.IsEnabled = true;
                                break;
                        }
                        break;
                    case 2:
                        switch (a.ToString())
                        {
                            case "Selection2":
                            case "Selection6":
                                cbi.IsEnabled = false;
                                break;
                            default:
                                cbi.IsEnabled = true;
                                break;
                        }
                        break;

                    default:
                        break;
                }
            }
        }
    }

}
</code>```

When I run, there is no change, I could not make none of the items of combobox2 disabled.

How can I do that? what's wrong?

EXTRA QUESTION

If Comboboxes have static items, I accomplished to change displaying ability of combobox items by support of neelesh bodgal.
But, in my original study, comboboxes' item sources are binded to database, so items of comboboxes' items can change by situations. I tryed to adapt neelesh bodgal's codes to my original study, but all of the items are enabled.
in my original study xaml codes are like that:

```<code><Window x:Class="MyStudy.Pencereler.MamulStkConfig"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:MyStudy.Pencereler"
    xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
    mc:Ignorable="d"
    TextElement.Foreground="{DynamicResource MaterialDesignBody}"
    TextElement.FontWeight="Regular"
    TextElement.FontSize="13"
    TextOptions.TextFormattingMode="Ideal"
    TextOptions.TextRenderingMode="Auto"
    Background="{DynamicResource MaterialDesignPaper}"
    FontFamily="{DynamicResource MaterialDesignFont}"
    Title="MamulStkConfig" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" AllowsTransparency="True" WindowStyle="None" WindowState="Maximized" Width="1300" Height="700">
<Window.Resources>
    <local:TekerDisabler x:Key="tekerDisabler"/>
</Window.Resources>
<Grid>
                <ComboBox x:Name="Cbx_UrunGrubu" SelectionChanged="Cbx_UrunGrubu_SelectionChanged"  materialDesign:HintAssist.Hint="ÜRÜN GRUBU"  Style="{StaticResource MaterialDesignFloatingHintComboBox}" DisplayMemberPath="kodTipTanim" SelectedValuePath="kodTipId" />
                <ComboBox x:Name="Cbx_Secim1" SelectionChanged="Cbx_Secim1_SelectionChanged"  materialDesign:HintAssist.Hint="{Binding ElementName=txt_Hint1,Path=Text}"  Style="{StaticResource MaterialDesignFloatingHintComboBox}" DisplayMemberPath="TANIM" SelectedValuePath="KOD" />
                <ComboBox x:Name="Cbx_Secim2" SelectionChanged="Cbx_Secim2_SelectionChanged"  materialDesign:HintAssist.Hint="{Binding ElementName=txt_Hint2,Path=Text}"  Style="{StaticResource MaterialDesignFloatingHintComboBox}" DisplayMemberPath="TANIM" SelectedValuePath="KOD" />
                <ComboBox x:Name="Cbx_Secim3" SelectionChanged="Cbx_Secim3_SelectionChanged"  materialDesign:HintAssist.Hint="{Binding ElementName=txt_Hint3,Path=Text}"  Style="{StaticResource MaterialDesignFloatingHintComboBox}" DisplayMemberPath="TANIM" SelectedValuePath="KOD" />
                <ComboBox x:Name="Cbx_Ops10" SelectionChanged="Cbx_Ops10_SelectionChanged"  materialDesign:HintAssist.Hint="{Binding ElementName=txt_Hint10,Path=Text}"  Style="{StaticResource MaterialDesignFloatingHintComboBox}" DisplayMemberPath="TANIM" SelectedValuePath="KOD"  >
                <ComboBox.ItemContainerStyle>
                   <Style TargetType="ComboBoxItem">
                      <Setter Property="IsEnabled">
                         <Setter.Value>
                            <MultiBinding Converter="{StaticResource tekerDisabler}">
                              <Binding ElementName="Cbx_UrunGrubu" Path="SelectedItem"/>
                              <Binding ElementName="Cbx_Ops3" Path="SelectedItem"/>
                              <Binding ElementName="Cbx_Ops2" Path="SelectedItem"/>
                              <Binding RelativeSource="{RelativeSource Self}"/>
                            </MultiBinding>
                         </Setter.Value>
                      </Setter>
                   </Style>
                </ComboBox.ItemContainerStyle>
            </ComboBox>
</Grid>
</code>```

And MyStudy C# codes are like that:

```<code>    public class TekerDisabler : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        bool enable = true;
        var cbxUrunGrupSelectedItem = values[0] as ComboBoxItem;
        var cbxOp3SelectedItem = values[1] as ComboBoxItem;
        var cbxOp2SelectedItem = values[2] as ComboBoxItem;
        var cbxOp10Item = values[3] as ComboBoxItem;
        if (cbxUrunGrupSelectedItem == null || cbxOp2SelectedItem == null || cbxOp3SelectedItem == null || cbxOp10Item == null)
            return true;
        switch (cbxUrunGrupSelectedItem.Content.ToString())
        {
            case "DÖNERLİ PULLUK":
                switch (cbxOp3SelectedItem.Content.ToString())
                {
                    case "(100X100X10) Profil":
                        if (cbxOp10Item.Content.ToString() == "LASTİK TEKER BÜYÜK (10x80-12)") { enable = false; }
                        break;
                    case "(120X120X10) Profil":
                        switch (cbxOp2SelectedItem.Content.ToString())
                        {
                            case "3'LÜ (2+1)":
                            case "3'LÜ (3+0)":
                            case "3'LÜ (FLANŞSIZ)":
                                if (cbxOp10Item.Content.ToString() == "TEKERSİZ" || cbxOp10Item.Content.ToString() == "LASTİK TEKER BÜYÜK (10x80-12)")
                                { enable = false; }
                                break;
                            case "1'Lİ (1+0)":
                            case "1'Lİ (FLANŞSIZ)":
                            case "2'Lİ (1+1)":
                            case "2'Lİ (2+0)":
                            case "2'Lİ (FLANŞSIZ)":
                                if (cbxOp10Item.Content.ToString() == "LASTİK TEKER BÜYÜK (10x80-12)")
                                { enable = false; }
                                break;
                            default:
                                if (cbxOp10Item.Content.ToString() == "TEKERSİZ" || cbxOp10Item.Content.ToString() == "DEMİR TEKER" || cbxOp10Item.Content.ToString() == "LASTİK TEKER (20,5x8,00-10)")
                                { enable = false; }
                                break;
                        }
                        break;
                    case "(140X140X10) Profil":
                    case "(140X140X14) Profil":
                        if (cbxOp10Item.Content.ToString() == "TEKERSİZ" || cbxOp10Item.Content.ToString() == "DEMİR TEKER" || cbxOp10Item.Content.ToString() == "LASTİK TEKER (20,5x8,00-10)")
                        { enable = false; }
                        break;

                    default:
                        enable = true;
                        break;
                }
                break;
            default:
                break;
        }
        return enable;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

How can I overcome this problem?

答:
This is a another way of doing it using data binding.
This is working code. You can replace this code in your project and check.

```<code>  <UserControl x:Class="WpfApplication1.UserControl1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:WpfApplication1"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
    <local:Disabler x:Key="disabler"/>
</UserControl.Resources>
<Grid>
<ComboBox x:Name="combobox1" HorizontalAlignment="Left" Margin="142,99,0,0"
        VerticalAlignment="Top" Width="319">
        <ComboBoxItem>Choice1</ComboBoxItem>
        <ComboBoxItem>Choice2</ComboBoxItem>
        <ComboBoxItem>Choice3</ComboBoxItem>

    </ComboBox>

     <ComboBox x:Name="combobox2" HorizontalAlignment="Left" Margin="520,99,0,0" VerticalAlignment="Top" Width="358">
        <ComboBoxItem>Selection1</ComboBoxItem>
        <ComboBoxItem>Selection2</ComboBoxItem>
        <ComboBoxItem>Selection3</ComboBoxItem>
        <ComboBoxItem>Selection4</ComboBoxItem>
        <ComboBoxItem>Selection5</ComboBoxItem>
        <ComboBoxItem>Selection6</ComboBoxItem>

        <ComboBox.ItemContainerStyle>
            <Style TargetType="ComboBoxItem">
                <Setter Property="IsEnabled">
                    <Setter.Value>
                        <MultiBinding Converter="{StaticResource disabler}">
                            <!--Here you can bind the proper u want to use in -->
                            <!--converter to enable/ disable comboboxitem-->
                            <Binding ElementName="combobox1" Path="SelectedItem"/>

                            <!--Bind to the current comboboxitem which needs to enabled/disabled-->
                            <Binding RelativeSource="{RelativeSource Self}"/>
                        </MultiBinding>
                    </Setter.Value>
                </Setter>
            </Style>
        </ComboBox.ItemContainerStyle>
    </ComboBox>
</Grid>
</UserControl>
</code>```

Define the converter in the code behind as follows

```<code>    using System;
    using System.Globalization;
    using System.Windows.Controls;
    using System.Windows.Data;

    namespace WpfApplication1
    {
        /// <summary>
        /// Interaction logic for UserControl1.xaml
        /// </summary>
        public partial class UserControl1 : UserControl
        {
            public UserControl1()
            {
                InitializeComponent();
            }
        }

        class Disabler : IMultiValueConverter
        {
            public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
            {

                bool enable = true;
                var comboxbox1SelectedItem = values[0] as ComboBoxItem;
                var comboxbox2Item = values[1]  as ComboBoxItem;

                if (comboxbox1SelectedItem == null || comboxbox2Item == null)
                    return true;

                if (comboxbox1SelectedItem.Content.ToString() == "Choice1")
                {
                    if(comboxbox2Item.Content.ToString() == "Selection4" || (comboxbox2Item.Content.ToString() == "Selection5")){
                        enable = false;
                    }
                }
                else if (comboxbox1SelectedItem.Content.ToString() == "Choice2")
                {
                    if (comboxbox2Item.Content.ToString() == "Selection1" || (comboxbox2Item.Content.ToString() == "Selection3")){
                        enable = false;
                    }
                }
                else if (comboxbox1SelectedItem.Content.ToString() == "Choice3")
                {
                    if (comboxbox2Item.Content.ToString() == "Selection2" || (comboxbox2Item.Content.ToString() == "Selection6")){
                        enable = false;
                    }
                }
                return enable;
            }

            public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }
    }
</code>```

For more than one combobox deciding the enable/disable items, same example can be extended as follows

```<code>    <UserControl x:Class="WpfApplication1.UserControl1"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
     xmlns:local="clr-namespace:WpfApplication1"
     mc:Ignorable="d"
     d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>
       <local:Disabler x:Key="disabler"/>
       <local:Disabler2 x:Key="disabler2"/>
    </UserControl.Resources>
   <Grid>
   <ComboBox x:Name="combobox1" HorizontalAlignment="Left" Margin="142,99,0,0"
    VerticalAlignment="Top" Width="319">
    <ComboBoxItem>Choice1</ComboBoxItem>
    <ComboBoxItem>Choice2</ComboBoxItem>
    <ComboBoxItem>Choice3</ComboBoxItem>

   </ComboBox>

   <ComboBox x:Name="combobox2" HorizontalAlignment="Left" Margin="142,99,0,0"
    VerticalAlignment="Top" Width="319">
    <ComboBoxItem>Choice21</ComboBoxItem>
    <ComboBoxItem>Choice22</ComboBoxItem>
    <ComboBoxItem>Choice23</ComboBoxItem>

   </ComboBox>

 <ComboBox x:Name="combobox3" HorizontalAlignment="Left" Margin="520,99,0,0" VerticalAlignment="Top" Width="358">
    <ComboBoxItem>Selection1</ComboBoxItem>
    <ComboBoxItem>Selection2</ComboBoxItem>
    <ComboBoxItem>Selection3</ComboBoxItem>
    <ComboBoxItem>Selection4</ComboBoxItem>
    <ComboBoxItem>Selection5</ComboBoxItem>
    <ComboBoxItem>Selection6</ComboBoxItem>

    <ComboBox.ItemContainerStyle>
        <Style TargetType="ComboBoxItem">
            <Setter Property="IsEnabled">
                <Setter.Value>
                    <MultiBinding Converter="{StaticResource disabler2}">
                        <!--Here you can bind the proper u want to use in -->
                        <!--converter to enable/ disable comboboxitem-->
                        <Binding ElementName="combobox1" Path="SelectedItem"/>
                        <Binding ElementName="combobox2" Path="SelectedItem"/>
                        <!--Bind to the current comboboxitem which needs to enabled/disabled-->
                        <Binding RelativeSource="{RelativeSource Self}"/>
                    </MultiBinding>
                </Setter.Value>
            </Setter>
        </Style>
    </ComboBox.ItemContainerStyle>
    </ComboBox>
    </Grid>
    </UserControl>
</code>```

You can create a new valueconveter for processing three item as follows

```<code>    class Disabler2 : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {

            bool enable = true;
            var comboxbox1SelectedItem = values[0] as ComboBoxItem;
            var comboxbox2SelectedItem = values[1]  as ComboBoxItem;
            var comboxbox3Item = values[2]  as ComboBoxItem;

            //Logic to disable items

            return enable;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
</code>```

Body:
I want to disable some specific items of combobox conditionally. For Example, I have two comboboxes (combobox1,combobox2), I want to disable some specific items of combobox2 (not to remove, just want to disable) according to selected item of combobox1.
My xaml codes are like that:

    <Grid>
    <ComboBox x:Name="combobox1" HorizontalAlignment="Left" Margin="142,99,0,0" VerticalAlignment="Top" Width="319">
        <ComboBoxItem>Choice1</ComboBoxItem>
        <ComboBoxItem>Choice2</ComboBoxItem>
        <ComboBoxItem>Choice3</ComboBoxItem>

    </ComboBox>
    <ComboBox x:Name="combobox2" HorizontalAlignment="Left" Margin="520,99,0,0" VerticalAlignment="Top" Width="358">
        <ComboBoxItem>Selection1</ComboBoxItem>
        <ComboBoxItem>Selection2</ComboBoxItem>
        <ComboBoxItem>Selection3</ComboBoxItem>
        <ComboBoxItem>Selection4</ComboBoxItem>
        <ComboBoxItem>Selection5</ComboBoxItem>
        <ComboBoxItem>Selection6</ComboBoxItem>
    </ComboBox>
</Grid>

and C#  codes are like that:

    public partial class UC_Servis : UserControl
{
    public UC_Servis()
    {
        InitializeComponent();
    }
    private void combobox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        switch (combobox1.SelectedIndex)
        {
            case 0:
                combobox2.SelectedIndex = 0;
                break;
            case 1:
                combobox2.SelectedIndex = 1;
                break;
            case 2:
                combobox2.SelectedIndex = 2;
                break;
            default:
                break;
        }
        combobox2.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged);
    }
    private void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
    {
        if (combobox2.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
        {
            foreach (var a in combobox2.Items)
            {
                int currentPosition = combobox2.Items.IndexOf(a);
                ComboBoxItem cbi = (ComboBoxItem)combobox2.ItemContainerGenerator.ContainerFromIndex(currentPosition);

                switch (combobox1.SelectedIndex)
                {
                    case 0:
                        switch (a.ToString())
                        {
                            case "Selection4":
                            case "Selection5":
                                cbi.IsEnabled = false;
                                break;
                            default:
                                cbi.IsEnabled = true;
                                break;
                        }
                        break;
                    case 1:
                        switch (a.ToString())
                        {
                            case "Selection1":
                            case "Selection3":
                                cbi.IsEnabled = false;
                                break;
                            default:
                                cbi.IsEnabled = true;
                                break;
                        }
                        break;
                    case 2:
                        switch (a.ToString())
                        {
                            case "Selection2":
                            case "Selection6":
                                cbi.IsEnabled = false;
                                break;
                            default:
                                cbi.IsEnabled = true;
                                break;
                        }
                        break;

                    default:
                        break;
                }
            }
        }
    }

}

When I run, there is no change, I could not make none of the items of combobox2 disabled.

How can I do that? what's wrong?

EXTRA QUESTION

If Comboboxes have static items, I accomplished to change displaying ability of combobox items by support of neelesh bodgal.
But, in my original study, comboboxes' item sources are binded to database, so items of comboboxes' items can change by situations. I tryed to adapt neelesh bodgal's codes to my original study, but all of the items are enabled.
in my original study xaml codes are like that:

<Window x:Class="MyStudy.Pencereler.MamulStkConfig"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:MyStudy.Pencereler"
    xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
    mc:Ignorable="d"
    TextElement.Foreground="{DynamicResource MaterialDesignBody}"
    TextElement.FontWeight="Regular"
    TextElement.FontSize="13"
    TextOptions.TextFormattingMode="Ideal"
    TextOptions.TextRenderingMode="Auto"
    Background="{DynamicResource MaterialDesignPaper}"
    FontFamily="{DynamicResource MaterialDesignFont}"
    Title="MamulStkConfig" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" AllowsTransparency="True" WindowStyle="None" WindowState="Maximized" Width="1300" Height="700">
<Window.Resources>
    <local:TekerDisabler x:Key="tekerDisabler"/>
</Window.Resources>
<Grid>
                <ComboBox x:Name="Cbx_UrunGrubu" SelectionChanged="Cbx_UrunGrubu_SelectionChanged"  materialDesign:HintAssist.Hint="ÜRÜN GRUBU"  Style="{StaticResource MaterialDesignFloatingHintComboBox}" DisplayMemberPath="kodTipTanim" SelectedValuePath="kodTipId" />
                <ComboBox x:Name="Cbx_Secim1" SelectionChanged="Cbx_Secim1_SelectionChanged"  materialDesign:HintAssist.Hint="{Binding ElementName=txt_Hint1,Path=Text}"  Style="{StaticResource MaterialDesignFloatingHintComboBox}" DisplayMemberPath="TANIM" SelectedValuePath="KOD" />
                <ComboBox x:Name="Cbx_Secim2" SelectionChanged="Cbx_Secim2_SelectionChanged"  materialDesign:HintAssist.Hint="{Binding ElementName=txt_Hint2,Path=Text}"  Style="{StaticResource MaterialDesignFloatingHintComboBox}" DisplayMemberPath="TANIM" SelectedValuePath="KOD" />
                <ComboBox x:Name="Cbx_Secim3" SelectionChanged="Cbx_Secim3_SelectionChanged"  materialDesign:HintAssist.Hint="{Binding ElementName=txt_Hint3,Path=Text}"  Style="{StaticResource MaterialDesignFloatingHintComboBox}" DisplayMemberPath="TANIM" SelectedValuePath="KOD" />
                <ComboBox x:Name="Cbx_Ops10" SelectionChanged="Cbx_Ops10_SelectionChanged"  materialDesign:HintAssist.Hint="{Binding ElementName=txt_Hint10,Path=Text}"  Style="{StaticResource MaterialDesignFloatingHintComboBox}" DisplayMemberPath="TANIM" SelectedValuePath="KOD"  >
                <ComboBox.ItemContainerStyle>

                </ComboBox.ItemContainerStyle>
            </ComboBox>
</Grid>

And MyStudy C# codes are like that:

    public class TekerDisabler : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        bool enable = true;
        var cbxUrunGrupSelectedItem = values[0] as ComboBoxItem;
        var cbxOp3SelectedItem = values[1] as ComboBoxItem;
        var cbxOp2SelectedItem = values[2] as ComboBoxItem;
        var cbxOp10Item = values[3] as ComboBoxItem;
        if (cbxUrunGrupSelectedItem == null || cbxOp2SelectedItem == null || cbxOp3SelectedItem == null || cbxOp10Item == null)
            return true;
        switch (cbxUrunGrupSelectedItem.Content.ToString())
        {
            case "DÖNERLİ PULLUK":
                switch (cbxOp3SelectedItem.Content.ToString())
                {
                    case "(100X100X10) Profil":
                        if (cbxOp10Item.Content.ToString() == "LASTİK TEKER BÜYÜK (10x80-12)") { enable = false; }
                        break;
                    case "(120X120X10) Profil":
                        switch (cbxOp2SelectedItem.Content.ToString())
                        {
                            case "3'LÜ (2+1)":
                            case "3'LÜ (3+0)":
                            case "3'LÜ (FLANŞSIZ)":
                                if (cbxOp10Item.Content.ToString() == "TEKERSİZ" || cbxOp10Item.Content.ToString() == "LASTİK TEKER BÜYÜK (10x80-12)")
                                { enable = false; }
                                break;
                            case "1'Lİ (1+0)":
                            case "1'Lİ (FLANŞSIZ)":
                            case "2'Lİ (1+1)":
                            case "2'Lİ (2+0)":
                            case "2'Lİ (FLANŞSIZ)":
                                if (cbxOp10Item.Content.ToString() == "LASTİK TEKER BÜYÜK (10x80-12)")
                                { enable = false; }
                                break;
                            default:
                                if (cbxOp10Item.Content.ToString() == "TEKERSİZ" || cbxOp10Item.Content.ToString() == "DEMİR TEKER" || cbxOp10Item.Content.ToString() == "LASTİK TEKER (20,5x8,00-10)")
                                { enable = false; }
                                break;
                        }
                        break;
                    case "(140X140X10) Profil":
                    case "(140X140X14) Profil":
                        if (cbxOp10Item.Content.ToString() == "TEKERSİZ" || cbxOp10Item.Content.ToString() == "DEMİR TEKER" || cbxOp10Item.Content.ToString() == "LASTİK TEKER (20,5x8,00-10)")
                        { enable = false; }
                        break;

                    default:
                        enable = true;
                        break;
                }
                break;
            default:
                break;
        }
        return enable;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

How can I overcome this problem?

Body:
This is a another way of doing it using data binding.
This is working code. You can replace this code in your project and check.

  <UserControl x:Class="WpfApplication1.UserControl1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:WpfApplication1"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
    <local:Disabler x:Key="disabler"/>
</UserControl.Resources>
<Grid>
<ComboBox x:Name="combobox1" HorizontalAlignment="Left" Margin="142,99,0,0"
        VerticalAlignment="Top" Width="319">
        <ComboBoxItem>Choice1</ComboBoxItem>
        <ComboBoxItem>Choice2</ComboBoxItem>
        <ComboBoxItem>Choice3</ComboBoxItem>

    </ComboBox>

     <ComboBox x:Name="combobox2" HorizontalAlignment="Left" Margin="520,99,0,0" VerticalAlignment="Top" Width="358">
        <ComboBoxItem>Selection1</ComboBoxItem>
        <ComboBoxItem>Selection2</ComboBoxItem>
        <ComboBoxItem>Selection3</ComboBoxItem>
        <ComboBoxItem>Selection4</ComboBoxItem>
        <ComboBoxItem>Selection5</ComboBoxItem>
        <ComboBoxItem>Selection6</ComboBoxItem>

        <ComboBox.ItemContainerStyle>
            <Style TargetType="ComboBoxItem">
                <Setter Property="IsEnabled">
                    <Setter.Value>
                        <MultiBinding Converter="{StaticResource disabler}">
                            <!--Here you can bind the proper u want to use in -->
                            <!--converter to enable/ disable comboboxitem-->
                            <Binding ElementName="combobox1" Path="SelectedItem"/>

                            <!--Bind to the current comboboxitem which needs to enabled/disabled-->
                            <Binding RelativeSource="{RelativeSource Self}"/>
                        </MultiBinding>
                    </Setter.Value>
                </Setter>
            </Style>
        </ComboBox.ItemContainerStyle>
    </ComboBox>
</Grid>
</UserControl>

Define the converter in the code behind as follows

    using System;
    using System.Globalization;
    using System.Windows.Controls;
    using System.Windows.Data;

    namespace WpfApplication1
    {
        /// <summary>
        /// Interaction logic for UserControl1.xaml
        /// </summary>
        public partial class UserControl1 : UserControl
        {
            public UserControl1()
            {
                InitializeComponent();
            }
        }

        class Disabler : IMultiValueConverter
        {
            public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
            {

                bool enable = true;
                var comboxbox1SelectedItem = values[0] as ComboBoxItem;
                var comboxbox2Item = values[1]  as ComboBoxItem;

                if (comboxbox1SelectedItem == null || comboxbox2Item == null)
                    return true;

                if (comboxbox1SelectedItem.Content.ToString() == "Choice1")
                {
                    if(comboxbox2Item.Content.ToString() == "Selection4" || (comboxbox2Item.Content.ToString() == "Selection5")){
                        enable = false;
                    }
                }
                else if (comboxbox1SelectedItem.Content.ToString() == "Choice2")
                {
                    if (comboxbox2Item.Content.ToString() == "Selection1" || (comboxbox2Item.Content.ToString() == "Selection3")){
                        enable = false;
                    }
                }
                else if (comboxbox1SelectedItem.Content.ToString() == "Choice3")
                {
                    if (comboxbox2Item.Content.ToString() == "Selection2" || (comboxbox2Item.Content.ToString() == "Selection6")){
                        enable = false;
                    }
                }
                return enable;
            }

            public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }
    }

For more than one combobox deciding the enable/disable items, same example can be extended as follows

    <UserControl x:Class="WpfApplication1.UserControl1"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
     xmlns:local="clr-namespace:WpfApplication1"
     mc:Ignorable="d"
     d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>
       <local:Disabler x:Key="disabler"/>
       <local:Disabler2 x:Key="disabler2"/>
    </UserControl.Resources>
   <Grid>
   <ComboBox x:Name="combobox1" HorizontalAlignment="Left" Margin="142,99,0,0"
    VerticalAlignment="Top" Width="319">
    <ComboBoxItem>Choice1</ComboBoxItem>
    <ComboBoxItem>Choice2</ComboBoxItem>
    <ComboBoxItem>Choice3</ComboBoxItem>

   </ComboBox>

   <ComboBox x:Name="combobox2" HorizontalAlignment="Left" Margin="142,99,0,0"
    VerticalAlignment="Top" Width="319">
    <ComboBoxItem>Choice21</ComboBoxItem>
    <ComboBoxItem>Choice22</ComboBoxItem>
    <ComboBoxItem>Choice23</ComboBoxItem>

   </ComboBox>

 <ComboBox x:Name="combobox3" HorizontalAlignment="Left" Margin="520,99,0,0" VerticalAlignment="Top" Width="358">
    <ComboBoxItem>Selection1</ComboBoxItem>
    <ComboBoxItem>Selection2</ComboBoxItem>
    <ComboBoxItem>Selection3</ComboBoxItem>
    <ComboBoxItem>Selection4</ComboBoxItem>
    <ComboBoxItem>Selection5</ComboBoxItem>
    <ComboBoxItem>Selection6</ComboBoxItem>

    <ComboBox.ItemContainerStyle>
        <Style TargetType="ComboBoxItem">
            <Setter Property="IsEnabled">
                <Setter.Value>
                    <MultiBinding Converter="{StaticResource disabler2}">
                        <!--Here you can bind the proper u want to use in -->
                        <!--converter to enable/ disable comboboxitem-->
                        <Binding ElementName="combobox1" Path="SelectedItem"/>
                        <Binding ElementName="combobox2" Path="SelectedItem"/>
                        <!--Bind to the current comboboxitem which needs to enabled/disabled-->
                        <Binding RelativeSource="{RelativeSource Self}"/>
                    </MultiBinding>
                </Setter.Value>
            </Setter>
        </Style>
    </ComboBox.ItemContainerStyle>
    </ComboBox>
    </Grid>
    </UserControl>

You can create a new valueconveter for processing three item as follows

    class Disabler2 : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {

            bool enable = true;
            var comboxbox1SelectedItem = values[0] as ComboBoxItem;
            var comboxbox2SelectedItem = values[1]  as ComboBoxItem;
            var comboxbox3Item = values[2]  as ComboBoxItem;

            //Logic to disable items

            return enable;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }


来源: stackexchange

问:
pagination of a specific context in multiple context in ListView not working in django?
in django, i am trying to list some queries of several objects like user lists, categoies and Post list. the homepage will be contained couple of blocks or boxes. each box will have different query list like Post list, User List, category list. But only one context will have pagination and other won't and ofcourse the pagination will be working on Post list.

here is the views.py:

```<code>class BlogappListView(ListView):
    model = Category,CustomUser
    template_name = 'home.html'
    context_object_name='category_list'
    queryset=Category.objects.all()
    paginate_by = 2

    def get_context_data(self, **kwargs):
        context = super(BlogappListView, self).get_context_data(**kwargs)
        context['user_list']= CustomUser.objects.all()
        context['post_list']=Post.objects.all()
        activities=context['post_list']
        return context
    def get_related_activities(self,activities):
        queryset=self.objects.activity_rel.all()
        paginator=Paginator(queryset,2)
        page=self.request.GET.get('page')
        activities=paginator.get_page(page)
        return(activities)
</code>```

in urls.py:

```<code>urlpatterns = [
    path('',BlogappListView.as_view(),name='home'),
]
</code>```

in base.html, the paginate portion code:

```<code><ul class="pagination justify-content-center mb-4">
              {% if is_paginated %}

                    {% if page_obj.has_previous %}
                    <li class="page-item">
                    <a class="page-link" href="?page=1">First</a>
                  </li>
                  <li class="page-item">
                      <a class="page-link" href="?page={{ page_obj.previous_page_number }}">Previous</a>
                    </li>
                    {% endif %}

                    {% for num in page_obj.paginator.page_range %}
                      {% if page_obj.number == num %}
                      <li class="page-item">
                        <a class="page-link" href="?page={{ num }}">{{ num }}</a>
                      </li>

                      {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                      <li class="page-item">
                        <a class="page-link" href="?page={{ num }}">{{ num }}</a>
                      </li>

                      {% endif %}
                    {% endfor %}

                    {% if page_obj.has_next %}
                    <li class="page-item">
                      <a class="page-link" href="?page={{ page_obj.next_page_number }}">Next</a>
                    </li>
                  <li class="page-item">
                      <a class="page-link" href="?page={{ page_obj.paginator.num_pages }}">Last</a>
                    </li>

                    {% endif %}

                  {% endif %}
                </ul>
</code>```

the main problem is that page number 1 is showing all the posts and also the second page. and category list is also truncated into 2 but the user list ok.

so how can i make it work ? is there any other way?

thank you in advance

答:
i solved it. the revised code is:

```<code>class BlogappListView(ListView):
    model = Category,CustomUser
    template_name = 'home.html'
    context_object_name='post_list'
    queryset=Post.objects.all()
    paginate_by=2

    def get_context_data(self, **kwargs):
        context = super(BlogappListView, self).get_context_data(**kwargs)
        context['user_list']= CustomUser.objects.all()
        context['category_list']=Category.objects.all()
        return context
</code>```

while looking for solution, i've got somewhere written that pagination will work only with queryset, not with the context. and that was so straight cut to understand and when i use paginate_by=2 in the queryset under Post it will only work for that.

the solution was quick and short but it took me a while to figure it out which is not good. but either way thanx to this platform to have this discussion and i am keeping this solution so that someone might get help from it.

ContentLicense: CC BY-SA 4.0

Body:
in django, i am trying to list some queries of several objects like user lists, categoies and Post list. the homepage will be contained couple of blocks or boxes. each box will have different query list like Post list, User List, category list. But only one context will have pagination and other won't and ofcourse the pagination will be working on Post list.

here is the views.py:

class BlogappListView(ListView):
    model = Category,CustomUser
    template_name = 'home.html'
    context_object_name='category_list'
    queryset=Category.objects.all()
    paginate_by = 2

    def get_context_data(self, **kwargs):
        context = super(BlogappListView, self).get_context_data(**kwargs)
        context['user_list']= CustomUser.objects.all()
        context['post_list']=Post.objects.all()
        activities=context['post_list']
        return context
    def get_related_activities(self,activities):
        queryset=self.objects.activity_rel.all()
        paginator=Paginator(queryset,2)
        page=self.request.GET.get('page')
        activities=paginator.get_page(page)
        return(activities)

in urls.py:

urlpatterns = [
    path('',BlogappListView.as_view(),name='home'),
]

in base.html, the paginate portion code:

              {% if is_paginated %}

                    {% if page_obj.has_previous %}

                    First

                      Previous

                    {% endif %}

                    {% for num in page_obj.paginator.page_range %}
                      {% if page_obj.number == num %}

                        {{ num }}

                      {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}

                        {{ num }}

                      {% endif %}
                    {% endfor %}

                    {% if page_obj.has_next %}

                      Next

                      Last

                    {% endif %}

                  {% endif %}

the main problem is that page number 1 is showing all the posts and also the second page. and category list is also truncated into 2 but the user list ok.

so how can i make it work ? is there any other way?

thank you in advance

Body:
i solved it. the revised code is:

class BlogappListView(ListView):
    model = Category,CustomUser
    template_name = 'home.html'
    context_object_name='post_list'
    queryset=Post.objects.all()
    paginate_by=2

    def get_context_data(self, **kwargs):
        context = super(BlogappListView, self).get_context_data(**kwargs)
        context['user_list']= CustomUser.objects.all()
        context['category_list']=Category.objects.all()
        return context

while looking for solution, i've got somewhere written that pagination will work only with queryset, not with the context. and that was so straight cut to understand and when i use paginate_by=2 in the queryset under Post it will only work for that.

the solution was quick and short but it took me a while to figure it out which is not good. but either way thanx to this platform to have this discussion and i am keeping this solution so that someone might get help from it.


问:
Pandoc: setting language of exported Word docx
I export Word docx from markdown using Pandoc.

By default, everything seems to be marked as English in the docx file. So I tried to override this, e.g. by command line option pandoc -s -S images.md -o images.docx -V lang=de or in the header YAML:

```<code>---
subtitle: <%= @report.name %>
toc-title: <%= t('.toc_title') %>
lang: de
---
</code>```

But none seems to work, all content in the exported docx file is marked red by the language spelling feature, telling me that words are not found in English.

How can I override the language?

Update

I tried specifying the language in the docx-file, by simply selecting all text (Cmd+A, I'm on OSX) and clicking on the language button on the bottom left.

Also, I tried using Tools -> Language:

None of it did have an effect though.

Update

Interestingly, when exporting to HTML, the language is set correctly in the  attribute.

答:
I have just checked again, and with Pandoc v 2.9.2.1 it seems to set the language correctly:

Hooray!! Thanks, Pandoc community! <3

Would be interesting though to know when exactly it was added (couldn't find a mention in the https://pandoc.org/changelog.txt).

ContentLicense: CC BY-SA 3.0

Body:
I export Word docx from markdown using Pandoc.

By default, everything seems to be marked as English in the docx file. So I tried to override this, e.g. by command line option pandoc -s -S images.md -o images.docx -V lang=de or in the header YAML:

---
subtitle: <%= @report.name %>
toc-title: <%= t('.toc_title') %>
lang: de
---

But none seems to work, all content in the exported docx file is marked red by the language spelling feature, telling me that words are not found in English.

How can I override the language?

Update

I tried specifying the language in the docx-file, by simply selecting all text (Cmd+A, I'm on OSX) and clicking on the language button on the bottom left.

Also, I tried using Tools -> Language:

None of it did have an effect though.

Update

Interestingly, when exporting to HTML, the language is set correctly in the  attribute.


问:
How to Desrialize JSON using C#
I am currently using Json.Net to deserialize my JSON. I now have the following situation:

I am getting the following JSON response:

```<code>{"Success":false,"Errors":{"UserName":"User Name already registered","EmailAddress":"Email Address already registered"}}
</code>```

I want to parse it into this type:

```<code>public class CustomJsonResult
{
    public bool Success { get; set; }
    public string[] Errors { get; set; }
}
</code>```

Using Json.net, I tried doing this:

```<code>CustomJsonResult regResult = JsonConvert.DeserializeObject<CustomJsonResult>(json);
</code>```

But this is not working, I get the error Cannot deserialize JSON object into type 'System.String[]'.

How can I fix this? (using Json.Net or any other library)

答:
Errors is not an array of string, it is an object with UserName and EmailAddress as it's property.

```<code>{
    "Success":false,
    "Errors":{
        "UserName":"User Name already registered",
        "EmailAddress":"Email Address already registered"
     }
}
</code>```

well, you can create another class to store the error message

```<code>public CustomJsonError
{
    public string UserName { get; set; }
    public string EmailAddress { get; set; }
}
</code>```

Then refactor the class

```<code>public class CustomJsonResult
{
    public bool Success { get; set; }
    public CustomJsonError Errors { get; set; } // I'm not sure if the property should be named as Errors
}
</code>```

BTW, will error contain an array / list of errors?

Update

Well, you can use Dictionary<string, string> (see other answer) or create a custom class for the Error. See http://james.newtonking.com/projects/json/help/SerializingCollections.html for serializing and deserializing Collection to and from JSON.

Title: How to Desrialize JSON using C#

Body:
I am currently using Json.Net to deserialize my JSON. I now have the following situation:

I am getting the following JSON response:

{"Success":false,"Errors":{"UserName":"User Name already registered","EmailAddress":"Email Address already registered"}}

I want to parse it into this type:

public class CustomJsonResult
{
    public bool Success { get; set; }
    public string[] Errors { get; set; }
}

Using Json.net, I tried doing this:

CustomJsonResult regResult = JsonConvert.DeserializeObject<CustomJsonResult>(json);

But this is not working, I get the error Cannot deserialize JSON object into type 'System.String[]'.

How can I fix this? (using Json.Net or any other library)

Body:
Errors is not an array of string, it is an object with UserName and EmailAddress as it's property.

{
    "Success":false,
    "Errors":{
        "UserName":"User Name already registered",
        "EmailAddress":"Email Address already registered"
     }
}

well, you can create another class to store the error message

public CustomJsonError
{
    public string UserName { get; set; }
    public string EmailAddress { get; set; }
}

Then refactor the class

public class CustomJsonResult
{
    public bool Success { get; set; }
    public CustomJsonError Errors { get; set; } // I'm not sure if the property should be named as Errors
}

BTW, will error contain an array / list of errors?

Update

Well, you can use Dictionary<string, string> (see other answer) or create a custom class for the Error. See http://james.newtonking.com/projects/json/help/SerializingCollections.html for serializing and deserializing Collection to and from JSON.


问:
LibGDX ImageButton image not to scale?

The red square is the button's boundary, while the image remains centered at 32x32px. I've tried using button.getImage() to set position and size to the button's values, but it doesn't seem to have any effect.

答:
Extending on the answer of @xitnesscomplex:
 You can use yourButton.getImage().setFillParent(true); to set the size.

To set an offset is somewhat counter-intuitive

ImageButton.ImageButtonStyle style = new ImageButton.ImageButtonStyle();
style.imageUp = new TextureRegionDrawable(new Texture(Gdx.files.internal(btn.png")));
ImageButton yourButton = new ImageButton(style);
style.unpressedOffsetX = -new_brush.getWidth()/4.0f;
style.unpressedOffsetY = -new_brush.getHeight()/4.0f;
style.pressedOffsetX = -new_brush.getWidth()/4.0f;
style.pressedOffsetY = -new_brush.getHeight()/4.0f;
style.checkedOffsetX = -new_brush.getWidth()/4.0f;
style.checkedOffsetY = -new_brush.getHeight()/4.0f;
yourButton.getImage().setFillParent(true);
```

Title: LibGDX ImageButton image not to scale?


问:
Python logger message collision when running in threads
Using modules threading and logger to do concurrent file downloads.
Seems to be working as expected.
Only problem is that my logged status lines for each download are colliding with one another

code snippet

```<code>import sys, os, re
import threading
import requests
import queue
import logging
import time
import argparse

def download(session, url, filename):
    connection_pool.acquire()

    url = re.sub(r'/+$', '', url)
    filename = re.sub(r'^/+', '', filename)
    localpath = args.basepath + "/" + filename
    os.makedirs(os.path.dirname(localpath), exist_ok=True)
    full_url = url + "/" + filename + "?B"
    starttime = time.time()
    logger.info("Downloading {}".format(full_url))

    response = session.get(full_url, allow_redirects=True, stream=True)
    filesize = response.headers.get('Content-Length')

    with open(localpath, 'wb') as f:
        for chunk in response.iter_content(1024):
            f.write(chunk)

    local_filesize = os.path.getsize(localpath)
    if (int(filesize) != int(local_filesize)):
        logger.error("File sizes do not match remote={} local={}".format(filesize, local_filesize))
        exit(1)
    endtime = time.time()
    elapsedtime = (endtime - starttime)
    bitrate = int(filesize) / elapsedtime
    logger.info("STATUS - file={} size={} time={} rate={} region={}".format(filename, filesize, elapsedtime, int(bitrate), args.region))
    connection_pool.release()

def setup_logger():
    hdlr = logging.StreamHandler()
    hdlr.flush = sys.stdout.flush
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    logger.setLevel(logging.DEBUG)

... bunch of other functions ...

</code>```

output:

```<code>895 2020-05-30 14:29:32,992 - get_files.py - INFO - Downloading https://10.12.134.17/3010A120200528.z
p?B 20-05-30 14:29:28,564 - get_files.py - INFO - STATUS - file=3066A120200528.zip size=9427150 time=8.5233154296875 rate=110604
2020-05-30 14:29:28,565 - get_files.py - INFO - Downloading https://10.12.134.17/3033A120200528.zip?
2020-05-30 14:29:29,610 - get_files.py - INFO - STATUS - file=3038A120200528.zip size=2472569 time=2.0577292442321777 rate=1201
00 2020-05-30 14:29:29,610 - get_files.py - INFO - Downloading https://10.12.134.17/3031A120200528.zi
?B 2020-05-30 14:29:29,836 - get_files.py - INFO - STATUS - file=3034A120200528.zip size=1441683 time=1.5025453567504883 rate=95
493 2020-05-30 14:29:29,836 - get_files.py - INFO - Downloading https://10.12.134.17/3030A120200528.z
p?B 2020-05-30 14:29:30,065 - get_files.py - INFO - STATUS - file=3037A120200528.zip size=3431121 time=2.3450839519500732 rate=14
3112 2020-05-30 14:29:30,065 - get_files.py - INFO - Downloading https://10.12.134.17/3029A120200528.
p?B 20-05-30 14:29:28,564 - get_files.py - INFO - STATUS - file=3066A120200528.zip size=9427150 time=8.5233154296875 rate=110604
2020-05-30 14:29:28,565 - get_files.py - INFO - Downloading https://10.12.134.17/3033A120200528.zip?
</code>```

As shown above, the logger messages from some thread are colliding with others.

Side note, this is running in an AWS ECS Fargate v1.4.0 container running amazonlinux:2 image and logging to an AWS Cloudwatch logstream with python 3.6

答: While the reason it works does not make sense to me, the solution came while from this post.  After completely removing the handler and just using the default handler, no more line collisions are occurring.</p>

Body:
Using modules threading and logger to do concurrent file downloads.
Seems to be working as expected.
Only problem is that my logged status lines for each download are colliding with one another

code snippet

import sys, os, re
import threading
import requests
import queue
import logging
import time
import argparse

def download(session, url, filename):
    connection_pool.acquire()

    url = re.sub(r'/+$', '', url)
    filename = re.sub(r'^/+', '', filename)
    localpath = args.basepath + "/" + filename
    os.makedirs(os.path.dirname(localpath), exist_ok=True)
    full_url = url + "/" + filename + "?B"
    starttime = time.time()
    logger.info("Downloading {}".format(full_url))

    response = session.get(full_url, allow_redirects=True, stream=True)
    filesize = response.headers.get('Content-Length')

    with open(localpath, 'wb') as f:
        for chunk in response.iter_content(1024):
            f.write(chunk)

    local_filesize = os.path.getsize(localpath)
    if (int(filesize) != int(local_filesize)):
        logger.error("File sizes do not match remote={} local={}".format(filesize, local_filesize))
        exit(1)
    endtime = time.time()
    elapsedtime = (endtime - starttime)
    bitrate = int(filesize) / elapsedtime
    logger.info("STATUS - file={} size={} time={} rate={} region={}".format(filename, filesize, elapsedtime, int(bitrate), args.region))
    connection_pool.release()

def setup_logger():
    hdlr = logging.StreamHandler()
    hdlr.flush = sys.stdout.flush
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    logger.setLevel(logging.DEBUG)

... bunch of other functions ...

output:

895 2020-05-30 14:29:32,992 - get_files.py - INFO - Downloading https://10.12.134.17/3010A120200528.z
p?B 20-05-30 14:29:28,564 - get_files.py - INFO - STATUS - file=3066A120200528.zip size=9427150 time=8.5233154296875 rate=110604
2020-05-30 14:29:28,565 - get_files.py - INFO - Downloading https://10.12.134.17/3033A120200528.zip?
2020-05-30 14:29:29,610 - get_files.py - INFO - STATUS - file=3038A120200528.zip size=2472569 time=2.0577292442321777 rate=1201
00 2020-05-30 14:29:29,610 - get_files.py - INFO - Downloading https://10.12.134.17/3031A120200528.zi
?B 2020-05-30 14:29:29,836 - get_files.py - INFO - STATUS - file=3034A120200528.zip size=1441683 time=1.5025453567504883 rate=95
493 2020-05-30 14:29:29,836 - get_files.py - INFO - Downloading https://10.12.134.17/3030A120200528.z
p?B 2020-05-30 14:29:30,065 - get_files.py - INFO - STATUS - file=3037A120200528.zip size=3431121 time=2.3450839519500732 rate=14
3112 2020-05-30 14:29:30,065 - get_files.py - INFO - Downloading https://10.12.134.17/3029A120200528.
p?B 20-05-30 14:29:28,564 - get_files.py - INFO - STATUS - file=3066A120200528.zip size=9427150 time=8.5233154296875 rate=110604
2020-05-30 14:29:28,565 - get_files.py - INFO - Downloading https://10.12.134.17/3033A120200528.zip?

As shown above, the logger messages from some thread are colliding with others.

Side note, this is running in an AWS ECS Fargate v1.4.0 container running amazonlinux:2 image and logging to an AWS Cloudwatch logstream with python 3.6


问:
Java Timer schedule task: servive JVM shutdown?
Java Timer schedule task: servive JVM shutdown?

```<code>Timer timer = new Timer();
timer.scheduleAtFixedRate(...)
</code>```

After JVM is shutdown, will the task scheduled still be executed?

答:
It won't survive the shutdown. The underlying thread will terminate. </p>

<p>Moreover, the termination will occur in an abrupt way since the JVM doesn't try to stop the application threads during a shutdown. </p>

Body:
Java Timer schedule task: servive JVM shutdown?

Timer timer = new Timer();
timer.scheduleAtFixedRate(...)

After JVM is shutdown, will the task scheduled still be executed?

Body:
It won't survive the shutdown. The underlying thread will terminate.

Moreover, the termination will occur in an abrupt way since the JVM doesn't try to stop the application threads during a shutdown.


问:
Can anyone explain the test case for the puzzle "Repairing Roads"?
I am trying to solve the following puzzle. I am confused by one of the test case.

Here is the problem:

The country of Byteland contains of N cities and N - 1 bidirectional roads between them such that there is a path between any two cities. The roads in Byteland were built long ago and now they are in need of repair. You have been hired to repair all the roads. You intend to do this by dispatching robots on some of the roads. Each robot will repair the road he is currently on and then move to one of the adjacent unrepaired roads. After repairing that, he will move to another adjacent unrepaired road, repair that and so on.

Two roads are adjacent if they have the same city at one of their endpoints. For the process to be efficient, no two robots will can ever repair the same road, and no road can be visited twice. What is the least number of robots needed to accomplish the task?

Input:
The first line contains the number of test cases T. T test cases follow. The first line of each testcase contains N, the number of cities in Byteland. The cities are numbered 0..N - 1. The following N - 1 lines contain the description of the roads. The ith line contains two integers ai and bi, meaning that there is a road connecting cities with numbers ai and bi.

Output:
Output T lines, one corresponding to each test case containing the required answer for that test case.

Constraints:
1 <= T <= 20

1 <= N <= 10000

0 <= ai,bi < N

Now bolow is the test case that I'm confused:

1

15

0 11

1 7

1 11

2 11

2 14

3 4

4 10

4 13

4 8

5 13

6 10

7 9

8 11

11 12

The correct answer is 2, but why?

答:
It is mentioned in this question that no two robots will ever repair the same road, and no road can be visited twice .

1> if the distance of
 the endpoint of one of the branch is greater than one than it is needed to send robot in that direction .

2> distance of endpoint from any vertex =1 then not require any extra robot

https://i.stack.imgur.com/o7zm6.png


问:
MongoDB - Execute a command conditionally
I need to execute a command that is part of my migration scripts (mongock java library) conditionally based on Mongo version

In case Mongo version is lower then 4.2 I need to execute this command. For Mongo 4.2 and higher it should not be executed.

```<code>db.getSiblingDB('admin').runCommand( { setParameter: 1, failIndexKeyTooLong: false } )
</code>```

Is there a way how to do it?

Thank you,

Lukas

答:
don't know if you already found a solution for this.

The idea is to figure out the Mongo's version inside the changeSet and then perform the required actions.

I will assume you are using the last Mongock's release for version 3.x.x, which is 3.3.2 or 4.0.x.alpha, so you should use MongockTemplate, instead of MongoTemplate. Don't worry, it's just a wrapper/decorator, you won't miss anything from the original API.

So you can do something like this:

@ChangeSet(id = "changeset-1", order = "001", author = "mongock")
public void changeSet(MongockTemplate mongockTemplate, ClientRepository clientRepository) {
    String version = mongockTemplate.executeCommand(new Document("buildinfo", new BsonString("")))
            .get("version")
            .toString();
    if(getNumericalVersion(version) < 42) {
        //do your actions
    } else {
        //do you other actions
    }
}
```

NOTE 1: We don't recommend using executeCommand. In this case, for taking the version it's fine, but in general we recommend not using it, specially for writes.

NOTE 2: Currently we are working on version 4, which will allow to scan multiple packages and even isolated ChangeLog classes. So another approach would be to take the version in the bean creation and inject the change or not depending on the MongoDB's version

Body:
I need to execute a command that is part of my migration scripts (mongock java library) conditionally based on Mongo version

In case Mongo version is lower then 4.2 I need to execute this command. For Mongo 4.2 and higher it should not be executed.

db.getSiblingDB('admin').runCommand( { setParameter: 1, failIndexKeyTooLong: false } )

Is there a way how to do it?

Thank you,

Lukas

Body:
don't know if you already found a solution for this.

The idea is to figure out the Mongo's version inside the changeSet and then perform the required actions.

I will assume you are using the last Mongock's release for version 3.x.x, which is 3.3.2 or 4.0.x.alpha, so you should use MongockTemplate, instead of MongoTemplate. Don't worry, it's just a wrapper/decorator, you won't miss anything from the original API.

So you can do something like this:

@ChangeSet(id = "changeset-1", order = "001", author = "mongock")
public void changeSet(MongockTemplate mongockTemplate, ClientRepository clientRepository) {
    String version = mongockTemplate.executeCommand(new Document("buildinfo", new BsonString("")))
            .get("version")
            .toString();
    if(getNumericalVersion(version) < 42) {
        //do your actions
    } else {
        //do you other actions
    }
}

NOTE 1: We don't recommend using executeCommand. In this case, for taking the version it's fine, but in general we recommend not using it, specially for writes.

NOTE 2: Currently we are working on version 4, which will allow to scan multiple packages and even isolated ChangeLog classes. So another approach would be to take the version in the bean creation and inject the change or not depending on the MongoDB's version


问:
Installing wordcloud using Jupyter Notebook
I need to solve a wordcloud problem for a homework assignment.

Unfortunately, I am having a hard time getting wordcloud installed into my environment.

Here is the code I am running:

```<code>import os
import matplotlib.pyplot as plt
from wordcloud import WordCloud
</code>```

I get the following error:

ImportError: No module named 'wordcloud'

Now, I know I need to use the pip install method in my command prompt to get wordcloud into my environment.  Even after doing this (and trying several different destinations, including my home directory and the Anaconda3 environment), I continue to get the same error.

What am I doing wrong?

答:
Try this on Jupyter cell:</p>

```<code>!pip install wordcloud
</code>```

Body:
I need to solve a wordcloud problem for a homework assignment.

Unfortunately, I am having a hard time getting wordcloud installed into my environment.

Here is the code I am running:

import os
import matplotlib.pyplot as plt
from wordcloud import WordCloud

I get the following error:

ImportError: No module named 'wordcloud'

Now, I know I need to use the pip install method in my command prompt to get wordcloud into my environment.  Even after doing this (and trying several different destinations, including my home directory and the Anaconda3 environment), I continue to get the same error.

What am I doing wrong?

Body:
Try this on Jupyter cell:

!pip install wordcloud


答: The problem is you're trying to convert a dictionary into an array. Try replacing your string[] with Dictionary<string, string>.

Title: How to Desrialize JSON using C#


问:
How to import pywikibot?
I have installed pywikibot and set up the config as described in the instructions. However when I put "importpywikibot" at the top of my script it says "No module named pywikibot". Do I have to install pywikibot somewhere special?

Thanks.

答:
If you haven't installed pywikibot then you can't import it. You need to

```<code>pip install pywikibot
</code>```

on the command line and then it should work.

Title: How to import pywikibot?

Body:
If you haven't installed pywikibot then you can't import it. You need to

pip install pywikibot

on the command line and then it should work.


问:
Pushbullet, push request successfully sent but no email arrives in inbox?
My code sends notifications but doesn't send emails. I receive the notifications in the Pushbullet extension in Google Chrome, but not in my email inbox. No errors (e.g. 404, 405 etc.) are returned.

I'm using Python3.

This is the data sent (email holds the email address I've passed to the function):

```<code>data_send = {
            "email": email,
            "type": "note",
            "title": "Title",
            "body": "Message"
        }
</code>```

This is the request:

```<code>resp = requests.post('https://api.pushbullet.com/v2/pushes',
                             data=json.dumps(data_send),
                             headers={'Authorization': 'Bearer ' +
                                      self.ACCESS_TOKEN,
                                      'Content-Type': 'application/json'})
</code>```

This is what I set up so if there's any errors it'll print it out on console:

```<code>if resp.status_code != 200:
            raise Exception('Something wrong')
        else:
            print(resp.text)
</code>```

When I run it, I get this response (I've xx'd out any personal details and copied it here like this so because it's easier to see than in the code format):

{"active":true,"iden":"xxxxxx","created":xxxxxx,"modified":xxxxxx,"type":"note","dismissed":false,"direction":"self","sender_iden":"xxxxxx","sender_email":"xxxxxx","sender_email_normalized":"xxxxxx","sender_name":"xxxxxx","receiver_iden":"xxxxxx","receiver_email":"xxxxxxxx","receiver_email_normalized":"xxxxxx","title":"Title","body":"Message"}

Plus, I get the notification in my Pushbullet extension in Google Chrome. But the email still hasn't arrived in my email.

The Pushbullet API documentation says to set target as "email". Ways I have tried to implement this:

```<code>data_send = {
            "target": "email",
            "type": "note",
            "title": "Title",
            "body": "Message"
        }
</code>```

and

```<code>data_send = {
            "target": {"email": email},
            "type": "note",
            "title": "Title",
            "body": "Message"
        }
</code>```

and

```<code>data_send = {
            "type": "note",
            "title": "Title",
            "body": "Message"
        }
data_send["target"] = "email"
</code>```

None of these work.

I understand there may be issues with sending emails to other email addresses because of spam, but sending an email to myself should work. And if it doesn't send an email to the specified email address, it is supposed to send an email to the email address associated with my account (the same email address).

Is it just meant to take a long time? It's been a few hours since the email was supposed to have been sent.

I have looked at other questions on SO and the most related ones seem to be this one and this one.

Both questions don't really help in this particular scenario as they have no mention about having no errors but email not being received.

Apologies if this is long, please let me know if this question is not appropriate/goes against guidelines.

Edit: I realised if the email was the same as the one associated with my account, it might only end up sending the notification and not the email since Pushbullet detects I have an account with that email. I have tried to make the email an email different to the one associated with my account. However, doing this still doesn't work.

Edit2: When I try to send an email to an external email, that email appears in the conversations list when I visit the Pushbullet website. When I go to settings > people, the email appears when I run my program. The email still doesn't arrive in their inbox.

TLDR: Is my code just not picking up an error I'm not seeing? Or does Pushbullet usually take more than a few hours to send emails?

答:
Developer confirmed email has been disabled in a reddit post.
The Pushbullet website links to this subreddit.

https://www.reddit.com/r/PushBullet/comments/gs5jz9/api_sending_emails_not_working/

Body:
My code sends notifications but doesn't send emails. I receive the notifications in the Pushbullet extension in Google Chrome, but not in my email inbox. No errors (e.g. 404, 405 etc.) are returned.

I'm using Python3.

This is the data sent (email holds the email address I've passed to the function):

data_send = {
            "email": email,
            "type": "note",
            "title": "Title",
            "body": "Message"
        }

This is the request:

resp = requests.post('https://api.pushbullet.com/v2/pushes',
                             data=json.dumps(data_send),
                             headers={'Authorization': 'Bearer ' +
                                      self.ACCESS_TOKEN,
                                      'Content-Type': 'application/json'})

This is what I set up so if there's any errors it'll print it out on console:

if resp.status_code != 200:
            raise Exception('Something wrong')
        else:
            print(resp.text)

When I run it, I get this response (I've xx'd out any personal details and copied it here like this so because it's easier to see than in the code format):

{"active":true,"iden":"xxxxxx","created":xxxxxx,"modified":xxxxxx,"type":"note","dismissed":false,"direction":"self","sender_iden":"xxxxxx","sender_email":"xxxxxx","sender_email_normalized":"xxxxxx","sender_name":"xxxxxx","receiver_iden":"xxxxxx","receiver_email":"xxxxxxxx","receiver_email_normalized":"xxxxxx","title":"Title","body":"Message"}

Plus, I get the notification in my Pushbullet extension in Google Chrome. But the email still hasn't arrived in my email.

The Pushbullet API documentation says to set target as "email". Ways I have tried to implement this:

data_send = {
            "target": "email",
            "type": "note",
            "title": "Title",
            "body": "Message"
        }

and

data_send = {
            "target": {"email": email},
            "type": "note",
            "title": "Title",
            "body": "Message"
        }

and

data_send = {
            "type": "note",
            "title": "Title",
            "body": "Message"
        }
data_send["target"] = "email"

None of these work.

I understand there may be issues with sending emails to other email addresses because of spam, but sending an email to myself should work. And if it doesn't send an email to the specified email address, it is supposed to send an email to the email address associated with my account (the same email address).

Is it just meant to take a long time? It's been a few hours since the email was supposed to have been sent.

I have looked at other questions on SO and the most related ones seem to be this one and this one.

Both questions don't really help in this particular scenario as they have no mention about having no errors but email not being received.

Apologies if this is long, please let me know if this question is not appropriate/goes against guidelines.

Edit: I realised if the email was the same as the one associated with my account, it might only end up sending the notification and not the email since Pushbullet detects I have an account with that email. I have tried to make the email an email different to the one associated with my account. However, doing this still doesn't work.

Edit2: When I try to send an email to an external email, that email appears in the conversations list when I visit the Pushbullet website. When I go to settings > people, the email appears when I run my program. The email still doesn't arrive in their inbox.

TLDR: Is my code just not picking up an error I'm not seeing? Or does Pushbullet usually take more than a few hours to send emails?


问:
R: Create Indicator Columns from list of conditions
I have a dataframe and a number of conditions. Each condition is supposed to check whether the value in a certain column of the dataframe is within a set of valid values.

This is what I tried:

```<code># create the sample dataframe
age <- c(120, 45)
sex <- c("x", "f")

df <-data.frame(age, sex)

# create the sample conditions
conditions <- list(
  list("age", c(18:100)),
  list("sex", c("f", "m"))
)

addIndicator <- function (df, columnName, validValues) {
  indicator <- vector()

  for (row in df[, toString(columnName)]) {
    # for some strange reason, %in% doesn't work correctly here, but always returns FALSe
    indicator <- append(indicator, row %in% validValues)
  }
  df <- cbind(df, indicator)

  # rename the column
  names(df)[length(names(df))] <- paste0("I_", columnName)

  return(df)
}

for (condition in conditions){
  columnName <- condition[1]
  validValues <- condition[2]
  df <- addIndicator(df, columnName, validValues)
}

print(df)
</code>```

However, this leads to all conditions considered not to be met - which is not what I expect:

```<code>  age sex I_age I_sex
1 120   x FALSE FALSE
2  45   f FALSE FALSE
</code>```

I figured that %in% does not return the expected result. I checked for the typeof(row) and tried to boil this down into a minimum example. In a simple ME, with the same type and values of the variables, the %in% works properly. So, something must be wrong within the context I try to apply this. Since this is my first attempt to write anything in R, I am stuck here.

What am I doing wrong and how can I achieve what I want?

答:
conditions appears to be a nested list. When you use:

```<code>validValues <- condition[2]
</code>```

in your for loop, your result is also a list.

To get the vector of values to use with %in%, you can extract [[ by:

```<code>validValues <- condition[[2]]
</code>```

A simplified approach to obtaining indicators could be with a simple list:

```<code>conditions_lst <- list(age = 18:100, sex = c("f", "m"))
</code>```

And using sapply instead of a for loop:

```<code>cbind(df, sapply(setNames(names(df), paste("I", names(df), sep = "_")), function(x) {
  df[[x]] %in% conditions_lst[[x]]
}))
</code>```

Output

```<code>  age sex I_age I_sex
1 120   x FALSE FALSE
2  45   f  TRUE  TRUE
</code>```

Body:
I have a dataframe and a number of conditions. Each condition is supposed to check whether the value in a certain column of the dataframe is within a set of valid values.

This is what I tried:

# create the sample dataframe
age <- c(120, 45)
sex <- c("x", "f")

df <-data.frame(age, sex)

# create the sample conditions
conditions <- list(
  list("age", c(18:100)),
  list("sex", c("f", "m"))
)

addIndicator <- function (df, columnName, validValues) {
  indicator <- vector()

  for (row in df[, toString(columnName)]) {
    # for some strange reason, %in% doesn't work correctly here, but always returns FALSe
    indicator <- append(indicator, row %in% validValues)
  }
  df <- cbind(df, indicator)

  # rename the column
  names(df)[length(names(df))] <- paste0("I_", columnName)

  return(df)
}

for (condition in conditions){
  columnName <- condition[1]
  validValues <- condition[2]
  df <- addIndicator(df, columnName, validValues)
}

print(df)

However, this leads to all conditions considered not to be met - which is not what I expect:

  age sex I_age I_sex
1 120   x FALSE FALSE
2  45   f FALSE FALSE

I figured that %in% does not return the expected result. I checked for the typeof(row) and tried to boil this down into a minimum example. In a simple ME, with the same type and values of the variables, the %in% works properly. So, something must be wrong within the context I try to apply this. Since this is my first attempt to write anything in R, I am stuck here.

What am I doing wrong and how can I achieve what I want?

Body:
conditions appears to be a nested list. When you use:

validValues <- condition[2]

in your for loop, your result is also a list.

To get the vector of values to use with %in%, you can extract [[ by:

validValues <- condition[[2]]

A simplified approach to obtaining indicators could be with a simple list:

conditions_lst <- list(age = 18:100, sex = c("f", "m"))

And using sapply instead of a for loop:

cbind(df, sapply(setNames(names(df), paste("I", names(df), sep = "_")), function(x) {
  df[[x]] %in% conditions_lst[[x]]
}))

Output

  age sex I_age I_sex
1 120   x FALSE FALSE
2  45   f  TRUE  TRUE


问:
Bind an image-src from array of objects
How can I bind the prod.src?

```<code><v-row>
    <v-col v-for="prod in products" :key="prod.id" cols="12" md="6" lg="3">

          <v-btn outline block class="primary">{{prod.id}}</v-btn>
          <img :src="require(`${prod.src}`)" />     <!-- I was trying this -->

    </v-col>
</v-row>

<script>
   export default {
      data: () => ({
        products: [
           { id: 1112, src: "https://freeimage1.jpg" },
           { id: 1113, src: "https://freeimage2.jpg" },
         ]
     }),
  };
</script>
</code>```

Chrome console shows an error:
Cannot find module 'https://freeimage1.jpg'

答:
You bind it wrong.

Change this line:

```<code><img :src="require(`${prod.src}`)" />
</code>```

To this:

```<code><img :src="prod.src" />
</code>```

Title: Bind an image-src from array of objects

Body:
How can I bind the prod.src?

<v-row>
    <v-col v-for="prod in products" :key="prod.id" cols="12" md="6" lg="3">

          <v-btn outline block class="primary">{{prod.id}}</v-btn>
          <img :src="require(`${prod.src}`)" />

    </v-col>
</v-row>

Chrome console shows an error:
Cannot find module 'https://freeimage1.jpg'

Body:
You bind it wrong.

Change this line:

<img :src="require(`${prod.src}`)" />

To this:

<img :src="prod.src" />


问:
Assigning null/Nullable to DateTime in Ternary Operation
I have a statement like

```<code>DateTime ? dt = (string1 == string2) ? null; (DateTime)(txtbox.Text);
</code>```

which I cannot compile. Reason is : null cannot be assigned to DateTime.

So, I have to declare a Nullable<DateTime> nullable variable and replace null with nullable.

I do not want to use if-statement and I want to do this in one line.

Also, Can I use operator ?? here.

答:
you can do it like that:</p>

```<code>DateTime ? dt = (string1 == string2) ? new Nullable <DateTime>(): (DateTime)(txtbox.Text);
</code>```

Body:
I have a statement like

DateTime ? dt = (string1 == string2) ? null; (DateTime)(txtbox.Text);

which I cannot compile. Reason is : null cannot be assigned to DateTime.

So, I have to declare a Nullable<DateTime> nullable variable and replace null with nullable.

I do not want to use if-statement and I want to do this in one line.

Also, Can I use operator ?? here.

Body:
you can do it like that:

DateTime ? dt = (string1 == string2) ? new Nullable <DateTime>(): (DateTime)(txtbox.Text);


问:
Live View app is constantly reloading after fresh install
I just generated a fresh live view app with phx.new --live and I'm getting this error constantly:

```<code>[info] GET /orgs
[debug] Processing with Phoenix.LiveView.Plug.index/2
  Parameters: %{}
  Pipelines: [:browser]
[debug] QUERY OK source="orgs" db=3.6ms idle=1614.0ms
SELECT o0."id", o0."avatar_url", o0."description", o0."email_end", o0."name", o0."inserted_at", o0."updated_at" FROM "orgs" AS o0 []
[info] Sent 200 in 4ms
[info] CONNECTED TO Phoenix.LiveView.Socket in 215µs
  Transport: :websocket
  Serializer: Phoenix.Socket.V2.JSONSerializer
  Parameters: %{"_csrf_token" => "...", "vsn" => "2.0.0"}
[error] an exception was raised:
    ** (FunctionClauseError) no function clause matching in Phoenix.LiveView.Channel.start_link/1
        (phoenix_live_view) lib/phoenix_live_view/channel.ex:12: Phoenix.LiveView.Channel.start_link({TopicalWeb.Endpoint, {#PID<0.3487.0>, #Reference<0.1633886798.3560439811.208106>}})
        (elixir) lib/dynamic_supervisor.ex:690: DynamicSupervisor.start_child/3
        (elixir) lib/dynamic_supervisor.ex:676: DynamicSupervisor.handle_start_child/2
        (stdlib) gen_server.erl:661: :gen_server.try_handle_call/4
        (stdlib) gen_server.erl:690: :gen_server.handle_msg/6
        (stdlib) proc_lib.erl:249: :proc_lib.init_p_do_apply/3
</code>```

Reproduction information

I'm using Phoenix version 1.5.3

Then I generated an "Org" module with mix phx.gen.live Orgs Org orgs name:string email_end:string avatar_url:string description:string

```<code>      scope "/orgs", TopicalWeb.OrgLive do
        live "/", Index, :index
        live "/new", Index, :new
        live "/:id/edit", Index, :edit

        live "/:id", Show, :show
        live "/:id/show/edit", Show, :edit
      end
</code>```

答:
I found out I was on too old a version of phoenix_live_view:

```<code>-      {:phoenix_live_view, "~> 0.12.0"},
+      {:phoenix_live_view, "~> 0.13"},
</code>```

NOTE: you might want to run mix hex.search phoenix_live_view to figure out the latest version:

```<code>Package                               Description                                            Version  URL
phoenix_live_view                     Rich, real-time user experiences with server-rende...  0.13.2   https://hex.pm/packages/phoenix_live_view
phoenix_view_assets                   Helps to manage view specific assets in phoenix pr...  0.1.4    https://hex.pm/packages/phoenix_view_assets
phx_custom_template                   An opinionated template to create phoenix apps, us...  0.1.3    https://hex.pm/packages/phx_custom_template
</code>```

Body:
I just generated a fresh live view app with phx.new --live and I'm getting this error constantly:

[info] GET /orgs
[debug] Processing with Phoenix.LiveView.Plug.index/2
  Parameters: %{}
  Pipelines: [:browser]
[debug] QUERY OK source="orgs" db=3.6ms idle=1614.0ms
SELECT o0."id", o0."avatar_url", o0."description", o0."email_end", o0."name", o0."inserted_at", o0."updated_at" FROM "orgs" AS o0 []
[info] Sent 200 in 4ms
[info] CONNECTED TO Phoenix.LiveView.Socket in 215µs
  Transport: :websocket
  Serializer: Phoenix.Socket.V2.JSONSerializer
  Parameters: %{"_csrf_token" => "...", "vsn" => "2.0.0"}
[error] an exception was raised:
    ** (FunctionClauseError) no function clause matching in Phoenix.LiveView.Channel.start_link/1
        (phoenix_live_view) lib/phoenix_live_view/channel.ex:12: Phoenix.LiveView.Channel.start_link({TopicalWeb.Endpoint, {#PID<0.3487.0>, #Reference<0.1633886798.3560439811.208106>}})
        (elixir) lib/dynamic_supervisor.ex:690: DynamicSupervisor.start_child/3
        (elixir) lib/dynamic_supervisor.ex:676: DynamicSupervisor.handle_start_child/2
        (stdlib) gen_server.erl:661: :gen_server.try_handle_call/4
        (stdlib) gen_server.erl:690: :gen_server.handle_msg/6
        (stdlib) proc_lib.erl:249: :proc_lib.init_p_do_apply/3

Reproduction information

I'm using Phoenix version 1.5.3

Then I generated an "Org" module with mix phx.gen.live Orgs Org orgs name:string email_end:string avatar_url:string description:string

      scope "/orgs", TopicalWeb.OrgLive do
        live "/", Index, :index
        live "/new", Index, :new
        live "/:id/edit", Index, :edit

        live "/:id", Show, :show
        live "/:id/show/edit", Show, :edit
      end

Body:
I found out I was on too old a version of phoenix_live_view:

-      {:phoenix_live_view, "~> 0.12.0"},
+      {:phoenix_live_view, "~> 0.13"},

NOTE: you might want to run mix hex.search phoenix_live_view to figure out the latest version:

Package                               Description                                            Version  URL
phoenix_live_view                     Rich, real-time user experiences with server-rende...  0.13.2   https://hex.pm/packages/phoenix_live_view
phoenix_view_assets                   Helps to manage view specific assets in phoenix pr...  0.1.4    https://hex.pm/packages/phoenix_view_assets
phx_custom_template                   An opinionated template to create phoenix apps, us...  0.1.3    https://hex.pm/packages/phx_custom_template


问:
How to capture each cell inside foreach; so, when a cell is empty, it shows an error text
At the beginning, my problem was how to validate an empty field of a grid, what this event do to validate all cells and how to show the error text when a cell is empty.

So, my new problem is how to capture each cell inside foreach; so, when a cell is empty, it shows an error text?

答:
You can run foreach loop like this. and based on the text you can do whatever you want to</p>

```<code>foreach (GridViewRow row in GridViewId.Rows)
{
    for (int i = 0; i < GridViewId.Columns.Count; i++)
    {
        String cellText = row.Cells[i].Text;
    }
}
</code>```

Body:
You can run foreach loop like this. and based on the text you can do whatever you want to

foreach (GridViewRow row in GridViewId.Rows)
{
    for (int i = 0; i < GridViewId.Columns.Count; i++)
    {
        String cellText = row.Cells[i].Text;
    }
}


问:
Create Kafka cluster for testing Java-based Kafka clients
I have a Kafka client and I need to test the functionalities of it. For this I need to create a Kafka Cluster locally, and connect to it. As per the limitations, I can't use a Docker image or K8s for this.

I did a search, and found This class used in testing, but I can't change the broker ports.

I tried using Debezium KafkaCluster but it fails to create the cluster intermittently, hence causes intermittent test failures.

Is there a way to create a Kafka Cluster locally, to run integration tests for java-based Kafka clients?

答:
Well, the posted answers helped, but I wanted something different. Ended up creating my own implementation. If anyone wants, they can use it.

I used kafka.server.KafkaServer and org.apache.zookeeper.server.ZooKeeperServerMain for this.


问:
Why does python not recognise this as my dataset even though the file clearly exists on my computer?
I am a beginner at python and i'm trying to improve my skills by trying to follow this python tutorial:
https://towardsdatascience.com/exploratory-analysis-python-kaggle-data-b0afb6ec1788

The line i typed in was:

df = pd.read_csv('C:\Stuff\Python\Medical Appointment Data\792_3538_bundle_archive.zip\KaggleV2-May-2016.csv')
```

<p>I think the line is meant to enable python to read the data so we can later construct a few graphs.
But when i type it in it gives me quite a long error here:</p>

<p>https://gyazo.com/28f7c49e70d3e968cdeb6fd653b4ea04 (sorry i didn't want to take up too much space including it all here)</p>

<p>I have tried a couple things including moving the file i'm trying to get it to use and also some formatting things like changing what quotes i use and the brackets.</p>

<p>I found this page which i think references this issue but haven't found any working solution from there.</p>

<p>"CSV file does not exist" for a filename with embedded quotes</p>

<p>This is my full code so far:</p>

```import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython import get_ipython
ipy = get_ipython()
if ipy is not None:
    ipy.run_line_magic('matplotlib', 'inline')
import plotly.plotly as pyimport plotly.offline as pyo
import plotly.graph_objs as go
pyo.offline.init_notebook_mode()
df = pd.read_csv('C:\Stuff\Python\Medical Appointment Data\792_3538_bundle_archive.zip\KaggleV2-May-2016.csv')
```

Thank you in advance for any and all help recieved.
Let me know if you need any extra information.
Also i'm sorry if this is layout is bad or improper. This is my first question and i tried my best. (I can also try fix it if necessary)

答:
The adress contains a lot of escape characters.It should be read as an raw string.Try putting an r infornt of the string like this.

```<code> df = pd.read_csv(r'C:\Stuff\Python\Medical Appointment Data\792_3538_bundle_archive.zip\KaggleV2-May-2016.csv')
</code>```

Alternatively you can put the data file in same folder as the program file,then you don't need to mention the path.

Body:
I am a beginner at python and i'm trying to improve my skills by trying to follow this python tutorial:
https://towardsdatascience.com/exploratory-analysis-python-kaggle-data-b0afb6ec1788

The line i typed in was:

df = pd.read_csv('C:\Stuff\Python\Medical Appointment Data\792_3538_bundle_archive.zip\KaggleV2-May-2016.csv')

I think the line is meant to enable python to read the data so we can later construct a few graphs.
But when i type it in it gives me quite a long error here:

https://gyazo.com/28f7c49e70d3e968cdeb6fd653b4ea04 (sorry i didn't want to take up too much space including it all here)

I have tried a couple things including moving the file i'm trying to get it to use and also some formatting things like changing what quotes i use and the brackets.

I found this page which i think references this issue but haven't found any working solution from there.

"CSV file does not exist" for a filename with embedded quotes

This is my full code so far:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython import get_ipython
ipy = get_ipython()
if ipy is not None:
    ipy.run_line_magic('matplotlib', 'inline')
import plotly.plotly as pyimport plotly.offline as pyo
import plotly.graph_objs as go
pyo.offline.init_notebook_mode()
df = pd.read_csv('C:\Stuff\Python\Medical Appointment Data\792_3538_bundle_archive.zip\KaggleV2-May-2016.csv')

Thank you in advance for any and all help recieved.
Let me know if you need any extra information.
Also i'm sorry if this is layout is bad or improper. This is my first question and i tried my best. (I can also try fix it if necessary)

Body:
The adress contains a lot of escape characters.It should be read as an raw string.Try putting an r infornt of the string like this.

 df = pd.read_csv(r'C:\Stuff\Python\Medical Appointment Data\792_3538_bundle_archive.zip\KaggleV2-May-2016.csv')

Alternatively you can put the data file in same folder as the program file,then you don't need to mention the path.


问:
Default Activity not found in Android Studio
I just upgraded to Android Studio 0.2.8 and I am getting an error that says "Default Activity not found" when I try to edit the run configurations.

When I launch Android Studio I get this error "Access is allowed from event dispatch thread only"

The activity I am using is a fragment activity.

So far I've tried rebuilding and invalidate caches/restart. Both were of no use.

Please let me know what I can do to fix the problem.

答: Default Activity name changed (like SplashActivity -> SplashActivity1) and  work for me </p>


问:
Load data from txt with pandas
I am loading a txt file containig a mix of float and string data. I want to store them in an array where I can access each element. Now I am just doing

```<code>import pandas as pd

data = pd.read_csv('output_list.txt', header = None)
print data
</code>```

This is the structure of the input file: 1 0 2000.0 70.2836942112 1347.28369421 /file_address.txt.

Now the data are imported as a unique column. How can I divide it, so to store different elements separately (so I can call data[i,j])? And how can I define a header?

答:
I usually take a look at the data first or just try to import it and do data.head(), if you see that the columns are separated with \t then you should specify sep="\t" otherwise, sep = " ".

```<code>import pandas as pd
data = pd.read_csv('data.txt', sep=" ", header=None)
</code>```

Title: Load data from txt with pandas

Body:
I am loading a txt file containig a mix of float and string data. I want to store them in an array where I can access each element. Now I am just doing

import pandas as pd

data = pd.read_csv('output_list.txt', header = None)
print data

This is the structure of the input file: 1 0 2000.0 70.2836942112 1347.28369421 /file_address.txt.

Now the data are imported as a unique column. How can I divide it, so to store different elements separately (so I can call data[i,j])? And how can I define a header?

Body:
I usually take a look at the data first or just try to import it and do data.head(), if you see that the columns are separated with \t then you should specify sep="\t" otherwise, sep = " ".

import pandas as pd
data = pd.read_csv('data.txt', sep=" ", header=None)


问:
Download an image with AsyncTask, I need help if there's no network connection
I'm new to programming so bear with me, this is a big learning experience for me, and it's been a lot of fun so far.

What I'm trying to do is to load an image into my app that I change and upload to my server on a regular basis. Right now, it loads a placement image until the proper image is finished downloading in the background, then shows the new image that it's downloaded.

My problem is that if there is no network connection, it ends up showing nothing at all. I'm assuming that there's something I can do in PostExecute that would show a drawable from within the app if it fails to load the image from the net, I'm just not sure how to do it!

Any help would be greatly appreciated!

EDIT: Am I on the right track to displaying an alternate image?

```<code>import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import android.widget.Toast;

public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {

private String url;
private final WeakReference<ImageView> imageViewReference;
private Resources res;

public ImageDownloader(ImageView imageView) {
    imageViewReference = new WeakReference<ImageView>(imageView);
}

@Override
protected Bitmap doInBackground(String... params) {
    url = params[0];
    try {
        return BitmapFactory.decodeStream(new URL(url).openConnection()
                .getInputStream());
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {

      return BitmapFactory.decodeResource(res, R.drawable.displayThis);

        }
}

@Override
protected void onPostExecute(Bitmap result) {
    if (isCancelled()) {
        result = null;
    }
    if (imageViewReference != null) {
        ImageView imageView = imageViewReference.get();
        if (imageView != null) {
            imageView.setImageBitmap(result);
        }
    }
}

@Override
protected void onPreExecute() {
    if (imageViewReference != null) {
        ImageView imageView = imageViewReference.get();
        if (imageView != null) {
            imageView.setImageResource(R.drawable.uboxback);
        }
    }
}
}
</code>```

答:
If you get null as a return value from you doInBackground function can you not just display another image?
Also you could always check if there is a network connection available before trying to do any of it and do something at that point?

You can check if a network connection is available by doing something similar to the following:

```<code>ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()) {
//this is connected
    }
</code>```

Does this help at all?

Bex

Body:
I'm new to programming so bear with me, this is a big learning experience for me, and it's been a lot of fun so far.

What I'm trying to do is to load an image into my app that I change and upload to my server on a regular basis. Right now, it loads a placement image until the proper image is finished downloading in the background, then shows the new image that it's downloaded.

My problem is that if there is no network connection, it ends up showing nothing at all. I'm assuming that there's something I can do in PostExecute that would show a drawable from within the app if it fails to load the image from the net, I'm just not sure how to do it!

Any help would be greatly appreciated!

EDIT: Am I on the right track to displaying an alternate image?

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import android.widget.Toast;

public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {

private String url;
private final WeakReference<ImageView> imageViewReference;
private Resources res;

public ImageDownloader(ImageView imageView) {
    imageViewReference = new WeakReference<ImageView>(imageView);
}

@Override
protected Bitmap doInBackground(String... params) {
    url = params[0];
    try {
        return BitmapFactory.decodeStream(new URL(url).openConnection()
                .getInputStream());
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {

      return BitmapFactory.decodeResource(res, R.drawable.displayThis);

        }
}

@Override
protected void onPostExecute(Bitmap result) {
    if (isCancelled()) {
        result = null;
    }
    if (imageViewReference != null) {
        ImageView imageView = imageViewReference.get();
        if (imageView != null) {
            imageView.setImageBitmap(result);
        }
    }
}

@Override
protected void onPreExecute() {
    if (imageViewReference != null) {
        ImageView imageView = imageViewReference.get();
        if (imageView != null) {
            imageView.setImageResource(R.drawable.uboxback);
        }
    }
}
}

Body:
If you get null as a return value from you doInBackground function can you not just display another image?
Also you could always check if there is a network connection available before trying to do any of it and do something at that point?

You can check if a network connection is available by doing something similar to the following:

ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()) {
//this is connected
    }

Does this help at all?

Bex