问:
data binding ListView Inside Listview
I have a class with ObservableCollection which one if is field is another ObservableCollection.

and I want to show the data in 1 row for the first ObservableCollection and using a plus sign or something else user can open the listview and see the other row which is the second ObseravableCollection.

however I am getting an error that could not take data from memory

will appreciate help with code example

attaching my code below

XAML

```<code> <ListView x:Name="dgEditEvent" ItemsSource="{Binding OMH1}"  >
                    <ListBox.ItemTemplate>
                        <DataTemplate >
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding a}" Width="50"></TextBlock>
                                <TextBlock Text="{Binding b}" Width="50"></TextBlock>
                                <TextBlock Text="{Binding c}" Width="50"></TextBlock>
                                <TextBlock Text="{Binding d}" Width="50"></TextBlock>
                                <TextBlock Text="{Binding Moshav1 }" Width="50"></TextBlock>
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListView>
</code>```

C#

```<code>public class Hartza : INotifyPropertyChanged
{
    private string _a;

    public string a
    {
       get
        {
            return _a;
        }

        set
        {
            _a = value;
            OnPropertyChanged("a");
        }
    }

    private string _b;

    public string b
    {
        get
        {
            return _b;
        }

        set
        {
            _b = value;
            OnPropertyChanged("b");
        }
    }

    private string _c;

    public string c
    {
        get
        {
            return _c;
        }

        set
        {
            _c = value;
            OnPropertyChanged("c");
        }
    }
    private string _d;

    public string d
    {
        get
        {
            return _d;
        }

        set
        {
            _d = value;
            OnPropertyChanged("d");
        }
    }

    public ObservableCollection<Moshav> Moshav1 { get; set; }

    public Hartza()
    {
        _a = "";
        _b = "";
        _c = "";
        _d = "";
        Moshav1 = new ObservableCollection<Moshav>();

    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

    public class Moshav
    {
        private string _e;

        public string e
        {
            get
            {
                return _e;
            }

            set
            {
                _e = value;
                OnPropertyChanged("e");
            }
        }

        private string _f;

        public string f
        {
            get
            {
                return _f;

            }

            set
            {
                    _f = value;
                OnPropertyChanged("f");
            }
        }

        private string _g;
        public string g
        {
            get
            {
                return _g;
            }

            set
            {
                _g = value;
                OnPropertyChanged("g");
            }
        }

        public Moshav()
        {
            _e = "";
            _f = "";
            _g = "";
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }

    }
}

    public MainPage()
    {
        InitializeComponent();
        _selectedEvent = new Modules.ShelegEventDetails();
        LM = new List<Modules.ShelegEventDetails>();
        LMA = new List<Modules.AppEvent>();
        _selectedAppEvent = new Modules.AppEvent();

        //dgEditEvent.Items.Add(a);

        Modules.Hartza.Moshav m = new Modules.Hartza.Moshav();

        m.e = "5";
        m.f = "5";
        m.g = "5";

        Modules.Hartza H = new Modules.Hartza();

        H.a = "1";
        H.b = "2";
        H.c = "3";
        H.d = "4";

        H.Moshav1.Add(m);

        OMH = new ObservableCollection<Hartza>();
        OMH.Add(H);

        //dgEditEvent.ItemsSource = OMH;

        dgEditEvent.ItemsSource = OMH1;
        dgEditEvent.DataContext = OMH1;

    }
</code>```

答:
You could use a nested ListView:

```<code><ListView x:Name="dgEditEvent" ItemsSource="{Binding OMH1}"  >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <TextBlock Text="{Binding a}" Width="50"></TextBlock>
                <TextBlock Text="{Binding b}" Width="50" Grid.Row="1"></TextBlock>
                <TextBlock Text="{Binding c}" Width="50" Grid.Row="2"></TextBlock>
                <TextBlock Text="{Binding d}" Width="50" Grid.Row="3"></TextBlock>

                <ListView ItemsSource="{Binding Moshav1}" Grid.Row="4">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <TextBlock Text="{Binding e}" />
                                <TextBlock Text="{Binding f}" />
                                <TextBlock Text="{Binding g}" />
                            </StackPanel>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListView>
</code>```

You may also put it in an Expander:

```<code><Expander Header="Expand/Collapse..." Grid.Row="4">
    <ListView ItemsSource="{Binding Moshav1}" Grid.Row="4">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding e}" />
                    <TextBlock Text="{Binding f}" />
                    <TextBlock Text="{Binding g}" />
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Expander>
</code>```

Title: data binding ListView Inside Listview

Body:
I have a class with ObservableCollection which one if is field is another ObservableCollection.

and I want to show the data in 1 row for the first ObservableCollection and using a plus sign or something else user can open the listview and see the other row which is the second ObseravableCollection.

however I am getting an error that could not take data from memory

will appreciate help with code example

attaching my code below

XAML

 <ListView x:Name="dgEditEvent" ItemsSource="{Binding OMH1}"  >
                    <ListBox.ItemTemplate>
                        <DataTemplate >
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding a}" Width="50"></TextBlock>
                                <TextBlock Text="{Binding b}" Width="50"></TextBlock>
                                <TextBlock Text="{Binding c}" Width="50"></TextBlock>
                                <TextBlock Text="{Binding d}" Width="50"></TextBlock>
                                <TextBlock Text="{Binding Moshav1 }" Width="50"></TextBlock>
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListView>

C#

public class Hartza : INotifyPropertyChanged
{
    private string _a;

    public string a
    {
       get
        {
            return _a;
        }

        set
        {
            _a = value;
            OnPropertyChanged("a");
        }
    }

    private string _b;

    public string b
    {
        get
        {
            return _b;
        }

        set
        {
            _b = value;
            OnPropertyChanged("b");
        }
    }

    private string _c;

    public string c
    {
        get
        {
            return _c;
        }

        set
        {
            _c = value;
            OnPropertyChanged("c");
        }
    }
    private string _d;

    public string d
    {
        get
        {
            return _d;
        }

        set
        {
            _d = value;
            OnPropertyChanged("d");
        }
    }

    public ObservableCollection<Moshav> Moshav1 { get; set; }

    public Hartza()
    {
        _a = "";
        _b = "";
        _c = "";
        _d = "";
        Moshav1 = new ObservableCollection<Moshav>();

    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

    public class Moshav
    {
        private string _e;

        public string e
        {
            get
            {
                return _e;
            }

            set
            {
                _e = value;
                OnPropertyChanged("e");
            }
        }

        private string _f;

        public string f
        {
            get
            {
                return _f;

            }

            set
            {
                    _f = value;
                OnPropertyChanged("f");
            }
        }

        private string _g;
        public string g
        {
            get
            {
                return _g;
            }

            set
            {
                _g = value;
                OnPropertyChanged("g");
            }
        }

        public Moshav()
        {
            _e = "";
            _f = "";
            _g = "";
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }

    }
}

    public MainPage()
    {
        InitializeComponent();
        _selectedEvent = new Modules.ShelegEventDetails();
        LM = new List<Modules.ShelegEventDetails>();
        LMA = new List<Modules.AppEvent>();
        _selectedAppEvent = new Modules.AppEvent();

        //dgEditEvent.Items.Add(a);

        Modules.Hartza.Moshav m = new Modules.Hartza.Moshav();

        m.e = "5";
        m.f = "5";
        m.g = "5";

        Modules.Hartza H = new Modules.Hartza();

        H.a = "1";
        H.b = "2";
        H.c = "3";
        H.d = "4";

        H.Moshav1.Add(m);

        OMH = new ObservableCollection<Hartza>();
        OMH.Add(H);

        //dgEditEvent.ItemsSource = OMH;

        dgEditEvent.ItemsSource = OMH1;
        dgEditEvent.DataContext = OMH1;

    }

Body:
You could use a nested ListView:

<ListView x:Name="dgEditEvent" ItemsSource="{Binding OMH1}"  >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <TextBlock Text="{Binding a}" Width="50"></TextBlock>
                <TextBlock Text="{Binding b}" Width="50" Grid.Row="1"></TextBlock>
                <TextBlock Text="{Binding c}" Width="50" Grid.Row="2"></TextBlock>
                <TextBlock Text="{Binding d}" Width="50" Grid.Row="3"></TextBlock>

                <ListView ItemsSource="{Binding Moshav1}" Grid.Row="4">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <TextBlock Text="{Binding e}" />
                                <TextBlock Text="{Binding f}" />
                                <TextBlock Text="{Binding g}" />
                            </StackPanel>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListView>

You may also put it in an Expander:

<Expander Header="Expand/Collapse..." Grid.Row="4">
    <ListView ItemsSource="{Binding Moshav1}" Grid.Row="4">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding e}" />
                    <TextBlock Text="{Binding f}" />
                    <TextBlock Text="{Binding g}" />
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Expander>


来源: stackexchange

问:
Cast type to va_arg return
Can i cast type to va_arg return as on example?
As i know va_arg can't read-return char/short int types</p>

```<code>if (flags->size == 0)
    u->s = (char)va_arg(pt, int);
if (flags->size == 1)
    u->s = (short int)va_arg(pt, int);
</code>```

答:
From the documentation:

va_arg returns the current argument

So in your case it returns the value of what pt is pointing to as an int. So yes, you can cast that value.

ContentLicense: CC BY-SA 3.0

Title: Cast type to va_arg return

Body:
Can i cast type to va_arg return as on example?
As i know va_arg can't read-return char/short int types

if (flags->size == 0)
    u->s = (char)va_arg(pt, int);
if (flags->size == 1)
    u->s = (short int)va_arg(pt, int);


问:
Passing array of ints to T-SQL stored proc via entity framework
I've read many posts and think I understand the concepts, but my small array of ints fails to pass from a C#/EF module to a SQL Server stored proc.  Hoping other eyes can spot the problem.

I'm using EF6, 4.5 .Net Framework, SQL Server 2014

In the database I've created these types/procs:

```<code>CREATE TYPE [dbo].[IntsTTV] AS TABLE(
  [Id] [int] NOT NULL
)
</code>```

Note that a table named 'Person' exists with columns 'Id' (int) and 'LastName' (nvarchar), and has data.

```<code>CREATE PROCEDURE [dbo].[GetUsers]
@UserIds dbo.IntsTTV READONLY
AS
BEGIN
  SELECT p.LastName
  FROM [dbo].[Person] p
  INNER JOIN @UserIds ids On p.Id = ids.Id;
END
</code>```

// C# code

```<code>SqlMetaData[] columns = new SqlMetaData[1];
columns[0] = new SqlMetaData("Id", SqlDbType.Int);

SqlDataRecord row = new SqlDataRecord(columns);
row.SetInt32(0, 1);  // Id of '1' is valid for the Person table

SqlDataRecord[] table = new SqlDataRecord[1];
table[0] = row;

SqlParameter parameter = new SqlParameter();
parameter.SqlDbType = SqlDbType.Structured;
parameter.ParameterName = "@UserIds";
parameter.TypeName = "dbo.IntsTTV";
parameter.Direction = ParameterDirection.Input;
parameter.Value = table;

SqlParameter[] parameters = new SqlParameter[1];
parameters[0] = parameter;

var res = _db.Database.SqlQuery<string>("GetUsers", parameters).ToList();
</code>```

The code does successfully call the proc, and if I hard code the proc to simply return a select of LastName's then the C# code does receive that.  This tells me what is working.

If I call the proc from other T-SQL code, passing in a prepared table-valued parameter (IntsTTV) of ints, it works.

In the proc, if I select count of rows of the passed parameter table I get zero when calling from the C# code, but I get a correct count when calling from T-SQL code.

What am I missing, please?

答:
I know this has been answered by found a different way that might help someone else out there

STRING_SPLIT

```<code>declare @intArray nvarchar(1000)
set @intArray = '1,2,3,4,5'
select value from STRING_SPLIT(@intArray , ',')
</code>```

This will return a new table with the numbers in your @intArray

Then you just need to use it as a normal table

```<code>select * from myMainTable where Id in (select value from STRING_SPLIT(@intArray , ','))
</code>```

Body:
I've read many posts and think I understand the concepts, but my small array of ints fails to pass from a C#/EF module to a SQL Server stored proc.  Hoping other eyes can spot the problem.

I'm using EF6, 4.5 .Net Framework, SQL Server 2014

In the database I've created these types/procs:

CREATE TYPE [dbo].[IntsTTV] AS TABLE(
  [Id] [int] NOT NULL
)

Note that a table named 'Person' exists with columns 'Id' (int) and 'LastName' (nvarchar), and has data.

CREATE PROCEDURE [dbo].[GetUsers]
@UserIds dbo.IntsTTV READONLY
AS
BEGIN
  SELECT p.LastName
  FROM [dbo].[Person] p
  INNER JOIN @UserIds ids On p.Id = ids.Id;
END

// C# code

SqlMetaData[] columns = new SqlMetaData[1];
columns[0] = new SqlMetaData("Id", SqlDbType.Int);

SqlDataRecord row = new SqlDataRecord(columns);
row.SetInt32(0, 1);  // Id of '1' is valid for the Person table

SqlDataRecord[] table = new SqlDataRecord[1];
table[0] = row;

SqlParameter parameter = new SqlParameter();
parameter.SqlDbType = SqlDbType.Structured;
parameter.ParameterName = "@UserIds";
parameter.TypeName = "dbo.IntsTTV";
parameter.Direction = ParameterDirection.Input;
parameter.Value = table;

SqlParameter[] parameters = new SqlParameter[1];
parameters[0] = parameter;

var res = _db.Database.SqlQuery<string>("GetUsers", parameters).ToList();

The code does successfully call the proc, and if I hard code the proc to simply return a select of LastName's then the C# code does receive that.  This tells me what is working.

If I call the proc from other T-SQL code, passing in a prepared table-valued parameter (IntsTTV) of ints, it works.

In the proc, if I select count of rows of the passed parameter table I get zero when calling from the C# code, but I get a correct count when calling from T-SQL code.

What am I missing, please?

Body:
I know this has been answered by found a different way that might help someone else out there

STRING_SPLIT

declare @intArray nvarchar(1000)
set @intArray = '1,2,3,4,5'
select value from STRING_SPLIT(@intArray , ',')

This will return a new table with the numbers in your @intArray

Then you just need to use it as a normal table

select * from myMainTable where Id in (select value from STRING_SPLIT(@intArray , ','))


问:
Adding a sudoers file in chef fails at verification

goal

I'm trying to add/edit a sudoers file in Chef.

After a lot of serach (and broken sudoers) I found this question and the answer seemed to be exactly what I am after.

My cookbook

So in my chef I added the following visudo cookbook:

The recipe: ~/chef-repo/cookbook/visudo/recipes/allowUpgrade.rb

```<code>template '/etc/sudoers.d/allowUpgrade' do
    cookbook 'visudo'
    source 'allowUpgrade.erb'

    owner'root'
    group 'root'
    mode '0440'

    verify "visudo -c -f %{path}"
end
</code>```

My template: ~/chef-repo/cookbooks/visudo/templates/allowUpgrade.erb

```<code>username ALL=(ALL) NOPASSWD: /usr/local/bin/upgrade
</code>```

Template and verification works manually

When I put this line/file there manually using

```<code>sudo nano /etc/sudoers.d/allowUpgrade
</code>```

(I know one shouldn't) and then verify it using

```<code>visudo -c -f /etc/sudoers.d/allowUpgrade
</code>```

I get

```<code>/etc/sudoers.d/allowUpgrade: parsed OK
</code>```

and it works meaning I can run

```<code>sudo upgrade
</code>```

without beeing prompted for the sudo password.

Verification fails running Chef

However it is not working using Chef. I'm trying it first on the local machine using

sudo chef-client -z --runlist 'recipe[visudo::allowUpgrade]'
```

<p>But I get this error</p>

<pre class="lang-none prettyprint-override"><code>Error executing action `create` on resource 'template[/etc/sudoers.d/allowUpgrade]'

Chef::Exceptions::ValidationFailed
</code>```

Why is the verification failing in chef? What am I doing wrong?

Here the complete error message

Recipe: visudo::allowUpgrade
  * template[/etc/sudoers.d/allowUpgrade] action create[2017-12-07T08:24:50+01:00] INFO: Processing template[/etc/sudoers.d/allowUpgrade] action create (visudo::                                         allowUpgrade line 7)

    ================================================================================
    Error executing action `create` on resource 'template[/etc/sudoers.d/allowUpgrade]'
    ================================================================================

    Chef::Exceptions::ValidationFailed
    ----------------------------------
    Proposed content for /etc/sudoers.d/allowUpgrade failed verification #<Chef::Resource::File::Verification:0x0000000004070c48>

    Resource Declaration:
    ---------------------
    # In /home/username/chef-repo/.chef/local-mode-cache/cache/cookbooks/visudo/recipes/allowUpgrade.rb

      7: template '/etc/sudoers.d/allowUpgrade' do
      8:     owner'root'
      9:     group 'root'
     10:     mode '0440'
     11:     source 'allowUpgrade.erb'
     12:     verify 'visudo -c -f %{path}'
     13: end

    Compiled Resource:
    ------------------
    # Declared in /home/username/chef-repo/.chef/local-mode-cache/cache/cookbooks/visudo/recipes/allowUpgrade.rb:7:in `from_file'

    template("/etc/sudoers.d/allowUpgrade") do
      action [:create]
      default_guard_interpreter :default
      source "allowUpgrade.erb"
      declared_type :template
      cookbook_name "visudo"
      recipe_name "allowUpgrade"
      owner "root"
      group "root"
      mode "0440"
      verifications [#<Chef::Resource::File::Verification:0x0000000004070c48 @command_opts={},
          @command="visudo -c -f %{path}", @block=nil, @parent_resource=<template[/etc/sudoers.d/allowUpgrade]
          @name: "/etc/sudoers.d/allowUpgrade" @before: nil @params: {}
          @provider: nil @allowed_actions: [:nothing, :create, :delete, :touch, :create_if_missing]
          @action: [:create] @updated: false @updated_by_last_action: false
          @source_line: "/home/username/chef-repo/.chef/local-mode-cache/cache/cookbooks/visudo/recipes/allowUpgrade.rb:7:in `from_file'"
          @guard_interpreter: nil @default_guard_interpreter: :default
          @elapsed_time: 0 @source: "allowUpgrade.erb" @cookbook: nil
          @local: false @variables: {} @inline_helper_blocks: {}
          @inline_helper_modules: [] @helper_modules: [] @declared_type: :template
          @cookbook_name: "visudo" @recipe_name: "allowUpgrade" @owner: "root" @group: "root" @mode: "0440"
          @verifications: [...] @path: "/etc/sudoers.d/allowUpgrade">>]
      path "/etc/sudoers.d/allowUpgrade"
    end
```

<hr>

<p><strong>Update</strong>:<br></p>

<p>When I leave the verification out and just do</p>

```template '/etc/sudoers.d/allowUpgrade' do
    cookbook 'visudo'
    source 'allowUpgrade.erb'

    owner 'root'
    group 'root'
    mode '0440'

    verify { 1 == 1 }
end
```

The sudo is broken! In recovery mode and the root console I checked and it looks just the same as when I insert it manually (what works fine)?!

答:
Thanks to the help of Tensibai here in the comments and the hint to lineendings I could finally solve this problem.

Indeed the issue was lineendings as noted in this ancient Issue

I generated the cookbooks, recipes and templates on an Ubuntu Server 16.04 but do all m editing on the repository in Brackets.io on Windows.

This made template (and other) files have CRLF instead of LF lineendings because Brackets seems to use automatically the lineendings of the OS it is running on. This ofcourse made the /etc/sudoers.d/allowUpgrade file brake the sudoers because it has to end in a new line.

After some research I found this was an old known Issue and could be solved by the Plug-In Newline.

After installing this Plug-In indeed I could see that the file had CRLF lineendings.

I switched it to LF thanks to the Plug-In by clicking on the CRLF. Now my cookbook runs as expected and I'm able to run

```<code>sudo upgrade
</code>```

without beeng prompted for the password - meaning it works.

Body:
goal

I'm trying to add/edit a sudoers file in Chef.

After a lot of serach (and broken sudoers) I found this question and the answer seemed to be exactly what I am after.

My cookbook

So in my chef I added the following visudo cookbook:

The recipe: ~/chef-repo/cookbook/visudo/recipes/allowUpgrade.rb

template '/etc/sudoers.d/allowUpgrade' do
    cookbook 'visudo'
    source 'allowUpgrade.erb'

    owner'root'
    group 'root'
    mode '0440'

    verify "visudo -c -f %{path}"
end

My template: ~/chef-repo/cookbooks/visudo/templates/allowUpgrade.erb

username ALL=(ALL) NOPASSWD: /usr/local/bin/upgrade

Template and verification works manually

When I put this line/file there manually using

sudo nano /etc/sudoers.d/allowUpgrade

(I know one shouldn't) and then verify it using

visudo -c -f /etc/sudoers.d/allowUpgrade

I get

/etc/sudoers.d/allowUpgrade: parsed OK

and it works meaning I can run

sudo upgrade

without beeing prompted for the sudo password.

Verification fails running Chef

However it is not working using Chef. I'm trying it first on the local machine using

sudo chef-client -z --runlist 'recipe[visudo::allowUpgrade]'

But I get this error

Error executing action `create` on resource 'template[/etc/sudoers.d/allowUpgrade]'

Chef::Exceptions::ValidationFailed

Why is the verification failing in chef? What am I doing wrong?

Here the complete error message

Recipe: visudo::allowUpgrade
  * template[/etc/sudoers.d/allowUpgrade] action create[2017-12-07T08:24:50+01:00] INFO: Processing template[/etc/sudoers.d/allowUpgrade] action create (visudo::                                         allowUpgrade line 7)

    ================================================================================
    Error executing action `create` on resource 'template[/etc/sudoers.d/allowUpgrade]'
    ================================================================================

    Chef::Exceptions::ValidationFailed
    ----------------------------------
    Proposed content for /etc/sudoers.d/allowUpgrade failed verification #<Chef::Resource::File::Verification:0x0000000004070c48>

    Resource Declaration:
    ---------------------
    # In /home/username/chef-repo/.chef/local-mode-cache/cache/cookbooks/visudo/recipes/allowUpgrade.rb

      7: template '/etc/sudoers.d/allowUpgrade' do
      8:     owner'root'
      9:     group 'root'
     10:     mode '0440'
     11:     source 'allowUpgrade.erb'
     12:     verify 'visudo -c -f %{path}'
     13: end

    Compiled Resource:
    ------------------
    # Declared in /home/username/chef-repo/.chef/local-mode-cache/cache/cookbooks/visudo/recipes/allowUpgrade.rb:7:in `from_file'

    template("/etc/sudoers.d/allowUpgrade") do
      action [:create]
      default_guard_interpreter :default
      source "allowUpgrade.erb"
      declared_type :template
      cookbook_name "visudo"
      recipe_name "allowUpgrade"
      owner "root"
      group "root"
      mode "0440"
      verifications [#<Chef::Resource::File::Verification:0x0000000004070c48 @command_opts={},
          @command="visudo -c -f %{path}", @block=nil, @parent_resource=<template[/etc/sudoers.d/allowUpgrade]
          @name: "/etc/sudoers.d/allowUpgrade" @before: nil @params: {}
          @provider: nil @allowed_actions: [:nothing, :create, :delete, :touch, :create_if_missing]
          @action: [:create] @updated: false @updated_by_last_action: false
          @source_line: "/home/username/chef-repo/.chef/local-mode-cache/cache/cookbooks/visudo/recipes/allowUpgrade.rb:7:in `from_file'"
          @guard_interpreter: nil @default_guard_interpreter: :default
          @elapsed_time: 0 @source: "allowUpgrade.erb" @cookbook: nil
          @local: false @variables: {} @inline_helper_blocks: {}
          @inline_helper_modules: [] @helper_modules: [] @declared_type: :template
          @cookbook_name: "visudo" @recipe_name: "allowUpgrade" @owner: "root" @group: "root" @mode: "0440"
          @verifications: [...] @path: "/etc/sudoers.d/allowUpgrade">>]
      path "/etc/sudoers.d/allowUpgrade"
    end

Update:

When I leave the verification out and just do

template '/etc/sudoers.d/allowUpgrade' do
    cookbook 'visudo'
    source 'allowUpgrade.erb'

    owner 'root'
    group 'root'
    mode '0440'

    verify { 1 == 1 }
end

The sudo is broken! In recovery mode and the root console I checked and it looks just the same as when I insert it manually (what works fine)?!

Body:
Thanks to the help of Tensibai here in the comments and the hint to lineendings I could finally solve this problem.

Indeed the issue was lineendings as noted in this ancient Issue

I generated the cookbooks, recipes and templates on an Ubuntu Server 16.04 but do all m editing on the repository in Brackets.io on Windows.

This made template (and other) files have CRLF instead of LF lineendings because Brackets seems to use automatically the lineendings of the OS it is running on. This ofcourse made the /etc/sudoers.d/allowUpgrade file brake the sudoers because it has to end in a new line.

After some research I found this was an old known Issue and could be solved by the Plug-In Newline.

After installing this Plug-In indeed I could see that the file had CRLF lineendings.

I switched it to LF thanks to the Plug-In by clicking on the CRLF. Now my cookbook runs as expected and I'm able to run

sudo upgrade

without beeng prompted for the password - meaning it works.


问:
How to increase selection area of UIButton?
I have made the UIButton programmatically

```<code>togglebutton = [UIButton buttonWithType:UIButtonTypeCustom];
togglebutton.frame = CGRectMake(42, 15, 80, 21);
[togglebutton addTarget:self action:@selector(toggleview)
forControlEvents:UIControlEventTouchUpInside];
[togglebutton setImage:[UIImage imageNamed:@"squ.png"] forState:UIControlStateNormal];
[buttonView addSubview:togglebutton];
</code>```

It is looked as the right button in above image. Now the requirement is that the selection area of this button should be more than then the uibutton image. So that the user will be able to click the button easily by touching on near by area of particular button.

```<code>[togglebutton setImageEdgeInsets: UIEdgeInsetsMake( 0, -30, 0, -25)];
</code>```

I tried to set the image inset but it making the image irregular. Please look upon this issue.

答:
in xcode 9 you can do the following:

that means you have to compensate the image offset and content offset to ensure a centered image positioning.

Body:
I have made the UIButton programmatically

togglebutton = [UIButton buttonWithType:UIButtonTypeCustom];
togglebutton.frame = CGRectMake(42, 15, 80, 21);
[togglebutton addTarget:self action:@selector(toggleview)
forControlEvents:UIControlEventTouchUpInside];
[togglebutton setImage:[UIImage imageNamed:@"squ.png"] forState:UIControlStateNormal];
[buttonView addSubview:togglebutton];

It is looked as the right button in above image. Now the requirement is that the selection area of this button should be more than then the uibutton image. So that the user will be able to click the button easily by touching on near by area of particular button.

[togglebutton setImageEdgeInsets: UIEdgeInsetsMake( 0, -30, 0, -25)];

I tried to set the image inset but it making the image irregular. Please look upon this issue.


问:
How to understand the throw method of JavaScript Generator?
This is my snippet of code.

var g = function*() {
  try {
    yield;
  } catch (e) {
    console.log("inner catch", e);
  }
};

var i = g();
i.next();

try {
  i.throw("a");
  i.throw("b");
} catch (e) {
  console.log("outer catch", e);
}```
</div>
</div>
</p>

<p>I expect this result :</p>

```inner catch a
inner catch a
```

So why the inner catch of generator can not catch twice?

答:
It's because your generator moved to the catch after the first throw(), so there's no try available to catch the second one, so the exception propagates from its call position.

var g = function*() {
  try {
   yield;
  } catch (e) {
   console.log("inner catch", e);
   try {
     yield;
   } catch (e) {
     console.log("inner catch 2", e);
   }
  }
};

var i = g();
i.next();

try {
  i.throw("a");
  i.throw("b");
} catch (e) {
  console.log("outer catch", e);
}```
</div>
</div>
</p>

<p>To not have to nest <code>try/catch</code> statements, you'd need a loop.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var g = function*() {
  while (true) {
   try {
    yield;
   } catch (e) {
    console.log("inner catch", e);
    if (e === "b") {
      console.log("breaking loop");
      break;
    }
   }
  }
};

var i = g();
i.next();

try {
  i.throw("a");
  i.throw("b");
  i.throw("c");
} catch (e) {
  console.log("outer catch", e);
}</code>```

Body:
This is my snippet of code.

var g = function*() {
  try {
    yield;
  } catch (e) {
    console.log("inner catch", e);
  }
};

var i = g();
i.next();

try {
  i.throw("a");
  i.throw("b");
} catch (e) {
  console.log("outer catch", e);
}

I expect this result :

inner catch a
inner catch a

So why the inner catch of generator can not catch twice?

Body:
It's because your generator moved to the catch after the first throw(), so there's no try available to catch the second one, so the exception propagates from its call position.

var g = function*() {
  try {
   yield;
  } catch (e) {
   console.log("inner catch", e);
   try {
     yield;
   } catch (e) {
     console.log("inner catch 2", e);
   }
  }
};

var i = g();
i.next();

try {
  i.throw("a");
  i.throw("b");
} catch (e) {
  console.log("outer catch", e);
}

To not have to nest try/catch statements, you'd need a loop.

var g = function*() {
  while (true) {
   try {
    yield;
   } catch (e) {
    console.log("inner catch", e);
    if (e === "b") {
      console.log("breaking loop");
      break;
    }
   }
  }
};

var i = g();
i.next();

try {
  i.throw("a");
  i.throw("b");
  i.throw("c");
} catch (e) {
  console.log("outer catch", e);
}


问:
How to use QImage repeatedly?
I have a horizontal sprite of images. This one for example:

All the images have the same width and height. I have stored it in my resources file, and declared it in my application by a define:

```<code>#define SPRITE QImage(":/sprite.png")
</code>```

So there are 4 images that I will need several times in my application. In order to do this, I implemented this function which retrieves the image at the position n in the sprite.

```<code>QImage getNthImageFromSprite(int n, QImage sprite)
{
    int size = sprite.height();
    return sprite.copy((n - 1) * size, 0, size, size);
}
</code>```

Then, I declared a general enum to put names on the position:

```<code>enum eImage
{
    eImage_black = 1,
    eImage_red,
    eImage_orange,
    eImage_green
}
</code>```

And finally, the function that I'm using anywhere in my application:

```<code>QImage getSpriteImage(eImage img)
{
    return getNthImageFromSprite(img, SPRITE);
}
</code>```

This works well.

But I have the impression that this is not very good, since I call the constructor of QImage each time I want to get a specific image. Knowing that a sprite can contain +40 images and that I will need these images several times, should I cache an image the first time it get called, or the way I'm doing it is good?

Note: I need QImage for various reasons, but a comparison with QPixmap would be appreciated.

答:
Replace the define with an object:

```<code>static QImage SPRITE(":/sprite.png");
</code>```

It will be initialized only once on startup.

You can even put it in the method:

```<code>QImage getSpriteImage(eImage img)
{
    static QImage SPRITE(":/sprite.png");
    return getNthImageFromSprite(img, SPRITE);
}
</code>```

In this case, it is initialized on first usage.

Howerver, you sill create new objects for every call to getNthSpriteImage. You could use a local static cache to re-use already returned objects:

```<code>QImage getNthSpriteImage(int n, QImage img) {
    static QMap<int, QImage> cache;
    if (!cache.contains(n)) {
        int size = sprite.height();
        cache[n] = sprite.copy((n - 1) * size, 0, size, size);
    }
    return cache[n];
}
</code>```

As for the difference for QImage/QPixmap, this is the main difference:

QImage is designed and optimized for I/O, and for direct pixel access and manipulation, while QPixmap is designed and optimized for showing images on screen.

So I would recommend to use QPixmap if you don't want special image formats (RGBA, premultiplied RGBA, indexed, ...) or use direct pixel manipulation.

Title: How to use QImage repeatedly?

Body:
I have a horizontal sprite of images. This one for example:

All the images have the same width and height. I have stored it in my resources file, and declared it in my application by a define:

#define SPRITE QImage(":/sprite.png")

So there are 4 images that I will need several times in my application. In order to do this, I implemented this function which retrieves the image at the position n in the sprite.

QImage getNthImageFromSprite(int n, QImage sprite)
{
    int size = sprite.height();
    return sprite.copy((n - 1) * size, 0, size, size);
}

Then, I declared a general enum to put names on the position:

enum eImage
{
    eImage_black = 1,
    eImage_red,
    eImage_orange,
    eImage_green
}

And finally, the function that I'm using anywhere in my application:

QImage getSpriteImage(eImage img)
{
    return getNthImageFromSprite(img, SPRITE);
}

This works well.

But I have the impression that this is not very good, since I call the constructor of QImage each time I want to get a specific image. Knowing that a sprite can contain +40 images and that I will need these images several times, should I cache an image the first time it get called, or the way I'm doing it is good?

Note: I need QImage for various reasons, but a comparison with QPixmap would be appreciated.

Body:
Replace the define with an object:

static QImage SPRITE(":/sprite.png");

It will be initialized only once on startup.

You can even put it in the method:

QImage getSpriteImage(eImage img)
{
    static QImage SPRITE(":/sprite.png");
    return getNthImageFromSprite(img, SPRITE);
}

In this case, it is initialized on first usage.

Howerver, you sill create new objects for every call to getNthSpriteImage. You could use a local static cache to re-use already returned objects:

QImage getNthSpriteImage(int n, QImage img) {
    static QMap<int, QImage> cache;
    if (!cache.contains(n)) {
        int size = sprite.height();
        cache[n] = sprite.copy((n - 1) * size, 0, size, size);
    }
    return cache[n];
}

As for the difference for QImage/QPixmap, this is the main difference:

QImage is designed and optimized for I/O, and for direct pixel access and manipulation, while QPixmap is designed and optimized for showing images on screen.

So I would recommend to use QPixmap if you don't want special image formats (RGBA, premultiplied RGBA, indexed, ...) or use direct pixel manipulation.


问:
How do I map true/false/unknown to -1/0/null without repetition?
I am currently working on a tool to help my users port their SQL code to SQL-Server 2005. For this purpose, I parse the SQL into a syntax tree, analyze it for constructs which need attentions, modify it and transform it back into T-SQL.

On thing that I want to support, is the "bools are values too" semantics of other RDBMS. For example, MS-Access allows me to write select A.x and A.y as r from A, which is impossible in T-SQL because:

Columns can't have boolean type (column values can't be and'ed)

Logical predicates can not be used where expressions are expected.

Therefore, my transformation routine converts the above statement into this:

```<code>select case
  when (A.x<>0) and (A.y<>0)
   then -1
  when not((A.x<>0) and (A.y<>0))
   then 0
  else
   null
  end as r
 from A;
</code>```

Which works, but is annoying, because I have to duplicate the logical expression (which can be very complex or contain subqueries etc.) in order to distinguish between true, false and unknown - the latter shall map to null. So I wonder if the T-SQL pro's here know a better way to achieve this?

UPDATE:
I would like to point out, that solutions which try to keep the operands in the integer domain have to take into account, that some operands may be logical expressions in the first place. This means that a efficient solution to convert a bool to a value is stil required. For example:

```<code>select A.x and exists (select * from B where B.y=A.y) from A;
</code>```

答:
I don't think there's a good answer, really it's a limitation of TSQL.

You could create a UDF for each boolean expression you need

```<code>CREATE FUNCTION AndIntInt
(
    @x as int,@y as int
)
RETURNS int
AS
BEGIN

    if (@x<>0) and (@y<>0)
        return -1
    if not((@x<>0) and (@y<>0))
        return  0
    return null
END
</code>```

used via

```<code>select AndIntInt(A.x,A.y) as r from A
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am currently working on a tool to help my users port their SQL code to SQL-Server 2005. For this purpose, I parse the SQL into a syntax tree, analyze it for constructs which need attentions, modify it and transform it back into T-SQL.

On thing that I want to support, is the "bools are values too" semantics of other RDBMS. For example, MS-Access allows me to write select A.x and A.y as r from A, which is impossible in T-SQL because:

Columns can't have boolean type (column values can't be and'ed)

Logical predicates can not be used where expressions are expected.

Therefore, my transformation routine converts the above statement into this:

select case
  when (A.x<>0) and (A.y<>0)
   then -1
  when not((A.x<>0) and (A.y<>0))
   then 0
  else
   null
  end as r
 from A;

Which works, but is annoying, because I have to duplicate the logical expression (which can be very complex or contain subqueries etc.) in order to distinguish between true, false and unknown - the latter shall map to null. So I wonder if the T-SQL pro's here know a better way to achieve this?

UPDATE:
I would like to point out, that solutions which try to keep the operands in the integer domain have to take into account, that some operands may be logical expressions in the first place. This means that a efficient solution to convert a bool to a value is stil required. For example:

select A.x and exists (select * from B where B.y=A.y) from A;

Body:
I don't think there's a good answer, really it's a limitation of TSQL.

You could create a UDF for each boolean expression you need

CREATE FUNCTION AndIntInt
(
    @x as int,@y as int
)
RETURNS int
AS
BEGIN

    if (@x<>0) and (@y<>0)
        return -1
    if not((@x<>0) and (@y<>0))
        return  0
    return null
END

used via

select AndIntInt(A.x,A.y) as r from A


问:
Spark aggregateByKey: using the key
I want to create a set of bloom filters from my RDD. The way I do it looks like the following:

```<code>rdd.aggregateByKey(create(size))(add, combine).collect()
</code>```

Where rdd is something like RDD[(Int, Long)]

The problem is that the values are not distributed uniformly within each group. That is, "one size fits all" doesn't work here and I want to initialize the bloom filters differently for each key, depending on how many elements are there.

So I want something like

```<code>rdd.aggregateByKey(key => create(count(key))(add, combine).collect()
</code>```

Where count is a map with counts.

This is something I can do with groupByKey, but I wonder, is there any other way?

答:
There is a simple trick you can use. Convert RDD from (key, value) to (key, (key, value)):

```<code>val kkvRdd = rdd.map { case (key, value) => (key, (key, value)) }
</code>```

and apply combineByKey:

```<code>def createCombiner(v: (Int, Long)) = create(count(_._1))  // And insert _._2

kkvRdd.combineByKey(createCombiner, add,  combine)
</code>```

where add and combine are adjusted to accept new type.

Title: Spark aggregateByKey: using the key

Body:
I want to create a set of bloom filters from my RDD. The way I do it looks like the following:

rdd.aggregateByKey(create(size))(add, combine).collect()

Where rdd is something like RDD[(Int, Long)]

The problem is that the values are not distributed uniformly within each group. That is, "one size fits all" doesn't work here and I want to initialize the bloom filters differently for each key, depending on how many elements are there.

So I want something like

rdd.aggregateByKey(key => create(count(key))(add, combine).collect()

Where count is a map with counts.

This is something I can do with groupByKey, but I wonder, is there any other way?

Body:
There is a simple trick you can use. Convert RDD from (key, value) to (key, (key, value)):

val kkvRdd = rdd.map { case (key, value) => (key, (key, value)) }

and apply combineByKey:

def createCombiner(v: (Int, Long)) = create(count(_._1))  // And insert _._2

kkvRdd.combineByKey(createCombiner, add,  combine)

where add and combine are adjusted to accept new type.


问:
BYTE, WORD and DWORD macros definition
I am trying to understand, what would be the best way to define BYTE, WORD and DWORD macros, which are mentioned in answers of this question.

```<code>#define LOWORD(l) ((WORD)(l))
#define HIWORD(l) ((WORD)(((DWORD)(l) >> 16) & 0xFFFF))
#define LOBYTE(w) ((BYTE)(w))
#define HIBYTE(w) ((BYTE)(((WORD)(w) >> 8) & 0xFF))
</code>```

Would it be correct to assume, that:

BYTE is macro defined as
#define BYTE __uint8_t

WORD is macro defined as
#define WORD __uint16_t

DWORD is macro defined as
#define DWORD __uint32_t

If yes, why cast to another macro instead of casting to __uint8_t, __uint16_t or __uint32_t? Is it written like that to increase clarity?

I also found another question which answers include typedef, with little bit more of research I've found answers to question about comparing #define and typedef. Would typedef be better to use in this case?

答:
This is a portable solution:</p>

```<code>#include <stdint.h>

typedef uint32_t DWORD;   // DWORD = unsigned 32 bit value
typedef uint16_t WORD;    // WORD = unsigned 16 bit value
typedef uint8_t BYTE;     // BYTE = unsigned 8 bit value
</code>```

ContentLicense: CC BY-SA 4.0

Title: BYTE, WORD and DWORD macros definition

Body:
I am trying to understand, what would be the best way to define BYTE, WORD and DWORD macros, which are mentioned in answers of this question.

#define LOWORD(l) ((WORD)(l))
#define HIWORD(l) ((WORD)(((DWORD)(l) >> 16) & 0xFFFF))
#define LOBYTE(w) ((BYTE)(w))
#define HIBYTE(w) ((BYTE)(((WORD)(w) >> 8) & 0xFF))

Would it be correct to assume, that:

BYTE is macro defined as
#define BYTE __uint8_t

WORD is macro defined as
#define WORD __uint16_t

DWORD is macro defined as
#define DWORD __uint32_t

If yes, why cast to another macro instead of casting to __uint8_t, __uint16_t or __uint32_t? Is it written like that to increase clarity?

I also found another question which answers include typedef, with little bit more of research I've found answers to question about comparing #define and typedef. Would typedef be better to use in this case?

Body:
This is a portable solution:

#include <stdint.h>

typedef uint32_t DWORD;   // DWORD = unsigned 32 bit value
typedef uint16_t WORD;    // WORD = unsigned 16 bit value
typedef uint8_t BYTE;     // BYTE = unsigned 8 bit value


问:
Nifi: how to transfer only last file from the flowFile list?
I want to get all  flowfile from the  queu   which  fileSize  is greater  than 831  and then put  them  into  the  list  after that   catch  last flowfile from the  list  and  transfer to  success relationship  and finally  remove all other  flowfiles  ,  here is  my  code   which throws  exception that transfer relationship not specified , what  should  i  change  in this case?

```<code> import org.apache.nifi.processor.FlowFileFilter;
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
import java.nio.charset.StandardCharsets
import org.apache.commons.io.IOUtils

def flowFile = session.get()
def  n=0;
if(!flowFile)return
def size = flowFile.getAttribute('fileSize');
log.error(size.toString())
int value = size as Integer;

if((value/831)>1){
def ffList = session.get(new FlowFileFilter(){
    public FlowFileFilterResult filter(FlowFile ff) {

        if( size == ff.getAttribute('fileSize') ) n++; return FlowFileFilterResult.ACCEPT_AND_CONTINUE
        return FlowFileFilterResult.REJECT_AND_CONTINUE
    }

})
session.transfer(ffList.get(n-1),REL_SUCCESS)
//session.remove(ffList);
}
session.remove(flowFile);
</code>```

答:
if you get flow file from queue you have to do something with it.

this code returns you a flowFile list:

```<code>def ffList = session.get(new FlowFileFilter(){...})
</code>```

if you wand just remove all of them except the last one just put this code after transferring the last one:

```<code>session.remove( ffList[0..-2] )
</code>```

and i guess there is a mistake in this line:

```<code>if( size == ff.getAttribute('fileSize') ) n++; return FlowFileFilterResult.ACCEPT_AND_CONTINUE
</code>```

the command return FlowFileFilterResult.ACCEPT_AND_CONTINUE executed in any case because it's not under if.

i think should be like this:

```<code>if( size == ff.getAttribute('fileSize') ){
    n++;
    return FlowFileFilterResult.ACCEPT_AND_CONTINUE
}
</code>```

Body:
I want to get all  flowfile from the  queu   which  fileSize  is greater  than 831  and then put  them  into  the  list  after that   catch  last flowfile from the  list  and  transfer to  success relationship  and finally  remove all other  flowfiles  ,  here is  my  code   which throws  exception that transfer relationship not specified , what  should  i  change  in this case?

 import org.apache.nifi.processor.FlowFileFilter;
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
import java.nio.charset.StandardCharsets
import org.apache.commons.io.IOUtils

def flowFile = session.get()
def  n=0;
if(!flowFile)return
def size = flowFile.getAttribute('fileSize');
log.error(size.toString())
int value = size as Integer;

if((value/831)>1){
def ffList = session.get(new FlowFileFilter(){
    public FlowFileFilterResult filter(FlowFile ff) {

        if( size == ff.getAttribute('fileSize') ) n++; return FlowFileFilterResult.ACCEPT_AND_CONTINUE
        return FlowFileFilterResult.REJECT_AND_CONTINUE
    }

})
session.transfer(ffList.get(n-1),REL_SUCCESS)
//session.remove(ffList);
}
session.remove(flowFile);

Body:
if you get flow file from queue you have to do something with it.

this code returns you a flowFile list:

def ffList = session.get(new FlowFileFilter(){...})

if you wand just remove all of them except the last one just put this code after transferring the last one:

session.remove( ffList[0..-2] )

and i guess there is a mistake in this line:

if( size == ff.getAttribute('fileSize') ) n++; return FlowFileFilterResult.ACCEPT_AND_CONTINUE

the command return FlowFileFilterResult.ACCEPT_AND_CONTINUE executed in any case because it's not under if.

i think should be like this:

if( size == ff.getAttribute('fileSize') ){
    n++;
    return FlowFileFilterResult.ACCEPT_AND_CONTINUE
}


问:
what happen when execute mvn install if there dont exist pom
I want to install pig-maven, I download it and run mvn install command, then it tell me an error:

```<code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-remote-resources-plugin:1.5:process (default) on project pig-main: Failed to resolve dependencies for one or more projects in the reactor. Reason: Missing:

[ERROR] ----------
[ERROR] 1) org.apache.hive:hive-exec:jar:core:0.14.0-SNAPSHOT`
</code>```

here is some relevant information in pom.xml:

```<code><repositories>
        <repository>
            <id>repo.apache.snapshots</id>
            <url>http://repository.apache.org/content/groups/snapshots-group/</url>
        </repository>
        <repository>
            <id>repo.jboss.org</id>
            <url>http://repository.jboss.com/nexus/content/groups/public/</url>
        </repository>
    </repositories>
    ...
    <hive.version>0.14.0-SNAPSHOT</hive.version>
    <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-exec</artifactId>
            <version>${hive.version}</version>
            <scope>compile</scope>
            <classifier>core</classifier>
     </dependency>
</code>```

in specified snapshot repository I find it has some information of target jar but havent jar and pom. So then what should I do to install pig. The relate data as below:

答:
It seems you are trying to install the development version of the project, however it depends on SNAPSHOT dependencies which are not available on your configured repositories.

Depending on what you really want you can:

As @grape_mao suggested, install a stable version using the proper guide (on the Github project go to releases and use the one you want)

If you really want to use this development version:

Find and configure a repository containing hive-exec-0.14.0-SNAPSHOT, the one your are showing does not contain the dependency or

Download and install yourself hive-exec-0.14.0-SNAPSHOT.jar from either a commit from the source code or a .jar file.

Body:
I want to install pig-maven, I download it and run mvn install command, then it tell me an error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-remote-resources-plugin:1.5:process (default) on project pig-main: Failed to resolve dependencies for one or more projects in the reactor. Reason: Missing:

[ERROR] ----------
[ERROR] 1) org.apache.hive:hive-exec:jar:core:0.14.0-SNAPSHOT`

here is some relevant information in pom.xml:

<repositories>
        <repository>
            <id>repo.apache.snapshots</id>
            <url>http://repository.apache.org/content/groups/snapshots-group/</url>
        </repository>
        <repository>
            <id>repo.jboss.org</id>
            <url>http://repository.jboss.com/nexus/content/groups/public/</url>
        </repository>
    </repositories>
    ...
    <hive.version>0.14.0-SNAPSHOT</hive.version>
    <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-exec</artifactId>
            <version>${hive.version}</version>
            <scope>compile</scope>
            <classifier>core</classifier>
     </dependency>

in specified snapshot repository I find it has some information of target jar but havent jar and pom. So then what should I do to install pig. The relate data as below:


问:
Git command for rollback rewriten history
I am doing some experiments with git. On my branch I did

```<code>git filter-branch --tree-filter "find . -name '*.java' -exec sed -i -e \ 's/stringToReplace/replacement/g' {} \;" 777b7d777c7777777dc16a8a939a8cdbabc28086..HEAD
</code>```

That is rewriting the history. I did not push the changes. Now I am wondering how I can reset that thing? I want to rollback that rewriting. What is the easiest way for that? Thanks a lot in advance.

答:
When you run git rebase, it stores the original commit ID of your branch in .git/refs/original/refs/heads/<branchname>.  If you want to undo your rebase, you can just run:

```<code>git reset --hard original/refs/heads/master
</code>```

This assumes that you are on your master branch; if not, change the branch name after heads/ appropriately.

Alternatively, if you just want to reset your local repository to the state of the upstream repository, you can:

```<code>git reset --hard origin/master
</code>```

This would reset your local branch to the master branch on your remote named origin.

Body:
I am doing some experiments with git. On my branch I did

git filter-branch --tree-filter "find . -name '*.java' -exec sed -i -e \ 's/stringToReplace/replacement/g' {} \;" 777b7d777c7777777dc16a8a939a8cdbabc28086..HEAD

That is rewriting the history. I did not push the changes. Now I am wondering how I can reset that thing? I want to rollback that rewriting. What is the easiest way for that? Thanks a lot in advance.

Body:
When you run git rebase, it stores the original commit ID of your branch in .git/refs/original/refs/heads/<branchname>.  If you want to undo your rebase, you can just run:

git reset --hard original/refs/heads/master

This assumes that you are on your master branch; if not, change the branch name after heads/ appropriately.

Alternatively, if you just want to reset your local repository to the state of the upstream repository, you can:

git reset --hard origin/master

This would reset your local branch to the master branch on your remote named origin.


问:
error: Unable to append to ./logs/HEAD: Permission denied
I've been pushing code to gitlab from my local computer. It's been working great but all of the sudden I've been getting this error:

```<code>Counting objects: 5, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 324 bytes | 0 bytes/s, done.
Total 3 (delta 2), reused 0 (delta 0)
error: Unable to append to ./logs/HEAD: Permission denied
To git@example.com:1/53.git
   2924375..78b7f43  master -> master
</code>```

Never seen it (error: Unable to append to ./logs/HEAD: Permission denied) before but I'm not seeing my new commits on my gitlab server. Any ideas?

Thanks.

答: Check the permissions of the file '/53.git/logs/HEAD' on server 'example.com:1'. It must belong to user 'git'.</p>

Body:
I've been pushing code to gitlab from my local computer. It's been working great but all of the sudden I've been getting this error:

Counting objects: 5, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 324 bytes | 0 bytes/s, done.
Total 3 (delta 2), reused 0 (delta 0)
error: Unable to append to ./logs/HEAD: Permission denied
To git@example.com:1/53.git
   2924375..78b7f43  master -> master

Never seen it (error: Unable to append to ./logs/HEAD: Permission denied) before but I'm not seeing my new commits on my gitlab server. Any ideas?

Thanks.


问:
Splitting a large XML file in Python
I'm looking to split a huge XML file into smaller bits. I'd like to scan through the file looking for a specific tag, then grab all info between  and , then save that into a file, then continue on through the rest of the file.

My issue is trying to find a clean way to note the start and end of the tags, so that I can grab the text inside as I scan through the file with "for line in f"

I'd rather not use sentinel variables. Is there a pythonic way to get this done?

The file is too big to read into memory.

答:
There are two common ways to handle XML data.

One is called DOM, which stands for Document Object Model.  This style of XML parsing is probably what you have seen when looking at documentation, because it reads the entire XML into memory to create the object model.

The second is called SAX, which is a streaming method.  The parser starts reading the XML and sends signals to your code about certain events, e.g. when a new start tag is found.

So SAX is clearly what you need for your situation. Sax parsers can be found in the python library under xml.sax and xml.parsers.expat.

OwnerDisplayName: benjamin

Title: Splitting a large XML file in Python

OwnerDisplayName: Van Gale


问:
C string arrays

Possible Duplicates:

  string literal in c

  Assigning strings to arrays of characters

I got the following code:

```<code>char result[3][4];

result[0] = "horse";
result[1] = "pig";
result[2] = "chicken";
</code>```

It won't compile saying Incompatible types in assignment. What am I doing wrong?

答:
The following works better:
char result[3][10] = {"horse", "pig", "chicken"};

Also, have in mind that "chicken" and "horse" have more that 4 characters and therefore result[3][4] (the [4] part) is not that right.

Title: C string arrays

Body:
Possible Duplicates:

  string literal in c

  Assigning strings to arrays of characters

I got the following code:

char result[3][4];

result[0] = "horse";
result[1] = "pig";
result[2] = "chicken";

It won't compile saying Incompatible types in assignment. What am I doing wrong?


问:
How to get images in Bootstrap's card to be the same height/width?
So here is my code, it displays 6 cards, three across and two rows. I would like for the images to all be the same size without having to manually resize the images. The responsiveness does work, I use "img-fluid" as a class and when I go to a mobile or smaller browser, they all have the same width, but the height is still off.

```<code><h1 class="display-4 text-xs-center m-y-3 text-muted" id="speakers">Ice Cream</h1>

<div class="row">
  <div class="col-md-6 col-lg-4">
    <div class="card"><img alt="Card image cap" class="card-img-top img-fluid" src="img/brownie.jpg" />
      <div class="card-block">
        <h4 class="card-title">Brownie Delight</h4>

        <p class="card-text">Our customer favorite chocolate ice cream jam packed with pieces of brownies and fudge</p>
      </div>
    </div>
  </div>

  <div class="col-md-6 col-lg-4">
    <div class="card"><img alt="Card image cap" class="card-img-top img-fluid" src="img/butterPecan.jpg" />
      <div class="card-block">
        <h4 class="card-title">Butter Pecan</h4>

        <p class="card-text">Roasted pecans, butter and vanilla come together to make this wonderful ice cream</p>
      </div>
    </div>
  </div>

  <div class="col-md-6 col-lg-4">
    <div class="card"><img alt="Card image cap" class="card-img-top img-fluid" src="img/bCherry.jpg" />
      <div class="card-block">
        <h4 class="card-title">Black Cherry</h4>

        <p class="card-text">Our classic vanilla loaded with plump black cherries to give flavor and color</p>
      </div>
    </div>
  </div>

  <div class="col-md-6 col-lg-4">
    <div class="card"><img alt="Card image cap" class="card-img-top img-fluid" src="img/mintChip.jpg" />
      <div class="card-block">
        <h4 class="card-title">Mint Chip</h4>

        <p class="card-text">Our signiture mint ice cream jam packed with mint chocolate chips</p>
      </div>
    </div>
  </div>

  <div class="col-md-6 col-lg-4">
    <div class="card"><img alt="Card image cap" class="card-img-top img-fluid" src="img/pistachio.jpg" />
      <div class="card-block">
        <h4 class="card-title">Pistachio</h4>

        <p class="card-text">Our classic pistachio is loaded with nuts to give it that great flavor, and of course comes in your favorite color</p>
      </div>
    </div>
  </div>

  <div class="col-md-6 col-lg-4">
    <div class="card"><img alt="Card image cap" class="card-img-top img-fluid" src="img/IceCream.jpg" />
      <div class="card-block">
        <h4 class="card-title">More Flavors</h4>

        <p class="card-text">We couldn not fit all of our wonderful flavors on one page, click here to see more!</p>
      </div>
    </div>
  </div>
</div>
</code>```

Here is an image of what I am getting and this is what I want to get where they are all the same size.

答:
Try this in your css:

```<code>.card-img-top {
    width: 100%;
    height: 15vw;
    object-fit: cover;
}
</code>```

Adjust the height vw as you see fit.
The object-fit: cover enables zoom instead of image stretching.

Body:
So here is my code, it displays 6 cards, three across and two rows. I would like for the images to all be the same size without having to manually resize the images. The responsiveness does work, I use "img-fluid" as a class and when I go to a mobile or smaller browser, they all have the same width, but the height is still off.

Ice Cream

Brownie Delight

Our customer favorite chocolate ice cream jam packed with pieces of brownies and fudge

Butter Pecan

Roasted pecans, butter and vanilla come together to make this wonderful ice cream

Black Cherry

Our classic vanilla loaded with plump black cherries to give flavor and color

Mint Chip

Our signiture mint ice cream jam packed with mint chocolate chips

Pistachio

Our classic pistachio is loaded with nuts to give it that great flavor, and of course comes in your favorite color

More Flavors

We couldn not fit all of our wonderful flavors on one page, click here to see more!

Here is an image of what I am getting and this is what I want to get where they are all the same size.

Body:
Try this in your css:

.card-img-top {
    width: 100%;
    height: 15vw;
    object-fit: cover;
}

Adjust the height vw as you see fit.
The object-fit: cover enables zoom instead of image stretching.


问:
Inherit URL path on Google Analytics Experiments
I want to run an A/B test using Google Analytics Content Experiments to test different pages.

I would like to know if there is a way to define variations inheriting parts of the URL path. I read the documentation but seems that Analytics only inherits URL dynamic parameters.

My URLs look like:

```<code>https://example.com/page1/{USER-DATA-123}
</code>```

where {USER-DATA-123} contains some data related to current user and it's different for every visitor.

And I want to create this experiment:

```<code>Original page: https://example.com/page1/{USER-DATA-123}
Variation page 1: https://example.com/page2/{USER-DATA-123}
</code>```

答:
I was investigaing the same issue, just had to test two desings of this page https://labiteam.com/services/landing-page. There are two variants:

Turn your static urls with id sessions into dynamic. According to this manual https://support.google.com/analytics/answer/2664470?hl=en it should work

You can customize testing script manually, though I doubt it's a practical decision

Upd: Also, one more suggestion. Forget about A/B experiments, just make your URLs appear randomly (coding it manually) and set goals to each url.

Body:
I want to run an A/B test using Google Analytics Content Experiments to test different pages.

I would like to know if there is a way to define variations inheriting parts of the URL path. I read the documentation but seems that Analytics only inherits URL dynamic parameters.

My URLs look like:

https://example.com/page1/{USER-DATA-123}

where {USER-DATA-123} contains some data related to current user and it's different for every visitor.

And I want to create this experiment:

Original page: https://example.com/page1/{USER-DATA-123}
Variation page 1: https://example.com/page2/{USER-DATA-123}


问:
Focus on the button using tab key and press enter
I have a simple jFrame with a submit button and a cancel button. Currently, everything works perfectly. User perform action on mouse click. Now I want to press 'tab' first to focus the button then it should fire whenever someone presses the enter key. It should work for both keys. What am I missing here? I am using netbean IDE. Below is a sample of the code that works perfectly using mouse click.</p>

```<code> private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
         String ws = null;
         if(unitno.getText().length() == 14)
        {
            String substr=unitno.getText().substring(unitno.getText().length()-4);
            if (substr.equals("0678"))
            {
                model.setSelectedItem("Tesla");
            }
            else if(substr.equals("0675"))
            {
                 model.setSelectedItem("Weber Base");
            }
            else if(substr.equals("0676"))
            {
                 model.setSelectedItem("Weber Mid");
            }
               else if(substr.equals("0677")|| substr.equals("067j")|| substr.equals("067J"))
            {
                 model.setSelectedItem("Weber PDL");
            }
        }
        try{
             Double wd = Double.parseDouble(w.getText());
             if(wd<251.43 || wd>253.03){
                  w.setForeground(Color.BLUE);
                  w.setBackground(Color.YELLOW);
                  wt.setForeground(Color.red);
             }
             else{
                   ws = w.getText();
                  w.setForeground(Color.BLACK);
                  w.setBackground(Color.WHITE);
             }

             if(ws ==null || unitno.getText().equals("")){
                int dialogButton = JOptionPane.YES_NO_OPTION;
                int dialogResult = JOptionPane.showConfirmDialog(this, "Empty field or out of spec is detected. Press YES to save and NO to edit.", "Error", dialogButton);
                if(dialogResult ==0){
                    ws = w.getText();

                    w.setForeground(Color.BLACK);
                    w.setBackground(Color.WHITE);

                    BufferedWriter output = null;
                    FileInputStream fs = null;
                    FileWriter fout = null;

                    try {
                        // TODO add your handling code here:
                        File desktop = new File(System.getProperty("user.home"), "Desktop");
                       // Double total = Double.parseDouble(ba) + Double.parseDouble(fr) ;
                        File dir = new File (desktop + "/WattCPC");
                        if(!dir.exists()){
                            dir.mkdirs();
                        }
                        File myFile = new File(desktop + "/WattCPC/topextimechwidth.txt");
                        if(!myFile.exists()) {
                            myFile.createNewFile();
                        }
                        fs = new FileInputStream(desktop + "/WattCPC/topextimechwidth.txt");
                        BufferedReader br = new BufferedReader(new InputStreamReader(fs));
                        output = new BufferedWriter(new FileWriter(myFile,true));
                        PrintWriter fileout = new PrintWriter(output,true);
                        if (br.readLine() == null) {
                               fileout.println("Model" + "," + "Date" + "," + "Line" + "," + "Shift" + "," + "Unit Number" + "," + "Width");
                         }
                        DateFormat dateFormat = new SimpleDateFormat("MMM/dd/yyyy hh:mm");
                        Date date = new Date();
                        for(int i = 1; i<100; ++i){
                            String linez = br.readLine();
                            if(linez==null){
                               fileout.println(model.getSelectedItem() + "," + dateFormat.format(date) + "," + line.getSelectedItem() + "," + shift.getSelectedItem() + "," + unitno.getText() + "," + ws  );
                               break;
                            }
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(setup.class.getName()).log(Level.SEVERE, null, ex);
                    } finally {
                        try {
                            output.close();
                        } catch (IOException ex) {
                            Logger.getLogger(setup.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    JOptionPane msg = new JOptionPane("Saved successfully", JOptionPane.INFORMATION_MESSAGE);
                    final JDialog dlg = msg.createDialog("Message");
                    dlg.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                    new Thread(new Runnable() {
</code>```

答:
See https://stackoverflow.com/a/16923982/1614775.
It suggests </p>

```<code>UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE);
</code>```

Body:
I have a simple jFrame with a submit button and a cancel button. Currently, everything works perfectly. User perform action on mouse click. Now I want to press 'tab' first to focus the button then it should fire whenever someone presses the enter key. It should work for both keys. What am I missing here? I am using netbean IDE. Below is a sample of the code that works perfectly using mouse click.

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
         String ws = null;
         if(unitno.getText().length() == 14)
        {
            String substr=unitno.getText().substring(unitno.getText().length()-4);
            if (substr.equals("0678"))
            {
                model.setSelectedItem("Tesla");
            }
            else if(substr.equals("0675"))
            {
                 model.setSelectedItem("Weber Base");
            }
            else if(substr.equals("0676"))
            {
                 model.setSelectedItem("Weber Mid");
            }
               else if(substr.equals("0677")|| substr.equals("067j")|| substr.equals("067J"))
            {
                 model.setSelectedItem("Weber PDL");
            }
        }
        try{
             Double wd = Double.parseDouble(w.getText());
             if(wd<251.43 || wd>253.03){
                  w.setForeground(Color.BLUE);
                  w.setBackground(Color.YELLOW);
                  wt.setForeground(Color.red);
             }
             else{
                   ws = w.getText();
                  w.setForeground(Color.BLACK);
                  w.setBackground(Color.WHITE);
             }

             if(ws ==null || unitno.getText().equals("")){
                int dialogButton = JOptionPane.YES_NO_OPTION;
                int dialogResult = JOptionPane.showConfirmDialog(this, "Empty field or out of spec is detected. Press YES to save and NO to edit.", "Error", dialogButton);
                if(dialogResult ==0){
                    ws = w.getText();

                    w.setForeground(Color.BLACK);
                    w.setBackground(Color.WHITE);

                    BufferedWriter output = null;
                    FileInputStream fs = null;
                    FileWriter fout = null;

                    try {
                        // TODO add your handling code here:
                        File desktop = new File(System.getProperty("user.home"), "Desktop");
                       // Double total = Double.parseDouble(ba) + Double.parseDouble(fr) ;
                        File dir = new File (desktop + "/WattCPC");
                        if(!dir.exists()){
                            dir.mkdirs();
                        }
                        File myFile = new File(desktop + "/WattCPC/topextimechwidth.txt");
                        if(!myFile.exists()) {
                            myFile.createNewFile();
                        }
                        fs = new FileInputStream(desktop + "/WattCPC/topextimechwidth.txt");
                        BufferedReader br = new BufferedReader(new InputStreamReader(fs));
                        output = new BufferedWriter(new FileWriter(myFile,true));
                        PrintWriter fileout = new PrintWriter(output,true);
                        if (br.readLine() == null) {
                               fileout.println("Model" + "," + "Date" + "," + "Line" + "," + "Shift" + "," + "Unit Number" + "," + "Width");
                         }
                        DateFormat dateFormat = new SimpleDateFormat("MMM/dd/yyyy hh:mm");
                        Date date = new Date();
                        for(int i = 1; i<100; ++i){
                            String linez = br.readLine();
                            if(linez==null){
                               fileout.println(model.getSelectedItem() + "," + dateFormat.format(date) + "," + line.getSelectedItem() + "," + shift.getSelectedItem() + "," + unitno.getText() + "," + ws  );
                               break;
                            }
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(setup.class.getName()).log(Level.SEVERE, null, ex);
                    } finally {
                        try {
                            output.close();
                        } catch (IOException ex) {
                            Logger.getLogger(setup.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                    JOptionPane msg = new JOptionPane("Saved successfully", JOptionPane.INFORMATION_MESSAGE);
                    final JDialog dlg = msg.createDialog("Message");
                    dlg.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                    new Thread(new Runnable() {

Body:
See https://stackoverflow.com/a/16923982/1614775.
It suggests

UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE);


问:
Unable to explore tables as admin in apache superset
I've just installed apache superset following instructions at https://superset.incubator.apache.org/installation.html. I then login to the web interface as admin. I also loaded sample data with 'superset load_examples'.

If i go to 'Sources > Tables' and click on any of the tables ('wb_health_population', for example) i get an error: 'This endpoint requires the datasource wb_health_population, database or all_datasource_access permission'.

I check permissions set for the admin role and existing permissions: 'all_datasource_access' is not enabled for the admin role, and does not exist in the list of existing permissions.

As i told, i just followed standard instalation instructions from superset's doc website. Any help on this? Thank you.

EDIT: Superset version is 0.20.6, python's 3.6.3.

答: I would also try all_database_access permission.


问:
"Flat links" with Apache
I'm attempting to convert URLs with GET variables from something like

```<code>http://domain.com/?username=john
</code>```

to

```<code>http://domain.com/john
</code>```

using following the articles here and here.

Using the example in the first article (with a slight modification) - RewriteRule .* index.php - I have gotten that to work. The first problem is, I still want to be able to access the other files in the same directory. So the closest I've gotten so far is RewriteRule index\.php/(.+) index.php?username=$1, which is still not ideal because I don't want the filename in the URL, but there's another problem. index.php is set as the DirectoryIndex, and I have no idea how to match that.

I'm still very much a beginner at configuring Apache, so any help is greatly appreciated.

答:
Try something like that

```<code>RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !\.php$
RewriteCond %{QUERY_STRING} \buser=\w+
RewriteRule .* user.php [L]
</code>```

put instead of user.php the name of your script.

Title: "Flat links" with Apache

Body:
I'm attempting to convert URLs with GET variables from something like

http://domain.com/?username=john

to

http://domain.com/john

using following the articles here and here.

Using the example in the first article (with a slight modification) - RewriteRule .* index.php - I have gotten that to work. The first problem is, I still want to be able to access the other files in the same directory. So the closest I've gotten so far is RewriteRule index\.php/(.+) index.php?username=$1, which is still not ideal because I don't want the filename in the URL, but there's another problem. index.php is set as the DirectoryIndex, and I have no idea how to match that.

I'm still very much a beginner at configuring Apache, so any help is greatly appreciated.

Body:
Try something like that

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !\.php$
RewriteCond %{QUERY_STRING} \buser=\w+
RewriteRule .* user.php [L]

put instead of user.php the name of your script.


问:
From SAML to LTPA2 Token for IBM BPM 8.5.6
I am building a TAI Interceptor for Websphere 8.5.5.x, the aim is to intercept the request and send it for 2-Factor authentication which will then return a SAML token.

I am doing this by implementing com.ibm.wsspi.security.web.saml.AuthnRequestProvider interface.

From what I understand I just need to ensure that this points the user to 2-Factor site.

When I get the response back it has a SAML Token which I can interrogate using the com.ibm.wsspi.security.web.saml.UserMapping interface. Where I can obtain all the returned attributes in the SAML token.

However I want to use this data to build an LTPA2 token asserting an identity and group membership for use within BPM.

Many thanks for any help

Benjamin

答:
As far as I know there is no WebSphere API to generate an LTPA token.

There are ways to do it in API Connect but that might not be helpful in your case:
https://www.ibm.com/support/knowledgecenter/en/SSMNED_5.0.0/com.ibm.apic.toolkit.doc/rapim_ref_ootb_policyltpagen.html


问:
What are Reactors/Reactions in Event-Sourcing?
I am new in CQRS and I read about projections and projectors also reactors but my resource does not cover it thoroughly. Can someone define reactors thoroughly in Event sourcing or give me a link or book to read? my main questions are:

what are reactors?

what is the structure of reactors?

how do we implement reactors?

答:
A projection is a function that receives a domain event and transforms it to an action on a list, tree, graph, whatever…

The idea here is that you want the semantic domain events to store them, and to be able to replay them, but that you need various interpretations of them to efficiently query them. Hence you need a projection that says that domain event X means INSERT or UPDATE or DELETE for a given view.

So, a projection is basically a mapping between domain events and CRUD operations. You might also say that a projection is one of many interpretations of a domain event.

Now, there may be actions requires in response to a domain event that are not related to updating a table. E.g., whenever you receive a userLoggedIn event, you may want to send an email to the user. It's like a simple if this then that rule. This is basically what you call a reaction. You just react to the domain event in some custom way.

The structure of a reactor (the component that reacts) is hence pretty similar to the one of a projector. The only difference is that a reactor does not update the read model, but does any arbitrary action you want to.

In other words: A projection is a special kind of a reaction, where it is always about updating the read model. Since this is so common, you have a dedicated pattern for this, but generally speaking: Whenever you do something in response to receiving an event, this is a reaction.

The question of how to implement reactors is hard to answer without having more details. In wolkenkit, a CQRS and event-sourcing framework for JavaScript and Node.js, reactors are nothing but flows. Flows can either be stateless flows or stateful flows, depending on whether they contain state themselves.

A simple example (which is of course specific to wolkenkit) may look like this:

```<code>'use strict';

const when = {
  'userManagement.user.loggedIn' (event, mark) {
    // ...
    mark.asDone();
  }
};

module.exports = { when };
</code>```

(Disclaimer: I am one of the authors of wolkenkit, so please take the examples with a grain of salt.)

Body:
A projection is a function that receives a domain event and transforms it to an action on a list, tree, graph, whatever…

The idea here is that you want the semantic domain events to store them, and to be able to replay them, but that you need various interpretations of them to efficiently query them. Hence you need a projection that says that domain event X means INSERT or UPDATE or DELETE for a given view.

So, a projection is basically a mapping between domain events and CRUD operations. You might also say that a projection is one of many interpretations of a domain event.

Now, there may be actions requires in response to a domain event that are not related to updating a table. E.g., whenever you receive a userLoggedIn event, you may want to send an email to the user. It's like a simple if this then that rule. This is basically what you call a reaction. You just react to the domain event in some custom way.

The structure of a reactor (the component that reacts) is hence pretty similar to the one of a projector. The only difference is that a reactor does not update the read model, but does any arbitrary action you want to.

In other words: A projection is a special kind of a reaction, where it is always about updating the read model. Since this is so common, you have a dedicated pattern for this, but generally speaking: Whenever you do something in response to receiving an event, this is a reaction.

The question of how to implement reactors is hard to answer without having more details. In wolkenkit, a CQRS and event-sourcing framework for JavaScript and Node.js, reactors are nothing but flows. Flows can either be stateless flows or stateful flows, depending on whether they contain state themselves.

A simple example (which is of course specific to wolkenkit) may look like this:

'use strict';

const when = {
  'userManagement.user.loggedIn' (event, mark) {
    // ...
    mark.asDone();
  }
};

module.exports = { when };

(Disclaimer: I am one of the authors of wolkenkit, so please take the examples with a grain of salt.)


问:
stale element references in loop after redirection to another page
i am trying to choose a certain element of similar objects on a website, in my e2e tests, and to click it then to change to another site, related to that element. The Problem is that the loop is still going on after the page is changed because the promise resolves asynchronous (i'm new to all this stuff)

Here the code:

```<code>    goToCartridge(name){
    let done = false;
    element(by.id('dashboard')).all(by.className('card z-depth-1')).then( elems => {
      for(let i = 0; i < elems.length ; i++ ){
        if(done) break;
          elems[i].element(by.tagName('h2')).getText().then( text => {
            if(name === text) {
              element(by.id('cartridge-' + i)).click();
              done = true;
            }
          return;
        });
      }
    });
  }
</code>```

How can i wait for the async part inside the loop before the next iteration starts? i searched alot for a solution, but couldnt find one yet.

答:
u can skip the loop of elems and call check next element of elems from inside gettext() callback like this</p>

```<code>goToCartridge(name){
    let done = false;
    element(by.id('dashboard')).all(by.className('card z-depth-1')).then( elems => {
    function check(i) {
      if( i >= elems.length ) return;
      elems[i].element(by.tagName('h2')).getText().then( text => {
        if(name === text) {
          element(by.id('cartridge-' + i)).click();
        }
        else {
          check(i+1);
        }
      });
    }
    check(0);
  });
}
</code>```

Body:
i am trying to choose a certain element of similar objects on a website, in my e2e tests, and to click it then to change to another site, related to that element. The Problem is that the loop is still going on after the page is changed because the promise resolves asynchronous (i'm new to all this stuff)

Here the code:

    goToCartridge(name){
    let done = false;
    element(by.id('dashboard')).all(by.className('card z-depth-1')).then( elems => {
      for(let i = 0; i < elems.length ; i++ ){
        if(done) break;
          elems[i].element(by.tagName('h2')).getText().then( text => {
            if(name === text) {
              element(by.id('cartridge-' + i)).click();
              done = true;
            }
          return;
        });
      }
    });
  }

How can i wait for the async part inside the loop before the next iteration starts? i searched alot for a solution, but couldnt find one yet.

Body:
u can skip the loop of elems and call check next element of elems from inside gettext() callback like this

goToCartridge(name){
    let done = false;
    element(by.id('dashboard')).all(by.className('card z-depth-1')).then( elems => {
    function check(i) {
      if( i >= elems.length ) return;
      elems[i].element(by.tagName('h2')).getText().then( text => {
        if(name === text) {
          element(by.id('cartridge-' + i)).click();
        }
        else {
          check(i+1);
        }
      });
    }
    check(0);
  });
}


答:
Try running superset init - this should initialize permissions.

See https://superset.incubator.apache.org/installation.html#superset-installation-and-initialization

(code-wise, init calls security.sync_role_definitions() which itself calls create_custom_permissions() which creates the said permissions)

Title: Unable to explore tables as admin in apache superset

Body:
I've just installed apache superset following instructions at https://superset.incubator.apache.org/installation.html. I then login to the web interface as admin. I also loaded sample data with 'superset load_examples'.

If i go to 'Sources > Tables' and click on any of the tables ('wb_health_population', for example) i get an error: 'This endpoint requires the datasource wb_health_population, database or all_datasource_access permission'.

I check permissions set for the admin role and existing permissions: 'all_datasource_access' is not enabled for the admin role, and does not exist in the list of existing permissions.

As i told, i just followed standard instalation instructions from superset's doc website. Any help on this? Thank you.

EDIT: Superset version is 0.20.6, python's 3.6.3.