问:
WPF ComboBox Doesn't Display SelectedItem after one DataTrigger but does for another
So I have a combobox I'd like to reuse for multiple sets of data rather than having 3 separate comboboxes. Maybe this is bad and someone can tell me so. I'm open to all ideas and suggestions. I'm just trying to clean up some code and thought one combobox rather than 3 was cleaner. Anyway the ItemsSource and SelectedItem all should change when another ComboBox'svalue is changed which Raises the Property Changed value for the ComboBox that isn't working. The worst part is when CurSetpoint.ActLowerModeIsTimerConditionis true it always loads the SelectedItem correctly but when going from that to CurSetpoint.ActLowerGseMode being True the combobox doesn't have the SelectedItem loaded.

Here is the XAML for the ComboBox with issues.

<ComboBox Grid.Row="1" Grid.Column="1" Margin="5,2" VerticalAlignment="Center" Name="cmbActTimersSetpointsGseVars">
       <ComboBox.Style>

          </Style>
       </ComboBox.Style>
</ComboBox>
```

<p>Here is an image of the two combo boxes. When the Mode is change from Timer to Variable it doesn't load anything despite its binding not being null and its instance and itemssource instance data not having changed. But If I go from Variable to Timer the Timer: 1 is displayed correctly.</p>

<p><img src="https://i.stack.imgur.com/ypKm9.png" alt="enter image description here"></p>

<p>Here is the Model Code behind the Mode ComboBox's value being changed. Along with the other two Properties that are the <code>SelectedItems</code> for the ComboBox in question. Along with the Properties of the <code>ItemsSource</code></p>

<pre class="lang-cs prettyprint-override"><code>private VarItem actLowerMode;
public VarItem ActLowerMode
{
   get { return this.actLowerMode; }
   set
   {
      if (value != null)
      {
         var oldValue = this.actLowerMode;

         this.actLowerMode = value;
         config.ActLowerMode.Value = value.ID;

         //if they weren't the same we need to reset the variable name
         //Note: 5/21/19 Needs to be this way instead of before because when changing from Timer->GseVariable it wouldn't change the config value because it
         //thought it was still a timer condition because the value hadn't been changed yet.
         if (oldValue != null && (oldValue.CheckAttribute("timer") != value.CheckAttribute("timer")))
         {
            if (value.CheckAttribute("timer"))
            {
               ActLowerTimerInstance = model.TimerInstances.First();
            }
            else
            {
               ActLowerVarName = "";
               if (GseMode)
               {
                  ActLowerGseVar = model.EnabledGseVars.FirstOrDefault();
               }
            }
         }

         RaisePropertyChanged("ActLowerMode");
         RaisePropertyChanged("HasActLowerScale");
         RaisePropertyChanged("ActLowerGseMode");
         RaisePropertyChanged("HasActLowerVarName");
         RaisePropertyChanged("ActLowerModeIsConstant");
         RaisePropertyChanged("ActLowerRow1Label");
         RaisePropertyChanged("ActLowerModeIsTimerCondition");
         RaisePropertyChanged("ShowActLowerConstTextBox");
         RaisePropertyChanged("ShowActLowerCmbBox");
         RaisePropertyChanged("ShowActLowerRow1Label");
         if (GseMode)
         {
            RaisePropertyChanged("ActLowerGseMode");
         }
      }
   }
}

private GseVariableModel actLowerGseVar;
public GseVariableModel ActLowerGseVar
{
   get { return this.actLowerGseVar; }
   set
   {
      if (value != null)
      {
         this.actLowerGseVar = value;
         if (!ActLowerModeIsTimerCondition)//only changing the config value if its not set to timer
         {
            config.ActLowerVarName.Value = value.Number.ToString();
         }
         RaisePropertyChanged("ActLowerGseVar");
      }
   }
}

private INumberedSelection actLowerTimerInstance;
public INumberedSelection ActLowerTimerInstance
{
   get { return this.actLowerTimerInstance; }
   set
   {
      if (value != null)
      {
         this.actLowerTimerInstance = value;
         config.ActLowerVarName.Value = value.Number.ToString();
         RaisePropertyChanged("ActLowerTimerInstance");
      }
   }
}

public ObservableCollection<INumberedSelection> TimerInstances { get { return this.timerInstances; } }

public ObservableCollection<GseVariableModel> EnabledGseVars
{
   get
   {
      return enabledGseVariables;
   }
}
</code>```

I'm sure I've probably overlooked some important info so I will update it with any questions you guys have or details you need.

Update: Just wanted to add as stated in the bounty. That if what I'm doing here isn't a good idea and there is a better way of doing it, someone with experience please just tell me why and how I should. If there are better ways and what I'm doing is bad I just need to know.

答:
There's nothing wrong with binding multiple ComboBoxes and setting their Visibility. For one, it greatly reduces the complexity compared to the code from your post.

Nonetheless, you can easily swap the context (not to be confused with DataContext) of an ItemsControl by introducing an additional abstraction between the viewmodel and the view.

This is how it works:

Create a context object with the relevant properties

Apply the context to your ItemsControl

Let de properties rebind on context changed

Your idea of gathering the properties per entity is certainly a good one. Though the implementation could be better, both the viewmodel and the view look bloated. That's what this context object is all about, gathering and keeping state as you swap contexts back and forth.

Starting with our model classes. Let's code against an interface (even though ItemsSource is untyped).

namespace WpfApp.Models
{
    public interface IEntity
    {
        string Name { get; }
    }

    public class Dog : IEntity
    {
        public Dog(string breed, string name)
        {
            Breed = breed;
            Name = name;
        }

        public string Breed { get; }
        public string Name { get; }
    }

    public class Author : IEntity
    {
        public Author(string genre, string name)
        {
            Genre = genre;
            Name = name;
        }

        public string Genre { get; }
        public string Name { get; }
    }
}
```

<p>Next, the ViewModels, starting with our context.</p>

<pre class="lang-cs prettyprint-override"><code>namespace WpfApp.ViewModels
{
    public class ItemsContext : ViewModelBase
    {
        public ItemsContext(IEnumerable<IEntity> items)
        {
            if (items == null || !items.Any()) throw new ArgumentException(nameof(Items));

            Items = new ObservableCollection<IEntity>(items);
            SelectedItem = Items.First();
        }

        public ObservableCollection<IEntity> Items { get; }

        private IEntity selectedItem;
        public IEntity SelectedItem
        {
            get { return selectedItem; }
            set
            {
                selectedItem = value;
                OnPropertyChanged();
            }
        }

        public string DisplayMemberPath { get; set; }
    }
}
</code>```

As said, the relevant properties, with notifications for SelectedItem, nothing special. We immediately see the effect on our MainViewModel.

```<code>namespace WpfApp.ViewModels
{
    public class MainViewModel : ViewModelBase
    {
        private readonly ItemsContext _dogContext;
        private readonly ItemsContext _authorContext;

        public MainViewModel()
        {
            _dogContext = new ItemsContext(FetchDogs()) { DisplayMemberPath = nameof(Dog.Breed) };
            _authorContext = new ItemsContext(FetchAuthors()) { DisplayMemberPath = nameof(Author.Genre) };
        }

        private ItemsContext selectedContext;
        public ItemsContext SelectedContext
        {
            get { return selectedContext; }
            set
            {
                selectedContext = value;
                OnPropertyChanged();
            }
        }

        private bool dogChecked;
        public bool DogChecked
        {
            get { return dogChecked; }
            set
            {
                dogChecked = value;
                if(dogChecked) SelectedContext = _dogContext;
            }
        }

        private bool authorChecked;
        public bool AuthorChecked
        {
            get { return authorChecked; }
            set
            {
                authorChecked = value;
                if(authorChecked) SelectedContext = _authorContext;
            }
        }

        private static IEnumerable<IEntity> FetchDogs() =>
            new List<IEntity>
            {
                new Dog("Terrier", "Ralph"),
                new Dog("Beagle", "Eddy"),
                new Dog("Poodle", "Fifi")
            };

        private static IEnumerable<IEntity> FetchAuthors() =>
            new List<IEntity>
            {
                new Author("SciFi", "Bradbury"),
                new Author("RomCom", "James")
            };
    }
}
</code>```

Two cleanly separated flows, each managing its own context. It's clear you could easily extend this to any number of contexts, without them getting in each others way. Now, to apply the context to our ItemsControl we have two options. We could subclass our Control or use an Attached Property. Favoring composition over inheritance, here's the class with the AP.

namespace WpfApp.Extensions
{
    public class Selector
    {
        public static ItemsContext GetContext(DependencyObject obj) => (ItemsContext)obj.GetValue(ContextProperty);
        public static void SetContext(DependencyObject obj, ItemsContext value) => obj.SetValue(ContextProperty, value);

        public static readonly DependencyProperty ContextProperty =
            DependencyProperty.RegisterAttached("Context", typeof(ItemsContext), typeof(Selector), new PropertyMetadata(null, OnItemsContextChanged));

        private static void OnItemsContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var selector = (System.Windows.Controls.Primitives.Selector)d;
            var ctx = (ItemsContext)e.NewValue;

            if (e.OldValue != null) // Clean up bindings from previous context, if any
            {
                BindingOperations.ClearBinding(selector, System.Windows.Controls.Primitives.Selector.SelectedItemProperty);
                BindingOperations.ClearBinding(selector, ItemsControl.ItemsSourceProperty);
                BindingOperations.ClearBinding(selector, ItemsControl.DisplayMemberPathProperty);
            }

            selector.SetBinding(System.Windows.Controls.Primitives.Selector.SelectedItemProperty, new Binding(nameof(ItemsContext.SelectedItem)) { Source = ctx, Mode = BindingMode.TwoWay });
            selector.SetBinding(ItemsControl.ItemsSourceProperty, new Binding(nameof(ItemsContext.Items)) { Source = ctx });
            selector.SetBinding(ItemsControl.DisplayMemberPathProperty, new Binding(nameof(ItemsContext.DisplayMemberPath)) { Source = ctx });
        }
    }
}
```

<p>That covers both steps 2 and 3. You can tweak this however you like. For example, we've made <code>ItemsContext.DisplayMemberPath</code> a non notifying prop, so you could just set the value directly instead of through binding.</p>

<p>Finally, the view, where it all comes together.</p>

<pre class="lang-xml prettyprint-override"><code><Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:vm="clr-namespace:WpfApp.ViewModels"
        xmlns:ext="clr-namespace:WpfApp.Extensions"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" WindowStartupLocation="CenterScreen">
    <Window.DataContext>
        <vm:MainViewModel/>
    </Window.DataContext>
    <Window.Resources>
        <Style x:Key="SelectorStyle" TargetType="{x:Type Selector}">
            <Setter Property="Width" Value="150"/>
            <Setter Property="HorizontalAlignment" Value="Left"/>
            <Setter Property="Margin" Value="0,20"/>
        </Style>
    </Window.Resources>
    <StackPanel Margin="20">
        <RadioButton GroupName="Entities" Content="Dogs" IsChecked="{Binding DogChecked}" />
        <RadioButton GroupName="Entities" Content="Authors" IsChecked="{Binding AuthorChecked}" />
        <ComboBox ext:Selector.Context="{Binding SelectedContext}" Style="{StaticResource SelectorStyle}" />
        <ListBox  ext:Selector.Context="{Binding SelectedContext}" Style="{StaticResource SelectorStyle}" />
        <DataGrid ext:Selector.Context="{Binding SelectedContext}" Style="{StaticResource SelectorStyle}" />
    </StackPanel>
</Window>
</code>```

The cool thing about the Attached Property is that we're coding against the abstract Selector control, which is a direct descendant of ItemsControl. So without changing our lower layers we can share our context with ListBox and DataGrid as well.

Body:
So I have a combobox I'd like to reuse for multiple sets of data rather than having 3 separate comboboxes. Maybe this is bad and someone can tell me so. I'm open to all ideas and suggestions. I'm just trying to clean up some code and thought one combobox rather than 3 was cleaner. Anyway the ItemsSource and SelectedItem all should change when another ComboBox'svalue is changed which Raises the Property Changed value for the ComboBox that isn't working. The worst part is when CurSetpoint.ActLowerModeIsTimerConditionis true it always loads the SelectedItem correctly but when going from that to CurSetpoint.ActLowerGseMode being True the combobox doesn't have the SelectedItem loaded.

Here is the XAML for the ComboBox with issues.

<ComboBox Grid.Row="1" Grid.Column="1" Margin="5,2" VerticalAlignment="Center" Name="cmbActTimersSetpointsGseVars">
       <ComboBox.Style>

          </Style>
       </ComboBox.Style>
</ComboBox>

Here is an image of the two combo boxes. When the Mode is change from Timer to Variable it doesn't load anything despite its binding not being null and its instance and itemssource instance data not having changed. But If I go from Variable to Timer the Timer: 1 is displayed correctly.

Here is the Model Code behind the Mode ComboBox's value being changed. Along with the other two Properties that are the SelectedItems for the ComboBox in question. Along with the Properties of the ItemsSource

private VarItem actLowerMode;
public VarItem ActLowerMode
{
   get { return this.actLowerMode; }
   set
   {
      if (value != null)
      {
         var oldValue = this.actLowerMode;

         this.actLowerMode = value;
         config.ActLowerMode.Value = value.ID;

         //if they weren't the same we need to reset the variable name
         //Note: 5/21/19 Needs to be this way instead of before because when changing from Timer->GseVariable it wouldn't change the config value because it
         //thought it was still a timer condition because the value hadn't been changed yet.
         if (oldValue != null && (oldValue.CheckAttribute("timer") != value.CheckAttribute("timer")))
         {
            if (value.CheckAttribute("timer"))
            {
               ActLowerTimerInstance = model.TimerInstances.First();
            }
            else
            {
               ActLowerVarName = "";
               if (GseMode)
               {
                  ActLowerGseVar = model.EnabledGseVars.FirstOrDefault();
               }
            }
         }

         RaisePropertyChanged("ActLowerMode");
         RaisePropertyChanged("HasActLowerScale");
         RaisePropertyChanged("ActLowerGseMode");
         RaisePropertyChanged("HasActLowerVarName");
         RaisePropertyChanged("ActLowerModeIsConstant");
         RaisePropertyChanged("ActLowerRow1Label");
         RaisePropertyChanged("ActLowerModeIsTimerCondition");
         RaisePropertyChanged("ShowActLowerConstTextBox");
         RaisePropertyChanged("ShowActLowerCmbBox");
         RaisePropertyChanged("ShowActLowerRow1Label");
         if (GseMode)
         {
            RaisePropertyChanged("ActLowerGseMode");
         }
      }
   }
}

private GseVariableModel actLowerGseVar;
public GseVariableModel ActLowerGseVar
{
   get { return this.actLowerGseVar; }
   set
   {
      if (value != null)
      {
         this.actLowerGseVar = value;
         if (!ActLowerModeIsTimerCondition)//only changing the config value if its not set to timer
         {
            config.ActLowerVarName.Value = value.Number.ToString();
         }
         RaisePropertyChanged("ActLowerGseVar");
      }
   }
}

private INumberedSelection actLowerTimerInstance;
public INumberedSelection ActLowerTimerInstance
{
   get { return this.actLowerTimerInstance; }
   set
   {
      if (value != null)
      {
         this.actLowerTimerInstance = value;
         config.ActLowerVarName.Value = value.Number.ToString();
         RaisePropertyChanged("ActLowerTimerInstance");
      }
   }
}

public ObservableCollection<INumberedSelection> TimerInstances { get { return this.timerInstances; } }

public ObservableCollection<GseVariableModel> EnabledGseVars
{
   get
   {
      return enabledGseVariables;
   }
}

I'm sure I've probably overlooked some important info so I will update it with any questions you guys have or details you need.

Update: Just wanted to add as stated in the bounty. That if what I'm doing here isn't a good idea and there is a better way of doing it, someone with experience please just tell me why and how I should. If there are better ways and what I'm doing is bad I just need to know.

Body:
There's nothing wrong with binding multiple ComboBoxes and setting their Visibility. For one, it greatly reduces the complexity compared to the code from your post.

Nonetheless, you can easily swap the context (not to be confused with DataContext) of an ItemsControl by introducing an additional abstraction between the viewmodel and the view.

This is how it works:

Create a context object with the relevant properties

Apply the context to your ItemsControl

Let de properties rebind on context changed

Your idea of gathering the properties per entity is certainly a good one. Though the implementation could be better, both the viewmodel and the view look bloated. That's what this context object is all about, gathering and keeping state as you swap contexts back and forth.

Starting with our model classes. Let's code against an interface (even though ItemsSource is untyped).

namespace WpfApp.Models
{
    public interface IEntity
    {
        string Name { get; }
    }

    public class Dog : IEntity
    {
        public Dog(string breed, string name)
        {
            Breed = breed;
            Name = name;
        }

        public string Breed { get; }
        public string Name { get; }
    }

    public class Author : IEntity
    {
        public Author(string genre, string name)
        {
            Genre = genre;
            Name = name;
        }

        public string Genre { get; }
        public string Name { get; }
    }
}

Next, the ViewModels, starting with our context.

namespace WpfApp.ViewModels
{
    public class ItemsContext : ViewModelBase
    {
        public ItemsContext(IEnumerable<IEntity> items)
        {
            if (items == null || !items.Any()) throw new ArgumentException(nameof(Items));

            Items = new ObservableCollection<IEntity>(items);
            SelectedItem = Items.First();
        }

        public ObservableCollection<IEntity> Items { get; }

        private IEntity selectedItem;
        public IEntity SelectedItem
        {
            get { return selectedItem; }
            set
            {
                selectedItem = value;
                OnPropertyChanged();
            }
        }

        public string DisplayMemberPath { get; set; }
    }
}

As said, the relevant properties, with notifications for SelectedItem, nothing special. We immediately see the effect on our MainViewModel.

namespace WpfApp.ViewModels
{
    public class MainViewModel : ViewModelBase
    {
        private readonly ItemsContext _dogContext;
        private readonly ItemsContext _authorContext;

        public MainViewModel()
        {
            _dogContext = new ItemsContext(FetchDogs()) { DisplayMemberPath = nameof(Dog.Breed) };
            _authorContext = new ItemsContext(FetchAuthors()) { DisplayMemberPath = nameof(Author.Genre) };
        }

        private ItemsContext selectedContext;
        public ItemsContext SelectedContext
        {
            get { return selectedContext; }
            set
            {
                selectedContext = value;
                OnPropertyChanged();
            }
        }

        private bool dogChecked;
        public bool DogChecked
        {
            get { return dogChecked; }
            set
            {
                dogChecked = value;
                if(dogChecked) SelectedContext = _dogContext;
            }
        }

        private bool authorChecked;
        public bool AuthorChecked
        {
            get { return authorChecked; }
            set
            {
                authorChecked = value;
                if(authorChecked) SelectedContext = _authorContext;
            }
        }

        private static IEnumerable<IEntity> FetchDogs() =>
            new List<IEntity>
            {
                new Dog("Terrier", "Ralph"),
                new Dog("Beagle", "Eddy"),
                new Dog("Poodle", "Fifi")
            };

        private static IEnumerable<IEntity> FetchAuthors() =>
            new List<IEntity>
            {
                new Author("SciFi", "Bradbury"),
                new Author("RomCom", "James")
            };
    }
}

Two cleanly separated flows, each managing its own context. It's clear you could easily extend this to any number of contexts, without them getting in each others way. Now, to apply the context to our ItemsControl we have two options. We could subclass our Control or use an Attached Property. Favoring composition over inheritance, here's the class with the AP.

namespace WpfApp.Extensions
{
    public class Selector
    {
        public static ItemsContext GetContext(DependencyObject obj) => (ItemsContext)obj.GetValue(ContextProperty);
        public static void SetContext(DependencyObject obj, ItemsContext value) => obj.SetValue(ContextProperty, value);

        public static readonly DependencyProperty ContextProperty =
            DependencyProperty.RegisterAttached("Context", typeof(ItemsContext), typeof(Selector), new PropertyMetadata(null, OnItemsContextChanged));

        private static void OnItemsContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var selector = (System.Windows.Controls.Primitives.Selector)d;
            var ctx = (ItemsContext)e.NewValue;

            if (e.OldValue != null) // Clean up bindings from previous context, if any
            {
                BindingOperations.ClearBinding(selector, System.Windows.Controls.Primitives.Selector.SelectedItemProperty);
                BindingOperations.ClearBinding(selector, ItemsControl.ItemsSourceProperty);
                BindingOperations.ClearBinding(selector, ItemsControl.DisplayMemberPathProperty);
            }

            selector.SetBinding(System.Windows.Controls.Primitives.Selector.SelectedItemProperty, new Binding(nameof(ItemsContext.SelectedItem)) { Source = ctx, Mode = BindingMode.TwoWay });
            selector.SetBinding(ItemsControl.ItemsSourceProperty, new Binding(nameof(ItemsContext.Items)) { Source = ctx });
            selector.SetBinding(ItemsControl.DisplayMemberPathProperty, new Binding(nameof(ItemsContext.DisplayMemberPath)) { Source = ctx });
        }
    }
}

That covers both steps 2 and 3. You can tweak this however you like. For example, we've made ItemsContext.DisplayMemberPath a non notifying prop, so you could just set the value directly instead of through binding.

Finally, the view, where it all comes together.

<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:vm="clr-namespace:WpfApp.ViewModels"
        xmlns:ext="clr-namespace:WpfApp.Extensions"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" WindowStartupLocation="CenterScreen">
    <Window.DataContext>
        <vm:MainViewModel/>
    </Window.DataContext>
    <Window.Resources>
        <Style x:Key="SelectorStyle" TargetType="{x:Type Selector}">
            <Setter Property="Width" Value="150"/>
            <Setter Property="HorizontalAlignment" Value="Left"/>
            <Setter Property="Margin" Value="0,20"/>
        </Style>
    </Window.Resources>
    <StackPanel Margin="20">
        <RadioButton GroupName="Entities" Content="Dogs" IsChecked="{Binding DogChecked}" />
        <RadioButton GroupName="Entities" Content="Authors" IsChecked="{Binding AuthorChecked}" />
        <ComboBox ext:Selector.Context="{Binding SelectedContext}" Style="{StaticResource SelectorStyle}" />
        <ListBox  ext:Selector.Context="{Binding SelectedContext}" Style="{StaticResource SelectorStyle}" />
        <DataGrid ext:Selector.Context="{Binding SelectedContext}" Style="{StaticResource SelectorStyle}" />
    </StackPanel>
</Window>

The cool thing about the Attached Property is that we're coding against the abstract Selector control, which is a direct descendant of ItemsControl. So without changing our lower layers we can share our context with ListBox and DataGrid as well.


来源: stackexchange

问:
UIAction with two delete buttons
I have an ActionSheets with 2 delete buttons, "delete all" and "delete selected item".

Since delete is an destructive behavior, should i definitely keep them as "destructive buttons" or can i keep them as normal buttons without any destructive button at all?

Advice would greatly help me.

Thanks

答:
See if this helps Multiple red/destructive buttons UIActionSheet

I personally think having the "delete all" button alone as destructive and the other as a normal button

ContentLicense: CC BY-SA 3.0

Title: UIAction with two delete buttons


问:
How to turn vue.js method inside a component to a created method
I am working with a vue.js code base where a method inside the component is being called by onclick()

instead I want the method to just be ran when the page loads rather than be called by onclick.  Reading the vue.js docs I believe I need to use a vue method called created(),  Can I simply replace 'method' with 'created' or what exactly do I need to do to run this method on page load.

```<code><script>
    Vue.component('job-execs', {
        delimiters: [ '[[', ']]' ],
        props: ['job'],
        data: function() {
                return {
                    showExecs: false,
                    build_ids: []
                }
            },
        methods: {
            jobExecs() {
                url = "api/v2/exec?" + this.job.api_url + "&limit=10"
                fetch(url)
                    .then(response => response.json())
                    .then(body => {
                        for(i=0; i<body.length; i++){
                            start_date = JSON.stringify(body[i].time_start)
                            start_date = start_date.match(/"?(.*)T(.*)/)[1];
                            this.build_ids.push({
                                'id': JSON.stringify(body[i].id),
                            })
                        }
                    })
                    .catch( err => {
                        console.log('Error Fetching:', url, err);
                        return { 'failure': url, 'reason': err };
                    });
                }
        },
</code>```

答:
as the lifecycle of vuejs app, to first thing vuejs do is to run the created,

so in your case, you should put the jobExecs function within created hook.

for more information check Instance Lifecycle Hooks Vuejs doc

in that case, your component will be like below :

```<code><script>
    Vue.component('job-execs', {
        delimiters: [ '[[', ']]' ],
        props: ['job'],
        data: function() {
                return {
                    showExecs: false,
                    build_ids: []
                }
            },
        created() {
               this.jobExecs();
        },
        methods: {
            jobExecs() {
                url = "api/v2/exec?" + this.job.api_url + "&limit=10"
                fetch(url)
                    .then(response => response.json())
                    .then(body => {
                        for(i=0; i<body.length; i++){
                            start_date = JSON.stringify(body[i].time_start)
                            start_date = start_date.match(/"?(.*)T(.*)/)[1];
                            this.build_ids.push({
                                'id': JSON.stringify(body[i].id),
                            })
                        }
                    })
                    .catch( err => {
                        console.log('Error Fetching:', url, err);
                        return { 'failure': url, 'reason': err };
                    });
                }
        },
</code>```

ContentLicense: CC BY-SA 4.0

Body:
as the lifecycle of vuejs app, to first thing vuejs do is to run the created,

so in your case, you should put the jobExecs function within created hook.

for more information check Instance Lifecycle Hooks Vuejs doc

in that case, your component will be like below :

<script>
    Vue.component('job-execs', {
        delimiters: [ '[[', ']]' ],
        props: ['job'],
        data: function() {
                return {
                    showExecs: false,
                    build_ids: []
                }
            },
        created() {
               this.jobExecs();
        },
        methods: {
            jobExecs() {
                url = "api/v2/exec?" + this.job.api_url + "&limit=10"
                fetch(url)
                    .then(response => response.json())
                    .then(body => {
                        for(i=0; i<body.length; i++){
                            start_date = JSON.stringify(body[i].time_start)
                            start_date = start_date.match(/"?(.*)T(.*)/)[1];
                            this.build_ids.push({
                                'id': JSON.stringify(body[i].id),
                            })
                        }
                    })
                    .catch( err => {
                        console.log('Error Fetching:', url, err);
                        return { 'failure': url, 'reason': err };
                    });
                }
        },


问:
How to create a Sudoku puzzle in Python
Goal is to create a 9x9 Sudoku matrix in Python.

So I got this far.  But I cannot seem to get the program to get the interior contingent boxes correct.

def sudoku(size):
    import random as rn
    mydict = {}
    n = 0
    while len(mydict) < 9:
        n += 1
        x = range(1, size+1)
        testlist = rn.sample(x, len(x))

        isgood = True
        for dictid,savedlist in mydict.items():
            if isgood == False:
                break
            for v in savedlist:
                if testlist[savedlist.index(v)] == v:
                    isgood = False
                    break
        if isgood == True:
            #print 'success', testlist
            mydict[len(mydict)] = testlist
    return mydict, n

return_dict, total_tries = sudoku(9)
for n,v in return_dict.items():
    print n,v
print 'in',total_tries,'tries'
```

答:
If your goal is to create 9 x 9 Sudoku, then why not a simpler program?
    Works on any of n^2 x n^2 (boards) in poly-time. To create a puzzle, you may have to remove elements manually. Guaranteeing one solution requires some backtracking. Poly-time is what you want for larger n^2 x n^2 Sudoku Latin-Squares.

```<code>#Provide a list of non-repeating n-elements to output a valid sudoku grid.
#this code runs on python3
print('enter with [1,2,3...] brackets')
tup = input()[1:-1].split(',')
    #Input required to map out valid n x m or n^2 x n^2 Sudoku Grid
x = input('Enter mapping valid Sudoku eg. 3 for 9 x 9:')
e = input('Enter 9 for 9 x 9 ...12 for 12 x 12:')
f = input('Enter 3 if its a 9 x 9 ... n^2 x n^2:')
x = int(x)
e = int(e)
f = int(f)
    #Manipulation of Elements to prepare valid grid
squares = []
for i in range(len(tup)):
      squares.append(tup[i:] + tup[:i])

        #Everything below here is just printing
for s in range(x):
          for d in range(0,e,f):
            for si in range(s,e,f):
              for li in range(d,d+f):
                print(squares[si][li], end = '')
            print('')

#Remember that if you want
#to create a single board of n^2 x n^2
#you need to edit the below
#for a valid grid
#for example
#a 9 x 9
#would be a 3 x 3
#and so on.
</code>```

No repeating elements!
For grids larger than 9 x 9 please use additonal brackets for readablity. eg. [[01],[02],[03],....]
Also, please remember that you need to know multiplication to output a properly mapped n^2 x n^2. For example, a 25 x 25
should be a 5 x 5 for the inputs as follows

For x, x = 5

For e, e = 25

for f, f = 5

Also, I had a buddy who helped me convert my algorithm into this python code for my amateur Sudoku project. Thanks to that Reddit user.

By the way, it's actually O(m^2) time.
Proof

Thank you Reddit buddy for the help.

Title: How to create a Sudoku puzzle in Python

Body:
If your goal is to create 9 x 9 Sudoku, then why not a simpler program?
    Works on any of n^2 x n^2 (boards) in poly-time. To create a puzzle, you may have to remove elements manually. Guaranteeing one solution requires some backtracking. Poly-time is what you want for larger n^2 x n^2 Sudoku Latin-Squares.

#Provide a list of non-repeating n-elements to output a valid sudoku grid.
#this code runs on python3
print('enter with [1,2,3...] brackets')
tup = input()[1:-1].split(',')
    #Input required to map out valid n x m or n^2 x n^2 Sudoku Grid
x = input('Enter mapping valid Sudoku eg. 3 for 9 x 9:')
e = input('Enter 9 for 9 x 9 ...12 for 12 x 12:')
f = input('Enter 3 if its a 9 x 9 ... n^2 x n^2:')
x = int(x)
e = int(e)
f = int(f)
    #Manipulation of Elements to prepare valid grid
squares = []
for i in range(len(tup)):
      squares.append(tup[i:] + tup[:i])

        #Everything below here is just printing
for s in range(x):
          for d in range(0,e,f):
            for si in range(s,e,f):
              for li in range(d,d+f):
                print(squares[si][li], end = '')
            print('')

#Remember that if you want
#to create a single board of n^2 x n^2
#you need to edit the below
#for a valid grid
#for example
#a 9 x 9
#would be a 3 x 3
#and so on.

No repeating elements!
For grids larger than 9 x 9 please use additonal brackets for readablity. eg. [[01],[02],[03],....]
Also, please remember that you need to know multiplication to output a properly mapped n^2 x n^2. For example, a 25 x 25
should be a 5 x 5 for the inputs as follows

For x, x = 5

For e, e = 25

for f, f = 5

Also, I had a buddy who helped me convert my algorithm into this python code for my amateur Sudoku project. Thanks to that Reddit user.

By the way, it's actually O(m^2) time.
Proof

Thank you Reddit buddy for the help.


问:
question to get the correct code for a specific query from a database
i have a problem with the code to get an specific information from a database.
What i want is the number of cities repeated in each CountryCode (country).

what is get until this moment is the number of cities reapeated in each group of city.Name (groups with the same value of city.Name),

```<code>SELECT count(*) as numberOfCitiesRepeated,city.CountryCode from city
group by city.Name
having count(*) >1
order by countryCode
</code>```

and thats good beacuse i only have to count the number of values group by CountryCode (country) and i will solve the problem, but i tried:

```<code>COUNT(SELECT count(*) as numberOfCitiesRepeated,city.CountryCode from city
group by city.Name
having count(*) >1
order by countryCode) from city group by city.CountryCode
</code>```

and it didnt work, it doesnt compile.

thats the mysql db im using:

and this is what the first query return me:

答:
I solved my problem with the help of Eric and a mysql concept called VIEWS.

I could obtain the number of cities repeated of a determined country using 2 queries. In this example i get the number of cities repeated of china which its countryCode is CHN.

With this query you create a view which get the cities repeated from a country and the countrycode of the country which it belong.

```<code>CREATE VIEW citiesRepeatedInCountries as
SELECT  city.Name, city.CountryCode FROM city
GROUP BY city.Name, city.CountryCode
HAVING count(*) > 1
order by countryCode
</code>```

An with this query you count the quantity of register which its countryCode is CHN.

```<code>select count(*) as numOfCitiesRepeatedInChina from world.citiesRepeatedInCountries
where world.citiesRepeatedInCountries.CountryCode='CHN'
</code>```

:)

Body:
i have a problem with the code to get an specific information from a database.
What i want is the number of cities repeated in each CountryCode (country).

what is get until this moment is the number of cities reapeated in each group of city.Name (groups with the same value of city.Name),

SELECT count(*) as numberOfCitiesRepeated,city.CountryCode from city
group by city.Name
having count(*) >1
order by countryCode

and thats good beacuse i only have to count the number of values group by CountryCode (country) and i will solve the problem, but i tried:

COUNT(SELECT count(*) as numberOfCitiesRepeated,city.CountryCode from city
group by city.Name
having count(*) >1
order by countryCode) from city group by city.CountryCode

and it didnt work, it doesnt compile.

thats the mysql db im using:

and this is what the first query return me:

Body:
I solved my problem with the help of Eric and a mysql concept called VIEWS.

I could obtain the number of cities repeated of a determined country using 2 queries. In this example i get the number of cities repeated of china which its countryCode is CHN.

With this query you create a view which get the cities repeated from a country and the countrycode of the country which it belong.

CREATE VIEW citiesRepeatedInCountries as
SELECT  city.Name, city.CountryCode FROM city
GROUP BY city.Name, city.CountryCode
HAVING count(*) > 1
order by countryCode

An with this query you count the quantity of register which its countryCode is CHN.

select count(*) as numOfCitiesRepeatedInChina from world.citiesRepeatedInCountries
where world.citiesRepeatedInCountries.CountryCode='CHN'

:)


问:
SOAP message error with addiotional XML tags
```<code>NSString *urlString = @"http://172.29.165.219:8090/abc/services/Abc";
NSString *soapMessage = [NSString stringWithFormat:
                         @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                         "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                         "<soap:Body>\n"
                         "<getUserInfo>\n"
                         "<email>%@</email>\n"
                         "<pwd>%@</pwd>\n"
                         "</getUserInfo>\n"
                         "</soap:Body>\n"
                         "</soap:Envelope>\n", @"babla.sharan@tcs.com",@"UGFzc0AxMjM="//,@"50006F0063006B0065007400500043000000-444556494345454D00",@"PocketPC"
                         ];
NSMutableURLRequest *loginRequest = [RequestGenerator -generateSOAPRequestWithURLString:urlString soapMessage:soapMessage contentType:@"text/xml; charset=utf-8" action:@"getUserInfo"];
WebServiceHandler *connection = [[WebServiceHandler alloc]init];
</code>```

For the Above code, it works fine, but when I add additional Tag  as parent tag to id and password

```<code>NSString *urlString = @"http://172.29.165.219:8090/abc/services/Abc";
NSString *soapMessage = [NSString stringWithFormat:
                         @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                         "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                         "<soap:Body>\n"
                         "<getUserInfo>\n"
                         **"<ABC>\n"**
                                                     "<email>%@</email>\n"
                         "<pwd>%@</pwd>\n"
                                                     **"</ABC>\n"**
                         "</getUserInfo>\n"
                         "</soap:Body>\n"
                         "</soap:Envelope>\n", @"babla.sharan@tcs.com",@"UGFzc0AxMjM="//,@"50006F0063006B0065007400500043000000-444556494345454D00",@"PocketPC"
                         ];
NSMutableURLRequest *loginRequest = [RequestGenerator generateSOAPRequestWithURLString:urlString soapMessage:soapMessage contentType:@"text/xml; charset=utf-8" action:@"getUserInfo"];
WebServiceHandler *connection = [[WebServiceHandler alloc]init];
</code>```

It shows exception and get this error:

org.xml.sax.SAXException: SimpleDeserializer encountered a child element, which is NOT expected, in something it was trying to deserialize.

It doesn't even allow me to hit the server.

答:
Here in second soap message you are sending an additional parent tag for you information, which may not be recognized by you server. If this tag is optional than there should be no problem at all, but if it is undesired then you should not use it. Below are the excerpts from W3.org(http://www.w3.org/TR/2000/NOTE-SOAP-20000508/) .... which tells about the receiving and processing of soap request.</p>

```<code>A SOAP application receiving a SOAP message MUST process that message by performing
    the following actions in the order listed below:

         1. Identify all parts of the SOAP message intended for that application
         2. Verify that all mandatory parts identified in step 1 are supported by
 the  application for this message (see section 4.2.3) and process them accordingly.
 If this is   not the case then discard the message .
 The processor MAY ignore optional parts identified in step 1 without affecting the outcome of the processing.
        3. If the SOAP application is not the ultimate destination of the message then
     remove all parts identified in step 1 before forwarding the message.

  Processing a message or a part of a message requires that the SOAP processor
  understands, among other things, the exchange pattern being used (one way,
  request/response, multicast, etc.), the role of the recipient in that pattern, the
  employment (if any) of RPC mechanisms such as the one documented in section 7, the
  representation or encoding of data, as well as other semantics necessary for correct
  processing
</code>```

Body:
NSString *urlString = @"http://172.29.165.219:8090/abc/services/Abc";
NSString *soapMessage = [NSString stringWithFormat:
                         @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                         "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                         "<soap:Body>\n"
                         "<getUserInfo>\n"
                         "<email>%@</email>\n"
                         "<pwd>%@</pwd>\n"
                         "</getUserInfo>\n"
                         "</soap:Body>\n"
                         "</soap:Envelope>\n", @"babla.sharan@tcs.com",@"UGFzc0AxMjM="//,@"50006F0063006B0065007400500043000000-444556494345454D00",@"PocketPC"
                         ];
NSMutableURLRequest *loginRequest = [RequestGenerator -generateSOAPRequestWithURLString:urlString soapMessage:soapMessage contentType:@"text/xml; charset=utf-8" action:@"getUserInfo"];
WebServiceHandler *connection = [[WebServiceHandler alloc]init];

For the Above code, it works fine, but when I add additional Tag  as parent tag to id and password

NSString *urlString = @"http://172.29.165.219:8090/abc/services/Abc";
NSString *soapMessage = [NSString stringWithFormat:
                         @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                         "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                         "<soap:Body>\n"
                         "<getUserInfo>\n"
                         **"<ABC>\n"**
                                                     "<email>%@</email>\n"
                         "<pwd>%@</pwd>\n"
                                                     **"</ABC>\n"**
                         "</getUserInfo>\n"
                         "</soap:Body>\n"
                         "</soap:Envelope>\n", @"babla.sharan@tcs.com",@"UGFzc0AxMjM="//,@"50006F0063006B0065007400500043000000-444556494345454D00",@"PocketPC"
                         ];
NSMutableURLRequest *loginRequest = [RequestGenerator generateSOAPRequestWithURLString:urlString soapMessage:soapMessage contentType:@"text/xml; charset=utf-8" action:@"getUserInfo"];
WebServiceHandler *connection = [[WebServiceHandler alloc]init];

It shows exception and get this error:

org.xml.sax.SAXException: SimpleDeserializer encountered a child element, which is NOT expected, in something it was trying to deserialize.

It doesn't even allow me to hit the server.

Body:
Here in second soap message you are sending an additional parent tag for you information, which may not be recognized by you server. If this tag is optional than there should be no problem at all, but if it is undesired then you should not use it. Below are the excerpts from W3.org(http://www.w3.org/TR/2000/NOTE-SOAP-20000508/) .... which tells about the receiving and processing of soap request.

A SOAP application receiving a SOAP message MUST process that message by performing
    the following actions in the order listed below:

         1. Identify all parts of the SOAP message intended for that application
         2. Verify that all mandatory parts identified in step 1 are supported by
 the  application for this message (see section 4.2.3) and process them accordingly.
 If this is   not the case then discard the message .
 The processor MAY ignore optional parts identified in step 1 without affecting the outcome of the processing.
        3. If the SOAP application is not the ultimate destination of the message then
     remove all parts identified in step 1 before forwarding the message.

  Processing a message or a part of a message requires that the SOAP processor
  understands, among other things, the exchange pattern being used (one way,
  request/response, multicast, etc.), the role of the recipient in that pattern, the
  employment (if any) of RPC mechanisms such as the one documented in section 7, the
  representation or encoding of data, as well as other semantics necessary for correct
  processing


问:
How to list pools in linux redhat?
In Solaris, using zpool list command to list available pools.
What is the command for listing pools in Linux red-hat 7.6</p>

答:
If you're using LVM-based storage pools, you can use something like virsh pool-list --all
There's extensive documentation at docs.redhat.com.
There's also ZFS on RedHat, but you have to install it separately.

Title: How to list pools in linux redhat?


问:
Is definining scale-down-utilization-threshold on GKE possible?
Can you even define the scale-down-utilization-threshold on GKE?  I can't figure out where I would define this if it is actually possible.</p>

答:
I'm not sure if you mean scale down an HPA or scale down a VPA or scale down cluster nodes based on the cluster autoscaler, or scale down GCP instance groups or an AWS ASGs.

A Kubernetes HPA supports it based on a metric (typically CPU utilization). It will scale down to a minimum number of replicas defined in the HPA Kubernetes resource.

A Kubernetes VPA supports it based on requests/limits (CPU, Memory). Keep in mind that it's not supported if used together with an HPA that is also using CPU and memory as scale metrics.

The Kubernetes cluster autoscaler also supports downscaling based on the --scale-down-utilization-threshold and --scan-interval options. It's not recommended to use this together with a GCP instance group or an AWS ASG.

GCP Instance groups or AWS ASGs scale down is supported on the nodes provided that you are not using the cluster autoscaler and using CPU or other metrics specific to the cloud provider VM instances.

Hope it helps


问:
How to get 'isalpha' to iterate through each character of string?
I am having trouble figuring out how to check each character in the keyword (argv[1]). I know I am probably missing something super obvious. :(

I have tried saving the string to an array, declaring a new int, but still same problem.

```<code>//check to make sure 2nd argument is fully alphabetic
string keyword = argv[1];

for(int i = 0, n = strlen(keyword); i < n; i++)
{
    if(isalpha(keyword[i]))
    {
        printf("Success! \n");
        return 0;
    }
    else
    {
        printf("Invalid key, must be fully alphabetic. \n");
        return 1;
    }
}
</code>```

Expected output should be "Invalid key, must be fully alphabetic." for anything not fully alphabetic. Instead, it only works for the beginning character, not the whole keyword.

答:
Don't short circuit (by returning) unless the value is non-alphabetic; save printing Success and returning 0 for when the whole loop completes without exiting due to non-alphabetic characters:

```<code>for(int i = 0, n = strlen(keyword); i < n; i++)
{
    if(!isalpha(keyword[i]))
    {
        printf("Invalid key, must be fully alphabetic. \n");
        return 1;
    }
}
printf("Success! \n");
return 0;
</code>```

Body:
I am having trouble figuring out how to check each character in the keyword (argv[1]). I know I am probably missing something super obvious. :(

I have tried saving the string to an array, declaring a new int, but still same problem.

//check to make sure 2nd argument is fully alphabetic
string keyword = argv[1];

for(int i = 0, n = strlen(keyword); i < n; i++)
{
    if(isalpha(keyword[i]))
    {
        printf("Success! \n");
        return 0;
    }
    else
    {
        printf("Invalid key, must be fully alphabetic. \n");
        return 1;
    }
}

Expected output should be "Invalid key, must be fully alphabetic." for anything not fully alphabetic. Instead, it only works for the beginning character, not the whole keyword.

Body:
Don't short circuit (by returning) unless the value is non-alphabetic; save printing Success and returning 0 for when the whole loop completes without exiting due to non-alphabetic characters:

for(int i = 0, n = strlen(keyword); i < n; i++)
{
    if(!isalpha(keyword[i]))
    {
        printf("Invalid key, must be fully alphabetic. \n");
        return 1;
    }
}
printf("Success! \n");
return 0;


问:
Unexpected behavior involving const_cast
I came up with the following example, which exposes some unexpected behavior.
I would expect that after push_back, whatever is in the vector is there.
It looks like the compiler somehow decided to re-use memory used by str.

Could someone explain what is happening in this example?
Is this valid c++ code?

The original problem arises from code responsible for serializing / deserializing messages and it uses const_cast to remove constness.
After noticing some unexpected behavior with that code, I created this simplified example, which tries to demonstrate the issue.

#include <vector>
#include <iostream>
#include <string>
using namespace std;
int main()
{
    auto str = std::string("XYZ"); // mutable string
    const auto& cstr(str);         // const ref to it

    vector<string> v;
    v.push_back(cstr);

    cout << v.front() << endl;  // XYZ is printed as expected

    *const_cast<char*>(&cstr[0])='*'; // this will modify the first element in the VECTOR (is this expected?)
    str[1]='#';  //

    cout << str << endl;  // prints *#Z as expected
    cout << cstr << endl; // prints *#Z as expected
    cout << v.front() << endl; // Why *YZ is printed, not XYZ and not *#Z ?

    return 0;
}
```

答:
Understanding the bug

The unexpected behavior occurs because of quirks in a depreciated implementation of std::string. Older versions of GCC implemented std::string using copy-on-write semantics. It's a clever idea, but it causes bugs like the one you're seeing. What that means is that GCC tried to define std::string so that the internal string buffer only got copied if the new std::string was modified. For example:

```<code>std::string A = "Hello, world";
std::string B = A; // No copy occurs (yet)
A[3] = '*'; // Copy occurs now because A got modified.
</code>```

When you take a constant pointer, however, no copy occurs because the library assumes that the string will not be modified through that pointer:

```<code>std::string A = "Hello, world";
std::string B = A;
std::string const& A_ref = A;

const_cast<char&>(A_ref[3]) = '*'; // No copy occurs (your bug)
</code>```

As you've noticed, copy-on-write semantics tends to cause bugs. Because of this, and because copying a string is pretty cheap (all things considered), the copy copy-on-write implementation of std::string was depreciated and removed in GCC 5.

So why are you seeing this bug if you're using GCC 5? It's likely that you're compiling and linking an older version of the C++ standard library (one where copy-on-write is still the implementation of std::string). This is what's causing the bug for you.

Check which version of the C++ standard library you're compiling against, and if possible, update your compiler.

How can I tell which implemenation of std::string my compiler is using?

New GCC implementation: sizeof(std::string) == 32 (when compiling for 64 bit)

Old GCC implementation: sizeof(std::string) == 8 (when compiling for 64 bit)

If your compiler is using the old implementation of std::string, then sizeof(std::string) is the same as sizeof(char*) because std::string is implemented as a pointer to a block of memory. The block of memory is the one that actually contains things like the size and capacity of the string.

```<code>struct string { //Old data layout
    size_t* _data;
    size_t size() const {
        return *(data - SIZE_OFFSET);
    }
    size_t capacity() const {
        return *(data - CAPACITY_OFFSET);
    }
    char const* data() const {
        return (char const*)_data;
    }
};
</code>```

On the other hand, if you're using the newer implementation of std::string, then sizeof(std::string) should be 32 bytes (on 64 bit systems). This is because the newer implementation stores the size and capacity of the string within the std::string itself, rather than in the data it points to:

```<code>struct string { // New data layout
    char* _data;
    size_t _size;
    size_t _capacity;
    size_t _padding;
    // ...
};
</code>```

What's good about the new implementation? The new implementation has a number of benefits:

Accessing size and capacity can be done more quickly (since the optimizer is more likely to store them in the registers, or at the very least they're likely to be in the cache)

Because std::string is 32 bytes, we can take advantage of Small String Optimization. Small String Optimization allows strings less than 16 characters long to be stored within the space normally taken up by _capacity and _padding. This avoids heap allocations, and is faster for most use cases.

We can see below that GDB uses the old implementation of std::string, because sizeof(std::string) returns 8 bytes:

Body:
Understanding the bug

The unexpected behavior occurs because of quirks in a depreciated implementation of std::string. Older versions of GCC implemented std::string using copy-on-write semantics. It's a clever idea, but it causes bugs like the one you're seeing. What that means is that GCC tried to define std::string so that the internal string buffer only got copied if the new std::string was modified. For example:

std::string A = "Hello, world";
std::string B = A; // No copy occurs (yet)
A[3] = '*'; // Copy occurs now because A got modified.

When you take a constant pointer, however, no copy occurs because the library assumes that the string will not be modified through that pointer:

std::string A = "Hello, world";
std::string B = A;
std::string const& A_ref = A;

const_cast<char&>(A_ref[3]) = '*'; // No copy occurs (your bug)

As you've noticed, copy-on-write semantics tends to cause bugs. Because of this, and because copying a string is pretty cheap (all things considered), the copy copy-on-write implementation of std::string was depreciated and removed in GCC 5.

So why are you seeing this bug if you're using GCC 5? It's likely that you're compiling and linking an older version of the C++ standard library (one where copy-on-write is still the implementation of std::string). This is what's causing the bug for you.

Check which version of the C++ standard library you're compiling against, and if possible, update your compiler.

How can I tell which implemenation of std::string my compiler is using?

New GCC implementation: sizeof(std::string) == 32 (when compiling for 64 bit)

Old GCC implementation: sizeof(std::string) == 8 (when compiling for 64 bit)

If your compiler is using the old implementation of std::string, then sizeof(std::string) is the same as sizeof(char*) because std::string is implemented as a pointer to a block of memory. The block of memory is the one that actually contains things like the size and capacity of the string.

struct string { //Old data layout
    size_t* _data;
    size_t size() const {
        return *(data - SIZE_OFFSET);
    }
    size_t capacity() const {
        return *(data - CAPACITY_OFFSET);
    }
    char const* data() const {
        return (char const*)_data;
    }
};

On the other hand, if you're using the newer implementation of std::string, then sizeof(std::string) should be 32 bytes (on 64 bit systems). This is because the newer implementation stores the size and capacity of the string within the std::string itself, rather than in the data it points to:

struct string { // New data layout
    char* _data;
    size_t _size;
    size_t _capacity;
    size_t _padding;
    // ...
};

What's good about the new implementation? The new implementation has a number of benefits:

Accessing size and capacity can be done more quickly (since the optimizer is more likely to store them in the registers, or at the very least they're likely to be in the cache)

Because std::string is 32 bytes, we can take advantage of Small String Optimization. Small String Optimization allows strings less than 16 characters long to be stored within the space normally taken up by _capacity and _padding. This avoids heap allocations, and is faster for most use cases.

We can see below that GDB uses the old implementation of std::string, because sizeof(std::string) returns 8 bytes:


问:
Can I use the custom layouts in android app widget design?
I want to create one widget in android.I am doing the following steps.

```<code>    1.I designed on panel which is the subclass of linear layout(panel.java).
    2.while designing the widget layout I am using this panel as background.
    3.While adding the view in the launcher I am getting the following exception.
      Is it possible to add a custom layout in the appwidget layout design.

83): cdmaDbmEcioToSignal(cdmaDbm:-81, cdmaEcio:-145)
D/PhoneWindow(  764): DebugMonitor class=com.android.settings.AppWidgetPickActivity focus=false
W/AppWidgetHostView(  176): updateAppWidget couldn't find any view, using error view
W/AppWidgetHostView(  176): android.view.InflateException: Binary XML file line #6: Error inflating class com.i10n.panel.TransparentPanel
W/AppWidgetHostView(  176):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:576)
W/AppWidgetHostView(  176):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:618)
W/AppWidgetHostView(  176):     at android.view.LayoutInflater.inflate(LayoutInflater.java:407)
W/AppWidgetHostView(  176):     at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
W/AppWidgetHostView(  176):     at android.widget.RemoteViews.apply(RemoteViews.java:900)
W/AppWidgetHostView(  176):     at android.appwidget.AppWidgetHostView.updateAppWidget(AppWidgetHostView.java:208)
W/AppWidgetHostView(  176):     at android.appwidget.AppWidgetHost.createView(AppWidgetHost.java:217)
W/AppWidgetHostView(  176):     at com.jiubang.ggheart.apps.desks.diy.frames.screen.ScreenFrame.a(ScreenFrame.java:1169)
W/AppWidgetHostView(  176):     at com.jiubang.ggheart.apps.desks.diy.frames.screen.ScreenFrame.handleMessage(ScreenFrame.java:621)
W/AppWidgetHostView(  176):     at com.jiubang.core.framework.frame.MessageManager.send(MessageManager.java:60)
W/AppWidgetHostView(  176):     at com.jiubang.core.framework.frame.MessageSender.sendMessage(MessageSender.java:75)
W/AppWidgetHostView(  176):     at com.jiubang.ggheart.apps.desks.diy.DiyScheduler.f(DiyScheduler.java:2563)
W/AppWidgetHostView(  176):     at com.jiubang.ggheart.apps.desks.diy.DiyScheduler.onActivityResult(DiyScheduler.java:1804)
W/AppWidgetHostView(  176):     at com.jiubang.ggheart.apps.desks.diy.DiyScheduler.d(DiyScheduler.java:2417)
W/AppWidgetHostView(  176):     at com.jiubang.ggheart.apps.desks.diy.DiyScheduler.a(DiyScheduler.java:2389)
W/AppWidgetHostView(  176):     at com.jiubang.ggheart.apps.desks.diy.DiyScheduler.onActivityResult(DiyScheduler.java:1798)
W/AppWidgetHostView(  176):     at com.jiubang.ggheart.apps.desks.diy.GoLauncher.onActivityResult(GoLauncher.java:295)
W/AppWidgetHostView(  176):     at android.app.Activity.dispatchActivityResult(Activity.java:3868)
W/AppWidgetHostView(  176):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3500)
W/AppWidgetHostView(  176):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3546)
W/AppWidgetHostView(  176):     at android.app.ActivityThread.access$2700(ActivityThread.java:126)
W/AppWidgetHostView(  176):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1962)
W/AppWidgetHostView(  176):     at android.os.Handler.dispatchMessage(Handler.java:99)
W/AppWidgetHostView(  176):     at android.os.Looper.loop(Looper.java:123)
W/AppWidgetHostView(  176):     at android.app.ActivityThread.main(ActivityThread.java:4595)
W/AppWidgetHostView(  176):     at java.lang.reflect.Method.invokeNative(Native Method)
W/AppWidgetHostView(  176):     at java.lang.reflect.Method.invoke(Method.java:521)
W/AppWidgetHostView(  176):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
W/AppWidgetHostView(  176):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
W/AppWidgetHostView(  176):     at dalvik.system.NativeStart.main(Native Method)
W/AppWidgetHostView(  176): Caused by: java.lang.ClassNotFoundException: com.i10n.panel.TransparentPanel in loader dalvik.system.PathClassLoader@4001b710
W/AppWidgetHostView(  176):     at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
W/AppWidgetHostView(  176):     at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
W/AppWidgetHostView(  176):     at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
W/AppWidgetHostView(  176):     at android.view.LayoutInflater.createView(LayoutInflater.java:466)
W/AppWidgetHostView(  176):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:565)
W/AppWidgetHostView(  176):     ... 29 more
</code>```

Can I use a custom layout in the appwidgets.

答: Home screen widgets support very limited number of standard views. You can't use custom view or layouts for them. See App Widgets.</p>

Body:
I want to create one widget in android.I am doing the following steps.

    1.I designed on panel which is the subclass of linear layout(panel.java).
    2.while designing the widget layout I am using this panel as background.
    3.While adding the view in the launcher I am getting the following exception.
      Is it possible to add a custom layout in the appwidget layout design.

83): cdmaDbmEcioToSignal(cdmaDbm:-81, cdmaEcio:-145)
D/PhoneWindow(  764): DebugMonitor class=com.android.settings.AppWidgetPickActivity focus=false
W/AppWidgetHostView(  176): updateAppWidget couldn't find any view, using error view
W/AppWidgetHostView(  176): android.view.InflateException: Binary XML file line #6: Error inflating class com.i10n.panel.TransparentPanel
W/AppWidgetHostView(  176):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:576)
W/AppWidgetHostView(  176):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:618)
W/AppWidgetHostView(  176):     at android.view.LayoutInflater.inflate(LayoutInflater.java:407)
W/AppWidgetHostView(  176):     at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
W/AppWidgetHostView(  176):     at android.widget.RemoteViews.apply(RemoteViews.java:900)
W/AppWidgetHostView(  176):     at android.appwidget.AppWidgetHostView.updateAppWidget(AppWidgetHostView.java:208)
W/AppWidgetHostView(  176):     at android.appwidget.AppWidgetHost.createView(AppWidgetHost.java:217)
W/AppWidgetHostView(  176):     at com.jiubang.ggheart.apps.desks.diy.frames.screen.ScreenFrame.a(ScreenFrame.java:1169)
W/AppWidgetHostView(  176):     at com.jiubang.ggheart.apps.desks.diy.frames.screen.ScreenFrame.handleMessage(ScreenFrame.java:621)
W/AppWidgetHostView(  176):     at com.jiubang.core.framework.frame.MessageManager.send(MessageManager.java:60)
W/AppWidgetHostView(  176):     at com.jiubang.core.framework.frame.MessageSender.sendMessage(MessageSender.java:75)
W/AppWidgetHostView(  176):     at com.jiubang.ggheart.apps.desks.diy.DiyScheduler.f(DiyScheduler.java:2563)
W/AppWidgetHostView(  176):     at com.jiubang.ggheart.apps.desks.diy.DiyScheduler.onActivityResult(DiyScheduler.java:1804)
W/AppWidgetHostView(  176):     at com.jiubang.ggheart.apps.desks.diy.DiyScheduler.d(DiyScheduler.java:2417)
W/AppWidgetHostView(  176):     at com.jiubang.ggheart.apps.desks.diy.DiyScheduler.a(DiyScheduler.java:2389)
W/AppWidgetHostView(  176):     at com.jiubang.ggheart.apps.desks.diy.DiyScheduler.onActivityResult(DiyScheduler.java:1798)
W/AppWidgetHostView(  176):     at com.jiubang.ggheart.apps.desks.diy.GoLauncher.onActivityResult(GoLauncher.java:295)
W/AppWidgetHostView(  176):     at android.app.Activity.dispatchActivityResult(Activity.java:3868)
W/AppWidgetHostView(  176):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3500)
W/AppWidgetHostView(  176):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3546)
W/AppWidgetHostView(  176):     at android.app.ActivityThread.access$2700(ActivityThread.java:126)
W/AppWidgetHostView(  176):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1962)
W/AppWidgetHostView(  176):     at android.os.Handler.dispatchMessage(Handler.java:99)
W/AppWidgetHostView(  176):     at android.os.Looper.loop(Looper.java:123)
W/AppWidgetHostView(  176):     at android.app.ActivityThread.main(ActivityThread.java:4595)
W/AppWidgetHostView(  176):     at java.lang.reflect.Method.invokeNative(Native Method)
W/AppWidgetHostView(  176):     at java.lang.reflect.Method.invoke(Method.java:521)
W/AppWidgetHostView(  176):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
W/AppWidgetHostView(  176):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
W/AppWidgetHostView(  176):     at dalvik.system.NativeStart.main(Native Method)
W/AppWidgetHostView(  176): Caused by: java.lang.ClassNotFoundException: com.i10n.panel.TransparentPanel in loader dalvik.system.PathClassLoader@4001b710
W/AppWidgetHostView(  176):     at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
W/AppWidgetHostView(  176):     at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
W/AppWidgetHostView(  176):     at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
W/AppWidgetHostView(  176):     at android.view.LayoutInflater.createView(LayoutInflater.java:466)
W/AppWidgetHostView(  176):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:565)
W/AppWidgetHostView(  176):     ... 29 more

Can I use a custom layout in the appwidgets.


问:
bz2 module fails when building Python 3.7
I'm trying to cross compile Python 3.7 for Android.  I see in my output that bz2 if failing with the following error

```<code>building '_bz2' extension
/home/dematic/SPE/python3-android/sdk/android-ndk-r19c/toolchains/llvm/prebuilt/linux-x86_64/bin/clang -isystem /home/dematic/SPE/python3-android/build/19c-22-aarch64-linux-androideabi-4.9/include -isystem /home/dematic/SPE/python3-android/build/19c-22-aarch64-linux-androideabi-4.9/include/openssl -no-integrated-as -I. -I./Include -target aarch64-none-linux-androideabi22 -target aarch64-none-linux-androideabi22 -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -fPIC -std=c99 -Wextra -Wno-unused-result -Wno-unused-parameter -Wno-missing-field-initializers -Wstrict-prototypes -Werror=implicit-function-declaration -I./Include -I. -I/home/dematic/SPE/python3-android/src/Python-3.7.3/Include -I/home/dematic/SPE/python3-android/src/Python-3.7.3 -c /home/dematic/SPE/python3-android/src/Python-3.7.3/Modules/_bz2module.c -o build/temp.linux-aarch64-3.7/home/dematic/SPE/python3-android/src/Python-3.7.3/Modules/_bz2module.o
/home/dematic/SPE/python3-android/sdk/android-ndk-r19c/toolchains/llvm/prebuilt/linux-x86_64/bin/clang -isystem /home/dematic/SPE/python3-android/build/19c-22-aarch64-linux-androideabi-4.9/include -isystem /home/dematic/SPE/python3-android/build/19c-22-aarch64-linux-androideabi-4.9/include/openssl -no-integrated-as -shared -target aarch64-none-linux-androideabi22 -fuse-ld=lld -L /home/dematic/SPE/python3-android/build/19c-22-aarch64-linux-androideabi-4.9/lib -target aarch64-none-linux-androideabi22 -fuse-ld=lld -L /home/dematic/SPE/python3-android/build/19c-22-aarch64-linux-androideabi-4.9/lib -target aarch64-none-linux-androideabi22 -fuse-ld=lld -L /home/dematic/SPE/python3-android/build/19c-22-aarch64-linux-androideabi-4.9/lib -fPIC -target aarch64-none-linux-androideabi22 build/temp.linux-aarch64-3.7/home/dematic/SPE/python3-android/src/Python-3.7.3/Modules/_bz2module.o -L. -L/home/dematic/SPE/python3-android/build/19c-22-aarch64-linux-androideabi-4.9/lib -lbz2 -lpython3.7m -o build/lib.linux-aarch64-3.7/_bz2.cpython-37m.so
ld.lld: error: /home/dematic/SPE/python3-android/build/19c-22-aarch64-linux-androideabi-4.9/lib/libbz2.a(bzlib.o) is incompatible with aarch64linux
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

I am building bzip2 1.0.6 without any issues, but I assume I'm not linking to it correctly or some other issue. Is there some sort of other architecture I'm supposed to be building?

This is the project I'm trying to build with
https://github.com/GRRedWings/python3-android

答:
I'm trying to cross compile Python 3.7 for Android. I see in my output that bz2 if failing with the following error

The Bzip2 makefiles are not written for cross-compiles. They effectively ignore a user's flags like CFLAGS and LDFLAGS. The makefiles actually blows away a user's CFLAGS and sets it to CFLAGS=-Wall -Winline -O2 -g $(BIGFILES). Your flags like -target aarch64-none-linux-androideabi22 are not used.

There are two Makefiles in play. One is called Makefile and it builds the static library, if I recall correctly. The second is Makefile-libbz2_so, and it build the shared object. You need to fix the omissions and apply the fixes to both makefiles.

You should probably use a patched Bzip like bzip2-noloader. It honors a user's CFLAGS, CXXFLAGS, LDFLAGS, etc. The check-in of interest is Commit 34d170f31106.

The makefile recipes in bzip2-noloader look similar to the following. They preserve Seward's original settings in BZIP_CFLAGS. But they also utilize CPPFLAGS and allow a user override in CFLAGS. The override will pickup your flags like -target aarch64-none-linux-androideabi22.

```<code>blocksort.o: blocksort.c
    $(CC) $(CPPFLAGS) $(BZIP_CFLAGS) $(CFLAGS) -c blocksort.c
</code>```

Programs use LDFLAGS as expected:

```<code>bzip2: libbz2.a bzip2.o
    $(CC) $(CPPFLAGS) $(BZIP_CFLAGS) $(CFLAGS) $(LDFLAGS) -o bzip2 bzip2.o -L. -lbz2
</code>```

Finally, the bzip2-noloader fork also honor's PREFIX, DESTDIR, etc. So you can perform staged installs, too.

I am building bzip2 1.0.6 without any issues ...

You are probably building for i686 or x86_64, and not Aarch64. The problem does not surface until link time. You can use objdump to inspect the object files, if interested.

Also note the makefile does this:

```<code>CC=gcc
AR=ar
RANLIB=ranlib
LDFLAGS=
</code>```

You may need to tweak those variable assignments, too. Sometimes ar and ranlib use unusual names, like ranlib-5.0. And also be sure the tools are on-path.

The way to write makefiles to avoid these sorts of problems is detailed at 7.2.3 Variables for Specifying Commands in the GNU Coding Standards. The short of it is, (1) leave CFLAGS (and friends) for the user; and (2) if a flag is needed, then always supply it.

The GNU Coding Standards uses this as an example:

```<code>CFLAGS = -g
ALL_CFLAGS = -I. $(CFLAGS)
.c.o:
    $(CC) -c $(CPPFLAGS) $(ALL_CFLAGS) $<
</code>```

Users can override the default CFLAGS of -g, and -I is always added because it is needed for the compile.

Body:
I'm trying to cross compile Python 3.7 for Android.  I see in my output that bz2 if failing with the following error

building '_bz2' extension
/home/dematic/SPE/python3-android/sdk/android-ndk-r19c/toolchains/llvm/prebuilt/linux-x86_64/bin/clang -isystem /home/dematic/SPE/python3-android/build/19c-22-aarch64-linux-androideabi-4.9/include -isystem /home/dematic/SPE/python3-android/build/19c-22-aarch64-linux-androideabi-4.9/include/openssl -no-integrated-as -I. -I./Include -target aarch64-none-linux-androideabi22 -target aarch64-none-linux-androideabi22 -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -fPIC -std=c99 -Wextra -Wno-unused-result -Wno-unused-parameter -Wno-missing-field-initializers -Wstrict-prototypes -Werror=implicit-function-declaration -I./Include -I. -I/home/dematic/SPE/python3-android/src/Python-3.7.3/Include -I/home/dematic/SPE/python3-android/src/Python-3.7.3 -c /home/dematic/SPE/python3-android/src/Python-3.7.3/Modules/_bz2module.c -o build/temp.linux-aarch64-3.7/home/dematic/SPE/python3-android/src/Python-3.7.3/Modules/_bz2module.o
/home/dematic/SPE/python3-android/sdk/android-ndk-r19c/toolchains/llvm/prebuilt/linux-x86_64/bin/clang -isystem /home/dematic/SPE/python3-android/build/19c-22-aarch64-linux-androideabi-4.9/include -isystem /home/dematic/SPE/python3-android/build/19c-22-aarch64-linux-androideabi-4.9/include/openssl -no-integrated-as -shared -target aarch64-none-linux-androideabi22 -fuse-ld=lld -L /home/dematic/SPE/python3-android/build/19c-22-aarch64-linux-androideabi-4.9/lib -target aarch64-none-linux-androideabi22 -fuse-ld=lld -L /home/dematic/SPE/python3-android/build/19c-22-aarch64-linux-androideabi-4.9/lib -target aarch64-none-linux-androideabi22 -fuse-ld=lld -L /home/dematic/SPE/python3-android/build/19c-22-aarch64-linux-androideabi-4.9/lib -fPIC -target aarch64-none-linux-androideabi22 build/temp.linux-aarch64-3.7/home/dematic/SPE/python3-android/src/Python-3.7.3/Modules/_bz2module.o -L. -L/home/dematic/SPE/python3-android/build/19c-22-aarch64-linux-androideabi-4.9/lib -lbz2 -lpython3.7m -o build/lib.linux-aarch64-3.7/_bz2.cpython-37m.so
ld.lld: error: /home/dematic/SPE/python3-android/build/19c-22-aarch64-linux-androideabi-4.9/lib/libbz2.a(bzlib.o) is incompatible with aarch64linux
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I am building bzip2 1.0.6 without any issues, but I assume I'm not linking to it correctly or some other issue. Is there some sort of other architecture I'm supposed to be building?

This is the project I'm trying to build with
https://github.com/GRRedWings/python3-android

Body:
I'm trying to cross compile Python 3.7 for Android. I see in my output that bz2 if failing with the following error

The Bzip2 makefiles are not written for cross-compiles. They effectively ignore a user's flags like CFLAGS and LDFLAGS. The makefiles actually blows away a user's CFLAGS and sets it to CFLAGS=-Wall -Winline -O2 -g $(BIGFILES). Your flags like -target aarch64-none-linux-androideabi22 are not used.

There are two Makefiles in play. One is called Makefile and it builds the static library, if I recall correctly. The second is Makefile-libbz2_so, and it build the shared object. You need to fix the omissions and apply the fixes to both makefiles.

You should probably use a patched Bzip like bzip2-noloader. It honors a user's CFLAGS, CXXFLAGS, LDFLAGS, etc. The check-in of interest is Commit 34d170f31106.

The makefile recipes in bzip2-noloader look similar to the following. They preserve Seward's original settings in BZIP_CFLAGS. But they also utilize CPPFLAGS and allow a user override in CFLAGS. The override will pickup your flags like -target aarch64-none-linux-androideabi22.

blocksort.o: blocksort.c
    $(CC) $(CPPFLAGS) $(BZIP_CFLAGS) $(CFLAGS) -c blocksort.c

Programs use LDFLAGS as expected:

bzip2: libbz2.a bzip2.o
    $(CC) $(CPPFLAGS) $(BZIP_CFLAGS) $(CFLAGS) $(LDFLAGS) -o bzip2 bzip2.o -L. -lbz2

Finally, the bzip2-noloader fork also honor's PREFIX, DESTDIR, etc. So you can perform staged installs, too.

I am building bzip2 1.0.6 without any issues ...

You are probably building for i686 or x86_64, and not Aarch64. The problem does not surface until link time. You can use objdump to inspect the object files, if interested.

Also note the makefile does this:

CC=gcc
AR=ar
RANLIB=ranlib
LDFLAGS=

You may need to tweak those variable assignments, too. Sometimes ar and ranlib use unusual names, like ranlib-5.0. And also be sure the tools are on-path.

The way to write makefiles to avoid these sorts of problems is detailed at 7.2.3 Variables for Specifying Commands in the GNU Coding Standards. The short of it is, (1) leave CFLAGS (and friends) for the user; and (2) if a flag is needed, then always supply it.

The GNU Coding Standards uses this as an example:

CFLAGS = -g
ALL_CFLAGS = -I. $(CFLAGS)
.c.o:
    $(CC) -c $(CPPFLAGS) $(ALL_CFLAGS) $<

Users can override the default CFLAGS of -g, and -I is always added because it is needed for the compile.


问:
How to accept `Box<dyn Error + Send>` in places that accept `Box<dyn Error>`?
Can I accept a Box<dyn Error + Send> in places that accept Box<dyn Error>? If yes, how? If no, why, and is there a more elegant way to do it than in the following example?

#![allow(unused)]

use std::error::Error as StdError;
use std::result::Result as StdResult;

type    Result = StdResult<(), Box< dyn StdError >>;
type SndResult = StdResult<(), Box< dyn StdError + Send >>;

fn fn_returning_result()    ->    Result { Ok(()) }
fn fn_returning_sndresult() -> SndResult { Ok(()) }

/// Accept a callback that returns a non-Send `Result`.
fn register_callback<CB: FnOnce() -> Result>(cb: CB) { /* ... */ }

fn main() -> Result {
    // Is there a way to get rid of ... vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv ... this part?
    let cb = || fn_returning_sndresult().map_err(|e| -> Box<dyn StdError> { e });
    register_callback(cb);

    Ok(())
}
```

Playground

Edit: What I would like to do here is just let cb = || fn_returning_sndresult();, but that won't compile.

Also, I'd like to call either fn_returning_result()? or fn_returning_sndresult()? inside the callback with a single return type and without doing a map_err.

答:
Q: Can I accept a Box<dyn Error + Send> in places that accept Box<dyn Error>?

A: Yes, with some newtype wrapping. The solution I finally ended up with was this: (Playground)

use std::error::Error as StdError;
use std::result::Result as StdResult;
use std::fmt;

type    Result = StdResult<(), Box< dyn StdError >>;
type SndResult = StdResult<(), Box< dyn StdError + Send >>;

fn fn_returning_result()    ->    Result { dbg!(Err("oops".into())) }
fn fn_returning_sndresult() -> SndResult { dbg!(Ok(())) }

/// Result type using `Er` defined below.
type Rt<T = ()> = StdResult<T, Er>;

// Error wrapper

#[derive(Debug)]
struct Er(Box<dyn StdError>);

impl fmt::Display for Er {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

impl StdError for Er {}

// Allow `?` operator

impl From<Box<dyn StdError>> for Er {
    fn from(err: Box<dyn StdError>) -> Self {
        Er(err)
    }
}

impl From<Box<dyn StdError + Send>> for Er {
    fn from(err: Box<dyn StdError + Send>) -> Self {
        Er(err)
    }
}

// List of callbacks

struct Callbacks<'a>(Vec<Box<dyn FnOnce() -> Rt + 'a>>);

impl<'a> Callbacks<'a> {
    fn new() -> Self {
        Callbacks(Vec::new())
    }

    fn add(&mut self, cb: impl FnOnce() -> Rt + 'a) {
        self.0.push(Box::new(cb));
    }

    fn pop_and_call(&mut self) -> Rt {
        self.0.pop().unwrap()()
    }
}

// Example

fn main() -> Result {
    let mut callbacks = Callbacks::new();

    callbacks.add(|| { Ok(fn_returning_result()?) });
    callbacks.add(|| { Ok(fn_returning_sndresult()?) });

    callbacks.pop_and_call()?;
    callbacks.pop_and_call()?;

    Ok(())
}
```

Note that the callbacks can use ? on either Result or SndResult values (thanks to the From trait impls), and that their return values are valid Results as well, allowing main to also use ? on their calls (thanks to the StdError trait impl).

Body:
Can I accept a Box<dyn Error + Send> in places that accept Box<dyn Error>? If yes, how? If no, why, and is there a more elegant way to do it than in the following example?

#![allow(unused)]

use std::error::Error as StdError;
use std::result::Result as StdResult;

type    Result = StdResult<(), Box< dyn StdError >>;
type SndResult = StdResult<(), Box< dyn StdError + Send >>;

fn fn_returning_result()    ->    Result { Ok(()) }
fn fn_returning_sndresult() -> SndResult { Ok(()) }

/// Accept a callback that returns a non-Send `Result`.
fn register_callback<CB: FnOnce() -> Result>(cb: CB) { /* ... */ }

fn main() -> Result {
    // Is there a way to get rid of ... vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv ... this part?
    let cb = || fn_returning_sndresult().map_err(|e| -> Box<dyn StdError> { e });
    register_callback(cb);

    Ok(())
}

Playground

Edit: What I would like to do here is just let cb = || fn_returning_sndresult();, but that won't compile.

Also, I'd like to call either fn_returning_result()? or fn_returning_sndresult()? inside the callback with a single return type and without doing a map_err.

Body:
Q: Can I accept a Box<dyn Error + Send> in places that accept Box<dyn Error>?

A: Yes, with some newtype wrapping. The solution I finally ended up with was this: (Playground)

use std::error::Error as StdError;
use std::result::Result as StdResult;
use std::fmt;

type    Result = StdResult<(), Box< dyn StdError >>;
type SndResult = StdResult<(), Box< dyn StdError + Send >>;

fn fn_returning_result()    ->    Result { dbg!(Err("oops".into())) }
fn fn_returning_sndresult() -> SndResult { dbg!(Ok(())) }

/// Result type using `Er` defined below.
type Rt<T = ()> = StdResult<T, Er>;

// Error wrapper

#[derive(Debug)]
struct Er(Box<dyn StdError>);

impl fmt::Display for Er {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

impl StdError for Er {}

// Allow `?` operator

impl From<Box<dyn StdError>> for Er {
    fn from(err: Box<dyn StdError>) -> Self {
        Er(err)
    }
}

impl From<Box<dyn StdError + Send>> for Er {
    fn from(err: Box<dyn StdError + Send>) -> Self {
        Er(err)
    }
}

// List of callbacks

struct Callbacks<'a>(Vec<Box<dyn FnOnce() -> Rt + 'a>>);

impl<'a> Callbacks<'a> {
    fn new() -> Self {
        Callbacks(Vec::new())
    }

    fn add(&mut self, cb: impl FnOnce() -> Rt + 'a) {
        self.0.push(Box::new(cb));
    }

    fn pop_and_call(&mut self) -> Rt {
        self.0.pop().unwrap()()
    }
}

// Example

fn main() -> Result {
    let mut callbacks = Callbacks::new();

    callbacks.add(|| { Ok(fn_returning_result()?) });
    callbacks.add(|| { Ok(fn_returning_sndresult()?) });

    callbacks.pop_and_call()?;
    callbacks.pop_and_call()?;

    Ok(())
}

Note that the callbacks can use ? on either Result or SndResult values (thanks to the From trait impls), and that their return values are valid Results as well, allowing main to also use ? on their calls (thanks to the StdError trait impl).


问:
GlassMapper Get Default Context V5
We recently updated to GlassMapper V5 (and also Sitecore 9) and our application is breaking almost everywhere.

I am not able to find enough documentation on this. I see that ISitecoreContext has become obsolete and we are asked to use IMvcContext, IRequestContext etc., but I don't know how to use them.

This is what I have currently and I am not sure how to get the default Sitecore context. It throws an error saying that

SitecoreContextFactory doesn't exist

My code:

```<code>   ILink link = SitecoreContextFactory.Default.GetSitecoreContext().GetItem<ILink>(SitecoreItems.StoreLocatorPage);
</code>```

This is one such example. Can someone point me to the right documentation where I can find all replacement methods?

答:
Documentation about upgrading to GlassMapper V5 with the replacement methods can be found here.

You are absolutely right, SitecoreContext class has been marked as obsolete and from now on you should be using the new context offers:

MvcContext - use it for Controller Renderings; it provides access to DataSourceItem, PageContextItem, RenderingItem and RederingParameteres.

RequestContext - use it when you are outside of a controller and do not have a DataSource item available, i.e. event handler, pipeline processor.

Both contexts use SitecoreService for communication with Sitecore.

Title: GlassMapper Get Default Context V5

Body:
We recently updated to GlassMapper V5 (and also Sitecore 9) and our application is breaking almost everywhere.

I am not able to find enough documentation on this. I see that ISitecoreContext has become obsolete and we are asked to use IMvcContext, IRequestContext etc., but I don't know how to use them.

This is what I have currently and I am not sure how to get the default Sitecore context. It throws an error saying that

SitecoreContextFactory doesn't exist

My code:

   ILink link = SitecoreContextFactory.Default.GetSitecoreContext().GetItem<ILink>(SitecoreItems.StoreLocatorPage);

This is one such example. Can someone point me to the right documentation where I can find all replacement methods?


问:
python pandas - set column value of column based on index and or ID of concatenated dataframes
I have a concatenated dataframe of at least two concatenated dataframes:

```<code>i.e.
df1
  Name | Type | ID
0 Joe     A     1
1 Fred    B     2
2 Mike   Both   3
3 Frank  Both   4

df2
  Name | Type | ID
0 Bill   Both    1
1 Jill   Both    2
2 Mill   B       3
3 Hill   A       4

ConcatDf:
  Name | Type | ID
0 Joe     A     1
1 Fred    B     2
2 Mike   Both   3
3 Frank  Both   4
0 Bill   Both   1
1 Jill   Both   2
2 Mill   B      3
3 Hill   A      4
</code>```

Suppose after they are concatenated, I'd like to set Type for all records from df1 to C and all records from df2 to B. Is this possible?

The indices of the dataframes can be vastly different sizes.

Thanks in advance.

答:
Use merge with indicator=True to find rows belong to df1 or df2. Next, use np.where to assign A or B.

```<code>t = concatdf.merge(df1, how='left', on=concatdf.columns.tolist(), indicator=True)
concatdf['Type'] = np.where(t._merge.eq('left_only'), 'B', 'C')

Out[2185]:
    Name Type  ID
0    Joe    C   1
1   Fred    C   2
2   Mike    C   3
3  Frank    C   4
0   Bill    B   1
1   Jill    B   2
2   Mill    B   3
3   Hill    B   4
</code>```

Body:
I have a concatenated dataframe of at least two concatenated dataframes:

i.e.
df1
  Name | Type | ID
0 Joe     A     1
1 Fred    B     2
2 Mike   Both   3
3 Frank  Both   4

df2
  Name | Type | ID
0 Bill   Both    1
1 Jill   Both    2
2 Mill   B       3
3 Hill   A       4

ConcatDf:
  Name | Type | ID
0 Joe     A     1
1 Fred    B     2
2 Mike   Both   3
3 Frank  Both   4
0 Bill   Both   1
1 Jill   Both   2
2 Mill   B      3
3 Hill   A      4

Suppose after they are concatenated, I'd like to set Type for all records from df1 to C and all records from df2 to B. Is this possible?

The indices of the dataframes can be vastly different sizes.

Thanks in advance.

Body:
Use merge with indicator=True to find rows belong to df1 or df2. Next, use np.where to assign A or B.

t = concatdf.merge(df1, how='left', on=concatdf.columns.tolist(), indicator=True)
concatdf['Type'] = np.where(t._merge.eq('left_only'), 'B', 'C')

Out[2185]:
    Name Type  ID
0    Joe    C   1
1   Fred    C   2
2   Mike    C   3
3  Frank    C   4
0   Bill    B   1
1   Jill    B   2
2   Mill    B   3
3   Hill    B   4


问:
How to best subscribe to NGRX state change in view?
I'm brand new to ngrx and rxjs, so I think there's probably a simple solution for this that is not obvious to me yet :-)

I've got an ngrx store set up and working fine with the following state:

AppState

ThreadsState (Entity)

I've got actions and reducers set up working fine.  When a user creates a new Message, I dispatch an action MessageCreated which results in a new message being added to my store (inside array property of Thread entity), which in turn updates my view. Hooray!

The observable for my Thread is working and now includes the new Message:

```<code>thread$ = store.pipe(select(selectThreadWithMessages(id));
</code>```

My problem is I need a way to update a property on the newly created Message (isNew = true so an animation gets applied in view).  But, I don't want to just apply this to all messages.  I have it 'working' by simply applying it to the last Message in the array (which should always be the newest), but this doesn't feel like the "right" way to go.

What if I want to react to a newest item that comes in, when there isn't an easy way to know which one it is?

Here's what I've thought of doing:

Maybe initially subscribe to store to get initial data, and also have a stream of Messages that get added to the collection..?  Seems like maybe that's sidestepping the purpose of the store to begin with...

Maybe break out Messages into their own feature state and have a separate selector for that?  But maybe that doesn't really help with my original problem.

I guess what it comes down to in general is referencing an observable collection Message[] and correctly applying new individual instances Message that come along after the view loads.

I'm loving the idea of reactive programming, it just obviously not second-nature to me yet.

Any advice much appreciated..!

答:
Easiest solution might be to augment ThreadsState (Entity) to seperately store the "most recently created message". Then you could subscribe to that message and, when it changes, react appropriately.

If you are using ngrx effects, an alternative idea might be to inject the Actions stream into your component and subscribe to MessageCreated actions (looks like this would only work if the MessageCreated action's payload contained enough information to identify which message was created).

i.e.

constructor(
  private actions$: Actions,
) {}

ngOnInit() {
  this.subscriptions.push(
    this.actions$.pipe(ofType(MessageCreated)).subscribe(action => {
      // do stuff
    })
  )
}

ngOnDestroy() {
  this.subscriptions.forEach(sub => sub.unsubscribe())
}
```

Body:
I'm brand new to ngrx and rxjs, so I think there's probably a simple solution for this that is not obvious to me yet :-)

I've got an ngrx store set up and working fine with the following state:

AppState

ThreadsState (Entity)

I've got actions and reducers set up working fine.  When a user creates a new Message, I dispatch an action MessageCreated which results in a new message being added to my store (inside array property of Thread entity), which in turn updates my view. Hooray!

The observable for my Thread is working and now includes the new Message:

thread$ = store.pipe(select(selectThreadWithMessages(id));

My problem is I need a way to update a property on the newly created Message (isNew = true so an animation gets applied in view).  But, I don't want to just apply this to all messages.  I have it 'working' by simply applying it to the last Message in the array (which should always be the newest), but this doesn't feel like the "right" way to go.

What if I want to react to a newest item that comes in, when there isn't an easy way to know which one it is?

Here's what I've thought of doing:

Maybe initially subscribe to store to get initial data, and also have a stream of Messages that get added to the collection..?  Seems like maybe that's sidestepping the purpose of the store to begin with...

Maybe break out Messages into their own feature state and have a separate selector for that?  But maybe that doesn't really help with my original problem.

I guess what it comes down to in general is referencing an observable collection Message[] and correctly applying new individual instances Message that come along after the view loads.

I'm loving the idea of reactive programming, it just obviously not second-nature to me yet.

Any advice much appreciated..!


问:
The exit code, the return echo is different from the exit code of the program. Why?
I wrote a program that returns an error code using processes.
The result of the work of the program, if at the entrance to it provide the command of a false, is 255.
However the command
false; echo $?
returns 1
Why it happens?
Solaris, unix

I found the file false.c in the source code, it returns 255 (not sure if this is the right command)
https://github.com/illumos/illumos-gate/blob/master/usr/src/cmd/false/false.c

```<code>#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <wait.h>

main(int argc, char *argv[])
{
        int status;
        pid_t pid = fork();
        if (pid == -1){
                perror("fork error");
                exit(-1);
        }
        if (pid == 0) {
                execvp(argv[1], &argv[1]);
                perror(argv[1]);
                exit(-5);
        }
        if( wait(&status) == -1){
                perror("wait");
                exit(-1);
        }
        if(WIFEXITED(status))
                printf("exit status: %d\n",WEXITSTATUS(status));

        exit(0);
}
</code>```

答: UNIX (Linux, Solaris, BSD, etc.) exit codes may only be 0 - 255, where 0 is good and non-zero is an error. Exit codes are not signed, so the -1 may be converted to another (non-zero) value, as are values over 255.</p>

Body:
I wrote a program that returns an error code using processes.
The result of the work of the program, if at the entrance to it provide the command of a false, is 255.
However the command
false; echo $?
returns 1
Why it happens?
Solaris, unix

I found the file false.c in the source code, it returns 255 (not sure if this is the right command)
https://github.com/illumos/illumos-gate/blob/master/usr/src/cmd/false/false.c

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <wait.h>

main(int argc, char *argv[])
{
        int status;
        pid_t pid = fork();
        if (pid == -1){
                perror("fork error");
                exit(-1);
        }
        if (pid == 0) {
                execvp(argv[1], &argv[1]);
                perror(argv[1]);
                exit(-5);
        }
        if( wait(&status) == -1){
                perror("wait");
                exit(-1);
        }
        if(WIFEXITED(status))
                printf("exit status: %d\n",WEXITSTATUS(status));

        exit(0);
}