问:
more virtualizing stack panel height/slowness issues
I need a scrollviewer around a virtualizing stackpanel populated by an items control.  Clearly the height is infinity and that's why it's not virtualizing.  Why?

```<code><Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <ScrollViewer>
        <ItemsControl ItemsSource="{Binding InterestingHosts}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <VirtualizingStackPanel IsItemsHost="True" />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Vertical">
                        <TextBlock FontSize="14"><TextBlock Text="{Binding Host.HostName}" FontWeight="Bold" FontSize="18" /> (<TextBlock Text="{Binding Host.IPAddress}" />)</TextBlock>
                        <StackPanel>
                            <StackPanel.Style>
                                <Style TargetType="StackPanel">
                                    <Setter Property="Margin" Value="10" />
                                    <Style.Triggers>
                                        <DataTrigger Binding="{Binding LoggedOnUsers.Count}" Value="0">
                                            <Setter Property="Visibility" Value="Collapsed" />
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </StackPanel.Style>
                            <TextBlock Text="The follow domain and/or enterprise admins are logged on to the host: "/>
                            <DataGrid AutoGenerateColumns="False" IsReadOnly="True" ItemsSource="{Binding LoggedOnUsers}">
                                <DataGrid.Columns>
                                    <DataGridTextColumn Width="200" Binding="{Binding Domain}" Header="Domain"/>
                                    <DataGridTextColumn Width="200" Binding="{Binding Name}" Header="Username"/>
                                </DataGrid.Columns>
                            </DataGrid>
                        </StackPanel>
                        <StackPanel>
                            <StackPanel.Style>
                                <Style TargetType="StackPanel">
                                    <Setter Property="Margin" Value="10" />
                                    <Style.Triggers>
                                        <DataTrigger Binding="{Binding Processes.Count}" Value="0">
                                            <Setter Property="Visibility" Value="Collapsed" />
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </StackPanel.Style>
                            <TextBlock Text="The follow domain and/or enterprise admins are running processes on the host: "/>
                            <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Processes}" IsReadOnly="True">
                                <DataGrid.Columns>
                                    <DataGridTextColumn Width="200" Header="Name" IsReadOnly="False" Binding="{Binding Name}"/>
                                    <DataGridTextColumn Width="200" Binding="{Binding Username}" Header="Username" />
                                    <DataGridTextColumn Binding="{Binding ID}" Header="ID" />
                                </DataGrid.Columns>
                            </DataGrid>
                        </StackPanel>
                        <StackPanel>
                            <StackPanel.Style>
                                <Style TargetType="StackPanel">
                                    <Setter Property="Margin" Value="10" />
                                    <Style.Triggers>
                                        <DataTrigger Binding="{Binding Services.Count}" Value="0">
                                            <Setter Property="Visibility" Value="Collapsed" />
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </StackPanel.Style>
                            <TextBlock Text="The follow domain and/or enterprise admins are authenticated for services on the host: "/>
                            <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Services}" IsReadOnly="True">
                                <DataGrid.Columns>
                                    <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
                                    <DataGridTextColumn Header="Username" Binding="{Binding Username}" />
                                    <DataGridTextColumn Header="Start Mode" Binding="{Binding StartMode}" />
                                    <DataGridTextColumn Header="State" Binding="{Binding State}" />
                                </DataGrid.Columns>
                            </DataGrid>
                        </StackPanel>
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </ScrollViewer>
</Grid>
</code>```

答:
The VirtualizingStackPanel needs to be a direct child of the ScrollViewer. You can see that it implements IScrollInfo, which is what ties it to the parent ScrollViewer.

So in the case of a ListBox, there is already a ScrollViewer in the control template (which will ultimately be the parent of the VirtualizingStackPanel. The default ControlTemplate for the ItemsControl does not have a ScrollViewer, so you would need to add it there. Something like:

```<code><Style x:Key="{x:Type ItemsControl}"
       TargetType="{x:Type ItemsControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ItemsControl}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}"
                        Padding="{TemplateBinding Padding}"
                        SnapsToDevicePixels="true">
                    <ScrollViewer CanContentScroll="True">
                        <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                    </ScrollViewer>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

Body:
I need a scrollviewer around a virtualizing stackpanel populated by an items control.  Clearly the height is infinity and that's why it's not virtualizing.  Why?

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <ScrollViewer>
        <ItemsControl ItemsSource="{Binding InterestingHosts}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <VirtualizingStackPanel IsItemsHost="True" />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Vertical">
                        <TextBlock FontSize="14"><TextBlock Text="{Binding Host.HostName}" FontWeight="Bold" FontSize="18" /> (<TextBlock Text="{Binding Host.IPAddress}" />)</TextBlock>
                        <StackPanel>
                            <StackPanel.Style>

                                </Style>
                            </StackPanel.Style>
                            <TextBlock Text="The follow domain and/or enterprise admins are logged on to the host: "/>
                            <DataGrid AutoGenerateColumns="False" IsReadOnly="True" ItemsSource="{Binding LoggedOnUsers}">
                                <DataGrid.Columns>
                                    <DataGridTextColumn Width="200" Binding="{Binding Domain}" Header="Domain"/>
                                    <DataGridTextColumn Width="200" Binding="{Binding Name}" Header="Username"/>
                                </DataGrid.Columns>
                            </DataGrid>
                        </StackPanel>
                        <StackPanel>
                            <StackPanel.Style>

                                </Style>
                            </StackPanel.Style>
                            <TextBlock Text="The follow domain and/or enterprise admins are running processes on the host: "/>
                            <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Processes}" IsReadOnly="True">
                                <DataGrid.Columns>
                                    <DataGridTextColumn Width="200" Header="Name" IsReadOnly="False" Binding="{Binding Name}"/>
                                    <DataGridTextColumn Width="200" Binding="{Binding Username}" Header="Username" />
                                    <DataGridTextColumn Binding="{Binding ID}" Header="ID" />
                                </DataGrid.Columns>
                            </DataGrid>
                        </StackPanel>
                        <StackPanel>
                            <StackPanel.Style>

                                </Style>
                            </StackPanel.Style>
                            <TextBlock Text="The follow domain and/or enterprise admins are authenticated for services on the host: "/>
                            <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Services}" IsReadOnly="True">
                                <DataGrid.Columns>
                                    <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
                                    <DataGridTextColumn Header="Username" Binding="{Binding Username}" />
                                    <DataGridTextColumn Header="Start Mode" Binding="{Binding StartMode}" />
                                    <DataGridTextColumn Header="State" Binding="{Binding State}" />
                                </DataGrid.Columns>
                            </DataGrid>
                        </StackPanel>
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </ScrollViewer>
</Grid>

Body:
The VirtualizingStackPanel needs to be a direct child of the ScrollViewer. You can see that it implements IScrollInfo, which is what ties it to the parent ScrollViewer.

So in the case of a ListBox, there is already a ScrollViewer in the control template (which will ultimately be the parent of the VirtualizingStackPanel. The default ControlTemplate for the ItemsControl does not have a ScrollViewer, so you would need to add it there. Something like:

<Style x:Key="{x:Type ItemsControl}"
       TargetType="{x:Type ItemsControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ItemsControl}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}"
                        Padding="{TemplateBinding Padding}"
                        SnapsToDevicePixels="true">
                    <ScrollViewer CanContentScroll="True">
                        <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                    </ScrollViewer>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


来源: stackexchange

问:
gitignore is not ignoring the files I added
The code below is what I have tried in the .gitignore file. Other folders when I put logs or **/wwwroot and save the file, every file in the folder is ignored but this object folder in the core project is not ignored somehow.

```<code>
obj/project.assets.json
obj/Debug/netcoreapp3.1/CDS.PORTAL.assets.cache
obj/Debug/netcoreapp3.1/CDS.PORTAL.csproj.FileListAbsolute.txt
obj/Debug/netcoreapp3.1/CDS.PORTAL.csprojAssemblyReference.cache
obj/Debug/netcoreapp3.1/staticwebassets/CDS.PORTAL.StaticWebAssets.Manifest.cache
obj/Debug/netcoreapp3.1/staticwebassets/CDS.PORTAL.StaticWebAssets.xml

</code>```

答:
The M next to the file names in VS Code stands for Modified. See git status modes.

Seems like at some point you've added those files to git, then added those entries to .gitignore later. git now knows those files exist and keeps track of them, and doesn't automatically rewrite, even though you have a new .gitignore list.

If you still want to do this, check this similar question: How to make Git "forget" about a file that was tracked but is now in .gitignore?

ContentLicense: CC BY-SA 4.0

Body:
The code below is what I have tried in the .gitignore file. Other folders when I put logs or **/wwwroot and save the file, every file in the folder is ignored but this object folder in the core project is not ignored somehow.

obj/project.assets.json
obj/Debug/netcoreapp3.1/CDS.PORTAL.assets.cache
obj/Debug/netcoreapp3.1/CDS.PORTAL.csproj.FileListAbsolute.txt
obj/Debug/netcoreapp3.1/CDS.PORTAL.csprojAssemblyReference.cache
obj/Debug/netcoreapp3.1/staticwebassets/CDS.PORTAL.StaticWebAssets.Manifest.cache
obj/Debug/netcoreapp3.1/staticwebassets/CDS.PORTAL.StaticWebAssets.xml


问:
Publish from Flux<String> into a Flux<List<String>> only when source is updated
I would like to publish list of keys, but only when keys are modified.

With the following, it's publishing in an endless loop the values, even if nothing changed

```<code>    RedisReactiveCommands<String, String> commands = connection.reactive();
    return commands
            .keys(String.format(AWAITING_USER_KEY_FORMAT, "*")) // returns Flux<String>
            .collectList() // returns Mono<List<String>>
            .repeat(); // returns Flux<List<String>>
</code>```

How could publish the list only when it changed ?

答:
distinctUntilChanged : "suppress duplicate items emitted by an Observable"

```<code>RedisReactiveCommands<String, String> commands = connection.reactive();
return commands
          .keys(String.format(AWAITING_USER_KEY_FORMAT, "*"))
          .collectList()
          .repeat()
          .distinctUntilChanged();
</code>```

This will publish the entire list of awaiting users, a response will be published whenever list is updated (element removed or added)

Body:
I would like to publish list of keys, but only when keys are modified.

With the following, it's publishing in an endless loop the values, even if nothing changed

    RedisReactiveCommands<String, String> commands = connection.reactive();
    return commands
            .keys(String.format(AWAITING_USER_KEY_FORMAT, "*")) // returns Flux<String>
            .collectList() // returns Mono<List<String>>
            .repeat(); // returns Flux<List<String>>

How could publish the list only when it changed ?

Body:
distinctUntilChanged : "suppress duplicate items emitted by an Observable"

RedisReactiveCommands<String, String> commands = connection.reactive();
return commands
          .keys(String.format(AWAITING_USER_KEY_FORMAT, "*"))
          .collectList()
          .repeat()
          .distinctUntilChanged();

This will publish the entire list of awaiting users, a response will be published whenever list is updated (element removed or added)


问:
How to automatically run the migrations in a Laravel package?
I just installed Cartalyst's Sentry 2 in a Laravel 4 application but I found out that I have to run that package's migrations separately by specifying --package=cartalyst/sentry, which makes automatic deployment impossible.

Is there a way to run php artisan migrate and have it run Sentry's migrations as well?

答:
The 3rd party package must declare a Service Provider, that declare migrations.

As you can see at https://github.com/laravel/passport/blob/9.x/src/PassportServiceProvider.php#L80:

```<code>protected function registerMigrations()
    {
        if (Passport::$runsMigrations && ! config('passport.client_uuids')) {
            return $this->loadMigrationsFrom(__DIR__.'/../database/migrations');
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The 3rd party package must declare a Service Provider, that declare migrations.

As you can see at https://github.com/laravel/passport/blob/9.x/src/PassportServiceProvider.php#L80:

protected function registerMigrations()
    {
        if (Passport::$runsMigrations && ! config('passport.client_uuids')) {
            return $this->loadMigrationsFrom(__DIR__.'/../database/migrations');
        }
    }


问:
object reference ist not défine of a instance c#
Hellow guys i am creating a desktop app for checking students,
after i linked my database(postgres)with project  and show my table when ever i try to delete something it shows me this error  and the ID_student and DELETE/UPDATE button change postions with the first colums  this is the normal one

then after i click on the delete button
but on my database the user was deleted and the same error apear on my inscription the students is added but i got this error
i search for many solution and checked my variables and almost lost hope
this is my table

```<code> private new void Select()
        {
            try
            {
                conn.Open();
                sql= @"select  etudiant.id_etudiant,etudiant.nom,etudiant.prenom,etudiant.age,etudiant.sexe,etudiant.num,class.nom_class
                        from etudiant
                        inner join class on etudiant.classess=class.id_class";
                cmd = new NpgsqlCommand(sql, conn);
                dt = new DataTable();
                dt.Load(cmd.ExecuteReader());

                conn.Close();
                bunifuCustomDataGrid1.DataSource = null;//resete
                bunifuCustomDataGrid1.DataSource = dt;
            }
            catch ( Exception ex)
            {
                conn.Close();
                MessageBox.Show("ERROR" + ex.Message);
            }
        }
</code>```

and this is my delete

```<code>        {
            if (bunifuCustomDataGrid1.Columns[e.ColumnIndex].Name == "Delete")
            {

                try
                {
                    conn.Open();
                    sql = @"Select   all from deleteEtudiant(:id_)  ";
                    cmd = new NpgsqlCommand(sql, conn);
                    cmd.Parameters.AddWithValue("id_", int.Parse(bunifuCustomDataGrid1.Rows[e.RowIndex].Cells["ID"].Value.ToString()));
                    if ((int)cmd.ExecuteScalar() == 1)
                    {
                        MessageBox.Show("Deleted");

                    }

                    conn.Close();

                }
                catch (Exception ex)
                {
                    conn.Close();
                    MessageBox.Show("User deleted don't forget the bug yassine" + ex.Message);

                }
            }
            if (bunifuCustomDataGrid1.Columns[e.ColumnIndex].Name == "Update")
            {

                try
                {
                    conn.Open();
                    sql = @"Select * from updateETUDIANT(':id_,:ST_Firstname ,:ST_prenom ,:ST_Age,:ST_Sexe,:ST_num');
";
                    cmd = new NpgsqlCommand(sql, conn);
                    cmd.Parameters.AddWithValue("id_", int.Parse(bunifuCustomDataGrid1.Rows[e.RowIndex].Cells["ID_etudiant"].Value.ToString()));
                    cmd.Parameters.AddWithValue("ST_Firstname", (bunifuCustomDataGrid1.Rows[e.RowIndex].Cells["Nom"].Value.ToString()));

                    if ((int)cmd.ExecuteScalar() == 1)
                    {
                        MessageBox.Show("UPDATED");

                        Select();

                    }

                    conn.Close();

                }
                catch (Exception ex)

                {
                    conn.Close();
                    MessageBox.Show("User UPDATED"+ex.Message);
                    Select();

                }

            }
</code>```

i am sorry for the long post and i hope u can tell me how to improve

edit: i have a little question is my query wrong here ?

```<code> public void Ajouter_Click(object sender, EventArgs e)
        {
            try
            {
                conn.Open();
                sql = "insert into etudiant (Nom, prenom, sexe) " +
                     "values(@Nom, @prenom,  @sexe);";
                cmd = new NpgsqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("nom", bunifuMaterialTextbox1.Text);
                cmd.Parameters.AddWithValue("prenom", bunifuMaterialTextbox2.Text);
                //cmd.Parameters.AddWithValue("Age", bunifuMaterialTextbox2.ToString());//
                cmd.Parameters.AddWithValue("sexe", bunifuMaterialTextbox3.Text);
                //cmd.Parameters.AddWithValue("Num", bunifuMaterialTextbox6.Text);
                //cmd.Parameters.AddWithValue("Classess", bunifuMaterialTextbox7.Text);
                 int result = (int)cmd.ExecuteScalar();

                if (result==1)
                {
                    conn.Close();

                    MessageBox.Show("Etudinat ajouter");

                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR" + ex.Message);
                conn.Close();

            }

        }

</code>```

it give me the same error object reference like the delete one

答:
I think that the problem is in the ExecuteScalar(), use ExecuteNonQuery() instead of it;

```<code>int result = (int)cmd.ExecuteScalar();
</code>```

replace it with :

```<code>int result = cmd.ExecuteNonQuery();
</code>```

Body:
Hellow guys i am creating a desktop app for checking students,
after i linked my database(postgres)with project  and show my table when ever i try to delete something it shows me this error  and the ID_student and DELETE/UPDATE button change postions with the first colums  this is the normal one

then after i click on the delete button
but on my database the user was deleted and the same error apear on my inscription the students is added but i got this error
i search for many solution and checked my variables and almost lost hope
this is my table

 private new void Select()
        {
            try
            {
                conn.Open();
                sql= @"select  etudiant.id_etudiant,etudiant.nom,etudiant.prenom,etudiant.age,etudiant.sexe,etudiant.num,class.nom_class
                        from etudiant
                        inner join class on etudiant.classess=class.id_class";
                cmd = new NpgsqlCommand(sql, conn);
                dt = new DataTable();
                dt.Load(cmd.ExecuteReader());

                conn.Close();
                bunifuCustomDataGrid1.DataSource = null;//resete
                bunifuCustomDataGrid1.DataSource = dt;
            }
            catch ( Exception ex)
            {
                conn.Close();
                MessageBox.Show("ERROR" + ex.Message);
            }
        }

and this is my delete

        {
            if (bunifuCustomDataGrid1.Columns[e.ColumnIndex].Name == "Delete")
            {

                try
                {
                    conn.Open();
                    sql = @"Select   all from deleteEtudiant(:id_)  ";
                    cmd = new NpgsqlCommand(sql, conn);
                    cmd.Parameters.AddWithValue("id_", int.Parse(bunifuCustomDataGrid1.Rows[e.RowIndex].Cells["ID"].Value.ToString()));
                    if ((int)cmd.ExecuteScalar() == 1)
                    {
                        MessageBox.Show("Deleted");

                    }

                    conn.Close();

                }
                catch (Exception ex)
                {
                    conn.Close();
                    MessageBox.Show("User deleted don't forget the bug yassine" + ex.Message);

                }
            }
            if (bunifuCustomDataGrid1.Columns[e.ColumnIndex].Name == "Update")
            {

                try
                {
                    conn.Open();
                    sql = @"Select * from updateETUDIANT(':id_,:ST_Firstname ,:ST_prenom ,:ST_Age,:ST_Sexe,:ST_num');
";
                    cmd = new NpgsqlCommand(sql, conn);
                    cmd.Parameters.AddWithValue("id_", int.Parse(bunifuCustomDataGrid1.Rows[e.RowIndex].Cells["ID_etudiant"].Value.ToString()));
                    cmd.Parameters.AddWithValue("ST_Firstname", (bunifuCustomDataGrid1.Rows[e.RowIndex].Cells["Nom"].Value.ToString()));

                    if ((int)cmd.ExecuteScalar() == 1)
                    {
                        MessageBox.Show("UPDATED");

                        Select();

                    }

                    conn.Close();

                }
                catch (Exception ex)

                {
                    conn.Close();
                    MessageBox.Show("User UPDATED"+ex.Message);
                    Select();

                }

            }

i am sorry for the long post and i hope u can tell me how to improve

edit: i have a little question is my query wrong here ?

 public void Ajouter_Click(object sender, EventArgs e)
        {
            try
            {
                conn.Open();
                sql = "insert into etudiant (Nom, prenom, sexe) " +
                     "values(@Nom, @prenom,  @sexe);";
                cmd = new NpgsqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("nom", bunifuMaterialTextbox1.Text);
                cmd.Parameters.AddWithValue("prenom", bunifuMaterialTextbox2.Text);
                //cmd.Parameters.AddWithValue("Age", bunifuMaterialTextbox2.ToString());//
                cmd.Parameters.AddWithValue("sexe", bunifuMaterialTextbox3.Text);
                //cmd.Parameters.AddWithValue("Num", bunifuMaterialTextbox6.Text);
                //cmd.Parameters.AddWithValue("Classess", bunifuMaterialTextbox7.Text);
                 int result = (int)cmd.ExecuteScalar();

                if (result==1)
                {
                    conn.Close();

                    MessageBox.Show("Etudinat ajouter");

                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR" + ex.Message);
                conn.Close();

            }

        }

it give me the same error object reference like the delete one

Body:
I think that the problem is in the ExecuteScalar(), use ExecuteNonQuery() instead of it;

int result = (int)cmd.ExecuteScalar();

replace it with :

int result = cmd.ExecuteNonQuery();


问:
Does the night mode need sqlite?
I just want to know if the night mode in Android needs sqlite?
or there's another way to save the mode in it
when the user close the app and reopen it again it will save the mode
pls help

If there's another way please share it with me
Thanks

答:
No, sqlite is not needed.

Local application settings such as night mode preference are typically stored in SharedPreferences.

Title: Does the night mode need sqlite?


问:
Targeting specific Micronaut WebSocket connections
I'm trying to create a Kotlin service which is able to pass data from Kafka on to (specific) WebSocket connections.
For instance if data from a user passes by on Kafka, the program receives it and I want to pass it on to the right WebSocket connection if this same user is currently connected.

The basics I have are:

```<code>@KafkaListener()
@Controller
@Secured(SecurityRule.IS_ANONYMOUS)
@ServerWebSocket("/ws/{id}")
class WebSocket() {

    @OnOpen
    fun onOpen(session: WebSocketSession, id: String): Publisher<String> {
        return session.send("connection opened")
    }
}
</code>```

However if in the same class I receive a Kafka message, which holds the user id I'm looking for, how can I pass this to the right WebSocket connection?

I figured maybe if I use the "/ws/{id}" from the url I could easily send it to the right id, but I can't figure out how.

The only way I know to send data to a connection is from inside the websocket annotated functions like OnOpen and OnMessage etc.
Furthermore, I've found the Micronaut WebSocketBroadcaster to be useful, but only for broadcasting of course.

And something else I'm trying to figure out is where to ensure that the id that's being connected to is also the user's actual id and not someone else's, should I implement that in the @Secured annotation?

答:
For anyone interested, i did find a solution to this.
Using the Micronaut WebSocketBroadcaster you can broadcast messages, and by using the second parameter, which takes a Predicate<WebSocketSession> which defines to which WebSocketSessions it sends the message.

If you do know the specific WebSocketSession ID, you can simply use { it.id == "id" } for a predicate, as is done in example 1.
If you do need to send it to a specific user, based on some other attribute, you can assign attributes to the WebSocketSession itself by using session.attributes.put("id", id) for example in the onOpen function. The predicate you can use for this is in example 2, only thing about this is that I couldn't find a way to retreive the attributes without casting it to a map, which isn't very pretty.

```<code>class ExampleClass(val broadcaster: WebSocketBroadcaster) {
    val userId = "user_001"
    val webSocketId = "asdasdasd"

    // [1] Send message to a specific socket ID
    broadcaster.broadcast("message", { it.id == webSocketId)

    // [2] Send message to a user with specific ID or any other identifying attribute of choice
    broadcaster.broadcast("message", { it.attributes.asMap()["id"]?.equals(id) ?: false})
}
</code>```

Body:
I'm trying to create a Kotlin service which is able to pass data from Kafka on to (specific) WebSocket connections.
For instance if data from a user passes by on Kafka, the program receives it and I want to pass it on to the right WebSocket connection if this same user is currently connected.

The basics I have are:

@KafkaListener()
@Controller
@Secured(SecurityRule.IS_ANONYMOUS)
@ServerWebSocket("/ws/{id}")
class WebSocket() {

    @OnOpen
    fun onOpen(session: WebSocketSession, id: String): Publisher<String> {
        return session.send("connection opened")
    }
}

However if in the same class I receive a Kafka message, which holds the user id I'm looking for, how can I pass this to the right WebSocket connection?

I figured maybe if I use the "/ws/{id}" from the url I could easily send it to the right id, but I can't figure out how.

The only way I know to send data to a connection is from inside the websocket annotated functions like OnOpen and OnMessage etc.
Furthermore, I've found the Micronaut WebSocketBroadcaster to be useful, but only for broadcasting of course.

And something else I'm trying to figure out is where to ensure that the id that's being connected to is also the user's actual id and not someone else's, should I implement that in the @Secured annotation?

Body:
For anyone interested, i did find a solution to this.
Using the Micronaut WebSocketBroadcaster you can broadcast messages, and by using the second parameter, which takes a Predicate<WebSocketSession> which defines to which WebSocketSessions it sends the message.

If you do know the specific WebSocketSession ID, you can simply use { it.id == "id" } for a predicate, as is done in example 1.
If you do need to send it to a specific user, based on some other attribute, you can assign attributes to the WebSocketSession itself by using session.attributes.put("id", id) for example in the onOpen function. The predicate you can use for this is in example 2, only thing about this is that I couldn't find a way to retreive the attributes without casting it to a map, which isn't very pretty.

class ExampleClass(val broadcaster: WebSocketBroadcaster) {
    val userId = "user_001"
    val webSocketId = "asdasdasd"

    // [1] Send message to a specific socket ID
    broadcaster.broadcast("message", { it.id == webSocketId)

    // [2] Send message to a user with specific ID or any other identifying attribute of choice
    broadcaster.broadcast("message", { it.attributes.asMap()["id"]?.equals(id) ?: false})
}


问:
Lambda or LINQ to Sort List<Employee> by Shift, C#
I have a List of Employee that I need to filter, and I'd like to see how to do this using a lambda and/or LINQ expression.

I want to return ALL of the Employees in the List, but I want them returned in order of Shift, Lastname, and Firstname.

```<code>List<Employee> empList = GetEmployeesInOtherCode();
// ...
int MAX_SHIFT = 5;
List<string> sortedNames = new List<string>(empList.Count);
for (int i = 0; i < MAX_SHIFT; i++) {
  List<string> localShift = new List<string>();
  for (int j = 0; j < empList.Count; j++) {
    Employee e = empList[j];
    if (e.Shift == i) {
      localShift.Add(string.Format("{0}, {1}", e.Lastname, e.Firstname));
    }
  }
  localShift.Sort();
  sortedNames.AddRange(localShift.ToArray());
}
foreach (string line in sortedNames) {
  Console.WriteLine(line);
}
</code>```

EDIT: Jeez you guys are fast! What do you use to generate this stuff? Are you hand coding it, or is there a tool out there that helps?

答:
```<code>var sortedNames = empList.Where(e => e.Shift >= 0 && e.Shift < MAX_SHIFT)
                         .OrderBy(e => e.Shift)
                         .ThenBy(e => e.LastName)
                         .ThenBy(e => e.FirstName)
                         .Select(e => string.Format("{0}, {1}", e.Lastname, e.Firstname))
                         .ToList();
</code>```

Body:
I have a List of Employee that I need to filter, and I'd like to see how to do this using a lambda and/or LINQ expression.

I want to return ALL of the Employees in the List, but I want them returned in order of Shift, Lastname, and Firstname.

List<Employee> empList = GetEmployeesInOtherCode();
// ...
int MAX_SHIFT = 5;
List<string> sortedNames = new List<string>(empList.Count);
for (int i = 0; i < MAX_SHIFT; i++) {
  List<string> localShift = new List<string>();
  for (int j = 0; j < empList.Count; j++) {
    Employee e = empList[j];
    if (e.Shift == i) {
      localShift.Add(string.Format("{0}, {1}", e.Lastname, e.Firstname));
    }
  }
  localShift.Sort();
  sortedNames.AddRange(localShift.ToArray());
}
foreach (string line in sortedNames) {
  Console.WriteLine(line);
}

EDIT: Jeez you guys are fast! What do you use to generate this stuff? Are you hand coding it, or is there a tool out there that helps?


问:
Address offset in RISC-V load instructions hardcoded or not?
For educational purposes I used https://godbolt.org/z/7F-Lhm to translate

```<code>// C++ code
char i = 3;
char A[] = {0,1,2,3,4,5};
int myfunction() {
    return A[i];
}
</code>```

into

```<code># RISC-V instructions
myfunction():                        # @myfunction()
        lui     a0, %hi(i)
        lbu     a0, %lo(i)(a0)
        lui     a1, %hi(A)
        addi    a1, a1, %lo(A)
        add     a0, a0, a1
        lbu     a0, 0(a0)
        ret
i:
        .byte   3                       # 0x3

A:
        .ascii  "\000\001\002\003\004\005"
</code>```

But why is A[i] loaded with add a0, a0, a1, lbu a0, 0(a0) and not just with lbu a0, a0(a1)?

It would make sense if for lbu dest, offset(baseAdress) only dest and baseAdresse are allowed to be register adresses, whereas offset is a hardcoded number in the instruction word itself. But in the same code above I see lbu a0, %lo(i)(a0) so offset can apparently also be "somewhat variable"?

Maybe the reason I don't understand this is because I don't really understand why this $hi $lo thing is necessary in the first place. Why are we doing lui a0, %hi(i), lbu a0, %lo(i)(a0) instead of just lbu a0, 0(i)?

答:
As Erik Eidt said, i is global variable, i.e. resides somewhere in the 32/64-bit addressable memory and can change at any time.

The 32/64-bit address of i is loaded in two parts, since 32/64-bits can not be encoded in an immediate. %hi(i) and %lo(i) are the higher and lower part of the address of i. i is loaded from memory since it might have changed between calls to myfunction().

Body:
For educational purposes I used https://godbolt.org/z/7F-Lhm to translate

// C++ code
char i = 3;
char A[] = {0,1,2,3,4,5};
int myfunction() {
    return A[i];
}

into

# RISC-V instructions
myfunction():                        # @myfunction()
        lui     a0, %hi(i)
        lbu     a0, %lo(i)(a0)
        lui     a1, %hi(A)
        addi    a1, a1, %lo(A)
        add     a0, a0, a1
        lbu     a0, 0(a0)
        ret
i:
        .byte   3                       # 0x3

A:
        .ascii  "\000\001\002\003\004\005"

But why is A[i] loaded with add a0, a0, a1, lbu a0, 0(a0) and not just with lbu a0, a0(a1)?

It would make sense if for lbu dest, offset(baseAdress) only dest and baseAdresse are allowed to be register adresses, whereas offset is a hardcoded number in the instruction word itself. But in the same code above I see lbu a0, %lo(i)(a0) so offset can apparently also be "somewhat variable"?

Maybe the reason I don't understand this is because I don't really understand why this $hi $lo thing is necessary in the first place. Why are we doing lui a0, %hi(i), lbu a0, %lo(i)(a0) instead of just lbu a0, 0(i)?


问:
Thymeleaf - Strict HTML parsing issue
HTML5 allows some tags to be written more liberally i.e without corresponding END tags. e.g. input need not be closed </input>.However if choose template mode HTML5 in Thymeleaf the Thymeleaf engine complains about this and does not parse the HTML template. I want to override this default Strict tag checking behavior. i.e Thymeleaf should parse an HTML template with meta and input (AND ALIKE) tags WITHOUT THEIR RESP. CLOSING TAGS. Pl. guide.

It also complains when you have something like this

```<code><a href="/home/pic/image.png" download="/path/to/file" data-gallery></a>
</code>```

It throws an exception when it encounters the data-gallery throws "should be followed by '=' " which is kind of annoying as it takes the flexibility out of HTML5.

答:
Using LEGACYHTML5 worked for me as well.

Also it is necessary to add

```<code><dependency>
    <groupId>net.sourceforge.nekohtml</groupId>
    <artifactId>nekohtml</artifactId>
</dependency>
</code>```

to pom.xml as stated above. But there is one more step which might occur. After doing those two steps I was getting:

```<code>java.lang.NoClassDefFoundError: org/w3c/dom/ElementTraversal
</code>```

To avoid this it is necessary to add

```<code><dependency>
    <groupId>xml-apis</groupId>
    <artifactId>xml-apis</artifactId>
    <version>1.4.01</version>
</dependency>
</code>```

to pom.xml

Title: Thymeleaf - Strict HTML parsing issue

Body:
HTML5 allows some tags to be written more liberally i.e without corresponding END tags. e.g. input need not be closed </input>.However if choose template mode HTML5 in Thymeleaf the Thymeleaf engine complains about this and does not parse the HTML template. I want to override this default Strict tag checking behavior. i.e Thymeleaf should parse an HTML template with meta and input (AND ALIKE) tags WITHOUT THEIR RESP. CLOSING TAGS. Pl. guide.

It also complains when you have something like this

It throws an exception when it encounters the data-gallery throws "should be followed by '=' " which is kind of annoying as it takes the flexibility out of HTML5.

Body:
Using LEGACYHTML5 worked for me as well.

Also it is necessary to add

<dependency>
    <groupId>net.sourceforge.nekohtml</groupId>
    <artifactId>nekohtml</artifactId>
</dependency>

to pom.xml as stated above. But there is one more step which might occur. After doing those two steps I was getting:

java.lang.NoClassDefFoundError: org/w3c/dom/ElementTraversal

To avoid this it is necessary to add

<dependency>
    <groupId>xml-apis</groupId>
    <artifactId>xml-apis</artifactId>
    <version>1.4.01</version>
</dependency>

to pom.xml


问:
What is the behaviour of lParam when WM_KEYDOWN message recived?
I started learning winapi using c++ language.
I am trying to understand the lParam on WM_KEYDOWN message.

From the Microsoft documentation:

0-15: The repeat count for the current message. The value is the number
  of times the keystroke is autorepeated as a result of the user holding
  down the key. If the keystroke is held long enough, multiple messages
  are sent. However, the repeat count is not cumulative.

16-23:    The scan
  code. The value depends on the OEM.

24: Indicates whether the key is an
  extended key, such as the right-hand ALT and CTRL keys that appear on
  an enhanced 101- or 102-key keyboard. The value is 1 if it is an
  extended key; otherwise, it is 0.

25-28: Reserved; do not use.

29:The context code. The value is always 0 for a WM_KEYDOWN message.

30: The previous key state. The value is 1 if the key is down before the
  message is sent, or it is zero if the key is up.

31: The transition state. The value is always 0 for a WM_KEYDOWN message.

I am handling this message by this way:

```<code>case WM_KEYDOWN:
    cout << ((lParam & 0b11111111111111110000000000000000) >> 16) << ", ";
    cout << ((lParam & 0b00000000000000001111111100000000) >> 8) << ", ";
    cout << ((lParam & 0b00000000000000000000000010000000) >> 7) << ", ";
    cout << ((lParam & 0b00000000000000000000000000000100) >> 2) << ", ";
    cout << ((lParam & 0b00000000000000000000000000000010) >> 1) << ", ";
    cout << ((lParam & 0b00000000000000000000000000000001) >> 0) << endl;
</code>```

And if I press "A" button on my keyboard I get ouput:
30, 0, 0, 0, 0, 1

If I hold "A" button I get muliple outputs:

```<code>16414, 0, 0, 0, 0, 1
16414, 0, 0, 0, 0, 1
16414, 0, 0, 0, 0, 1
</code>```

If I press other letter button, I get same result but with other first number. (For example, for "B" button I get 48 as simple press, 49200 as holding)

How can I understand it?

Body:
I started learning winapi using c++ language.
I am trying to understand the lParam on WM_KEYDOWN message.

From the Microsoft documentation:

0-15: The repeat count for the current message. The value is the number
  of times the keystroke is autorepeated as a result of the user holding
  down the key. If the keystroke is held long enough, multiple messages
  are sent. However, the repeat count is not cumulative.

16-23:    The scan
  code. The value depends on the OEM.

24: Indicates whether the key is an
  extended key, such as the right-hand ALT and CTRL keys that appear on
  an enhanced 101- or 102-key keyboard. The value is 1 if it is an
  extended key; otherwise, it is 0.

25-28: Reserved; do not use.

29:The context code. The value is always 0 for a WM_KEYDOWN message.

30: The previous key state. The value is 1 if the key is down before the
  message is sent, or it is zero if the key is up.

31: The transition state. The value is always 0 for a WM_KEYDOWN message.

I am handling this message by this way:

case WM_KEYDOWN:
    cout << ((lParam & 0b11111111111111110000000000000000) >> 16) << ", ";
    cout << ((lParam & 0b00000000000000001111111100000000) >> 8) << ", ";
    cout << ((lParam & 0b00000000000000000000000010000000) >> 7) << ", ";
    cout << ((lParam & 0b00000000000000000000000000000100) >> 2) << ", ";
    cout << ((lParam & 0b00000000000000000000000000000010) >> 1) << ", ";
    cout << ((lParam & 0b00000000000000000000000000000001) >> 0) << endl;

And if I press "A" button on my keyboard I get ouput:
30, 0, 0, 0, 0, 1

If I hold "A" button I get muliple outputs:

16414, 0, 0, 0, 0, 1
16414, 0, 0, 0, 0, 1
16414, 0, 0, 0, 0, 1

If I press other letter button, I get same result but with other first number. (For example, for "B" button I get 48 as simple press, 49200 as holding)

How can I understand it?

Body:
I didn't test this, but your bit ordering appears to be reversed. According to MS Documentation, bits 0-15 are the LOW bits.

case WM_KEYDOWN:
    cout << ((lParam & 0b00000000000000001111111111111111) >> 0) << ", ";
    cout << ((lParam & 0b00000000111111110000000000000000) >> 16) << ", ";
    cout << ((lParam & 0b00000001000000000000000000000000) >> 24) << ", ";
    cout << ((lParam & 0b00100000000000000000000000000000) >> 29) << ", ";
    cout << ((lParam & 0b01000000000000000000000000000000) >> 30) << ", ";
    cout << ((lParam & 0b10000000000000000000000000000000) >> 31) << ", ";


问:
`componentDidMount()` function is not called after navigation
I am using stackNavigator for navigating between screens. I am calling two API's in componentDidMount() function in my second activity. When i load it first time, it gets loaded successfully. Then i press back button to go back to first activity. Then, if i am again going to second activity, the APIs are not called and I get render error. I am not able to find any solution for this. Any suggestions would be appreciated.

答:
```<code>//na pagina que você quer voltar
import {NavigationEvents} from 'react-navigation';

async atualizarEstado() {
  this.props.navigation.setParams({
  number: await AsyncStorage.getItem('count'),
});}

render() {
return (
  <View style={styles.container}>
    <NavigationEvents onDidFocus={() => this.atualizarEstado()} />
  </View>
);
}
</code>```


问:
Numpy memory error with 1GB matrix, 64bit Python and load of RAM
[Note: although there are already some posts about dealing with large matrices in numpy, they do not address my specific concerns.]

I am trying to load a 30820x12801 matrix stored in a .txt file of size 1.02G with numpy.loadtxt(). I get a Memory error.

This wouldn't be so surprising except that:

I am using 64bit Python.

I am running the job in a supercomputer with 50G of virtual memory allocated for it.

From what I know, a 1G matrix shouldn't be a problem for 64bit Python, and certainly shouldn't be a problem for 50G of RAM.

(This is the first time I am dealing with large datasets so I may be missing something basic).

Extra information:

When using open() the file loads into Python without any problems.

Output of ulimit -a | grep "max memory size: '(kbytes, -m) unlimited'

Full error message:

```<code>
    Traceback (most recent call last):
      File "jPCA/jPCA_pipeline.py", line 87, in <module>
        MATRIX = get_matrix(new_file_prefix, N)
      File "jPCA/jPCA_pipeline.py", line 70, in get_matrix
        MATRIX = np.loadtxt('{}_N={}.txt'.format(new_file_prefix, N))
      File "/home/hers_en/fsimoes/miniconda3/lib/python3.7/site-packages/numpy/lib/npyio.py", line 1159, in loadtxt
        for x in read_data(_loadtxt_chunksize):
      File "/home/hers_en/fsimoes/miniconda3/lib/python3.7/site-packages/numpy/lib/npyio.py", line 1087, in read_data
        items = [conv(val) for (conv, val) in zip(converters, vals)]
      File "/home/hers_en/fsimoes/miniconda3/lib/python3.7/site-packages/numpy/lib/npyio.py", line 1087, in <listcomp>
        items = [conv(val) for (conv, val) in zip(converters, vals)]
    MemoryError

</code>```

答:
It turns out that using 50G of virtual memory was sufficient: it turns out that my job was only using 10G before (not 200G after all - I had some problems with the job submission). After I solved this, 50G was enough but it still took approximately 6 hours to run.

This is still surprising for me because I would think that 10G would be more than enough to import a 1G matrix, but from the comments this has to do with the way loadtxt works.

Body:
[Note: although there are already some posts about dealing with large matrices in numpy, they do not address my specific concerns.]

I am trying to load a 30820x12801 matrix stored in a .txt file of size 1.02G with numpy.loadtxt(). I get a Memory error.

This wouldn't be so surprising except that:

I am using 64bit Python.

I am running the job in a supercomputer with 50G of virtual memory allocated for it.

From what I know, a 1G matrix shouldn't be a problem for 64bit Python, and certainly shouldn't be a problem for 50G of RAM.

(This is the first time I am dealing with large datasets so I may be missing something basic).

Extra information:

When using open() the file loads into Python without any problems.

Output of ulimit -a | grep "max memory size: '(kbytes, -m) unlimited'

Full error message:

    Traceback (most recent call last):
      File "jPCA/jPCA_pipeline.py", line 87, in <module>
        MATRIX = get_matrix(new_file_prefix, N)
      File "jPCA/jPCA_pipeline.py", line 70, in get_matrix
        MATRIX = np.loadtxt('{}_N={}.txt'.format(new_file_prefix, N))
      File "/home/hers_en/fsimoes/miniconda3/lib/python3.7/site-packages/numpy/lib/npyio.py", line 1159, in loadtxt
        for x in read_data(_loadtxt_chunksize):
      File "/home/hers_en/fsimoes/miniconda3/lib/python3.7/site-packages/numpy/lib/npyio.py", line 1087, in read_data
        items = [conv(val) for (conv, val) in zip(converters, vals)]
      File "/home/hers_en/fsimoes/miniconda3/lib/python3.7/site-packages/numpy/lib/npyio.py", line 1087, in <listcomp>
        items = [conv(val) for (conv, val) in zip(converters, vals)]
    MemoryError


问:
Jekyll alias to static file
I have a Jekyll blog at example.com and want the path example.com/doc to point to a static file (a pdf, in particular). Jekyll alias generators seem to work only for individual posts, not static files.

What's the trick?

答:
alias alpha/beta => omega

Create folder _alpha/beta

update _config.yml

```<code>includes_dir: _alpha

collections:
  alpha:
    collections_dir: _alpha/beta
    output: true
    permalink: /omega/:name
</code>```

Title: Jekyll alias to static file

Body:
alias alpha/beta => omega

Create folder _alpha/beta

update _config.yml

includes_dir: _alpha

collections:
  alpha:
    collections_dir: _alpha/beta
    output: true
    permalink: /omega/:name


问:
Is it possible to access the arguments of the failed method in RetryListener?
I have a method that takes a session object to talk to an external system. The session object contains a username and a session token. If the external system doesn't recognize the session token then an exception is thrown. In that case  I want to login with the passed username, create a new session object and call the original method with the new session object containing a valid session token.

I created a Listener extending RetryListenerSupport. I annotated the method with @Retry and specified my listener as listener. But in the onError method of my listener I can not access the arguments of the method.

@Value
public class Session {
    private final String username;
    private final String sessionToken;
}

@Component
public class EmployeeRetryListener extends RetryListenerSupport {
    @Override
    public <T, E extends Throwable> void onError(RetryContext context,
                                                 RetryCallback<T, E> callback, Throwable throwable) {
        if (throwable instance of UnknownSessionException) {
            // Here I want to access the arguments of the createEmployee method
        }
        super.onError(context, callback, throwable);
    }

}

@Service
public class EmployeeService {

    @Retryable(listeners = "employeeRetryListener")
    public void createEmployee(Session session, String employeeName) throws UnknownSessionException {
    }
}

```

I want to know the username in the Session instance with which the method is called. And I also want to modify the Session instance to update to sessionToken.

答:
I believe you might be needing the @Recover annotation on specific exception. As the name suggests, the retry would just redo the failed operation. However the recover method will give you options to do specific things in code while you recover an error. This also allows access to the parameters of the method being "retried".

Spring Recover documentation.

Retry with Recover guide.

Look at section 4.2 in link 2. It has examples on using retry with recover

Body:
I have a method that takes a session object to talk to an external system. The session object contains a username and a session token. If the external system doesn't recognize the session token then an exception is thrown. In that case  I want to login with the passed username, create a new session object and call the original method with the new session object containing a valid session token.

I created a Listener extending RetryListenerSupport. I annotated the method with @Retry and specified my listener as listener. But in the onError method of my listener I can not access the arguments of the method.

@Value
public class Session {
    private final String username;
    private final String sessionToken;
}

@Component
public class EmployeeRetryListener extends RetryListenerSupport {
    @Override
    public <T, E extends Throwable> void onError(RetryContext context,
                                                 RetryCallback<T, E> callback, Throwable throwable) {
        if (throwable instance of UnknownSessionException) {
            // Here I want to access the arguments of the createEmployee method
        }
        super.onError(context, callback, throwable);
    }

}

@Service
public class EmployeeService {

    @Retryable(listeners = "employeeRetryListener")
    public void createEmployee(Session session, String employeeName) throws UnknownSessionException {
    }
}

I want to know the username in the Session instance with which the method is called. And I also want to modify the Session instance to update to sessionToken.


问:
The importance of design in a spring app
I've been taking a look into using the spring framework for my java apps.

It is such a different way of looking at programming in general, i'm talking about DI and AOP!

The level of breaking the fundamental parts up into reusable components to me seems like a lot of work up front(in the design process). Im questioning the part of when I'll know its ready to get coding(this might just be in experience)

Guess I am looking at some tips? Where should you begin? It seems it has to be perfectly designed from the get go to avoid this tightly coupling scenario that seems so common amongst other applications I have worked with(not necessarily made them myself) When will I know its time to shoot my load and code?

Please don't tag this is a subjective or something I just want some honest and decent advice from the community.

Thanks in advance!

答:
Ive never seen an app that was completely designed (on the implementation level) up front.  On the contrary, refactoring is (well should be) part of the process, regardless of whether or not you use Spring.

Perhaps you are overcome by the scope of the Spring framework.  Don't be.  The main goal is to use dependency injection to invert control, and allow you to write simple POJOS to structure your app.  It doesn't make an app more complicated, it makes one simpler.

This is not to say that everything with Spring is strait forward - it isn't.  But you can learn the more complicated things as you go.

In response to your comment, think of the spring configuration as metadata for your class.  You cannot configure Spring with a class you have not defined.  Spring handles the creation and life cycles of the defined beans for you.  So if ClassA depends on ClassB, then when a ClassA gets created, the framework will create the dependencies (and inject them) for you.


问:
login to website with onclick button to submit
I am trying to use python3.7 for web-scraping a website that needs user_email and password to login.

The login form of the login page is as follows:

```<code>  <div id="login">
<form action="/account/orthodox_login" method="post" id="orthodox_login">
  <input id="slugs_input_login" name="slugs[]" type="hidden" value="" />
  <input id="return_after_login" name="rt" type="hidden" value="" />
  <input name="user[url_source]" type="hidden" value="" id="login_form_url_source" />
  <input name="user[location_source]" type="hidden" value="orthodox_login" />

  <h1 id="member_h1">Member sign in</h1>

  <div id="notice_login" class="notice_message" style="margin-top: 20px"></div>

  <div id="with_email" class="fwb login_update" style="display: none; margin-bottom: 0; font-size: 13px; color: #484848;">Sign in with email:</div>

  <fieldset>
    <span>Email:</span>
    <input name="user[email]" id="login_user_email" type="email" autocorrect="off" autocapitalize="off" spellcheck="false" />
  </fieldset>

  <fieldset>
    <span>Password:</span>
    <div id='password_wrapper'><input name="user[password]" type="password" id="login_user_password" autocorrect="off" autocapitalize="off" /></div>
  </fieldset>

      <div class="register_button" onclick="submit_orthodox_login_form();">
        <span class="l"></span>
        <input class="c" type="button" value="Sign in" />
        <span class="r"></span>
      </div>
    </form>

      <div id="or_google" class="fwb mb7 login_update" style="display: none; width: 250px; font-size: 13px; color: #484848;">Or sign in with Google:</div>
  <div id="another_place" class="login_update" style="display: none; margin-left: -10px;"></div>
  <div class="secret_line login_update" style="display: none; margin-bottom: 16px">
    <div style="border-bottom: 1px solid #ebebeb; width: 313px; margin-bottom: 0;"></div>
  </div>
  <div id="dont_have" class="roy-gray login_update" style="display: none">Don't have an account? <span class="link" onclick="open_header_log_in_popup_lightbox('headtabs_login',''); return false">Join now</span></div>
  </div>
</code>```

I searched other posts about login, the answer are given as ones using mechanicalsoup:

```<code>br = mechanicalsoup.StatefulBrowser(
    soup_config={'features': 'lxml'},
    raise_on_404=True,
    user_agent='MyBot/0.1: mysite.example.com/bot_info',
)

br.open("https://seekingalpha.com/account/login")
br.select_form('#orthodox_login')

browser["login"] = args.username
browser["password"] = args.password
resp = browser.submit_selected()
</code>```

However, this does not work in my case, since in the form there's no <input type="submit"> like in github's login, but a
.

I  would also like to redirect to this link after login, which is the actual website that I would like to web scraping.

答:
I think your web site you want to automate uses JavaScript, and MechanicalSoup doesn't support javascript.
You should look for solutions like selenium which support javascript</p>

Body:
I am trying to use python3.7 for web-scraping a website that needs user_email and password to login.

The login form of the login page is as follows:

<form action="/account/orthodox_login" method="post" id="orthodox_login">
  <input id="slugs_input_login" name="slugs[]" type="hidden" value="" />
  <input id="return_after_login" name="rt" type="hidden" value="" />
  <input name="user[url_source]" type="hidden" value="" id="login_form_url_source" />
  <input name="user[location_source]" type="hidden" value="orthodox_login" />

Member sign in

Sign in with email:

  <fieldset>
    Email:
    <input name="user[email]" id="login_user_email" type="email" autocorrect="off" autocapitalize="off" spellcheck="false" />
  </fieldset>

  <fieldset>
    Password:

<input name="user[password]" type="password" id="login_user_password" autocorrect="off" autocapitalize="off" />

  </fieldset>

        <input class="c" type="button" value="Sign in" />

    </form>

Or sign in with Google:

Don't have an account? Join now

I searched other posts about login, the answer are given as ones using mechanicalsoup:

br = mechanicalsoup.StatefulBrowser(
    soup_config={'features': 'lxml'},
    raise_on_404=True,
    user_agent='MyBot/0.1: mysite.example.com/bot_info',
)

br.open("https://seekingalpha.com/account/login")
br.select_form('#orthodox_login')

browser["login"] = args.username
browser["password"] = args.password
resp = browser.submit_selected()

However, this does not work in my case, since in the form there's no <input type="submit"> like in github's login, but a
.

I  would also like to redirect to this link after login, which is the actual website that I would like to web scraping.


问:
Does getDefinitionByName worked with linked MovieClips?
I have a MovieClip named "Dress" that I would like to create using:

```<code>var c:Class = getDefinitionByName("Dress") as Class;
var dress:MovieClip = new c();
</code>```

However, it doesn't seem to work...

答:
getDefinitionByName will work only if Dress class was mentioned somewhere in the code. E.g. you may just import it:

```<code>import package.Dress
</code>```

Body:
I have a MovieClip named "Dress" that I would like to create using:

var c:Class = getDefinitionByName("Dress") as Class;
var dress:MovieClip = new c();

However, it doesn't seem to work...

Body:
getDefinitionByName will work only if Dress class was mentioned somewhere in the code. E.g. you may just import it:

import package.Dress


问:
Searching for a key and printing a value from a hashmap
I have created a Hashmap with a String key representing memberID (which is a numeric value) and the values are instances of Athlete objects such as name, address and age.

I need to write a method which takes a String argument representing the memberId and return the associated values.  I am struggling with the method, in particular how to return only the values associated with the key if found.  My method below returns all Athlete values after a particular key entry is found and I am not sure how to isolate to just the key values where a match is found.   Can someone point me in the right direction?

Thank you!

```<code>public void findAthlete(String aNum)
   {
      if(athletes.containsKey(aNum))
      {
            System.out.println("Key Value Present: " + athletes);
      }
      else
      {

         System.out.println("Key Value not present within data");
      }
   }

</code>```

答:
Try this:  stadium is an instance of the Stadium class.

```<code>Optional<Athlete> op = stadium.getAthlete("some key");
if (op.isPresent()) {
     Athlete at = op.get();
} else {
   // take action if no athlete found
}

// within the Stadium class

Map<String, Athlete> athletes = new HashMap<>();
public Optional<Athlete> getAthlete(String key) {
    return Optional.ofNullable(athletes.get(key));
}

</code>```

Body:
I have created a Hashmap with a String key representing memberID (which is a numeric value) and the values are instances of Athlete objects such as name, address and age.

I need to write a method which takes a String argument representing the memberId and return the associated values.  I am struggling with the method, in particular how to return only the values associated with the key if found.  My method below returns all Athlete values after a particular key entry is found and I am not sure how to isolate to just the key values where a match is found.   Can someone point me in the right direction?

Thank you!

public void findAthlete(String aNum)
   {
      if(athletes.containsKey(aNum))
      {
            System.out.println("Key Value Present: " + athletes);
      }
      else
      {

         System.out.println("Key Value not present within data");
      }
   }

Body:
Try this:  stadium is an instance of the Stadium class.

Optional<Athlete> op = stadium.getAthlete("some key");
if (op.isPresent()) {
     Athlete at = op.get();
} else {
   // take action if no athlete found
}

// within the Stadium class

Map<String, Athlete> athletes = new HashMap<>();
public Optional<Athlete> getAthlete(String key) {
    return Optional.ofNullable(athletes.get(key));
}


问:
filtered data not refreshing in angular
I am trying to filter an array of object on basis on last_name.

```<code> filterItems(searchTerm) {
    return this.EmpData.filter(emp => {
      return emp.lastName.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1 || driver.firstName.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1;
    });
  }
</code>```

and in html template

```<code> <ion-list *ngIf="showEmpList">
                <ion-item *ngFor="let item of EmpData" button (click)="selectEmp(item.lastName)">
                    <ion-label>{{item.lastName}}, {{item.middle}}, {{item.firstName}}</ion-label>
                </ion-item>
     </ion-list>
</code>```

this is working when i am typing name in search box but when i am deleting characters from name that result is not refreshing with new data.
for example-
i have data=[{name:'Amir','age':28},{name:'AAmir', age:26},{name:'AAAmir', age:30}]
now i if put AA in search box it will display last two result and if i put AAA then it will display only last emp data now if i delete two or more characters from input field suppose new input is A then result is displaying as only last employee data

please help.Thanks in advance

答:
May be your filtered array is pointing to same array as original, thats why you are altering original Array. I have done some code for same :-

Stackblitz URL :-  https://stackblitz.com/edit/ionic-gqingy

HTML :-

```<code> <input type="text" [(ngModel)]="filterText" (ngModelChange)="filterValues()"/>

 <ion-list>
                <ion-item *ngFor="let item of filteredData" button (click)="selectEmp(item.lastName)">
                    <ion-label>{{item.name}}, {{item.age}}</ion-label>
                </ion-item>
     </ion-list>
</code>```

TS :-

```<code>import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';

import { TabsPage } from '../pages/tabs/tabs';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = TabsPage;
  EmpData = [{name:'Amir',age:28},{name:'AAmir', age:26},{name:'AAAmir', age:30}];
  filteredData = [{name:'Amir',age:28},{name:'AAmir', age:26},{name:'AAAmir', age:30}];
  public filterText: string = '';
  constructor(platform: Platform) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.

    });
  }

  public filterValues() {
    this.filteredData = this.EmpData.filter((data) => data.name.toLowerCase().includes(this.filterText? this.filterText.toLowerCase():''));
  }
}
</code>```

Title: filtered data not refreshing in angular

Body:
I am trying to filter an array of object on basis on last_name.

 filterItems(searchTerm) {
    return this.EmpData.filter(emp => {
      return emp.lastName.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1 || driver.firstName.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1;
    });
  }

and in html template

 <ion-list *ngIf="showEmpList">
                <ion-item *ngFor="let item of EmpData" button (click)="selectEmp(item.lastName)">
                    <ion-label>{{item.lastName}}, {{item.middle}}, {{item.firstName}}</ion-label>
                </ion-item>
     </ion-list>

this is working when i am typing name in search box but when i am deleting characters from name that result is not refreshing with new data.
for example-
i have data=[{name:'Amir','age':28},{name:'AAmir', age:26},{name:'AAAmir', age:30}]
now i if put AA in search box it will display last two result and if i put AAA then it will display only last emp data now if i delete two or more characters from input field suppose new input is A then result is displaying as only last employee data

please help.Thanks in advance

Body:
May be your filtered array is pointing to same array as original, thats why you are altering original Array. I have done some code for same :-

Stackblitz URL :-  https://stackblitz.com/edit/ionic-gqingy

HTML :-

 <input type="text" [(ngModel)]="filterText" (ngModelChange)="filterValues()"/>

 <ion-list>
                <ion-item *ngFor="let item of filteredData" button (click)="selectEmp(item.lastName)">
                    <ion-label>{{item.name}}, {{item.age}}</ion-label>
                </ion-item>
     </ion-list>

TS :-

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';

import { TabsPage } from '../pages/tabs/tabs';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = TabsPage;
  EmpData = [{name:'Amir',age:28},{name:'AAmir', age:26},{name:'AAAmir', age:30}];
  filteredData = [{name:'Amir',age:28},{name:'AAmir', age:26},{name:'AAAmir', age:30}];
  public filterText: string = '';
  constructor(platform: Platform) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.

    });
  }

  public filterValues() {
    this.filteredData = this.EmpData.filter((data) => data.name.toLowerCase().includes(this.filterText? this.filterText.toLowerCase():''));
  }
}


问:
Setting the Focus to an Entry in Xamarin.Forms
This is just a simplified example, but I'm trying to set this up so that when I open up this page in my Application, the first thing that happens is the keyboard pops up ready for the user to type in their response to an Entry field.

```<code>    var namelabel = new Label { Text = "What is your name?" };
    var nameentry = new Entry { Placeholder = "Type here..." };
    var colorlabel = new Label { Text = "What's your fav color?" };
    var colorentry = new Entry { Placeholder = "Type here..." };
    Content = new StackLayout {
       Spacing = 15,
       Children = { namelabel, nameentry, colorlabel, colorentry }
    };
</code>```

How can I set the focus of the page to the first entry? And additionally, after the user has put in their first entry, how could I set this up so that the user could press a "Next" Button on the Keyboard (or something along those lines) and the app will take them to fill in the second entry?

答:
Can anyone explain to me why this doesn't work

```<code>    protected override void OnAppearing()
    {
       base.OnAppearing();
       CustomerNameEntry.Focus();
    }
</code>```

But this does (adding async and Task.Delay(1))

```<code>    protected override async void OnAppearing()
    {
         base.OnAppearing();
         await Task.Delay(1);
         CustomerNameEntry.Focus();
    }
</code>```

I'd rather not add this clutter, it seems hacky but it's the only way I've been able to get it to work (I've also tried invoking on main thread, to no avail).

Body:
This is just a simplified example, but I'm trying to set this up so that when I open up this page in my Application, the first thing that happens is the keyboard pops up ready for the user to type in their response to an Entry field.

    var namelabel = new Label { Text = "What is your name?" };
    var nameentry = new Entry { Placeholder = "Type here..." };
    var colorlabel = new Label { Text = "What's your fav color?" };
    var colorentry = new Entry { Placeholder = "Type here..." };
    Content = new StackLayout {
       Spacing = 15,
       Children = { namelabel, nameentry, colorlabel, colorentry }
    };

How can I set the focus of the page to the first entry? And additionally, after the user has put in their first entry, how could I set this up so that the user could press a "Next" Button on the Keyboard (or something along those lines) and the app will take them to fill in the second entry?

Body:
Can anyone explain to me why this doesn't work

    protected override void OnAppearing()
    {
       base.OnAppearing();
       CustomerNameEntry.Focus();
    }

But this does (adding async and Task.Delay(1))

    protected override async void OnAppearing()
    {
         base.OnAppearing();
         await Task.Delay(1);
         CustomerNameEntry.Focus();
    }

I'd rather not add this clutter, it seems hacky but it's the only way I've been able to get it to work (I've also tried invoking on main thread, to no avail).


问:
Bukkit/Spigot - Projectile locations on hit detection completely wrong
I am making a custom 'gun' plugin for a minecraft server. My problem is that when attempting to detect where a projectile has landed, the locational difference between the projectile and the player being hit is too large to be detected by my headshot method. The only reason I am using a projectile trace for 'isHeadshot' is due to debugging trials.

This is my shoot method

```<code>public void shootGun(Player p) {
        if (getFirearmAction().isDelayed(p))
            return;

        double shiftYaw = (p.getLocation().getYaw() + 180) * (Math.PI/180);
        Vector shiftVec = new Vector(Math.cos(shiftYaw), 0.0D, Math.sin(shiftYaw)); //TODO: add bullet_spread

        for (int i = 0; i < projectileInfo.getAmount(); i++) {
            Projectile proj = (Projectile)p.getWorld().spawn(p.getEyeLocation().toVector().add(shiftVec.multiply(0.2D)).toLocation(p.getWorld()), getProjectileInfo().getProjectileClass());
            proj.setVelocity(UtilMethods.getBulletVelocity(p).multiply(projectileInfo.getSpeed()));
            proj.setShooter(p);
        }
        projectileInfo.playShootGunSound(p);
        getFirearmAction().performAction(p);
    }
</code>```

This is the listener for a 'hit'

```<code>@EventHandler
    public void onEntDamage(EntityDamageByEntityEvent event) {
        if (event.getDamager() instanceof Projectile) {
            Projectile p = (Projectile)event.getDamager();
            if (p.getShooter() instanceof Player) {
                Player player = (Player)p.getShooter();
                Gun gun = UtilMethods.getGun(player);
                if (gun != null) {
                    int damage = gun.getProjectileInfo().getDamage();
                    if (event.getEntity() instanceof Player) {
                        Player ent = (Player)event.getEntity();

                        if (UtilMethods.isHeadShot(ent, p))
                            damage *= 2;
                    }
                    event.setDamage(damage);
                }
            }
        }
    }
</code>```

And finally, this is [isHeadshot, isInCuboid, and bulletVelocity] methods. The first two are substitute methods for trying to figure out a failed headshot detection... The getBulletVelocity method sets the correct velocity and direction of the projectile. (In this case I am working with Snowball.class)

```<code>public static boolean isHeadShot(Player victim, Projectile projectile) {

        Location locA = new Location(victim.getWorld(), victim.getEyeLocation().getX() -0.5, victim.getEyeLocation().getY() - 0.5, victim.getEyeLocation().getZ() - 0.5);
        Location locB = new Location(victim.getWorld(), victim.getEyeLocation().getX() +0.5, victim.getEyeLocation().getY() + 0.5, victim.getEyeLocation().getZ() + 0.5);

        for (double i = 0; i < 256; i+=0.8D) {
            System.out.println(projectile.getLocation() + " | " + victim.getLocation());
            projectile.getLocation().add(projectile.getVelocity().normalize().multiply(i));
            if (isInCuboid(locA, locB, projectile.getLocation())) {
                System.out.println(i);
                return true;
            }
        }
        return false;
    }

    public static boolean isInCuboid(Location min, Location max, Location varying) {
        double[] locs = new double[2];
        locs[0] = min.getX();
        locs[1] = max.getX();
        Arrays.sort(locs);
        if (varying.getX() > locs[1] || varying.getX() < locs[0])
            return false;
        locs[0] = min.getY();
        locs[1] = max.getY();
        Arrays.sort(locs);
        if (varying.getY() > locs[1] || varying.getY() < locs[0])
            return false;
        locs[0] = min.getZ();
        locs[1] = max.getZ();
        Arrays.sort(locs);
        if (varying.getZ() > locs[1] || varying.getZ() < locs[0])
            return false;
        return true;
    }

    public static Vector getBulletVelocity(Player shooter) {
        double yaw = Math.toRadians((-shooter.getLocation().getYaw() - 90.0f));
        double pitch = Math.toRadians(-shooter.getLocation().getPitch());

        double x = Math.cos(pitch) * Math.cos(yaw);
        double y = Math.sin(pitch);
        double z = -Math.sin(yaw) * Math.cos(pitch);

        Vector dirVec = new Vector(x, y, z).normalize();
        return dirVec;
    }
</code>```

I would like some help since it seems that when the bullet causes damage, the bullet is already through the player's hitbox and can not be detected as a headshot anylonger. Any advice?

This is the locational difference. First location is projectile, second location is victim. However, for there to be a hit, the bullet must pass through the player at one point..

[08:53:22] [Server thread/INFO]: Location{world=CraftWorld{name=San_Andreas},x=2501.8249706725665,y=73.62000000476837,z=1681.0750064188326,pitch=0.0,yaw=0.0} | Location{world=CraftWorld{name=San_Andreas},x=2508.7144181513295,y=72.0,z=1671.9424013003206,pitch=0.3,yaw=-8.100003}

答: Listen for the ProjectileHitEvent and check if the projectile's y-coord is within a certain distance of the y-coord of the hit player's eye location (the x and z coords are irrelevant for determining a headshot on a player).</p>

Body:
I am making a custom 'gun' plugin for a minecraft server. My problem is that when attempting to detect where a projectile has landed, the locational difference between the projectile and the player being hit is too large to be detected by my headshot method. The only reason I am using a projectile trace for 'isHeadshot' is due to debugging trials.

This is my shoot method

public void shootGun(Player p) {
        if (getFirearmAction().isDelayed(p))
            return;

        double shiftYaw = (p.getLocation().getYaw() + 180) * (Math.PI/180);
        Vector shiftVec = new Vector(Math.cos(shiftYaw), 0.0D, Math.sin(shiftYaw)); //TODO: add bullet_spread

        for (int i = 0; i < projectileInfo.getAmount(); i++) {
            Projectile proj = (Projectile)p.getWorld().spawn(p.getEyeLocation().toVector().add(shiftVec.multiply(0.2D)).toLocation(p.getWorld()), getProjectileInfo().getProjectileClass());
            proj.setVelocity(UtilMethods.getBulletVelocity(p).multiply(projectileInfo.getSpeed()));
            proj.setShooter(p);
        }
        projectileInfo.playShootGunSound(p);
        getFirearmAction().performAction(p);
    }

This is the listener for a 'hit'

@EventHandler
    public void onEntDamage(EntityDamageByEntityEvent event) {
        if (event.getDamager() instanceof Projectile) {
            Projectile p = (Projectile)event.getDamager();
            if (p.getShooter() instanceof Player) {
                Player player = (Player)p.getShooter();
                Gun gun = UtilMethods.getGun(player);
                if (gun != null) {
                    int damage = gun.getProjectileInfo().getDamage();
                    if (event.getEntity() instanceof Player) {
                        Player ent = (Player)event.getEntity();

                        if (UtilMethods.isHeadShot(ent, p))
                            damage *= 2;
                    }
                    event.setDamage(damage);
                }
            }
        }
    }

And finally, this is [isHeadshot, isInCuboid, and bulletVelocity] methods. The first two are substitute methods for trying to figure out a failed headshot detection... The getBulletVelocity method sets the correct velocity and direction of the projectile. (In this case I am working with Snowball.class)

public static boolean isHeadShot(Player victim, Projectile projectile) {

        Location locA = new Location(victim.getWorld(), victim.getEyeLocation().getX() -0.5, victim.getEyeLocation().getY() - 0.5, victim.getEyeLocation().getZ() - 0.5);
        Location locB = new Location(victim.getWorld(), victim.getEyeLocation().getX() +0.5, victim.getEyeLocation().getY() + 0.5, victim.getEyeLocation().getZ() + 0.5);

        for (double i = 0; i < 256; i+=0.8D) {
            System.out.println(projectile.getLocation() + " | " + victim.getLocation());
            projectile.getLocation().add(projectile.getVelocity().normalize().multiply(i));
            if (isInCuboid(locA, locB, projectile.getLocation())) {
                System.out.println(i);
                return true;
            }
        }
        return false;
    }

    public static boolean isInCuboid(Location min, Location max, Location varying) {
        double[] locs = new double[2];
        locs[0] = min.getX();
        locs[1] = max.getX();
        Arrays.sort(locs);
        if (varying.getX() > locs[1] || varying.getX() < locs[0])
            return false;
        locs[0] = min.getY();
        locs[1] = max.getY();
        Arrays.sort(locs);
        if (varying.getY() > locs[1] || varying.getY() < locs[0])
            return false;
        locs[0] = min.getZ();
        locs[1] = max.getZ();
        Arrays.sort(locs);
        if (varying.getZ() > locs[1] || varying.getZ() < locs[0])
            return false;
        return true;
    }

    public static Vector getBulletVelocity(Player shooter) {
        double yaw = Math.toRadians((-shooter.getLocation().getYaw() - 90.0f));
        double pitch = Math.toRadians(-shooter.getLocation().getPitch());

        double x = Math.cos(pitch) * Math.cos(yaw);
        double y = Math.sin(pitch);
        double z = -Math.sin(yaw) * Math.cos(pitch);

        Vector dirVec = new Vector(x, y, z).normalize();
        return dirVec;
    }

I would like some help since it seems that when the bullet causes damage, the bullet is already through the player's hitbox and can not be detected as a headshot anylonger. Any advice?

This is the locational difference. First location is projectile, second location is victim. However, for there to be a hit, the bullet must pass through the player at one point..

[08:53:22] [Server thread/INFO]: Location{world=CraftWorld{name=San_Andreas},x=2501.8249706725665,y=73.62000000476837,z=1681.0750064188326,pitch=0.0,yaw=0.0} | Location{world=CraftWorld{name=San_Andreas},x=2508.7144181513295,y=72.0,z=1671.9424013003206,pitch=0.3,yaw=-8.100003}


问:
Call to a member function roles() on null in laravel when I redirect to a create page
Please help me with this Call to a member function roles() on null error in laravel. In every page It works but when i call a create method it throw this error. i am giving the code below.

web.php

```<code>Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::namespace('Admin')->middleware('can:access-all')->group(function (){
    Route::resource('/library','LibraryController', ['except' => ['show']]);
});

</code>```

in User.php

```<code>public function hasAnyRoles($roles)
{
    if ($this->roles()->whereIn('name', $roles)->first()) {
        return true;
    }

    return false;
}

public function hasRole($role)
{
    if ($this->roles()->where('name', $role)->first()) {
        return true;
    }

    return false;
}
</code>```

in role.php

```<code>public function users()
{
    return $this->belongsToMany('App\User');
}
</code>```

in LibraryController

```<code>public function __construct()
{
    $this->middleware('auth');
}
public function create()
{
    return redirect('books.create');
}
</code>```

in layouts\app.blade.php

```<code><span>{{ implode(', ',Auth::user()->roles()->get()->pluck('name')->toArray()) }}</span>
</code>```

from every page I have done in my project everywhere it works correctly but here it's not working. Any solution to handle this error on every page before I made and after I working for?

答:
Solved my own problem. I was my fault. Now I change in return redirect to view() it works correctly..

```<code>public function create()
{
    return view('books.create');
}
</code>```

Body:
Please help me with this Call to a member function roles() on null error in laravel. In every page It works but when i call a create method it throw this error. i am giving the code below.

web.php

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::namespace('Admin')->middleware('can:access-all')->group(function (){
    Route::resource('/library','LibraryController', ['except' => ['show']]);
});

in User.php

public function hasAnyRoles($roles)
{
    if ($this->roles()->whereIn('name', $roles)->first()) {
        return true;
    }

    return false;
}

public function hasRole($role)
{
    if ($this->roles()->where('name', $role)->first()) {
        return true;
    }

    return false;
}

in role.php

public function users()
{
    return $this->belongsToMany('App\User');
}

in LibraryController

public function __construct()
{
    $this->middleware('auth');
}
public function create()
{
    return redirect('books.create');
}

in layouts\app.blade.php

{{ implode(', ',Auth::user()->roles()->get()->pluck('name')->toArray()) }}

from every page I have done in my project everywhere it works correctly but here it's not working. Any solution to handle this error on every page before I made and after I working for?

Body:
Solved my own problem. I was my fault. Now I change in return redirect to view() it works correctly..

public function create()
{
    return view('books.create');
}


问:
Change Color of selection Angular Material Table with selection
How to change the color of the selector in the angular material table with selection

答:
Add additional Color argument to pass the theme name
Example: <mat-checkbox color="primary"></mat-checkbox>


问:
Can you use multiple conditionals in SASS/SCSS CSS
I am using SCSS code for styling my ruby app and am trying to write my own "rounded" mixin to help out with multi-browser border rounding.

Currently I have the following:

```<code>@mixin rounded($corner: all , $radius: 8px) {
  @if $corner==all || $corner==bottom || $corner == right || $corner==bottom-right{webkit-border-bottom-right-radius: $radius;}
  @if $corner==all || $corner==bottom || $corner == left || $corner==bottom-left{-webkit-border-bottom-left-radius: $radius;}
  @if $corner==all || $corner==top || $corner == right || $corner==top-right{-webkit-border-top-right-radius: $radius;}
  @if $corner==all || $corner==bottom || $corner == left || $corner==top-left{-webkit-border-top-left-radius: $radius;}

  @if $corner==all || $corner==bottom || $corner == right || $corner==bottom-right{-khtml-border-radius-bottomright: $radius;}
  @if $corner==all || $corner==bottom || $corner == left || $corner==bottom-left{-khtml-border-radius-bottomleft: $radius;}
  @if $corner==all || $corner==top || $corner == right || $corner==top-right{-khtml-border-radius-topright: $radius;}
  @if $corner==all || $corner==bottom || $corner == left || $corner==top-left{-khtml-border-radius-topleft: $radius;}

  @if $corner==all || $corner==bottom || $corner == right || $corner==bottom-right{-moz-border-radius-bottomright: $radius;}
  @if $corner==all || $corner==bottom || $corner == left || $corner==bottom-left{-moz-border-radius-bottomleft: $radius;}
  @if $corner==all || $corner==top || $corner == right || $corner==top-right{-moz-border-radius-topright: $radius;}
  @if $corner==all || $corner==bottom || $corner == left || $corner==top-left{-moz-border-radius-topleft: $radius;}

  @if $corner==all || $corner==bottom || $corner == right || $corner==bottom-right{border-bottom-right-radius: $radius;}
  @if $corner==all || $corner==bottom || $corner == left || $corner==bottom-left{border-bottom-left-radius: $radius;}
  @if $corner==all || $corner==top || $corner == right || $corner==top-right{border-top-right-radius: $radius;}
  @if $corner==all || $corner==bottom || $corner == left || $corner==top-left{border-top-left-radius: $radius;}
}
</code>```

However, it appears that SASS can only handle one conditional in the if statements? Is there a way round this or do I have to do four if statements for each rounded corner?

答:
You need to use or instead of ||. See the Sass Docs.

Also it looks like you have a typo in the last @if statement for each block:

```<code>$corner==bottom should be $corner==top
</code>```

Body:
I am using SCSS code for styling my ruby app and am trying to write my own "rounded" mixin to help out with multi-browser border rounding.

Currently I have the following:

@mixin rounded($corner: all , $radius: 8px) {
  @if $corner==all || $corner==bottom || $corner == right || $corner==bottom-right{webkit-border-bottom-right-radius: $radius;}
  @if $corner==all || $corner==bottom || $corner == left || $corner==bottom-left{-webkit-border-bottom-left-radius: $radius;}
  @if $corner==all || $corner==top || $corner == right || $corner==top-right{-webkit-border-top-right-radius: $radius;}
  @if $corner==all || $corner==bottom || $corner == left || $corner==top-left{-webkit-border-top-left-radius: $radius;}

  @if $corner==all || $corner==bottom || $corner == right || $corner==bottom-right{-khtml-border-radius-bottomright: $radius;}
  @if $corner==all || $corner==bottom || $corner == left || $corner==bottom-left{-khtml-border-radius-bottomleft: $radius;}
  @if $corner==all || $corner==top || $corner == right || $corner==top-right{-khtml-border-radius-topright: $radius;}
  @if $corner==all || $corner==bottom || $corner == left || $corner==top-left{-khtml-border-radius-topleft: $radius;}

  @if $corner==all || $corner==bottom || $corner == right || $corner==bottom-right{-moz-border-radius-bottomright: $radius;}
  @if $corner==all || $corner==bottom || $corner == left || $corner==bottom-left{-moz-border-radius-bottomleft: $radius;}
  @if $corner==all || $corner==top || $corner == right || $corner==top-right{-moz-border-radius-topright: $radius;}
  @if $corner==all || $corner==bottom || $corner == left || $corner==top-left{-moz-border-radius-topleft: $radius;}

  @if $corner==all || $corner==bottom || $corner == right || $corner==bottom-right{border-bottom-right-radius: $radius;}
  @if $corner==all || $corner==bottom || $corner == left || $corner==bottom-left{border-bottom-left-radius: $radius;}
  @if $corner==all || $corner==top || $corner == right || $corner==top-right{border-top-right-radius: $radius;}
  @if $corner==all || $corner==bottom || $corner == left || $corner==top-left{border-top-left-radius: $radius;}
}

However, it appears that SASS can only handle one conditional in the if statements? Is there a way round this or do I have to do four if statements for each rounded corner?

Body:
You need to use or instead of ||. See the Sass Docs.

Also it looks like you have a typo in the last @if statement for each block:

$corner==bottom should be $corner==top


问:
Calculate End time from Start time field in codeigniter from database
I have a table structure something like :

```<code>id | name | start_time | duration
1    xyz      05:00 PM     4
</code>```

Code

```<code>$from_time=9:30 AM;
 $sessionData=$this->db->where('start_time>=',$from_time)->get('user_session')->result();
</code>```

In the above code i want end time calculated but i want endtime calculated from duration such as in my case for 5:00 pm endtime should be 9:00 pm. I want to select those rows only.

答:
You can do that by using Mysql function Date_add. It would look like so:

```<code>SELECT * from `Hours` where DATE_ADD(start_time, INTERVAL duration HOUR) >= '07:00'
</code>```

I have made a table that looks like:
id  name    start_time  duration

```<code>1   test    05:00:00    6
2   early test  05:00:00    1
3   late test   05:00:00    11
</code>```

When I execute the query I do get the following results:

```<code>id  name    start_time  duration
1   test    05:00:00    6
3   late test   05:00:00    11
</code>```

I don't think however you would be able to use the codeigniter query builder for this one. I would suggest querying directly the database by $result = $this->db->query($your_query);

You would however need to escape your data if there is user input in this one.

Body:
I have a table structure something like :

id | name | start_time | duration
1    xyz      05:00 PM     4

Code

$from_time=9:30 AM;
 $sessionData=$this->db->where('start_time>=',$from_time)->get('user_session')->result();

In the above code i want end time calculated but i want endtime calculated from duration such as in my case for 5:00 pm endtime should be 9:00 pm. I want to select those rows only.

Body:
You can do that by using Mysql function Date_add. It would look like so:

SELECT * from `Hours` where DATE_ADD(start_time, INTERVAL duration HOUR) >= '07:00'

I have made a table that looks like:
id  name    start_time  duration

1   test    05:00:00    6
2   early test  05:00:00    1
3   late test   05:00:00    11

When I execute the query I do get the following results:

id  name    start_time  duration
1   test    05:00:00    6
3   late test   05:00:00    11

I don't think however you would be able to use the codeigniter query builder for this one. I would suggest querying directly the database by $result = $this->db->query($your_query);

You would however need to escape your data if there is user input in this one.


问:
How do you debug your Nest queries?
I'm new to Nest, and I very likely am not creating my query like I think I am.  My question is more along the lines of teach a man to fish rather than give me a fish.  However, I'll use my current problem as an example.

I have several documents in ElasticSearch of the type Series.  I'll stub it out below without the attributes and public modifiers with just the information pertinent to the query:

```<code>class Series
{
    string Id {get; set;}
    DateTime StartDate {get; set;}
    DateTime EndDate {get; set;}
    HashSet<Role> ReleasableTo {get; set;}
}
</code>```

These are all fine and dandy.  I can Get() a Series object no problem.  The problem I'm running into is trying to figure out how Nest is formatting my query.  My immediate goal is to find the most recent Series that is releasable to Role.Visitor.  I set up the Nest query like this:

```<code>ISearchResponse<Series> response = client
    .Search<Series>(r =>
         r.Filter(f =>
             f.Term<Role>(t=>t.ReleasableTo.First(), Role.Visitor))
    .SortDescending(ser => ser.EndDate).Size(1));
</code>```

In my mind, this should be producing a query that filters the Series so it only considers the ones that are ReleasableTo my Role.Visitor, reverse sorts by end date, and limits the results to one returned.  That would be exactly what I want.  In the multiple thousands of records I have for Series, about 90% fit this profile.  Unfortunately the query returns 0 results.  There is no error, just no results.  What I don't know is if I'm using the API incorrectly, if Nest is producing a query structure that doesn't make sense, or I simply don't know ElasticSearch well enough.  When I remove the Filter clause I get a result, but I'm not guaranteed everyone is allowed to see it.

How do I view the JSON that Nest produces and sends to ElasticSearch?

答:
Elasticsearch.Net and NEST: the .NET clients [7.x]

ref: https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/debug-information.html`

Enable DisableDirectStreaming in ES Global setting like following.

ref code

```<code>Var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

var settings = new ConnectionSettings(connectionPool)
    .DisableDirectStreaming(true);

var client = new ElasticClient(settings);
</code>```

2.)  var response = client.Search<Project>(s =>....)

3.)

```<code>var jsonOutput = System.Text.Encoding.UTF8.GetString(
            result.ApiCall.RequestBodyInBytes);
</code>```

Above can be achieved on a per request basis with following.

```<code>var response = client.Search<Project>(s => s
    .RequestConfiguration(r => r
        .DisableDirectStreaming()
    )
    .Query(q => q
        .MatchAll()
    )
);
</code>```

Title: How do you debug your Nest queries?

Body:
I'm new to Nest, and I very likely am not creating my query like I think I am.  My question is more along the lines of teach a man to fish rather than give me a fish.  However, I'll use my current problem as an example.

I have several documents in ElasticSearch of the type Series.  I'll stub it out below without the attributes and public modifiers with just the information pertinent to the query:

class Series
{
    string Id {get; set;}
    DateTime StartDate {get; set;}
    DateTime EndDate {get; set;}
    HashSet<Role> ReleasableTo {get; set;}
}

These are all fine and dandy.  I can Get() a Series object no problem.  The problem I'm running into is trying to figure out how Nest is formatting my query.  My immediate goal is to find the most recent Series that is releasable to Role.Visitor.  I set up the Nest query like this:

ISearchResponse<Series> response = client
    .Search<Series>(r =>
         r.Filter(f =>
             f.Term<Role>(t=>t.ReleasableTo.First(), Role.Visitor))
    .SortDescending(ser => ser.EndDate).Size(1));

In my mind, this should be producing a query that filters the Series so it only considers the ones that are ReleasableTo my Role.Visitor, reverse sorts by end date, and limits the results to one returned.  That would be exactly what I want.  In the multiple thousands of records I have for Series, about 90% fit this profile.  Unfortunately the query returns 0 results.  There is no error, just no results.  What I don't know is if I'm using the API incorrectly, if Nest is producing a query structure that doesn't make sense, or I simply don't know ElasticSearch well enough.  When I remove the Filter clause I get a result, but I'm not guaranteed everyone is allowed to see it.

How do I view the JSON that Nest produces and sends to ElasticSearch?

Body:
Elasticsearch.Net and NEST: the .NET clients [7.x]

ref: https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/debug-information.html`

Enable DisableDirectStreaming in ES Global setting like following.

ref code

Var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

var settings = new ConnectionSettings(connectionPool)
    .DisableDirectStreaming(true);

var client = new ElasticClient(settings);

2.)  var response = client.Search<Project>(s =>....)

3.)

var jsonOutput = System.Text.Encoding.UTF8.GetString(
            result.ApiCall.RequestBodyInBytes);

Above can be achieved on a per request basis with following.

var response = client.Search<Project>(s => s
    .RequestConfiguration(r => r
        .DisableDirectStreaming()
    )
    .Query(q => q
        .MatchAll()
    )
);