问:
Call to a member function format() on boolean using PHP and FuelPHP MVC Framework
I am aware that this is a common error and has more than likely been answered, but the issue I am having is when the function is executed it's returning the $down_time variable as null when a new website becomes offline on this line $diff_in_seconds = $now_time->getTimestamp() - $down_time->getTimestamp(); however when I run the function again in my terminal the error then goes. Basically it's returning $down_time variable as null before it is updated into the database, which I'm confused about since the update query is executed first. I would really appreciate the help and guidance thanks.

```<code>    public static function run()
    {
        $dept_emails = array(
            19 => 'test@email.co.uk'
        );

        $active_clients = Client::get_active_clients();

        foreach ($active_clients as $client) {
            $websites = $client->websites;

            $services = $client->services;

            foreach ($websites as $website) {
                $website_url = $website->url;
                $website_url_parse = parse_url($website_url);
                $new_website_url = "https://" . $website_url;
                $website_status = Client::get_website_status($new_website_url);

                if(array_key_exists('host', $website_url_parse)) {
                    $website_url = $website_url_parse['host'];
                }

                if($website_status == false) {
                    $new_website_url = "http://" . $website_url;
                    $website_status = Client::get_website_status($new_website_url);
                }

                $now = date('Y-m-d H:i:s');
                $now_time = DateTime::createFromFormat('Y-m-d H:i:s', $now);

                $down_time = DateTime::createFromFormat('Y-m-d H:i:s', $website->down_at);

                $result = DB::update('clients_websites')
                    ->set(array(
                        'last_checked' => $now
                    ))
                    ->where('id', '=', $website->id)
                    ->execute();

                if ($website_status) {
                    // Website is back online, send email
                    if($website->down_at != null && $website_status == true){

                        $diff_in_seconds = $now_time->getTimestamp() - $down_time->getTimestamp();
                        // Website has been down for more than 5 minutes
                        if($diff_in_seconds >= 300){

                            Cli::write("Emailing: " . $website->url . " is back online");

                            $result = DB::update('clients_websites')
                                ->set(array(
                                    'down_at' => null,
                                    'up_at' => date('Y-m-d H:i:s'),
                                ))
                                ->where('id', '=', $website->id)
                                ->execute();

                            $notify_emails = array();

                            foreach ($services as $service)
                            {
                                $service_id = $service->service_id;
                                if (in_array($service_id, $dept_emails))
                                {
                                    $notify_emails[] = $dept_emails[$service_id];
                                }
                            }

                            $message = "Hi " . $website->url . " is back online.";
                            $email = Model_Mail::send_email($dept_emails, "" . $website->url . " is back online", $message);
                        }

                    } else {
                        // Website is online insert up time in to DB
                        Cli::write("Online: " . $website->url . " is online");

                        $result = DB::update('clients_websites')
                            ->set(array(
                                'down_at' => null,
                                'up_at' => date('Y-m-d H:i:s'),
                            ))
                            ->where('id', '=', $website->id)
                            ->execute();
                    }

                } else {
                    // Website is down insert down time in to DB
                    Cli::write("Offline: " . $website->url . " is offline");

                   if(is_null($website->down_at)){
                        $result = DB::update('clients_websites')
                            ->set(array(
                                'down_at' => date('Y-m-d H:i:s')
                            ))
                            ->where('id', '=', $website->id)
                            ->execute();

                            $query = DB::select('*')->from('clients_websites')->where('id', '=', $website->id)
                                ->and_where_open()
                                ->where('down_at', 'IS NOT', NULL)
                                ->and_where_close()
                                ->execute();

                        $down_time = DateTime::createFromFormat('Y-m-d H:i:s',  $query['down_at']);
                        $down_time_email = $down_time->format('d-m-Y H:i:s');
                        $diff_in_seconds = $now_time->getTimestamp() - $down_time->getTimestamp();

                        if($diff_in_seconds >= 300){

                            Cli::write("Emailing: " . $website->url . " is offline");

                            $notify_emails = array();

                            foreach ($services as $service)
                            {
                                $service_id = $service->service_id;
                                $active = $service->end_date;
                                if (in_array($service_id, $dept_emails ) && ($active == null || $active > $now))
                                {
                                    $notify_emails[] = $dept_emails[$service_id];
                                }
                            }

                            $message = "Hi " . $website->url . " has been down since " . $down_time_email . ".";
                            $email = Model_Mail::send_email($dept_emails, "" . $website->url . " is down", $message);

                            $result = DB::update('clients_websites')
                                ->set(array(
                                    'down_email_sent' => date('Y-m-d H:i:s')
                                ))
                                ->where('id', '=', $website->id)
                                ->execute();
                        }
                    }
                }
            }
        }
    }
</code>```

答:
Figured this out at the beginning of the website foreach I defined a new variable $time_now = date('Y-m-d H:i:s'); which was then used in the update for query for the down_at time and assigned to $down_time variable.

```<code>$result = DB::update('clients_websites')
                            ->set(array(
                                'down_at' => $time_now
                            ))
                            ->where('id', '=', $website->id)
                            ->execute();
                    }

                    $down_time = DateTime::createFromFormat('Y-m-d H:i:s', $time_now);
</code>```

Body:
I am aware that this is a common error and has more than likely been answered, but the issue I am having is when the function is executed it's returning the $down_time variable as null when a new website becomes offline on this line $diff_in_seconds = $now_time->getTimestamp() - $down_time->getTimestamp(); however when I run the function again in my terminal the error then goes. Basically it's returning $down_time variable as null before it is updated into the database, which I'm confused about since the update query is executed first. I would really appreciate the help and guidance thanks.

    public static function run()
    {
        $dept_emails = array(
            19 => 'test@email.co.uk'
        );

        $active_clients = Client::get_active_clients();

        foreach ($active_clients as $client) {
            $websites = $client->websites;

            $services = $client->services;

            foreach ($websites as $website) {
                $website_url = $website->url;
                $website_url_parse = parse_url($website_url);
                $new_website_url = "https://" . $website_url;
                $website_status = Client::get_website_status($new_website_url);

                if(array_key_exists('host', $website_url_parse)) {
                    $website_url = $website_url_parse['host'];
                }

                if($website_status == false) {
                    $new_website_url = "http://" . $website_url;
                    $website_status = Client::get_website_status($new_website_url);
                }

                $now = date('Y-m-d H:i:s');
                $now_time = DateTime::createFromFormat('Y-m-d H:i:s', $now);

                $down_time = DateTime::createFromFormat('Y-m-d H:i:s', $website->down_at);

                $result = DB::update('clients_websites')
                    ->set(array(
                        'last_checked' => $now
                    ))
                    ->where('id', '=', $website->id)
                    ->execute();

                if ($website_status) {
                    // Website is back online, send email
                    if($website->down_at != null && $website_status == true){

                        $diff_in_seconds = $now_time->getTimestamp() - $down_time->getTimestamp();
                        // Website has been down for more than 5 minutes
                        if($diff_in_seconds >= 300){

                            Cli::write("Emailing: " . $website->url . " is back online");

                            $result = DB::update('clients_websites')
                                ->set(array(
                                    'down_at' => null,
                                    'up_at' => date('Y-m-d H:i:s'),
                                ))
                                ->where('id', '=', $website->id)
                                ->execute();

                            $notify_emails = array();

                            foreach ($services as $service)
                            {
                                $service_id = $service->service_id;
                                if (in_array($service_id, $dept_emails))
                                {
                                    $notify_emails[] = $dept_emails[$service_id];
                                }
                            }

                            $message = "Hi " . $website->url . " is back online.";
                            $email = Model_Mail::send_email($dept_emails, "" . $website->url . " is back online", $message);
                        }

                    } else {
                        // Website is online insert up time in to DB
                        Cli::write("Online: " . $website->url . " is online");

                        $result = DB::update('clients_websites')
                            ->set(array(
                                'down_at' => null,
                                'up_at' => date('Y-m-d H:i:s'),
                            ))
                            ->where('id', '=', $website->id)
                            ->execute();
                    }

                } else {
                    // Website is down insert down time in to DB
                    Cli::write("Offline: " . $website->url . " is offline");

                   if(is_null($website->down_at)){
                        $result = DB::update('clients_websites')
                            ->set(array(
                                'down_at' => date('Y-m-d H:i:s')
                            ))
                            ->where('id', '=', $website->id)
                            ->execute();

                            $query = DB::select('*')->from('clients_websites')->where('id', '=', $website->id)
                                ->and_where_open()
                                ->where('down_at', 'IS NOT', NULL)
                                ->and_where_close()
                                ->execute();

                        $down_time = DateTime::createFromFormat('Y-m-d H:i:s',  $query['down_at']);
                        $down_time_email = $down_time->format('d-m-Y H:i:s');
                        $diff_in_seconds = $now_time->getTimestamp() - $down_time->getTimestamp();

                        if($diff_in_seconds >= 300){

                            Cli::write("Emailing: " . $website->url . " is offline");

                            $notify_emails = array();

                            foreach ($services as $service)
                            {
                                $service_id = $service->service_id;
                                $active = $service->end_date;
                                if (in_array($service_id, $dept_emails ) && ($active == null || $active > $now))
                                {
                                    $notify_emails[] = $dept_emails[$service_id];
                                }
                            }

                            $message = "Hi " . $website->url . " has been down since " . $down_time_email . ".";
                            $email = Model_Mail::send_email($dept_emails, "" . $website->url . " is down", $message);

                            $result = DB::update('clients_websites')
                                ->set(array(
                                    'down_email_sent' => date('Y-m-d H:i:s')
                                ))
                                ->where('id', '=', $website->id)
                                ->execute();
                        }
                    }
                }
            }
        }
    }

Body:
Figured this out at the beginning of the website foreach I defined a new variable $time_now = date('Y-m-d H:i:s'); which was then used in the update for query for the down_at time and assigned to $down_time variable.

$result = DB::update('clients_websites')
                            ->set(array(
                                'down_at' => $time_now
                            ))
                            ->where('id', '=', $website->id)
                            ->execute();
                    }

                    $down_time = DateTime::createFromFormat('Y-m-d H:i:s', $time_now);


来源: stackexchange

问:
After updating record in MySql through vb.net, rest of the Columns remain the same except 1st and 2nd column swaps in my application
I tried so many things but nothing fixes it, as any of the INSERT Command or DELETE Command in MySQL Database are working fine, only UPDATE Command swaps the first and second column unnecessarily, when it's displayed using the SELECT Command.
So, I need to close my app. and then re-Run it, then the columns are then displayed correctly, only until I execute UPDATE Command again, which messes with the first and second column.

Any idea why this is happening!

Here is my code

Sub DB_CMD_FUNC(SENDER As String)
        'Database realted script
        Dim con As New MySqlConnection("server=localhost; user=root; password=****; database=****;")
        Dim cmd As New MySqlCommand
        Dim dt As New DataTable
        Dim da As New MySqlDataAdapter
        Dim sql As String
        Dim DR As MySqlDataReader
        Dim SQL_CMD_TXT = "UPDATE `employees` SET `NAME`= '" & EMPLOYEE_EDIT_FRM.EDIT_NAME_TXT.Text & "', _
`FATHER_NAME`='" & EMPLOYEE_EDIT_FRM.EDIT_FATHER_NAME_TXT.Text & "', `DOB`='" &
        EMPLOYEE_EDIT_FRM.EDIT_DOB_TXT.Text & "',`DOJ`='" &
        EMPLOYEE_EDIT_FRM.EDIT_DOJ_TXT.Text & "',`POSITION`='" &
        EMPLOYEE_EDIT_FRM.EDIT_POSITION_TXT.Text &
        "',`EMP_STATUS`='" & EMPLOYEE_EDIT_FRM.EDIT_EMP_STATUS_TXT.Text & "', _
`SALARY`='" & EMPLOYEE_EDIT_FRM.EDIT_SALARY_TXT.Text & "',`EOS`='" &
    EMPLOYEE_EDIT_FRM.EDIT_EOS_TXT.Text & "', _
`MOBILE`='" & EMPLOYEE_EDIT_FRM.EDIT_REMARKS_TXT.Text & "' WHERE
    `EMPLOYEE_ID` = '" & EMPLOYEE_EDIT_FRM.EDIT_ID_TXT.Text & "';
Select `NAME` FROM `employees` WHERE
    `EMPLOYEE_ID`='" & EMPLOYEE_EDIT_FRM.EDIT_ID_TXT.Text & "';"
        Try
            'DB CMD EXECUTION
            con.Open()
            With cmd
                sql = SQL_CMD_TXT
                .Connection = con
                .CommandText = sql
            End With
            dt.Clear()
            da.SelectCommand = cmd
            da.Fill(dt)
            'Command for datagridview object
            With OBJECT_DATAGRIDVIEW
                .DataSource = dt
                'Scroll to the last row.
                .Name = "MYDATAGRIDVIEW"
                .FirstDisplayedScrollingRowIndex = .RowCount - 1
            End With
            con.Close()
        Catch ex As Exception
            MessageBox.Show("ERROR FOR SQL CMD EXECUTION SECTION-" & ex.Message,
                                      "SQL CMD EXECUTION", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try
    End Sub
```

答:
Your UPDATE-query seems to be structurally fine. But please do use SQL parameters, because if you now include an apostrophe (') within your entered textbox values, the query will most likely crash. (Or worse: some malicious user might apply SQL injection to manipulate your database!)

But after the UPDATE-query, you execute a small SELECT query. This SELECT query returns only the NAME of only the updated record. This single row with a single column is captured in a DataTable object, and that DataTable object is set as the new data source for your DataGridView.

Is that your real intention? In your place, I would probably want to select all relevant fields from the database table and include all records, so that everything will be shown/refreshed in the DataGridView...

You probably already have some SELECT query in your application's startup code to initially fill the DataGridView. I would personally put that code in a separate subroutine (called something like FillDataGridView) and call that subroutine in the application's (or the form's) startup code and also call it after executing the UPDATE query. So there would not be any need to include a separate SELECT query after your UPDATE query.

You could check out the following code for some inspiration. Note that I haven't tested the code (because I do not have MySQL installed on my machine), so it might quite certainly require some additional tweaking and bugfixing inside your application's code.

Private Sub DB_CMD_FUNC(SENDER As String)
    Dim SQL_CMD_TXT As New StringBuilder()

    SQL_CMD_TXT.AppendLine("UPDATE `employees`")
    SQL_CMD_TXT.AppendLine("SET")
    SQL_CMD_TXT.AppendLine("  `NAME` = @name,")
    SQL_CMD_TXT.AppendLine("  `FATHER_NAME` = @father_name,")
    SQL_CMD_TXT.AppendLine("  `DOB` = @dob,")
    SQL_CMD_TXT.AppendLine("  `DOJ` = @doj,")
    SQL_CMD_TXT.AppendLine("  `POSITION` = @position,")
    SQL_CMD_TXT.AppendLine("  `EMP_STATUS` = @status,")
    SQL_CMD_TXT.AppendLine("  `SALARY` = @salary,")
    SQL_CMD_TXT.AppendLine("  `EOS` = @eos,")
    SQL_CMD_TXT.AppendLine("  `MOBILE` = @mobile'")
    SQL_CMD_TXT.AppendLine("WHERE")
    SQL_CMD_TXT.AppendLine("  `EMPLOYEE_ID` = @ID;")

    Try
        Dim ID As String = EMPLOYEE_EDIT_FRM.EDIT_ID_TXT.Text

        If String.IsNullOrWhiteSpace(ID) Then
            Throw New Exception("The ID is required.")
        End If

        Dim NAME As String = EMPLOYEE_EDIT_FRM.EDIT_NAME_TXT.Text

        If String.IsNullOrWhiteSpace(NAME) Then
            NAME = Nothing
        End If

        Dim FATHER_NAME As String = EMPLOYEE_EDIT_FRM.EDIT_FATHER_NAME_TXT.Text

        If String.IsNullOrWhiteSpace(FATHER_NAME) Then
            FATHER_NAME = Nothing
        End If

        Dim DD As Date
        Dim DOB As Date?
        Dim DOJ As Date?

        If Date.TryParse(EMPLOYEE_EDIT_FRM.EDIT_DOB_TXT.Text, DD) Then
            DOB = DD
        Else
            DOB = Nothing
        End If

        If Not Date.TryParse(EMPLOYEE_EDIT_FRM.EDIT_DOJ_TXT.Text, DD) Then
            DOJ = DD
        Else
            DOJ = Nothing
        End If

        Dim POSITION As String = EMPLOYEE_EDIT_FRM.EDIT_POSITION_TXT.Text

        If String.IsNullOrWhiteSpace(POSITION) Then
            POSITION = Nothing
        End If

        Dim STATUS As String = EMPLOYEE_EDIT_FRM.EDIT_EMP_STATUS_TXT.Text

        If String.IsNullOrWhiteSpace(STATUS) Then
            STATUS = Nothing
        End If

        Dim DEC As Decimal
        Dim SALARY As Decimal?

        If Decimal.TryParse(EMPLOYEE_EDIT_FRM.EDIT_SALARY_TXT.Text, DEC) Then
            SALARY = DEC
        Else
            SALARY = Nothing
        End If

        Dim EOS As Date?

        If Date.TryParse(EMPLOYEE_EDIT_FRM.EDIT_EOS_TXT.Text, DD) Then
            EOS = DD
        Else
            EOS = Nothing
        End If

        Dim MOBILE As String = EMPLOYEE_EDIT_FRM.EDIT_REMARKS_TXT.Text

        If String.IsNullOrWhiteSpace(MOBILE) Then
            MOBILE = Nothing
        End If

        Using con As New MySqlConnection("server=localhost; user=root; password=****; database=****;")
            ''Do not open the database connection just yet...
            'con.Open()

            Using cmd As New MySqlCommand(SQL_CMD_TXT.ToString(), con)
                cmd.Parameters.Add("@id", MySqlDbType.VarChar).Value = ID
                cmd.Parameters.Add("@name", MySqlDbType.VarChar).Value = NAME
                cmd.Parameters.Add("@father_name", MySqlDbType.VarChar).Value = FATHER_NAME
                cmd.Parameters.Add("@dob", MySqlDbType.Date).Value = DOB
                cmd.Parameters.Add("@doj", MySqlDbType.Date).Value = DOJ
                cmd.Parameters.Add("@position", MySqlDbType.VarChar).Value = POSITION
                cmd.Parameters.Add("@status", MySqlDbType.VarChar).Value = STATUS
                cmd.Parameters.Add("@salary", MySqlDbType.Decimal).Value = SALARY
                cmd.Parameters.Add("@eos", MySqlDbType.Date).Value = EOS
                cmd.Parameters.Add("@mobile", MySqlDbType.VarChar).Value = MOBILE

                con.Open() 'Delayed opening the database connection until the very last moment.
                cmd.ExecuteNonQuery()
            End Using

            ''Explicitly closing the database connection is not necessary, because the disposal (triggered when the Using-block is ended) takes care of that.
            'con.Close()
        End Using
    Catch ex As Exception
        MessageBox.Show($"ERROR FOR SQL CMD EXECUTION SECTION - {ex.Message}",
                        "SQL CMD EXECUTION",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error)
        Exit Sub
    End Try

    FillDataGridView()
End Sub

Private Sub FillDataGridView()
    Dim SQL_CMD_TXT As New StringBuilder()

    SQL_CMD_TXT.AppendLine("SELECT")
    SQL_CMD_TXT.AppendLine("  `ID`,")
    SQL_CMD_TXT.AppendLine("  `NAME`,")
    SQL_CMD_TXT.AppendLine("  `FATHER_NAME`,")
    SQL_CMD_TXT.AppendLine("  `DOB`,")
    SQL_CMD_TXT.AppendLine("  `DOJ`,")
    SQL_CMD_TXT.AppendLine("  `POSITION`,")
    SQL_CMD_TXT.AppendLine("  `EMP_STATUS`,")
    SQL_CMD_TXT.AppendLine("  `SALARY`,")
    SQL_CMD_TXT.AppendLine("  `EOS`,")
    SQL_CMD_TXT.AppendLine("  `MOBILE`")
    SQL_CMD_TXT.AppendLine("FROM")
    SQL_CMD_TXT.AppendLine("  `employees`;")

    Try
        Dim dt As New DataTable()

        Using con As New MySqlConnection("server=localhost; user=root; password=****; database=****;")
            ''Do not open the database connection just yet...
            'con.Open()

            Using cmd As New MySqlCommand(SQL_CMD_TXT.ToString(), con)
                Using da As New MySqlDataAdapter(cmd)
                    con.Open() 'Delayed opening the database connection until the very last moment.
                    da.Fill(dt)
                End Using
            End Using

            ''Explicitly closing the database connection is not necessary, because the disposal (triggered when the Using-block is ended) takes care of that.
            'con.Close()
        End Using

        With OBJECT_DATAGRIDVIEW
            .DataSource = dt
            .FirstDisplayedScrollingRowIndex = .RowCount - 1 'Scroll to the last row.
        End With
    Catch ex As Exception
        MessageBox.Show($"ERROR FOR SQL CMD EXECUTION SECTION - {ex.Message}",
                        "SQL CMD EXECUTION",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error)
    End Try
End Sub
```

ContentLicense: CC BY-SA 4.0


问:
How to delete folders that are older than some days using camel
I wanted to poll a directory and delete the files and folders that are older than a specified time. I wrote the following code :-

```<code>            from("file:input?filterFile=${date:file:yyyyMMddHHmm} <= ${date:now-240h:yyyyMMddHHmm}&delay=60000&delete=true")
            .log("The headers are ${headers}");
</code>```

It works fine for files and the old files are deleted but this does not work on folders. Can anyone suggest a way to make it work on folders also?

答:
You can write a processor to write your logic in java as Apache camel doesn't work on directories, you can try something like below.</p>

```<code>from("timer://myTimer?period=2000")
.process(new Processor() {

    public void process(Exchange exchange)
            throws Exception {
        System.out.println("Deleting Directories");
        File directory = new File("D:\\basedirectory");
        removeDirectory(1, directory);
    }

    public void removeDirectory(int daysBack, File directory) {
        if(directory.exists()){
            final File[] listFiles = directory.listFiles();
            final long purgeTime =
                System.currentTimeMillis() - (daysBack * 24 * 60 * 60 * 1000);

            for(File listFile : listFiles) {
                if(listFile.lastModified() < purgeTime) {
                    System.out.println(listFile.getName() + " - deleted");
                    listFile.delete();
                }
            }
        }
    }
})
.end();
</code>```

Body:
I wanted to poll a directory and delete the files and folders that are older than a specified time. I wrote the following code :-

            from("file:input?filterFile=${date:file:yyyyMMddHHmm} <= ${date:now-240h:yyyyMMddHHmm}&delay=60000&delete=true")
            .log("The headers are ${headers}");

It works fine for files and the old files are deleted but this does not work on folders. Can anyone suggest a way to make it work on folders also?

Body:
You can write a processor to write your logic in java as Apache camel doesn't work on directories, you can try something like below.

from("timer://myTimer?period=2000")
.process(new Processor() {

    public void process(Exchange exchange)
            throws Exception {
        System.out.println("Deleting Directories");
        File directory = new File("D:\\basedirectory");
        removeDirectory(1, directory);
    }

    public void removeDirectory(int daysBack, File directory) {
        if(directory.exists()){
            final File[] listFiles = directory.listFiles();
            final long purgeTime =
                System.currentTimeMillis() - (daysBack * 24 * 60 * 60 * 1000);

            for(File listFile : listFiles) {
                if(listFile.lastModified() < purgeTime) {
                    System.out.println(listFile.getName() + " - deleted");
                    listFile.delete();
                }
            }
        }
    }
})
.end();


问:
Custom behavior if silverlight does not exist
using the Silverlight control (asp:Silverlight) on an aspx page, is there a way to customize the behavior if silverlight does not exist?  I want to display a table with images in them if silverlight does not exist on the client.</p>

答:
Tim Heuer has written lots of info about this.
Here's the main point, straight from his blog:

```<code>    <asp:Silverlight ID="Xaml1" runat="server"
     Source="~/ClientBin_SilverlightApplication1.xap"
                 MinimumVersion="2.0.30523" Width="100%" Height="100%">
             <PluginNotInstalledTemplate>

             Your Content goes here.

             </PluginNotInstalledTemplate>
        </asp:Silverlight>
</code>```

Here is the original blog post

http://timheuer.com/blog/archive/2008/03/25/creating-a-great-silverlight-deployment-experience.aspx

And a couple follow ups

http://timheuer.com/blog/archive/2008/09/08/silverlight-install-experience-too-hard.aspx
http://timheuer.com/blog/archive/2008/12/02/silverlight-install-experience-best-practices-netflix.aspx

And, for your viewing pleasure

http://silverlight.net/learn/learnvideo.aspx?video=57016

OwnerDisplayName: Jeremy

ContentLicense: CC BY-SA 2.5

Body:
Tim Heuer has written lots of info about this.
Here's the main point, straight from his blog:

    <asp:Silverlight ID="Xaml1" runat="server"
     Source="~/ClientBin_SilverlightApplication1.xap"
                 MinimumVersion="2.0.30523" Width="100%" Height="100%">
             <PluginNotInstalledTemplate>

             Your Content goes here.

             </PluginNotInstalledTemplate>
        </asp:Silverlight>

Here is the original blog post

http://timheuer.com/blog/archive/2008/03/25/creating-a-great-silverlight-deployment-experience.aspx

And a couple follow ups

http://timheuer.com/blog/archive/2008/09/08/silverlight-install-experience-too-hard.aspx
http://timheuer.com/blog/archive/2008/12/02/silverlight-install-experience-best-practices-netflix.aspx

And, for your viewing pleasure

http://silverlight.net/learn/learnvideo.aspx?video=57016

OwnerDisplayName: TJB


问:
What is the right way to send a watch dog request to an ASP.NET web server?
I have an ASP.NET web server and I wish to have a watchdog sending it periodic requests. Currently, I am planning to add an EmptyPage.aspx and then request it periodically from a locally running watchdog application.

Is there a better way to implement the watchdog facility?

P.S.

The server may be deployed in an intranet without the access to Internet, hence please do not suggest using 3rd party watchdog sites.

答:
What exactly is the purpose of WatchDog here? Do you want to make sure that your site is always running (in case of application-pool/machine restarts) or you want to do some health check? Your approach is more than sufficient for the former whilst for later, you may want to do more than Empty Page. Few things that can be considered for health checking are:

Return information about system resources such as memory utilization, average CPU utilization etc so that watchdog may raise alarm on some threasholds

Make a database query to ensure that the database is running or not

ContentLicense: CC BY-SA 3.0


问:
Django model_to_dict stack overflow crash
In my app, I use a common Base model for all my models. I'v encountered a behaviour I can't explain with the Campus and Hall models:

class Base(models.Model):
    id: int = models.AutoField(primary_key=True, editable=False)

    class Meta:
        abstract = True

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._initial = self.as_dict

    ...
    @property
    def as_dict(self) -> dict:
        fields = [field.name for field in self._meta.fields]
        res = model_to_dict(self, fields=fields)
        return res
    ...

class Campus(Base):
    name: str = models.CharField(max_length=100)

    class Meta:
        verbose_name_plural = "campuses"

    def __str__(self):
        return self.name

class Hall(Base):
    name: str = models.CharField(max_length=100)
    campus: Campus = models.ForeignKey(Campus, on_delete=models.SET_NULL, null=True)

    def save(self, *args, **kwargs):
        if self.campus is not None and isinstance(self.campus, str):
            self.campus = Campus.objects.get_or_create(name=self.campus)[0]
        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.name}{f' ({self.campus})' if self.campus else ''}"
```

<p>On the admin console, when I try to delete a certain <code>Campus</code> instance, the server crashes. This is a very small part of the (very long) trace:</p>

```Fatal Python error: Cannot recover from stack overflow.
...
Current thread 0x00000bdc (most recent call first):
...
  File "P:\Python\Coursist\academic_helper\models\base.py", line 142 in as_dict
  File "P:\Python\Coursist\academic_helper\models\base.py", line 98 in __init__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\base.py", line 512 in from_db
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 75 in __iter__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 1261 in _fetch_all
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 258 in __len__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 411 in get
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\base.py", line 627 in refresh_from_db
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query_utils.py", line 139 in __get__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\fields\__init__.py", line 931 in value_from_object
  File "C:\Venvs\Coursist\lib\site-packages\django\forms\models.py", line 93 in model_to_dict
  File "P:\Python\Coursist\academic_helper\models\base.py", line 142 in as_dict
  File "P:\Python\Coursist\academic_helper\models\base.py", line 98 in __init__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\base.py", line 512 in from_db
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 75 in __iter__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 1261 in _fetch_all
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 258 in __len__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 411 in get
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\base.py", line 627 in refresh_from_db
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query_utils.py", line 139 in __get__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\fields\__init__.py", line 931 in value_from_object
  File "C:\Venvs\Coursist\lib\site-packages\django\forms\models.py", line 93 in model_to_dict
  File "P:\Python\Coursist\academic_helper\models\base.py", line 142 in as_dict
  File "P:\Python\Coursist\academic_helper\models\base.py", line 98 in __init__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\base.py", line 512 in from_db
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 75 in __iter__
...
```

At first I thought it is some kind of circular pointing issue between Hall and Campus, but that doesn't seem to be the case (when debugging, I can't see any pointer from Campus to a Hall). The weird thing is that if I first delete all Hall instances, the deletion of the Campus goes smoothly.

I'm using python 3.7 and Django 3.0.6

答:
Your design of BaseModel is causing this problem, because model_to_dict will resolve *ToMany relations and create possibly huge lists. This is amplified by the admin creating it's own in-memory list to show you all the related models you are about to delete.

You are basically putting a serialized representation on the model in it's init method, which you already have as a property. If this is your way of caching the value, then I suggest you use django.utils.functions.cached_property and change the mechanism to "cache at first access" rather than "cache at init":

from django.utils.functional import cached_property

class Base(models.Model):
    id: int = models.AutoField(primary_key=True, editable=False)

    class Meta:
        abstract = True

    ...
    @cached_property
    def as_dict(self) -> dict:
        fields = [field.name for field in self._meta.fields]
        res = model_to_dict(self, fields=fields)
        return res

    @property
    def _initial(self) -> dict:
        # if you're set on the _initial name
        return self.as_dict
```

Body:
In my app, I use a common Base model for all my models. I'v encountered a behaviour I can't explain with the Campus and Hall models:

class Base(models.Model):
    id: int = models.AutoField(primary_key=True, editable=False)

    class Meta:
        abstract = True

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._initial = self.as_dict

    ...
    @property
    def as_dict(self) -> dict:
        fields = [field.name for field in self._meta.fields]
        res = model_to_dict(self, fields=fields)
        return res
    ...

class Campus(Base):
    name: str = models.CharField(max_length=100)

    class Meta:
        verbose_name_plural = "campuses"

    def __str__(self):
        return self.name

class Hall(Base):
    name: str = models.CharField(max_length=100)
    campus: Campus = models.ForeignKey(Campus, on_delete=models.SET_NULL, null=True)

    def save(self, *args, **kwargs):
        if self.campus is not None and isinstance(self.campus, str):
            self.campus = Campus.objects.get_or_create(name=self.campus)[0]
        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.name}{f' ({self.campus})' if self.campus else ''}"

On the admin console, when I try to delete a certain Campus instance, the server crashes. This is a very small part of the (very long) trace:

Fatal Python error: Cannot recover from stack overflow.
...
Current thread 0x00000bdc (most recent call first):
...
  File "P:\Python\Coursist\academic_helper\models\base.py", line 142 in as_dict
  File "P:\Python\Coursist\academic_helper\models\base.py", line 98 in __init__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\base.py", line 512 in from_db
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 75 in __iter__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 1261 in _fetch_all
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 258 in __len__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 411 in get
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\base.py", line 627 in refresh_from_db
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query_utils.py", line 139 in __get__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\fields\__init__.py", line 931 in value_from_object
  File "C:\Venvs\Coursist\lib\site-packages\django\forms\models.py", line 93 in model_to_dict
  File "P:\Python\Coursist\academic_helper\models\base.py", line 142 in as_dict
  File "P:\Python\Coursist\academic_helper\models\base.py", line 98 in __init__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\base.py", line 512 in from_db
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 75 in __iter__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 1261 in _fetch_all
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 258 in __len__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 411 in get
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\base.py", line 627 in refresh_from_db
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query_utils.py", line 139 in __get__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\fields\__init__.py", line 931 in value_from_object
  File "C:\Venvs\Coursist\lib\site-packages\django\forms\models.py", line 93 in model_to_dict
  File "P:\Python\Coursist\academic_helper\models\base.py", line 142 in as_dict
  File "P:\Python\Coursist\academic_helper\models\base.py", line 98 in __init__
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\base.py", line 512 in from_db
  File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 75 in __iter__
...

At first I thought it is some kind of circular pointing issue between Hall and Campus, but that doesn't seem to be the case (when debugging, I can't see any pointer from Campus to a Hall). The weird thing is that if I first delete all Hall instances, the deletion of the Campus goes smoothly.

I'm using python 3.7 and Django 3.0.6


问:
Passing a function on the content of a HTML textarea in Javascript
How can I pass a function on the content of a HTML textarea if the content is an array?

eg:

https://i.stack.imgur.com/8v0kg.png

the textarea.value is a string but I want to use a javascript function such that textarea.value.forEach() works

答:
Use JSON.parse() function to convert string into json object

you can find more here JSON.parse


问:
Windows 10 iot core UWP bluetooth sound connection
I want to connect bluetooth headset, headphone, speakers to my uwp application. I can list all bluetooth devices and I can pair to clicked one but I couldn't manage to connect sound device (pairing is successful but can't transfer sound and when paired no response from sound device). Is it possible to do that ? What's my mistake ?
Thanks</p>

答: As far as i know, Windows IoT Core does not support bluetooch sound connection, since Windows IoT Core does not implement the A2DP (Advanced Audio Distribution Profile) Profile and stream audio to a head set  that implements the HSP (Headset) Profile OBEX (Object Exchange) is a symmetric connection between two devices as they exchange data between them. Windows IoT Core uses the GATT (Generic Attribute Profile Profile).This provides profile discovery and description services for  the Bluetooth Low Energy protocol.With this protocol simple low power devices can be connected at one end generating data to be consumed by a complex processor. </p>


问:
Nested SQL IN statement for cell with more than 1 value

How do i write the SQL such that it will return me

tom,ken,jerry

I tried this SQL as

```<code>select name
  from staffDB
 where dept in (select value
                  from ConfigDB
                 where key = 'dept')
</code>```

but it returns no value, no nope, i'm not allowed to alter the database design.

答:
You can use the hierarchy query to split the value and then join it as follows:</p>

```<code>SQL>  SELECT
2      C.KEY,
3      LISTAGG(S.NAME, ',') WITHIN GROUP(ORDER BY S.DEPT) DEPARTMENTS
4     FROM
5      CONFIGDB   C
6      CROSS JOIN TABLE ( CAST(MULTISET(
7          SELECT REGEXP_SUBSTR(C.VALUE, '[^,]+', 1, LEVEL)
8            FROM DUAL
9          CONNECT BY LEVEL <= REGEXP_COUNT(C.VALUE, '[^,]+')
10      ) AS SYS.ODCIVARCHAR2LIST) ) C1
11      LEFT JOIN STAFFDB    S ON S.DEPT = C1.COLUMN_VALUE
12    GROUP BY C.KEY;

KEY   DEPARTMENTS
----- ---------------
dept  tom,ken,jerry

SQL>
</code>```

Body:
How do i write the SQL such that it will return me

tom,ken,jerry

I tried this SQL as

select name
  from staffDB
 where dept in (select value
                  from ConfigDB
                 where key = 'dept')

but it returns no value, no nope, i'm not allowed to alter the database design.

Body:
You can use the hierarchy query to split the value and then join it as follows:

SQL>  SELECT
2      C.KEY,
3      LISTAGG(S.NAME, ',') WITHIN GROUP(ORDER BY S.DEPT) DEPARTMENTS
4     FROM
5      CONFIGDB   C
6      CROSS JOIN TABLE ( CAST(MULTISET(
7          SELECT REGEXP_SUBSTR(C.VALUE, '[^,]+', 1, LEVEL)
8            FROM DUAL
9          CONNECT BY LEVEL <= REGEXP_COUNT(C.VALUE, '[^,]+')
10      ) AS SYS.ODCIVARCHAR2LIST) ) C1
11      LEFT JOIN STAFFDB    S ON S.DEPT = C1.COLUMN_VALUE
12    GROUP BY C.KEY;

KEY   DEPARTMENTS
----- ---------------
dept  tom,ken,jerry

SQL>


问:
Make an existing row readonly while new row is editable Angular FormArray
I currently have a scenario as follow:

I have a html table, that is bound to a Reactive Form's FormArray.

The data returned from the server displays in the table, and should always be readonly. However, I want to be able to add a new row, which should be editable, for instance, contains input fields and dropdowns.

Here is a Stackblitz of an example, where I can add a new row, but it is also read-only.  I want the new row added, to contain editable input controls.

Is this possible?

答:
There are a lot of ways to do this:

You can add the  editiable property to a new user object and in your td rendering you have to look if is editable or not.
Pseudo code:

```<code><td *ngIf="!user.editable">{{user.name}}</td>
<td *ngIf="user.editable"><input matInput ... ></td>
</code>```

Or you can have an editableIndex in your component. -1 nothing is editable, else the index of the editable row.

```<code><td *ngIf="editableIndex!==i">{{user.name}}</td>
<td *ngIf="editableIndex===i"><input matInput ... ></td>
</code>```

Instead of two tds in the template, you can make your input readonly (or disabled for selects):

```<code><td><input [readonly]="editableIndex!==i" matInput ... ></td>
</code>```

Body:
There are a lot of ways to do this:

You can add the  editiable property to a new user object and in your td rendering you have to look if is editable or not.
Pseudo code:

<td *ngIf="!user.editable">{{user.name}}</td>
<td *ngIf="user.editable"><input matInput ... ></td>

Or you can have an editableIndex in your component. -1 nothing is editable, else the index of the editable row.

<td *ngIf="editableIndex!==i">{{user.name}}</td>
<td *ngIf="editableIndex===i"><input matInput ... ></td>

Instead of two tds in the template, you can make your input readonly (or disabled for selects):

<td><input [readonly]="editableIndex!==i" matInput ... ></td>


问:
Python Pandas - use Multiple Character Delimiter when writing to_csv
It appears that the pandas to_csv function only allows single character delimiters/separators.

Is there some way to allow for a string of characters to be used like, "::" or "%%" instead?

I tried:

```<code>df.to_csv(local_file,  sep = '::', header=None, index=False)
</code>```

and getting:

```<code>TypeError: "delimiter" must be a 1-character string
</code>```

答:
Use numpy-savetxt

Ex:

```<code>np.savetxt(file.csv, np.char.decode(chunk_data.values.astype(np.bytes_), 'UTF-8'), delimiter='~|', fmt='%s',encoding=None)

np.savetxt(file.dat, chunk_data.values, delimiter='~|', fmt='%s',encoding='utf-8')
</code>```

Body:
It appears that the pandas to_csv function only allows single character delimiters/separators.

Is there some way to allow for a string of characters to be used like, "::" or "%%" instead?

I tried:

df.to_csv(local_file,  sep = '::', header=None, index=False)

and getting:

TypeError: "delimiter" must be a 1-character string

Body:
Use numpy-savetxt

Ex:

np.savetxt(file.csv, np.char.decode(chunk_data.values.astype(np.bytes_), 'UTF-8'), delimiter='~|', fmt='%s',encoding=None)

np.savetxt(file.dat, chunk_data.values, delimiter='~|', fmt='%s',encoding='utf-8')


问:
Should I stop breaking .NET events guidelines?
Over and over I find myself implementing events in C# following the guidelines and then falling back to a simpler implementation using just Action when the client code does not need any of the benefits added by the guidelines.

Arguably, I'll add that omitting the sender object unless it is actually required is a good thing because it promotes decoupling of triggers and handlers. More in general, I think it is a good habit to avoid writing code that is not needed.

I don't mean that the guidelines should be always dismissed, there are benefits in following them (see links below). My question is if I should always follow it.

The example below shows how terse the "naive events" patterns is compared to the guidelines pattern.

```<code>// This is neat
class NaiveEvents
{
    public event Action<string> OnAlert;
    public void TriggerOnAlert(string message)
    {
        OnAlert(message);
    }
}

// Is this bloated?
class ProperEvents
{
    public event EventHandler<OnAlertEventArgs> OnAlertEvent;

    public void TriggerOnAlert(string message)
    {
        OnAlertEvent(this, new OnAlertEventArgs(message));
    }

    public class OnAlertEventArgs : EventArgs
    {
        private readonly string _message;
        public OnAlertEventArgs(string message)
        {
            _message = message;
        }
        public string Message { get { return _message; } }
    }
}

class EventsDemo
{
    public static void DemoNaiveEvents()
    {
        var ev = new NaiveEvents();
        ev.OnAlert += (msg) => { Console.WriteLine(msg); };
        ev.TriggerOnAlert("Hello World");
    }

    public static void DemoProperEvents()
    {
        var ev = new ProperEvents();
        ev.OnAlertEvent += (sender, args) => Console.WriteLine(args.Message);
        ev.TriggerOnAlert("Hello World");
    }
}
</code>```

See the Guidelines: http://msdn.microsoft.com/en-us/library/w369ty8x.aspx

Benefits: What are the benefits of having events conforming to Net guidelines?

Thanks!

答:
Guidelines or conventions are arbitrary and non of them can fit all situations, environments, solutions or points of views, but that's the reason of creating these documents: standarization.

Sometimes some guideline would seem useless, but my humild opinion is never following a guideline and/or convention will be worst than don't doing so.

Maintainability, code re-use, predictability, readability and the absence of discussions everyday because every developer has his/her opinion of everything in trivial things, for me, has more value than anything.

Focusing in your current question, and based on what I said above, even if there's no performance or design quality benefit, I would suggest and recommend that global guidelines and conventions must be followed if some software development is for professional purposes. And if it's for open source audiencie, these should be followed too.

As an enthusiast and professional developer, I love writing, reading and maintaining code that follows de facto coding standards, because I know everyone will understand my work - obviously, documentation is a plus! -.

Body:
Over and over I find myself implementing events in C# following the guidelines and then falling back to a simpler implementation using just Action when the client code does not need any of the benefits added by the guidelines.

Arguably, I'll add that omitting the sender object unless it is actually required is a good thing because it promotes decoupling of triggers and handlers. More in general, I think it is a good habit to avoid writing code that is not needed.

I don't mean that the guidelines should be always dismissed, there are benefits in following them (see links below). My question is if I should always follow it.

The example below shows how terse the "naive events" patterns is compared to the guidelines pattern.

// This is neat
class NaiveEvents
{
    public event Action<string> OnAlert;
    public void TriggerOnAlert(string message)
    {
        OnAlert(message);
    }
}

// Is this bloated?
class ProperEvents
{
    public event EventHandler<OnAlertEventArgs> OnAlertEvent;

    public void TriggerOnAlert(string message)
    {
        OnAlertEvent(this, new OnAlertEventArgs(message));
    }

    public class OnAlertEventArgs : EventArgs
    {
        private readonly string _message;
        public OnAlertEventArgs(string message)
        {
            _message = message;
        }
        public string Message { get { return _message; } }
    }
}

class EventsDemo
{
    public static void DemoNaiveEvents()
    {
        var ev = new NaiveEvents();
        ev.OnAlert += (msg) => { Console.WriteLine(msg); };
        ev.TriggerOnAlert("Hello World");
    }

    public static void DemoProperEvents()
    {
        var ev = new ProperEvents();
        ev.OnAlertEvent += (sender, args) => Console.WriteLine(args.Message);
        ev.TriggerOnAlert("Hello World");
    }
}

See the Guidelines: http://msdn.microsoft.com/en-us/library/w369ty8x.aspx

Benefits: What are the benefits of having events conforming to Net guidelines?

Thanks!


问:
NGRX - spread operator remove atribute instead of replace in reducer
In my reducer I am trying to merge current state with value pased trought action. But problem is that merge operation remove object atribut instead of updating it.
I am using:

```<code>    on(WineActions.SetCurrentWine, (state, data) => {
        const newState = deepCopy(state);
        return {
            ...newState,
            currentWine: {...newState.currentWine, ...data}
        };
    }),
    ...
    export function deepCopy(state) {
       return JSON.parse(JSON.stringify(state));
    }
</code>```

ionic cli 6.9.1

angular 8.2.14

ngrx/store 8.6.0

ngrx/store-devtools 8.6.0

Action snapshot
Diff snapshot

Thank to all of you!!!!

Edit:
I did went trough whole reducer and find out that problem was initialize action... I hate that I do not know why merge does not work but it is working now...

答:
The first thing - never do deep copy, only update the value you need.

if you want data to replace currentWine, do like that.

    on(WineActions.SetCurrentWine, (state, data) => {
        return {
            ...state,
            currentWine: data,
        };
    }),
```

and nothing else.

Body:
In my reducer I am trying to merge current state with value pased trought action. But problem is that merge operation remove object atribut instead of updating it.
I am using:

    on(WineActions.SetCurrentWine, (state, data) => {
        const newState = deepCopy(state);
        return {
            ...newState,
            currentWine: {...newState.currentWine, ...data}
        };
    }),
    ...
    export function deepCopy(state) {
       return JSON.parse(JSON.stringify(state));
    }

ionic cli 6.9.1

angular 8.2.14

ngrx/store 8.6.0

ngrx/store-devtools 8.6.0

Action snapshot
Diff snapshot

Thank to all of you!!!!

Edit:
I did went trough whole reducer and find out that problem was initialize action... I hate that I do not know why merge does not work but it is working now...

Body:
The first thing - never do deep copy, only update the value you need.

if you want data to replace currentWine, do like that.

    on(WineActions.SetCurrentWine, (state, data) => {
        return {
            ...state,
            currentWine: data,
        };
    }),

and nothing else.


问:
TypeError: Cannot read property 'RichEmbed' of undefined
I've Been Searching For A Solutions For This Error But Until Now I Didn't Found Any Solutions And Now Took More Than 2 Days To Find A Solution So I Published My Problem Here So Anybody Can See It And Comment Why The Error Shows ?

The Problem : TypeError: Cannot read property 'RichEmbed' of undefined(18:35)

My Code :

```<code>1:  module.exports.run = async (bot, message, args) => {
2:
3:      let target = message.guild.member(message.mentions.users.first());
4:      let reason = args.slice(1).join(' ');
5:      let logs = message.guild.channels.cache.find(channel => channel.name === "⚠server_logs");
6:
7:      // member.guild.channels.cache.find('⚠server_logs', config.logsChannel);
8:
9:      if (!message.member.hasPermission('BAN_MEMBERS')) return message.reply('you don\'t have permissions to use this command!s');
10:
11:      if (!target) return message.reply('please specify a member to ban!');
12:      if (!reason) return message.reply('please specify a reason for this ban!');
13:      if (!logs) return message.reply(`please create a channel called ${config.logsChannel} to log the bans!`);
14:
15:      let embed = new discord.cache.RichEmbed()
16:          .setColor('RANDOM')
17:          .setThumbnail(target.user.avatarURL)
18:          .addField('Banned Member', `${target.user.username} with an ID: ${target.user,id}`)
19:          .addField('Banned By', `${message.author.username} with an ID: ${message.author.id}`)
20:          .addField('Banned Time', message.createdAt)
21:          .addField('Banned At', message.channel)
22:          .addField('Banned Reason', reason)
23:          .addFooter('Banned user information', target.user.displayAvatarURL);
24:
25:      message.channel.send(`${target.user.username} was banned by ${message.author} for ${reason}`);
26:      target.ban(reason);
27:      logs.send(embed);
28:  };
</code>```

答:
You don't seem to have discord.cache defined.
If you're using discord.js v12 or higher, use Discord.MessageEmbed(). If using v11, use Discord.RichEmbed().

Make sure to add

```<code>const Discord = require("discord.js");
</code>```

at the top.

Example

```<code>const Discord = require("discord.js"); // v12
let embed = new Discord.MessageEmbed()
.setColor("RED")
.setTitle("This is an embed.");
</code>```

Body:
I've Been Searching For A Solutions For This Error But Until Now I Didn't Found Any Solutions And Now Took More Than 2 Days To Find A Solution So I Published My Problem Here So Anybody Can See It And Comment Why The Error Shows ?

The Problem : TypeError: Cannot read property 'RichEmbed' of undefined(18:35)

My Code :

1:  module.exports.run = async (bot, message, args) => {
2:
3:      let target = message.guild.member(message.mentions.users.first());
4:      let reason = args.slice(1).join(' ');
5:      let logs = message.guild.channels.cache.find(channel => channel.name === "⚠server_logs");
6:
7:      // member.guild.channels.cache.find('⚠server_logs', config.logsChannel);
8:
9:      if (!message.member.hasPermission('BAN_MEMBERS')) return message.reply('you don\'t have permissions to use this command!s');
10:
11:      if (!target) return message.reply('please specify a member to ban!');
12:      if (!reason) return message.reply('please specify a reason for this ban!');
13:      if (!logs) return message.reply(`please create a channel called ${config.logsChannel} to log the bans!`);
14:
15:      let embed = new discord.cache.RichEmbed()
16:          .setColor('RANDOM')
17:          .setThumbnail(target.user.avatarURL)
18:          .addField('Banned Member', `${target.user.username} with an ID: ${target.user,id}`)
19:          .addField('Banned By', `${message.author.username} with an ID: ${message.author.id}`)
20:          .addField('Banned Time', message.createdAt)
21:          .addField('Banned At', message.channel)
22:          .addField('Banned Reason', reason)
23:          .addFooter('Banned user information', target.user.displayAvatarURL);
24:
25:      message.channel.send(`${target.user.username} was banned by ${message.author} for ${reason}`);
26:      target.ban(reason);
27:      logs.send(embed);
28:  };

Body:
You don't seem to have discord.cache defined.
If you're using discord.js v12 or higher, use Discord.MessageEmbed(). If using v11, use Discord.RichEmbed().

Make sure to add

const Discord = require("discord.js");

at the top.

Example

const Discord = require("discord.js"); // v12
let embed = new Discord.MessageEmbed()
.setColor("RED")
.setTitle("This is an embed.");


问:
Object.forEach in filter function
I am using Discord.js to write a Discord bot in this project. I am trying to put a ReactionCollector on a message and check if the reaction used is inside my data.

The data is stored in this config.json

```<code>{
  "botId": "xxxxxxxxxxxxxxx",
  "emojis": {
    "classes": [{
      "one": "716821724884238506",
      "two": "716821724863266876",
      "three": "716821724884369488"
    }]
  }
}
</code>```

This is the filter I want to assign to the ReactionController. It should trigger if the found reaction is inside the config.json and is not written by the bot itself.

```<code>const filter = (reaction, user) => {

  if(user.id === CONFIG.botId) {
    return false;
  }

  CONFIG.emojis.classes.forEach(obj => {
    Object.entries(obj).forEach(([key, value]) => {
      if(value === reaction.emoji.id) {
        console.log(`key: ${key}, value: ${value}`)
        return true;
      }
    });
  });
}
</code>```

And finally the collector i want to use the filter in:

```<code>const collector = message.createReactionCollector(filter);
collector.on('collect', (reaction, user) => {
  console.log(`Collected: ${reaction.emoji.id}`);
  let alreadySetClass = '';
  if (message.channel.name.includes(reaction.emoji.name.toLowerCase())) {
    alreadySetClass = reaction.emoji.name.toLowerCase()
  }

  console.log("setClass: " + alreadySetClass)
  setChannelName(message.channel, reaction.emoji.name, alreadySetClass)

})
</code>```

The response i get by collecting the reaction is a MessageReaction object.

The consol.log of the filter will print the key, value pair correctly. But the console.log('collected: ') inside the collector won't execute at all. There are no errors in the console. I don't know what I'm missing here. I think there is something wrong with the way I wrote the filter. Some help would be awesome. Thx in advance.

答:
That's because in your filter you're returning true from the callback of the forEach method: that means that the callback will return true, but your filter won't receive any return and so will return undefined, which is interpreted as false (and so won't collect any reaction).

Instead of forEach, try using the Array.some() method: if any of the callbacks return true for one element, the method will return true.

Here's how I would do it:

const filter = (reaction, user) => {
  // Check if the id is different and if for any of the classes ...
  return user.id != CONFIG.botId && CONFIG.emojis.classes.some(obj => {
    // ... at least one entry ...
    return Object.entries(obj).some(([key, value]) => {
      // ... has a value that matches the emoji id
      if (value == reaction.emoji.id) {
        console.log(`key: ${key}, value: ${value}`)
        // If so, return true
        return true
      }
    })
  })
}
```

PS: I know there's a lot of nested functions and it's not the most readable code, but it should do the trick.

Title: Object.forEach in filter function

Body:
I am using Discord.js to write a Discord bot in this project. I am trying to put a ReactionCollector on a message and check if the reaction used is inside my data.

The data is stored in this config.json

{
  "botId": "xxxxxxxxxxxxxxx",
  "emojis": {
    "classes": [{
      "one": "716821724884238506",
      "two": "716821724863266876",
      "three": "716821724884369488"
    }]
  }
}

This is the filter I want to assign to the ReactionController. It should trigger if the found reaction is inside the config.json and is not written by the bot itself.

const filter = (reaction, user) => {

  if(user.id === CONFIG.botId) {
    return false;
  }

  CONFIG.emojis.classes.forEach(obj => {
    Object.entries(obj).forEach(([key, value]) => {
      if(value === reaction.emoji.id) {
        console.log(`key: ${key}, value: ${value}`)
        return true;
      }
    });
  });
}

And finally the collector i want to use the filter in:

const collector = message.createReactionCollector(filter);
collector.on('collect', (reaction, user) => {
  console.log(`Collected: ${reaction.emoji.id}`);
  let alreadySetClass = '';
  if (message.channel.name.includes(reaction.emoji.name.toLowerCase())) {
    alreadySetClass = reaction.emoji.name.toLowerCase()
  }

  console.log("setClass: " + alreadySetClass)
  setChannelName(message.channel, reaction.emoji.name, alreadySetClass)

})

The response i get by collecting the reaction is a MessageReaction object.

The consol.log of the filter will print the key, value pair correctly. But the console.log('collected: ') inside the collector won't execute at all. There are no errors in the console. I don't know what I'm missing here. I think there is something wrong with the way I wrote the filter. Some help would be awesome. Thx in advance.

Body:
That's because in your filter you're returning true from the callback of the forEach method: that means that the callback will return true, but your filter won't receive any return and so will return undefined, which is interpreted as false (and so won't collect any reaction).

Instead of forEach, try using the Array.some() method: if any of the callbacks return true for one element, the method will return true.

Here's how I would do it:

const filter = (reaction, user) => {
  // Check if the id is different and if for any of the classes ...
  return user.id != CONFIG.botId && CONFIG.emojis.classes.some(obj => {
    // ... at least one entry ...
    return Object.entries(obj).some(([key, value]) => {
      // ... has a value that matches the emoji id
      if (value == reaction.emoji.id) {
        console.log(`key: ${key}, value: ${value}`)
        // If so, return true
        return true
      }
    })
  })
}

PS: I know there's a lot of nested functions and it's not the most readable code, but it should do the trick.


问:
Gradle sync failed: Could not find org.jetbrains.kotlin (no intention to use Kotlin)
(not a duplicate of this question in my opinion)

Error message in Android Studio:

Gradle sync failed: Could not find
  org.jetbrains.kotlin:kotlin-stdlib:1.1.3-2

I do not understand why Gradle will not sync without this library, and why Kotlin is mandatory. Also, I have not tried or intended to install or use the Kotlin plugin.

Note: This occurred just after I have upgraded to the latest Android Canary version just now on the dev update channel. There was no issue or anything Kotlin related in the stable version or in my code itself.

答:
I had the same issue, and updating the version from JetBrains' site fixed it

In the file build.gradle(project:);

Either

in "ext" section, as a number in a variable (probably like kotlin_version)

Or

it might be in the "dependencies" section, simply in the end of the classpath declaration

Link:
https://kotlinlang.org/docs/reference/using-gradle.html#plugin-and-versions


问:
How to call destroy on a component from inside the component?
I have a modal component and I want to be able to destroy it when the user clicks on the x button, I also have a notification popup that  destroys itself after  an  interval but  I'd like to give the user the ability to close it with the x button too.
I know I can pass an event to the component but I think it'll be better if the component is self destructive.
Also there might be a better design for such case but that's the way  I thought about it, other pointers will be appreciated.</p>

答:
If by destruction you mean node removal from the DOM, then all you need to do is obtain a reference to the top-most element in your component using Svelte's bind:this and remove said element using Node.removeChild():

Hey I'm a component

  <button on:click={() => nodeRef.parentNode.removeChild(nodeRef)}>
    Remove me :(
  </button>

```

<p>Demo REPL</p>

<h3>Edit</h3>

<p>I had missed the point about suggesting a different approach. Since the display of the modal or notification will be triggered by the parent component (be it from a user action or as a programmatic response), it feels more natural to me that the parent would handle the dismissal of the modal or notification as well.</p>

<p>You don't have to use events to handle closing a modal or notification, you can simply pass a close handler as a prop. This will also save you from having to handle node removal yourself (or node create/append for that matter).</p>

<p>Something like the following would be more 'Svelte-like':</p>

<p><strong>App.svelte</strong></p>

<pre class="lang-js prettyprint-override"><code><script>
  import MyModal from './MyModal.svelte'

  let showModal = false
</script>

<div>
  {#if showModal}
    <MyModal onClose={() => showModal = false} />
  {/if}
  <button on:click={() => showModal = true}>Show Modal</button>
</div>
</code>```

MyModal.svelte

Hi I'm a modal X

```

Demo 2 REPL

Body:
If by destruction you mean node removal from the DOM, then all you need to do is obtain a reference to the top-most element in your component using Svelte's bind:this and remove said element using Node.removeChild():

<script>
  let nodeRef
</script>

<div bind:this={nodeRef}>
  <h3>Hey I'm a component</h3>
  <button on:click={() => nodeRef.parentNode.removeChild(nodeRef)}>
    Remove me :(
  </button>
</div>

Demo REPL

Edit

I had missed the point about suggesting a different approach. Since the display of the modal or notification will be triggered by the parent component (be it from a user action or as a programmatic response), it feels more natural to me that the parent would handle the dismissal of the modal or notification as well.

You don't have to use events to handle closing a modal or notification, you can simply pass a close handler as a prop. This will also save you from having to handle node removal yourself (or node create/append for that matter).

Something like the following would be more 'Svelte-like':

App.svelte

<script>
  import MyModal from './MyModal.svelte'

  let showModal = false
</script>

<div>
  {#if showModal}
    <MyModal onClose={() => showModal = false} />
  {/if}
  <button on:click={() => showModal = true}>Show Modal</button>
</div>

MyModal.svelte

<script>
  export let onClose
</script>

<div>
  <h3>Hi I'm a modal <span on:click={onClose}>X</span></h3>
</div>

Demo 2 REPL


问:
The mysqli_connect not working
I installed apache, php and mysql. Now when I execute the php code, the mysqli_connect() is not working, neither it's showing the message in die.

```<code>$dbc=mysqli_connect(' ', ' ', ' ', ' ') or die('not connecting');
</code>```

Now someone tell me what database username shall I pass to mysqli_connect and what password. I don't remember I was asked for any username or password
and why isn't the message in die() showing up?

My var_dump(function_exists('mysqli_connect')); outputs bool(false).. if it has anything to do with it, how do I correct it.?

答:
Do you have error_reporting(E_ALL); And ini_set('display_errors',1); ?

The problem could be somewhere else.

Also how do you know it's failing if it is not priting the message in Die()?

Title: The mysqli_connect not working

Body:
I installed apache, php and mysql. Now when I execute the php code, the mysqli_connect() is not working, neither it's showing the message in die.

$dbc=mysqli_connect(' ', ' ', ' ', ' ') or die('not connecting');

Now someone tell me what database username shall I pass to mysqli_connect and what password. I don't remember I was asked for any username or password
and why isn't the message in die() showing up?

My var_dump(function_exists('mysqli_connect')); outputs bool(false).. if it has anything to do with it, how do I correct it.?


问:
Code to flag a square number is not working, why is this?
I am trying to learn Java and have to create a small script that tells you if a number you have selected is a square number or not:

```<code>public class NumberShapes{
    public static void main(String[] args) {

        class Number {
            int number;

            public boolean isSquare(){
                int y = 1;
                int squareNumber = 1;

                while (squareNumber <= number) {
                    y += 1;
                    squareNumber = (y * y);
                }

                if (squareNumber == number) {
                    return true;
                }
                else {
                    return false;
                }
            }

        }
        Number myNumber = new Number();

        myNumber.number = 9;

        System.out.println("Is " + myNumber.number + " a square number?: " + myNumber.isSquare());

}
}
</code>```

Let's say you choose a number, in this case myNumber = 9. The logic is then supposed to take every integer < 9 and square it. If any number is squared to equal myNumber, then myNumber is a square number (and returns true) otherwise it isn't and returns false.

However when I try with 9, I get the output to be false, when it should be true.

My thinking is that somehow it squares numbers up to 9, but then instead of comparing 9 with 9, it is comparing 3 with 9, and as 3 != 9, it outputs as false. Is this correct?

How would I fix it?

(Just FYI, I have seen an alternative where you can square root the number and check if it is an integer, but I would like to figure out why this way isn't working).

答:
The problem is in your loop's condition:

```<code>while (squareNumber <= number) {
    y += 1;
    squareNumber = (y * y);
}
</code>```

When y reaches 3, and squareNumber becomes 9 (3 * 3), you are not exiting the loop, since 9 <= 9 is true. Therefore, in the next iteration of the loop, you assign 4 * 4 to squareNumber before ending the loop, and you return false.

Change the condition to while (squareNumber < number).

Body:
I am trying to learn Java and have to create a small script that tells you if a number you have selected is a square number or not:

public class NumberShapes{
    public static void main(String[] args) {

        class Number {
            int number;

            public boolean isSquare(){
                int y = 1;
                int squareNumber = 1;

                while (squareNumber <= number) {
                    y += 1;
                    squareNumber = (y * y);
                }

                if (squareNumber == number) {
                    return true;
                }
                else {
                    return false;
                }
            }

        }
        Number myNumber = new Number();

        myNumber.number = 9;

        System.out.println("Is " + myNumber.number + " a square number?: " + myNumber.isSquare());

}
}

Let's say you choose a number, in this case myNumber = 9. The logic is then supposed to take every integer < 9 and square it. If any number is squared to equal myNumber, then myNumber is a square number (and returns true) otherwise it isn't and returns false.

However when I try with 9, I get the output to be false, when it should be true.

My thinking is that somehow it squares numbers up to 9, but then instead of comparing 9 with 9, it is comparing 3 with 9, and as 3 != 9, it outputs as false. Is this correct?

How would I fix it?

(Just FYI, I have seen an alternative where you can square root the number and check if it is an integer, but I would like to figure out why this way isn't working).

Body:
The problem is in your loop's condition:

while (squareNumber <= number) {
    y += 1;
    squareNumber = (y * y);
}

When y reaches 3, and squareNumber becomes 9 (3 * 3), you are not exiting the loop, since 9 <= 9 is true. Therefore, in the next iteration of the loop, you assign 4 * 4 to squareNumber before ending the loop, and you return false.

Change the condition to while (squareNumber < number).


问:
Should I setup network address with the Tarantool Cartridge application with docker?
When I use the docker pack for an application, how should I configure network addresses?</p>

答:
The logic of network connectivity in tarantool cartridge doesn't depend on whether you use regular virtual machines, or Docker. You need your tarantool instances to be able to reach each other through TCP and UDP.

In Docker it means either:

Setting up containers on the same internal network

And using internal network addresses to connect instances together. By default, instances on the same internal network will be able to reach each other on any tcp/udp ports. If you want multiple machines to share the same internal network, you may configure Docker Swarm, which will give you a so-called "overlay network" that spans multiple machines.

Binding to host's port

When running a container, you can pass -p 3301:3301/tcp -p 3301:3301/udp to docker run. It will expose a port from container to the external network on the host. Be very careful to always expose a udp port, because otherwise instances won't be able to talk to each other through the gossip protocol.

In addition to that, since you change the public address of your instances to be your host's IP and not the internal container's IP, you also need to specify additional parameter that changes the advertise URI of the tarantool instance. You can do that with the following option to docker run: -e TARANTOOL_ADVERTISE_URI=<your_host_ip>:3301.


问:
In React/Redux app why is my props.property in child component showing undefined in console log
I have built a Flashcard app and decided to implement Redux. On componentMount() it is running a getRandomCard action which sets the state of the randomCard.
My redux state shows the correct state of the random card which changes randomly with each refresh however when I pass the props to a child card component to display the question, answer and graphic the props.randomCard.question etc shows as undefined.
I don't know why. Here is the code for my reducer.

```<code> import CARD_DATA from '../components/card.data'

const INITIAL_STATE = {
  cards: CARD_DATA,
  randomCard: {},
  seenCard: [],
  endOfDeck: false
}

const cardReducer = function cards(state = INITIAL_STATE, action) {

  switch (action.type) {
    case 'GET_RANDOM_CARD':
      return {
        ...state,
        randomCard: [action.currentCards[Math.floor((Math.random() * action.currentCards.length))]]
      }

    default: return state
  }
}

export default cardReducer
</code>```

Here is the action:

```<code>export function getRandomCard(currentCards) {
  return {
    type: 'GET_RANDOM_CARD',
    currentCards: currentCards,
  }
}
enter code here
enter code here
</code>```

Here is the parent componentDidMount method:

```<code>class App extends Component {

  componentDidMount() {
    const {getRandomCard, cardData} = this.props
    getRandomCard(cardData)
  }
</code>```

And here is the child component which is trying to render the props:

```<code>return (
      <div className="card-container">
        <div className="card">
          <div className="front">
            <div className="question">{props.randomCard.question}</div>
            <div className="image">
              <img src={props.randomCard.imageUrl} alt='graphic not available' />
            </div>
          </div>
          <div className="back">
            <div className="answer">{props.randomCard.answer}</div>
          </div>
        </div>
      </div>
    )

}

export default Card
</code>```

Props.randomCard console.logs this:

```<code>0: {id: 3, question: "What is immutablity?", answer: "When an object or an array does not get mutated when being passed to a function", imageLink: "https://miro.medium.com/max/600/1*2N0l3bLqaBgmOSIay-uc5w.png", priority: 5}
length: 1
__proto__: Array(0)
</code>```

I have tried accessing these props using props.randomCard.question and props.randomCard[0].question all to no avail and I am blocked.

答:
I have figured out why I was getting props.randomCard[0].question undefined. The component was rendering before it received the props.

I fixed issue by adding the following conditional statement:

```<code>render () {
  if (this.props.card[0]) {
  return (
  <div className="card-container">
    <div className="card">
      <div className="front">
        <div className="question">{this.props.card[0].question}</div>
        <div className="image">
          <img src={this.props.card[0].imageLink} alt='graphic not available' />
        </div>
      </div>
      <div className="back">
        <div className="answer">{this.props.card[0].answer}</div>
      </div>
    </div>
  </div>
)

} else {
  return null
}
}
</code>```

}

Body:
I have built a Flashcard app and decided to implement Redux. On componentMount() it is running a getRandomCard action which sets the state of the randomCard.
My redux state shows the correct state of the random card which changes randomly with each refresh however when I pass the props to a child card component to display the question, answer and graphic the props.randomCard.question etc shows as undefined.
I don't know why. Here is the code for my reducer.

 import CARD_DATA from '../components/card.data'

const INITIAL_STATE = {
  cards: CARD_DATA,
  randomCard: {},
  seenCard: [],
  endOfDeck: false
}

const cardReducer = function cards(state = INITIAL_STATE, action) {

  switch (action.type) {
    case 'GET_RANDOM_CARD':
      return {
        ...state,
        randomCard: [action.currentCards[Math.floor((Math.random() * action.currentCards.length))]]
      }

    default: return state
  }
}

export default cardReducer

Here is the action:

export function getRandomCard(currentCards) {
  return {
    type: 'GET_RANDOM_CARD',
    currentCards: currentCards,
  }
}
enter code here
enter code here

Here is the parent componentDidMount method:

class App extends Component {

  componentDidMount() {
    const {getRandomCard, cardData} = this.props
    getRandomCard(cardData)
  }

And here is the child component which is trying to render the props:

return (

{props.randomCard.question}

{props.randomCard.answer}

    )

}

export default Card

Props.randomCard console.logs this:

0: {id: 3, question: "What is immutablity?", answer: "When an object or an array does not get mutated when being passed to a function", imageLink: "https://miro.medium.com/max/600/1*2N0l3bLqaBgmOSIay-uc5w.png", priority: 5}
length: 1
__proto__: Array(0)

I have tried accessing these props using props.randomCard.question and props.randomCard[0].question all to no avail and I am blocked.

Body:
I have figured out why I was getting props.randomCard[0].question undefined. The component was rendering before it received the props.

I fixed issue by adding the following conditional statement:

render () {
  if (this.props.card[0]) {
  return (
  <div className="card-container">
    <div className="card">
      <div className="front">
        <div className="question">{this.props.card[0].question}</div>
        <div className="image">
          <img src={this.props.card[0].imageLink} alt='graphic not available' />
        </div>
      </div>
      <div className="back">
        <div className="answer">{this.props.card[0].answer}</div>
      </div>
    </div>
  </div>
)

} else {
  return null
}
}

}


问:
How to Display the messages only once?
I have 2 struct arrays. i need to check each array of tempo to each array of buff and if a match is found i shall break our of the entire loop and output the message "a match is found" once and exits. Else "no match" should be outputted.

How to Display the messages only once after checking the two arrays with each other? i need to break out of the loop after a match. else output mismatch.
the output is being displayed multiple times.

```<code>for (int g = 0; g < lines; g++) {
    for (int y = 0; y < lines; y++) {
        if ((strstr(tempo[g], buff[y])) != NULL) //Cheking if enter username and Password Exist in record file.
        {
            printf("A match found on line");
            break;

        } else
        {
            printf("Mismatch in Username or Password");
        }
    }
}
</code>```

答:
To start with I'm wondering whether you really want to use strstr - it searches for a string in another string. That seems a bit strange. Did you mean to use strcmp.

I would separate the logic from the print out by writing a function that takes care of the search. The function shall not do any printing.

Something like:

```<code>int checkForPW(char** tempo, char** buff, int lines)
{
    for (int g = 0; g < lines; g++)
    {
        for (int y = 0; y < lines; y++)
        {
            if ((strstr(tempo[g], buff[y])) != NULL)
            {
                // Found - so return 1
                return 1;
            };
        };
    };
    return 0;
}
</code>```

and call it like

```<code>if (checkForPW(tempo, buff, lines))
{
    printf("A match found on line");
}
else
{
    printf("Mismatch in Username or Password");
}
</code>```

Title: How to Display the messages only once?

Body:
I have 2 struct arrays. i need to check each array of tempo to each array of buff and if a match is found i shall break our of the entire loop and output the message "a match is found" once and exits. Else "no match" should be outputted.

How to Display the messages only once after checking the two arrays with each other? i need to break out of the loop after a match. else output mismatch.
the output is being displayed multiple times.

for (int g = 0; g < lines; g++) {
    for (int y = 0; y < lines; y++) {
        if ((strstr(tempo[g], buff[y])) != NULL) //Cheking if enter username and Password Exist in record file.
        {
            printf("A match found on line");
            break;

        } else
        {
            printf("Mismatch in Username or Password");
        }
    }
}

Body:
To start with I'm wondering whether you really want to use strstr - it searches for a string in another string. That seems a bit strange. Did you mean to use strcmp.

I would separate the logic from the print out by writing a function that takes care of the search. The function shall not do any printing.

Something like:

int checkForPW(char** tempo, char** buff, int lines)
{
    for (int g = 0; g < lines; g++)
    {
        for (int y = 0; y < lines; y++)
        {
            if ((strstr(tempo[g], buff[y])) != NULL)
            {
                // Found - so return 1
                return 1;
            };
        };
    };
    return 0;
}

and call it like

if (checkForPW(tempo, buff, lines))
{
    printf("A match found on line");
}
else
{
    printf("Mismatch in Username or Password");
}


问:
Open a Facebook post URL in android Facebook app programmatically
I'm coding an android - java app which can open a Facebook post url
(ex: https://www.facebook.com/BaHangXom.0/videos/2377836809193490).
I tried some ways to start Facebook app with intent but unsuccessfully.

```<code>    Intent intent =  new Intent(Intent.ACTION_VIEW, Uri.parse("fb://facewebmodal/f?href=" + "https://www.facebook.com/BaHangXom.0/videos/2377836809193490"));
    intent.setPackage("com.facebook.katana");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
</code>```

Could you please give me any idea?
Thank you so much.

答:
Simply open the url:

Intent intent =  new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/BaHangXom.0/videos/2377836809193490"));
startActivity(intent);
```

This is the most simple and universal way: user will be able to choose (and remember the choice) whether they want to open the link via main Facebook app, Facebook lite, or the browser.

Body:
I'm coding an android - java app which can open a Facebook post url
(ex: https://www.facebook.com/BaHangXom.0/videos/2377836809193490).
I tried some ways to start Facebook app with intent but unsuccessfully.

    Intent intent =  new Intent(Intent.ACTION_VIEW, Uri.parse("fb://facewebmodal/f?href=" + "https://www.facebook.com/BaHangXom.0/videos/2377836809193490"));
    intent.setPackage("com.facebook.katana");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);

Could you please give me any idea?
Thank you so much.

Body:
Simply open the url:

Intent intent =  new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/BaHangXom.0/videos/2377836809193490"));
startActivity(intent);

This is the most simple and universal way: user will be able to choose (and remember the choice) whether they want to open the link via main Facebook app, Facebook lite, or the browser.


问:
How can I clear the hover and selection style of ListView in Xamarin.WPF
Here is the XAML:

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="App1.MainPage">

    <ListView ItemsSource="{Binding TestList}" SeparatorVisibility="None" HasUnevenRows="True">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <ViewCell.View>
                        <ContentView>
                            <Label Text="{Binding TestName}"></Label>
                        </ContentView>
                    </ViewCell.View>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>
</code>```

Here is code-behind:

```<code>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace App1
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            this.BindingContext = this;
            TestList.Add(new Test() { TestName = "aaa" });
            TestList.Add(new Test() { TestName = "bbb" });
            TestList.Add(new Test() { TestName = "ccc" });
            TestList.Add(new Test() { TestName = "ddd" });
        }
        public ObservableCollection<Test> TestList { get; set; } = new ObservableCollection<Test>();
        public class Test {
            public string TestName { get; set; }
        }
    }
}
</code>```

The project above will cross-platform running both in android and WPF.

In android:

When the item is hovered, there is not any style for true.

When the item is selected, it will change the color into orange and I can change it by changing the background of the Label.

Well, in WPF:

When selected or hovered the item, it will show a blue rectangle that I don't need.

I don't want to show the blue rectangle while selected or hovered the item in WPF, that's why I ask the question.

I probably know I should set some property in the WPF program while I don't know which property I should set it.

Would you please help me? Thank you.

答:
You could try to use Custom Renderer to achieve this effect.

define ListViewItem style in your App.xaml of WPF project:

```<code><Application.Resources>
    <Style x:Key="LvItemStyle" TargetType="ListViewItem">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListViewItem">
                    <Border x:Name="border" Background="Transparent">
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal" />
                                <VisualState x:Name="Disabled" />
                            </VisualStateGroup>
                            <VisualStateGroup x:Name="SelectionStates">
                                <VisualState x:Name="Unselected" />
                                <VisualState x:Name="Selected">
                                    <Storyboard>
                                        <ColorAnimationUsingKeyFrames Storyboard.TargetName="border"
                                                          Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)">
                                            <EasingColorKeyFrame KeyTime="0" Value="LightBlue" />
                                        </ColorAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="SelectedUnfocused">
                                    <Storyboard>
                                        <ColorAnimationUsingKeyFrames Storyboard.TargetName="border"
                                                          Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)">
                                            <EasingColorKeyFrame KeyTime="0" Value="SkyBlue" />
                                        </ColorAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <ContentPresenter/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Application.Resources>
</code>```

then create custom renderer in Wpf project,MyListView.cs:

```<code>using System.Windows.Controls;
using WpfApp1;
using Xamarin.Forms.Platform.WPF;

[assembly: ExportRenderer(typeof(Xamarin.Forms.ListView), typeof(MyListView))]
namespace WpfApp1
{
   class MyListView:ListViewRenderer
   {
      protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.ListView> e)
      {
          base.OnElementChanged(e);
          foreach (var item in Control.Children)
           {
            if (item is ListView)
             {
                var list = item as ListView;
                list.ItemContainerStyle = App.Current.Resources["LvItemStyle"] as System.Windows.Style;
             }
           }
      }

  }
}
</code>```

Body:
Here is the XAML:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="App1.MainPage">

    <ListView ItemsSource="{Binding TestList}" SeparatorVisibility="None" HasUnevenRows="True">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <ViewCell.View>
                        <ContentView>

                        </ContentView>
                    </ViewCell.View>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>

Here is code-behind:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace App1
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            this.BindingContext = this;
            TestList.Add(new Test() { TestName = "aaa" });
            TestList.Add(new Test() { TestName = "bbb" });
            TestList.Add(new Test() { TestName = "ccc" });
            TestList.Add(new Test() { TestName = "ddd" });
        }
        public ObservableCollection<Test> TestList { get; set; } = new ObservableCollection<Test>();
        public class Test {
            public string TestName { get; set; }
        }
    }
}

The project above will cross-platform running both in android and WPF.

In android:

When the item is hovered, there is not any style for true.

When the item is selected, it will change the color into orange and I can change it by changing the background of the Label.

Well, in WPF:

When selected or hovered the item, it will show a blue rectangle that I don't need.

I don't want to show the blue rectangle while selected or hovered the item in WPF, that's why I ask the question.

I probably know I should set some property in the WPF program while I don't know which property I should set it.

Would you please help me? Thank you.

Body:
You could try to use Custom Renderer to achieve this effect.

define ListViewItem style in your App.xaml of WPF project:

<Application.Resources>
    <Style x:Key="LvItemStyle" TargetType="ListViewItem">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListViewItem">
                    <Border x:Name="border" Background="Transparent">
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal" />
                                <VisualState x:Name="Disabled" />
                            </VisualStateGroup>
                            <VisualStateGroup x:Name="SelectionStates">
                                <VisualState x:Name="Unselected" />
                                <VisualState x:Name="Selected">
                                    <Storyboard>
                                        <ColorAnimationUsingKeyFrames Storyboard.TargetName="border"
                                                          Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)">
                                            <EasingColorKeyFrame KeyTime="0" Value="LightBlue" />
                                        </ColorAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="SelectedUnfocused">
                                    <Storyboard>
                                        <ColorAnimationUsingKeyFrames Storyboard.TargetName="border"
                                                          Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)">
                                            <EasingColorKeyFrame KeyTime="0" Value="SkyBlue" />
                                        </ColorAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <ContentPresenter/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Application.Resources>

then create custom renderer in Wpf project,MyListView.cs:

using System.Windows.Controls;
using WpfApp1;
using Xamarin.Forms.Platform.WPF;

[assembly: ExportRenderer(typeof(Xamarin.Forms.ListView), typeof(MyListView))]
namespace WpfApp1
{
   class MyListView:ListViewRenderer
   {
      protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.ListView> e)
      {
          base.OnElementChanged(e);
          foreach (var item in Control.Children)
           {
            if (item is ListView)
             {
                var list = item as ListView;
                list.ItemContainerStyle = App.Current.Resources["LvItemStyle"] as System.Windows.Style;
             }
           }
      }

  }
}