问:
Not implemented exception was unhandled by user code
Everytime I try to print the error shows up.
it says "Not implemented exception was unhandled by user code".
how to fix this sh!t?
here's my code

```<code>namespace RunwayMedlinc
{
public partial class patient : Form
{
    Print print;
    MySqlConnection con;
    String sql;
    MySqlCommand cmd;
    MySqlDataAdapter data, data2, data3;
    DataTable table = new DataTable();
    DataTable table2 = new DataTable();
    DataTable table3 = new DataTable();
    DataSet da = new DataSet();
    int age;

    public patient()
    {
        InitializeComponent();
    }

    public void view()
    {
    try
        {
            sql = "select p.mrn AS 'MRN', pp.name AS 'PATIENT NAME', pp.bday AS 'BIRTHDAY', p.age AS 'AGE', pp.gender AS 'GENDER',  p.admit AS 'ADMIT DATE', p.discharge AS 'DISCHARGE DATE', p.md AS 'PHYSICIAN'FROM p inner join pp ON p.mrn=pp.mrn where admit like'%" + year.Text + "%' and admit like'%" + month.Text + "%'";
            cmd = new MySqlCommand(sql, con);
            data.SelectCommand = cmd;
            pview.DataSource = table;
            table.Clear();
            data.Fill(table);
            pview.DataSource = table;
        }
        catch (Exception exx)
        {
            MessageBox.Show(exx.Message, "Error");
        }
    }

    public void bew()
    {
        try
        {
            sql = "select p.mrn AS 'MRN', pp.name AS 'PATIENT NAME', pp.bday AS 'BIRTHDAY', p.age AS 'AGE', pp.gender AS 'GENDER',  p.admit AS 'ADMIT DATE', p.discharge AS 'DISCHARGE DATE', p.md AS 'PHYSICIAN'FROM p inner join pp ON p.mrn=pp.mrn where admit like'%" + year2.Text + "%' and admit like'%" + month2.Text + "%'";
            cmd = new MySqlCommand(sql, con);
            data2.SelectCommand = cmd;
            pview2.DataSource = table2;
            table2.Clear();
            data2.Fill(table2);
        }
        catch (Exception exx)
        {
            MessageBox.Show(exx.Message, "Error");
        }
    }

    private void search_Enter(object sender, EventArgs e)
    {
        if (search.ForeColor == Color.Gray)
        {
            search.Clear();
            search.ForeColor = Color.Black;
        }
    }

    private void search_Leave(object sender, EventArgs e)
    {
        if (search.Text == "")
        {
            search.ForeColor = Color.Gray;
            search.Text = "SEARCH PATIENT...";
        }
    }

    private void search2_Enter(object sender, EventArgs e)
    {
        if (search2.ForeColor == Color.Gray)
        {
            search2.Clear();
            search2.ForeColor = Color.Black;
        }
    }

    private void search2_Leave(object sender, EventArgs e)
    {
        if (search2.Text == "")
        {
            search2.ForeColor = Color.Gray;
            search2.Text = "SEARCH PATIENT...";
        }
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        time.Text = DateTime.Now.ToString("h:mm:ss tt");
        date.Text = DateTime.Now.ToString("MMMM d, yyyy");
    }

    private void patient_Load(object sender, EventArgs e)
    {
        con = new MySqlConnection();
        con.ConnectionString = "server=Localhost;" + "username=root;" + "password=;" + "database=runway";
        con.Open();
        sql = "select mrn from p";
        cmd = new MySqlCommand(sql, con);
        data = new MySqlDataAdapter();
        data2 = new MySqlDataAdapter();

        month.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
        year.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));

        month2.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
        year2.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));

        view();

        bew();
    }

    private void clear_Click(object sender, EventArgs e)
    {
        mrn.Clear();
        name.Clear();
        phy.Clear();
        m.Checked = false;
        f.Checked = false;
        bdate.Value = DateTime.Now;
        admit.Value = DateTime.Now;
        disch.Value = DateTime.Now;

        add.Enabled = true;
        mrn.ReadOnly = false;
        name.ReadOnly = false;
        phy.ReadOnly = false;
        m.Enabled = true;
        f.Enabled = true;
        bdate.Enabled = true;
        admit.Enabled = true;
    }

    private void phy_Enter(object sender, EventArgs e)
    {
        if (phy.ReadOnly == false)
        {
            phy.Clear();
        }
    }

    private void add_Click(object sender, EventArgs e)
    {
        if (mrn.Text == "" || name.Text == "" || (m.Checked == false && f.Checked == false))
        {
            MessageBox.Show("Please fill out all information.", "", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }
        else
        {
                DateTime x = admit.Value;
                DateTime y = bdate.Value;
                if (x.Month < y.Month || (x.Month == y.Month && x.Day < y.Day))
                {
                    age = x.Year - y.Year - 1;
                }
                else
                {
                    age = x.Year - y.Year;
                }

                if (m.Checked == true)
                {
                    if (name.ReadOnly == false)
                    {
                        sql = "insert into pp(mrn, name, gender, bday)values (?a, ?b, ?c, ?d)";
                        cmd = new MySqlCommand(sql, con);

                        cmd.Parameters.AddWithValue("?a", mrn.Text);
                        cmd.Parameters.AddWithValue("?b", name.Text);
                        cmd.Parameters.AddWithValue("?c", m.Text);
                        cmd.Parameters.AddWithValue("?d", bdate.Text);
                        cmd.ExecuteNonQuery();
                    }
                }

                if (f.Checked == true)
                {
                    if (name.ReadOnly == false)
                    {
                        sql = "insert into pp(mrn, name, gender, bday)values (?a, ?b, ?c, ?d)";
                        cmd = new MySqlCommand(sql, con);

                        cmd.Parameters.AddWithValue("?a", mrn.Text);
                        cmd.Parameters.AddWithValue("?b", name.Text);
                        cmd.Parameters.AddWithValue("?c", f.Text);
                        cmd.Parameters.AddWithValue("?d", bdate.Text);
                        cmd.ExecuteNonQuery();
                    }
                }

                sql = "insert into p(mrn, admit, discharge, md, age)values (?a, ?e, ?f, ?g, ?z)";
                cmd = new MySqlCommand(sql, con);

                cmd.Parameters.AddWithValue("?a", mrn.Text);
                cmd.Parameters.AddWithValue("?e", admit.Text);
                cmd.Parameters.AddWithValue("?f", null);
                cmd.Parameters.AddWithValue("?g", phy.Text);
                cmd.Parameters.AddWithValue("?z", age);
                cmd.ExecuteNonQuery();
                MessageBox.Show("Patient Successfully Added!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);

                mrn.Clear();
                name.Clear();
                phy.Text = "MANGASEP, CONCEPCION R.";
                m.Checked = false;
                f.Checked = false;
                bdate.Value = DateTime.Now;
                admit.Value = DateTime.Now;
                disch.Value = DateTime.Now;

                month2.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
                year2.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));
                bew();

        }
    }

    private void search_TextChanged(object sender, EventArgs e)
    {
        if (search.ForeColor != Color.Gray)
        {
            try
            {
                sql = "select p.mrn AS 'MRN', pp.name AS 'PATIENT NAME', pp.bday AS 'BIRTHDAY', p.age AS 'AGE', pp.gender AS 'GENDER',  p.admit AS 'ADMIT DATE', p.discharge AS 'DISCHARGE DATE', p.md AS 'PHYSICIAN'FROM p inner join pp ON p.mrn=pp.mrn where admit like'%" + year.Text + "%' and admit like'%" + month.Text + "%' and name like'%" + search.Text + "%'";
                cmd = new MySqlCommand(sql, con);
                data.SelectCommand = cmd;
                pview.DataSource = table;
                table.Clear();
                data.Fill(table);
            }
            catch (Exception exx)
            {
                MessageBox.Show(exx.Message, "Error");
            }
        }
    }

    private void search2_TextChanged(object sender, EventArgs e)
    {
        if (search2.ForeColor != Color.Gray)
        {
            try
            {
                sql = "select p.mrn AS 'MRN', pp.name AS 'PATIENT NAME', pp.bday AS 'BIRTHDAY', p.age AS 'AGE', pp.gender AS 'GENDER',  p.admit AS 'ADMIT DATE', p.discharge AS 'DISCHARGE DATE', p.md AS 'PHYSICIAN'FROM p inner join pp ON p.mrn=pp.mrn where admit like'%" + year2.Text + "%' and admit like'%" + month2.Text + "%' and name like'%" + search2.Text + "%'";
                cmd = new MySqlCommand(sql, con);
                data2.SelectCommand = cmd;
                pview2.DataSource = table2;
                table2.Clear();
                data2.Fill(table2);
            }
            catch (Exception exx)
            {
                MessageBox.Show(exx.Message, "Error");
            }
        }
    }

    private void pview2_Click(object sender, EventArgs e)
    {
        mrn.Text = pview2.SelectedRows[0].Cells[0].Value.ToString();
        name.Text = pview2.SelectedRows[0].Cells[1].Value.ToString();
        if (pview2.SelectedRows[0].Cells[4].Value.ToString() == "MALE")
        {
            m.Checked = true;
        }
        else
        {
            f.Checked = true;
        }
        bdate.Text = pview2.SelectedRows[0].Cells[2].Value.ToString();
        admit.Text = pview2.SelectedRows[0].Cells[5].Value.ToString();
        phy.Text = pview2.SelectedRows[0].Cells[7].Value.ToString();

        add.Enabled = false;
        mrn.ReadOnly = true;
        name.ReadOnly = true;
        phy.ReadOnly = true;
        m.Enabled = false;
        f.Enabled = false;
        bdate.Enabled = false;
        admit.Enabled = false;
    }

    private void update_Click(object sender, EventArgs e)
    {
        sql = "Update p set discharge= '" + disch.Text + "' where mrn = '" + mrn.Text + "'";
        cmd = new MySqlCommand(sql, con);
        cmd.ExecuteNonQuery();
        MessageBox.Show("Patient Successfuly Updated!");

        add.Enabled = true;
        mrn.Clear();
        mrn.ReadOnly = false;
        name.Clear();
        name.ReadOnly = false;
        phy.Text = "MANGASEP, CONCEPCION R.";
        phy.ReadOnly = false;
        m.Checked = false;
        f.Checked = false;
        bdate.Value = DateTime.Now;
        admit.Value = DateTime.Now;
        disch.Value = DateTime.Now;

        month2.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
        year2.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));
        bew();
    }

    private void mrn_TextChanged(object sender, EventArgs e)
    {
        sql = "Select name, gender, bday from pp where mrn = '" + mrn.Text + "'";
        cmd = new MySqlCommand(sql, con);
        data3 = new MySqlDataAdapter();
        data3.SelectCommand = cmd;
        table3 = new DataTable();
        data3.Fill(table3);

        if (table3.Rows.Count > 0)
        {
            name.Text = Convert.ToString(table3.Rows[0][0]);
            if (Convert.ToString(table3.Rows[0][1]) == "MALE")
            {
                m.Checked = true; ;
            }
            else
            {
                f.Checked = true;
            }
            bdate.Value = Convert.ToDateTime(table3.Rows[0][2]);
            name.ReadOnly = true;
            m.Enabled = false;
            f.Enabled = false;
            bdate.Enabled = false;

        }
        else
        {
            name.Clear();
            m.Checked = false;
            f.Checked = false;
            bdate.Value = DateTime.Now;
            name.ReadOnly = false;
            m.Enabled = true;
            f.Enabled = true;
            bdate.Enabled = true;
        }
    }

    private void year_SelectedIndexChanged(object sender, EventArgs e)
    {
        view();
    }

    private void month_SelectedIndexChanged(object sender, EventArgs e)
    {
        view();
    }

    private void mrn_KeyPress(object sender, KeyPressEventArgs e)
    {

        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
            (e.KeyChar != '.'))
        {
            e.Handled = true;
        }

        if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
        {
            e.Handled = true;
        }
    }

    private void TabControl1_SelectedIndexChanged(object sender, EventArgs e)
    {
        month.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
        year.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));

        month2.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
        year2.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));
        search.ForeColor = Color.Gray;
        search.Text = "SEARCH PATIENT...";
        search2.ForeColor = Color.Gray;
        search2.Text = "SEARCH PATIENT...";
        mrn.Clear();
        name.Clear();
        phy.Text = "MANGASEP, CONCEPCION R.";
        m.Checked = false;
        f.Checked = false;
        bdate.Value = DateTime.Now;
        admit.Value = DateTime.Now;
        disch.Value = DateTime.Now;
    }

    private void month2_SelectedIndexChanged(object sender, EventArgs e)
    {
        bew();
    }

    private void year2_SelectedIndexChanged(object sender, EventArgs e)
    {
        bew();
    }

    private bool SetupThePrinting()
     {
         PrintDialog MyPrintDialog = new PrintDialog();
         MyPrintDialog.AllowCurrentPage = false;
         MyPrintDialog.AllowPrintToFile = false;
         MyPrintDialog.AllowSelection = false;
         MyPrintDialog.AllowSomePages = false;
         MyPrintDialog.PrintToFile = false;
         MyPrintDialog.ShowHelp = false;
         MyPrintDialog.ShowNetwork = false;
         if (MyPrintDialog.ShowDialog() != DialogResult.OK)
         return false;
         dokumento.DocumentName = "List of Patients";
         dokumento.PrinterSettings = MyPrintDialog.PrinterSettings;
         dokumento.DefaultPageSettings = MyPrintDialog.PrinterSettings.DefaultPageSettings;
         dokumento.DefaultPageSettings.Landscape = false;
         dokumento.DefaultPageSettings.Margins = new System.Drawing.Printing.Margins(10, 10, 10, 10);
         dokumento.DefaultPageSettings.Landscape = MyPrintDialog.PrinterSettings.DefaultPageSettings.Landscape;
         print = new Print(pview, dokumento, true, true, Environment.NewLine + "" + Environment.NewLine + "" + "Runway Medlinc"  + Environment.NewLine + "" + Environment.NewLine + "List of Patients"
         + Environment.NewLine + "" + Environment.NewLine + month.Text + "  " + year.Text, new Font("Times New Roman", 12, FontStyle.Bold, GraphicsUnit.Point), Color.Black, true);
         return true;
     }

    private void printer_Click(object sender, EventArgs e)
       {
           if (SetupThePrinting())
           {
               PrintPreviewDialog MyPrintPreviewDialog = new PrintPreviewDialog();
               MyPrintPreviewDialog.Document = dokumento;
               MyPrintPreviewDialog.ShowDialog();
               dokumento.Print();
           }
       }

    private void dokumento_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
      {
          bool more = print.DrawDataGridView(e.Graphics);
          if (more == true)
          e.HasMorePages = true;
     }

}
}
</code>```

Everytime I try to print the error shows up.
it says "Not implemented exception was unhandled by user code".
how to fix this sh!t?
and the other class is here

```<code>namespace RunwayMedlinc
{
class Print
{
    private System.Windows.Forms.DataGridView pview;
    private System.Drawing.Printing.PrintDocument dokumento;
    private bool p;
    private bool p_2;
    private string p_3;
    private System.Drawing.Font font;
    private System.Drawing.Color color;
    private bool p_4;

    public Print(System.Windows.Forms.DataGridView pview, System.Drawing.Printing.PrintDocument dokumento, bool p, bool p_2, string p_3, System.Drawing.Font font, System.Drawing.Color color, bool p_4)
    {
        this.pview = pview;
        this.dokumento = dokumento;
        this.p = p;
        this.p_2 = p_2;
        this.p_3 = p_3;
        this.font = font;
        this.color = color;
        this.p_4 = p_4;
    }

    internal bool DrawDataGridView(System.Drawing.Graphics graphics)
    {
        throw new NotImplementedException();
    }
}
}
</code>```

答:
The PrintDocument, by itself, has no way of knowing what it is you want to print. You've told it the formatting, but not the content.

The way to tell it is to draw the document, using the System.Drawing namespace mostly, using the Graphics property of the event as the output device. The output device is a printer driver which will translate your lines, text, etc. into the appropriate code for rendering on your specific printer, e.g. Postscript, PCL, whatever. That doesn't matter to you. You just need to output text, lines, and images in a virtual two-dimensional space.

So

Put those methods back

Implement DrawDataGridView !!! Just do something simple for now so you know that it works, like

```<code>internal bool DrawDataGridView(System.Drawing.Graphics graphics)
{
    graphics.DrawString("Hello world!");
}
</code>```

Once you have that working, next you'll have to figure out how to render the contents of the document properly. But that could be another SO question.

Body:
Everytime I try to print the error shows up.
it says "Not implemented exception was unhandled by user code".
how to fix this sh!t?
here's my code

namespace RunwayMedlinc
{
public partial class patient : Form
{
    Print print;
    MySqlConnection con;
    String sql;
    MySqlCommand cmd;
    MySqlDataAdapter data, data2, data3;
    DataTable table = new DataTable();
    DataTable table2 = new DataTable();
    DataTable table3 = new DataTable();
    DataSet da = new DataSet();
    int age;

    public patient()
    {
        InitializeComponent();
    }

    public void view()
    {
    try
        {
            sql = "select p.mrn AS 'MRN', pp.name AS 'PATIENT NAME', pp.bday AS 'BIRTHDAY', p.age AS 'AGE', pp.gender AS 'GENDER',  p.admit AS 'ADMIT DATE', p.discharge AS 'DISCHARGE DATE', p.md AS 'PHYSICIAN'FROM p inner join pp ON p.mrn=pp.mrn where admit like'%" + year.Text + "%' and admit like'%" + month.Text + "%'";
            cmd = new MySqlCommand(sql, con);
            data.SelectCommand = cmd;
            pview.DataSource = table;
            table.Clear();
            data.Fill(table);
            pview.DataSource = table;
        }
        catch (Exception exx)
        {
            MessageBox.Show(exx.Message, "Error");
        }
    }

    public void bew()
    {
        try
        {
            sql = "select p.mrn AS 'MRN', pp.name AS 'PATIENT NAME', pp.bday AS 'BIRTHDAY', p.age AS 'AGE', pp.gender AS 'GENDER',  p.admit AS 'ADMIT DATE', p.discharge AS 'DISCHARGE DATE', p.md AS 'PHYSICIAN'FROM p inner join pp ON p.mrn=pp.mrn where admit like'%" + year2.Text + "%' and admit like'%" + month2.Text + "%'";
            cmd = new MySqlCommand(sql, con);
            data2.SelectCommand = cmd;
            pview2.DataSource = table2;
            table2.Clear();
            data2.Fill(table2);
        }
        catch (Exception exx)
        {
            MessageBox.Show(exx.Message, "Error");
        }
    }

    private void search_Enter(object sender, EventArgs e)
    {
        if (search.ForeColor == Color.Gray)
        {
            search.Clear();
            search.ForeColor = Color.Black;
        }
    }

    private void search_Leave(object sender, EventArgs e)
    {
        if (search.Text == "")
        {
            search.ForeColor = Color.Gray;
            search.Text = "SEARCH PATIENT...";
        }
    }

    private void search2_Enter(object sender, EventArgs e)
    {
        if (search2.ForeColor == Color.Gray)
        {
            search2.Clear();
            search2.ForeColor = Color.Black;
        }
    }

    private void search2_Leave(object sender, EventArgs e)
    {
        if (search2.Text == "")
        {
            search2.ForeColor = Color.Gray;
            search2.Text = "SEARCH PATIENT...";
        }
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        time.Text = DateTime.Now.ToString("h:mm:ss tt");
        date.Text = DateTime.Now.ToString("MMMM d, yyyy");
    }

    private void patient_Load(object sender, EventArgs e)
    {
        con = new MySqlConnection();
        con.ConnectionString = "server=Localhost;" + "username=root;" + "password=;" + "database=runway";
        con.Open();
        sql = "select mrn from p";
        cmd = new MySqlCommand(sql, con);
        data = new MySqlDataAdapter();
        data2 = new MySqlDataAdapter();

        month.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
        year.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));

        month2.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
        year2.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));

        view();

        bew();
    }

    private void clear_Click(object sender, EventArgs e)
    {
        mrn.Clear();
        name.Clear();
        phy.Clear();
        m.Checked = false;
        f.Checked = false;
        bdate.Value = DateTime.Now;
        admit.Value = DateTime.Now;
        disch.Value = DateTime.Now;

        add.Enabled = true;
        mrn.ReadOnly = false;
        name.ReadOnly = false;
        phy.ReadOnly = false;
        m.Enabled = true;
        f.Enabled = true;
        bdate.Enabled = true;
        admit.Enabled = true;
    }

    private void phy_Enter(object sender, EventArgs e)
    {
        if (phy.ReadOnly == false)
        {
            phy.Clear();
        }
    }

    private void add_Click(object sender, EventArgs e)
    {
        if (mrn.Text == "" || name.Text == "" || (m.Checked == false && f.Checked == false))
        {
            MessageBox.Show("Please fill out all information.", "", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }
        else
        {
                DateTime x = admit.Value;
                DateTime y = bdate.Value;
                if (x.Month < y.Month || (x.Month == y.Month && x.Day < y.Day))
                {
                    age = x.Year - y.Year - 1;
                }
                else
                {
                    age = x.Year - y.Year;
                }

                if (m.Checked == true)
                {
                    if (name.ReadOnly == false)
                    {
                        sql = "insert into pp(mrn, name, gender, bday)values (?a, ?b, ?c, ?d)";
                        cmd = new MySqlCommand(sql, con);

                        cmd.Parameters.AddWithValue("?a", mrn.Text);
                        cmd.Parameters.AddWithValue("?b", name.Text);
                        cmd.Parameters.AddWithValue("?c", m.Text);
                        cmd.Parameters.AddWithValue("?d", bdate.Text);
                        cmd.ExecuteNonQuery();
                    }
                }

                if (f.Checked == true)
                {
                    if (name.ReadOnly == false)
                    {
                        sql = "insert into pp(mrn, name, gender, bday)values (?a, ?b, ?c, ?d)";
                        cmd = new MySqlCommand(sql, con);

                        cmd.Parameters.AddWithValue("?a", mrn.Text);
                        cmd.Parameters.AddWithValue("?b", name.Text);
                        cmd.Parameters.AddWithValue("?c", f.Text);
                        cmd.Parameters.AddWithValue("?d", bdate.Text);
                        cmd.ExecuteNonQuery();
                    }
                }

                sql = "insert into p(mrn, admit, discharge, md, age)values (?a, ?e, ?f, ?g, ?z)";
                cmd = new MySqlCommand(sql, con);

                cmd.Parameters.AddWithValue("?a", mrn.Text);
                cmd.Parameters.AddWithValue("?e", admit.Text);
                cmd.Parameters.AddWithValue("?f", null);
                cmd.Parameters.AddWithValue("?g", phy.Text);
                cmd.Parameters.AddWithValue("?z", age);
                cmd.ExecuteNonQuery();
                MessageBox.Show("Patient Successfully Added!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);

                mrn.Clear();
                name.Clear();
                phy.Text = "MANGASEP, CONCEPCION R.";
                m.Checked = false;
                f.Checked = false;
                bdate.Value = DateTime.Now;
                admit.Value = DateTime.Now;
                disch.Value = DateTime.Now;

                month2.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
                year2.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));
                bew();

        }
    }

    private void search_TextChanged(object sender, EventArgs e)
    {
        if (search.ForeColor != Color.Gray)
        {
            try
            {
                sql = "select p.mrn AS 'MRN', pp.name AS 'PATIENT NAME', pp.bday AS 'BIRTHDAY', p.age AS 'AGE', pp.gender AS 'GENDER',  p.admit AS 'ADMIT DATE', p.discharge AS 'DISCHARGE DATE', p.md AS 'PHYSICIAN'FROM p inner join pp ON p.mrn=pp.mrn where admit like'%" + year.Text + "%' and admit like'%" + month.Text + "%' and name like'%" + search.Text + "%'";
                cmd = new MySqlCommand(sql, con);
                data.SelectCommand = cmd;
                pview.DataSource = table;
                table.Clear();
                data.Fill(table);
            }
            catch (Exception exx)
            {
                MessageBox.Show(exx.Message, "Error");
            }
        }
    }

    private void search2_TextChanged(object sender, EventArgs e)
    {
        if (search2.ForeColor != Color.Gray)
        {
            try
            {
                sql = "select p.mrn AS 'MRN', pp.name AS 'PATIENT NAME', pp.bday AS 'BIRTHDAY', p.age AS 'AGE', pp.gender AS 'GENDER',  p.admit AS 'ADMIT DATE', p.discharge AS 'DISCHARGE DATE', p.md AS 'PHYSICIAN'FROM p inner join pp ON p.mrn=pp.mrn where admit like'%" + year2.Text + "%' and admit like'%" + month2.Text + "%' and name like'%" + search2.Text + "%'";
                cmd = new MySqlCommand(sql, con);
                data2.SelectCommand = cmd;
                pview2.DataSource = table2;
                table2.Clear();
                data2.Fill(table2);
            }
            catch (Exception exx)
            {
                MessageBox.Show(exx.Message, "Error");
            }
        }
    }

    private void pview2_Click(object sender, EventArgs e)
    {
        mrn.Text = pview2.SelectedRows[0].Cells[0].Value.ToString();
        name.Text = pview2.SelectedRows[0].Cells[1].Value.ToString();
        if (pview2.SelectedRows[0].Cells[4].Value.ToString() == "MALE")
        {
            m.Checked = true;
        }
        else
        {
            f.Checked = true;
        }
        bdate.Text = pview2.SelectedRows[0].Cells[2].Value.ToString();
        admit.Text = pview2.SelectedRows[0].Cells[5].Value.ToString();
        phy.Text = pview2.SelectedRows[0].Cells[7].Value.ToString();

        add.Enabled = false;
        mrn.ReadOnly = true;
        name.ReadOnly = true;
        phy.ReadOnly = true;
        m.Enabled = false;
        f.Enabled = false;
        bdate.Enabled = false;
        admit.Enabled = false;
    }

    private void update_Click(object sender, EventArgs e)
    {
        sql = "Update p set discharge= '" + disch.Text + "' where mrn = '" + mrn.Text + "'";
        cmd = new MySqlCommand(sql, con);
        cmd.ExecuteNonQuery();
        MessageBox.Show("Patient Successfuly Updated!");

        add.Enabled = true;
        mrn.Clear();
        mrn.ReadOnly = false;
        name.Clear();
        name.ReadOnly = false;
        phy.Text = "MANGASEP, CONCEPCION R.";
        phy.ReadOnly = false;
        m.Checked = false;
        f.Checked = false;
        bdate.Value = DateTime.Now;
        admit.Value = DateTime.Now;
        disch.Value = DateTime.Now;

        month2.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
        year2.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));
        bew();
    }

    private void mrn_TextChanged(object sender, EventArgs e)
    {
        sql = "Select name, gender, bday from pp where mrn = '" + mrn.Text + "'";
        cmd = new MySqlCommand(sql, con);
        data3 = new MySqlDataAdapter();
        data3.SelectCommand = cmd;
        table3 = new DataTable();
        data3.Fill(table3);

        if (table3.Rows.Count > 0)
        {
            name.Text = Convert.ToString(table3.Rows[0][0]);
            if (Convert.ToString(table3.Rows[0][1]) == "MALE")
            {
                m.Checked = true; ;
            }
            else
            {
                f.Checked = true;
            }
            bdate.Value = Convert.ToDateTime(table3.Rows[0][2]);
            name.ReadOnly = true;
            m.Enabled = false;
            f.Enabled = false;
            bdate.Enabled = false;

        }
        else
        {
            name.Clear();
            m.Checked = false;
            f.Checked = false;
            bdate.Value = DateTime.Now;
            name.ReadOnly = false;
            m.Enabled = true;
            f.Enabled = true;
            bdate.Enabled = true;
        }
    }

    private void year_SelectedIndexChanged(object sender, EventArgs e)
    {
        view();
    }

    private void month_SelectedIndexChanged(object sender, EventArgs e)
    {
        view();
    }

    private void mrn_KeyPress(object sender, KeyPressEventArgs e)
    {

        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
            (e.KeyChar != '.'))
        {
            e.Handled = true;
        }

        if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
        {
            e.Handled = true;
        }
    }

    private void TabControl1_SelectedIndexChanged(object sender, EventArgs e)
    {
        month.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
        year.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));

        month2.Text = Convert.ToString(DateTime.Now.ToString("MMMM"));
        year2.Text = Convert.ToString(DateTime.Now.ToString("yyyy"));
        search.ForeColor = Color.Gray;
        search.Text = "SEARCH PATIENT...";
        search2.ForeColor = Color.Gray;
        search2.Text = "SEARCH PATIENT...";
        mrn.Clear();
        name.Clear();
        phy.Text = "MANGASEP, CONCEPCION R.";
        m.Checked = false;
        f.Checked = false;
        bdate.Value = DateTime.Now;
        admit.Value = DateTime.Now;
        disch.Value = DateTime.Now;
    }

    private void month2_SelectedIndexChanged(object sender, EventArgs e)
    {
        bew();
    }

    private void year2_SelectedIndexChanged(object sender, EventArgs e)
    {
        bew();
    }

    private bool SetupThePrinting()
     {
         PrintDialog MyPrintDialog = new PrintDialog();
         MyPrintDialog.AllowCurrentPage = false;
         MyPrintDialog.AllowPrintToFile = false;
         MyPrintDialog.AllowSelection = false;
         MyPrintDialog.AllowSomePages = false;
         MyPrintDialog.PrintToFile = false;
         MyPrintDialog.ShowHelp = false;
         MyPrintDialog.ShowNetwork = false;
         if (MyPrintDialog.ShowDialog() != DialogResult.OK)
         return false;
         dokumento.DocumentName = "List of Patients";
         dokumento.PrinterSettings = MyPrintDialog.PrinterSettings;
         dokumento.DefaultPageSettings = MyPrintDialog.PrinterSettings.DefaultPageSettings;
         dokumento.DefaultPageSettings.Landscape = false;
         dokumento.DefaultPageSettings.Margins = new System.Drawing.Printing.Margins(10, 10, 10, 10);
         dokumento.DefaultPageSettings.Landscape = MyPrintDialog.PrinterSettings.DefaultPageSettings.Landscape;
         print = new Print(pview, dokumento, true, true, Environment.NewLine + "" + Environment.NewLine + "" + "Runway Medlinc"  + Environment.NewLine + "" + Environment.NewLine + "List of Patients"
         + Environment.NewLine + "" + Environment.NewLine + month.Text + "  " + year.Text, new Font("Times New Roman", 12, FontStyle.Bold, GraphicsUnit.Point), Color.Black, true);
         return true;
     }

    private void printer_Click(object sender, EventArgs e)
       {
           if (SetupThePrinting())
           {
               PrintPreviewDialog MyPrintPreviewDialog = new PrintPreviewDialog();
               MyPrintPreviewDialog.Document = dokumento;
               MyPrintPreviewDialog.ShowDialog();
               dokumento.Print();
           }
       }

    private void dokumento_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
      {
          bool more = print.DrawDataGridView(e.Graphics);
          if (more == true)
          e.HasMorePages = true;
     }

}
}

Everytime I try to print the error shows up.
it says "Not implemented exception was unhandled by user code".
how to fix this sh!t?
and the other class is here

namespace RunwayMedlinc
{
class Print
{
    private System.Windows.Forms.DataGridView pview;
    private System.Drawing.Printing.PrintDocument dokumento;
    private bool p;
    private bool p_2;
    private string p_3;
    private System.Drawing.Font font;
    private System.Drawing.Color color;
    private bool p_4;

    public Print(System.Windows.Forms.DataGridView pview, System.Drawing.Printing.PrintDocument dokumento, bool p, bool p_2, string p_3, System.Drawing.Font font, System.Drawing.Color color, bool p_4)
    {
        this.pview = pview;
        this.dokumento = dokumento;
        this.p = p;
        this.p_2 = p_2;
        this.p_3 = p_3;
        this.font = font;
        this.color = color;
        this.p_4 = p_4;
    }

    internal bool DrawDataGridView(System.Drawing.Graphics graphics)
    {
        throw new NotImplementedException();
    }
}
}

Body:
The PrintDocument, by itself, has no way of knowing what it is you want to print. You've told it the formatting, but not the content.

The way to tell it is to draw the document, using the System.Drawing namespace mostly, using the Graphics property of the event as the output device. The output device is a printer driver which will translate your lines, text, etc. into the appropriate code for rendering on your specific printer, e.g. Postscript, PCL, whatever. That doesn't matter to you. You just need to output text, lines, and images in a virtual two-dimensional space.

So

Put those methods back

Implement DrawDataGridView !!! Just do something simple for now so you know that it works, like

internal bool DrawDataGridView(System.Drawing.Graphics graphics)
{
    graphics.DrawString("Hello world!");
}

Once you have that working, next you'll have to figure out how to render the contents of the document properly. But that could be another SO question.


来源: stackexchange

问:
Moving a star marker along a hexagon trajectory?
I want to move a star marker along hexagon trajectory similar to "Circle trajectory" that I have added at the end of my question. Thanks.

This is the source code to that I have written yet for creating concentric hegzagons but I don't know how to move a star marker which traverses the concentric hexagons, I had written a similar simulation code for circle trajectory but I couldn't do it for hexagon.

```<code>%clc;    % Clear the command window.
%close all;  % Close all figures (except those of imtool.)
%clear;  % Erase all existing variables. Or clearvars if you want.
workspace;  % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
angles = linspace(0, 360, 7);
radii = [20, 35, 50,70];
% First create and draw the hexagons.
numberOfHexagons = 4;
% Define x and y arrays.  Each row is one hexagon.
% Columns are the vertices.

x1=radii(1) * cosd(angles)+50;
y1 = radii(1) * sind(angles)+50;
x2=radii(2) * cosd(angles)+50;
y2 = radii(2) * sind(angles)+50;
x3=radii(3) * cosd(angles)+50;
y3 = radii(3) * sind(angles)+50;
 x4=radii(4) * cosd(angles)+50;
y4 = radii(4) * sind(angles)+50;
    plot(x1 , y1, 'b');
    hold on
      plot(x2, y2, 'b');
      hold on
       plot(x3, y3, 'b');
      hold on
       plot(x4, y4, 'b');
      hold on
      % Connecting Line:
plot([70 100], [50 50],'color','b')
    axis([0 100 0 100])
    hold on
</code>```

Circle trajectory:

```<code>% Initialization steps.
format long g;
format compact;
fontSize = 20;
r1 = 50;
r2 = 35;
r3=  20;
xc = 50;
yc = 50;
% Since arclength = radius * (angle in radians),
% (angle in radians) = arclength / radius = 5 / radius.
deltaAngle1 = 5 / r1;
deltaAngle2 = 5 / r2;
deltaAngle3 = 5 / r3;
theta1 = 0 : deltaAngle1 : (2 * pi);
theta2 = 0 : deltaAngle2 : (2 * pi);
theta3 = 0 : deltaAngle3 : (2 * pi);
x1 = r1*cos(theta1) + xc;
y1 = r1*sin(theta1) + yc;
x2 = r2*cos(theta2) + xc;
y2 = r2*sin(theta2) + yc;
x3 = r3*cos(theta3) + xc;
y3 = r3*sin(theta3) + yc;
plot(x1,y1,'color',[1 0.5 0])
hold on
plot(x2,y2,'color',[1 0.5 0])
hold on
plot(x3,y3,'color',[1 0.5 0])
hold on

% Connecting Line:
plot([70 100], [50 50],'color',[1 0.5 0])
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0, 1, 1]);
drawnow;
axis square;
for i = 1 : length(theta1)
    plot(x1(i),y1(i),'r*')
    pause(0.1)
end
for i = 1 : length(theta2)
    plot(x2(i),y2(i),'r*')
    pause(0.1)
end
for i = 1 : length(theta3)
    plot(x3(i),y3(i),'r*')
    pause(0.1)
end
</code>```

答:
I would generalize your problem with parametric function for the trajectory. In it use rotation kernel which you want here few examples in C++/VCL/GDI (sorry I am not Matlab friendly but the equations should be the same in Matlab too) for circle,square and hexagon rotation kernels:

void getpnt_circle(double &x,double &y,double &pi2,double r,double t)   // (x,y) = circle(r,t) t=<0,1>
    {
    pi2=2.0*M_PI;   // circumference(r=1) 6.283185307179586476925286766559
    t*=pi2;
    x=r*cos(t);
    y=r*sin(t);
    }
//---------------------------------------------------------------------------
void getpnt_square(double &x,double &y,double &pi2,double r,double t)   // (x,y) = square(r,t) t=<0,1>
    {
    pi2=8.0;        // circumference(r=1)
    // kernel
    const int n=4;                              // sides
    const double x0[n]={+1.0,+1.0,-1.0,-1.0};   // side start point
    const double y0[n]={-1.0,+1.0,+1.0,-1.0};
    const double dx[n]={ 0.0,-2.0, 0.0,+2.0};   // side tangent
    const double dy[n]={+2.0, 0.0,-2.0, 0.0};

    int ix;
    t-=floor(t);    // t = <0, 1.0)
    t*=n;           // t = <0,n)
    ix=floor(t);    // side of square
    t-=ix;          // distance from side start

    x=r*(x0[ix]+t*dx[ix]);
    y=r*(y0[ix]+t*dy[ix]);
    }
//---------------------------------------------------------------------------
void getpnt_hexagon(double &x,double &y,double &pi2,double r,double t)  // (x,y) = square(r,t) t=<0,1>
    {
    pi2=6.0;        // circumference(r=1)
    // kernel
    const int n=6;                                      // sides
    const double c60=cos(60.0*M_PI/180.0);
    const double s60=sin(60.0*M_PI/180.0);
    const double x0[n]={+1.0,+c60,-c60,-1.0,-c60,+c60}; // side start point
    const double y0[n]={ 0.0,+s60,+s60, 0.0,-s60,-s60};
    const double dx[n]={-c60,-1.0,-c60,+c60,+1.0,+c60}; // side tangent
    const double dy[n]={+s60, 0.0,-s60,-s60, 0.0,+s60};

    int ix;
    t-=floor(t);    // t = <0, 1.0)
    t*=n;           // t = <0,n)
    ix=floor(t);    // side of square
    t-=ix;          // distance from side start

    x=r*(x0[ix]+t*dx[ix]);
    y=r*(y0[ix]+t*dy[ix]);
    }
//---------------------------------------------------------------------------
void TMain::draw()
    {
    if (!_redraw) return;

    // clear buffer
    bmp->Canvas->Brush->Color=clBlack;
    bmp->Canvas->FillRect(TRect(0,0,xs,ys));

    int e;
    double r,t,x,y,c,dr=15.0,dl=15.0;
    int xx,yy,rr=3;
    bmp->Canvas->MoveTo(xs2,ys2);
    bmp->Canvas->Pen->Color=clAqua;
    bmp->Canvas->Brush->Color=clBlue;
    for (r=dr,t=0.0;;)
        {
        // get point from selected kernel
//      getpnt_circle (x,y,c,r,t);
//      getpnt_square (x,y,c,r,t);
        getpnt_hexagon(x,y,c,r,t);
        // render it
        xx=xs2+x;
        yy=ys2+y;
        bmp->Canvas->LineTo(xx,yy);
        bmp->Canvas->Ellipse(xx-rr,yy-rr,xx+rr,yy+rr);
        // update position
        r+=dr*dr/(r*c);
        t+=dl/(r*c); t-=floor(t);
        if (r>=xs2) break;
        if (r>=ys2) break;
        }

    // render backbuffer
    Main->Canvas->Draw(0,0,bmp);
    _redraw=false;
    }
//---------------------------------------------------------------------------
```

You can ignore the VCL/GDI rendering stuff.

xs,ys is full and xs2,ys2 is half resolution of window to scale the plot properly...

dl is distance between markers [pixels]

dr is distance between spiral screws [pixels]

the spiral is sampled with r,t step depending on the actual circumference (that is what the pi2 or c is for). The getpnt_xxxxx function will return x,y coordinate of your shape from parameter t=<0,1> and actual radius r. It also returns the actual value of circumference/r ratio called pi2

Here preview of the 3 kernels used for spiral ...

ContentLicense: CC BY-SA 3.0

Body:
I want to move a star marker along hexagon trajectory similar to "Circle trajectory" that I have added at the end of my question. Thanks.

This is the source code to that I have written yet for creating concentric hegzagons but I don't know how to move a star marker which traverses the concentric hexagons, I had written a similar simulation code for circle trajectory but I couldn't do it for hexagon.

%clc;    % Clear the command window.
%close all;  % Close all figures (except those of imtool.)
%clear;  % Erase all existing variables. Or clearvars if you want.
workspace;  % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
angles = linspace(0, 360, 7);
radii = [20, 35, 50,70];
% First create and draw the hexagons.
numberOfHexagons = 4;
% Define x and y arrays.  Each row is one hexagon.
% Columns are the vertices.

x1=radii(1) * cosd(angles)+50;
y1 = radii(1) * sind(angles)+50;
x2=radii(2) * cosd(angles)+50;
y2 = radii(2) * sind(angles)+50;
x3=radii(3) * cosd(angles)+50;
y3 = radii(3) * sind(angles)+50;
 x4=radii(4) * cosd(angles)+50;
y4 = radii(4) * sind(angles)+50;
    plot(x1 , y1, 'b');
    hold on
      plot(x2, y2, 'b');
      hold on
       plot(x3, y3, 'b');
      hold on
       plot(x4, y4, 'b');
      hold on
      % Connecting Line:
plot([70 100], [50 50],'color','b')
    axis([0 100 0 100])
    hold on

Circle trajectory:

% Initialization steps.
format long g;
format compact;
fontSize = 20;
r1 = 50;
r2 = 35;
r3=  20;
xc = 50;
yc = 50;
% Since arclength = radius * (angle in radians),
% (angle in radians) = arclength / radius = 5 / radius.
deltaAngle1 = 5 / r1;
deltaAngle2 = 5 / r2;
deltaAngle3 = 5 / r3;
theta1 = 0 : deltaAngle1 : (2 * pi);
theta2 = 0 : deltaAngle2 : (2 * pi);
theta3 = 0 : deltaAngle3 : (2 * pi);
x1 = r1*cos(theta1) + xc;
y1 = r1*sin(theta1) + yc;
x2 = r2*cos(theta2) + xc;
y2 = r2*sin(theta2) + yc;
x3 = r3*cos(theta3) + xc;
y3 = r3*sin(theta3) + yc;
plot(x1,y1,'color',[1 0.5 0])
hold on
plot(x2,y2,'color',[1 0.5 0])
hold on
plot(x3,y3,'color',[1 0.5 0])
hold on

% Connecting Line:
plot([70 100], [50 50],'color',[1 0.5 0])
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0, 1, 1]);
drawnow;
axis square;
for i = 1 : length(theta1)
    plot(x1(i),y1(i),'r*')
    pause(0.1)
end
for i = 1 : length(theta2)
    plot(x2(i),y2(i),'r*')
    pause(0.1)
end
for i = 1 : length(theta3)
    plot(x3(i),y3(i),'r*')
    pause(0.1)
end

Body:
I would generalize your problem with parametric function for the trajectory. In it use rotation kernel which you want here few examples in C++/VCL/GDI (sorry I am not Matlab friendly but the equations should be the same in Matlab too) for circle,square and hexagon rotation kernels:

void getpnt_circle(double &x,double &y,double &pi2,double r,double t)   // (x,y) = circle(r,t) t=<0,1>
    {
    pi2=2.0*M_PI;   // circumference(r=1) 6.283185307179586476925286766559
    t*=pi2;
    x=r*cos(t);
    y=r*sin(t);
    }
//---------------------------------------------------------------------------
void getpnt_square(double &x,double &y,double &pi2,double r,double t)   // (x,y) = square(r,t) t=<0,1>
    {
    pi2=8.0;        // circumference(r=1)
    // kernel
    const int n=4;                              // sides
    const double x0[n]={+1.0,+1.0,-1.0,-1.0};   // side start point
    const double y0[n]={-1.0,+1.0,+1.0,-1.0};
    const double dx[n]={ 0.0,-2.0, 0.0,+2.0};   // side tangent
    const double dy[n]={+2.0, 0.0,-2.0, 0.0};

    int ix;
    t-=floor(t);    // t = <0, 1.0)
    t*=n;           // t = <0,n)
    ix=floor(t);    // side of square
    t-=ix;          // distance from side start

    x=r*(x0[ix]+t*dx[ix]);
    y=r*(y0[ix]+t*dy[ix]);
    }
//---------------------------------------------------------------------------
void getpnt_hexagon(double &x,double &y,double &pi2,double r,double t)  // (x,y) = square(r,t) t=<0,1>
    {
    pi2=6.0;        // circumference(r=1)
    // kernel
    const int n=6;                                      // sides
    const double c60=cos(60.0*M_PI/180.0);
    const double s60=sin(60.0*M_PI/180.0);
    const double x0[n]={+1.0,+c60,-c60,-1.0,-c60,+c60}; // side start point
    const double y0[n]={ 0.0,+s60,+s60, 0.0,-s60,-s60};
    const double dx[n]={-c60,-1.0,-c60,+c60,+1.0,+c60}; // side tangent
    const double dy[n]={+s60, 0.0,-s60,-s60, 0.0,+s60};

    int ix;
    t-=floor(t);    // t = <0, 1.0)
    t*=n;           // t = <0,n)
    ix=floor(t);    // side of square
    t-=ix;          // distance from side start

    x=r*(x0[ix]+t*dx[ix]);
    y=r*(y0[ix]+t*dy[ix]);
    }
//---------------------------------------------------------------------------
void TMain::draw()
    {
    if (!_redraw) return;

    // clear buffer
    bmp->Canvas->Brush->Color=clBlack;
    bmp->Canvas->FillRect(TRect(0,0,xs,ys));

    int e;
    double r,t,x,y,c,dr=15.0,dl=15.0;
    int xx,yy,rr=3;
    bmp->Canvas->MoveTo(xs2,ys2);
    bmp->Canvas->Pen->Color=clAqua;
    bmp->Canvas->Brush->Color=clBlue;
    for (r=dr,t=0.0;;)
        {
        // get point from selected kernel
//      getpnt_circle (x,y,c,r,t);
//      getpnt_square (x,y,c,r,t);
        getpnt_hexagon(x,y,c,r,t);
        // render it
        xx=xs2+x;
        yy=ys2+y;
        bmp->Canvas->LineTo(xx,yy);
        bmp->Canvas->Ellipse(xx-rr,yy-rr,xx+rr,yy+rr);
        // update position
        r+=dr*dr/(r*c);
        t+=dl/(r*c); t-=floor(t);
        if (r>=xs2) break;
        if (r>=ys2) break;
        }

    // render backbuffer
    Main->Canvas->Draw(0,0,bmp);
    _redraw=false;
    }
//---------------------------------------------------------------------------

You can ignore the VCL/GDI rendering stuff.

xs,ys is full and xs2,ys2 is half resolution of window to scale the plot properly...

dl is distance between markers [pixels]

dr is distance between spiral screws [pixels]

the spiral is sampled with r,t step depending on the actual circumference (that is what the pi2 or c is for). The getpnt_xxxxx function will return x,y coordinate of your shape from parameter t=<0,1> and actual radius r. It also returns the actual value of circumference/r ratio called pi2

Here preview of the 3 kernels used for spiral ...


问:
How to order a list of paragraphs
A have a list:

§ 21 Item

§ 1 Item

§ 13 Item

§ 3 Item

§ 2 Item

I need to order it like this:

§ 1 Item

§ 2 Item

§ 3 Item

§ 13 Item

§ 21 Item

But after

```<code>newList = (from a in list orderby a.Name ascending select a).ToList();
</code>```

I get this:

§ 1 Item

§ 13 Item

§ 2 Item

§ 21 Item

§ 3 Item

How to fix it?

答:
This should work:</p>

```<code>var list = new List<string> {"§ 21 Item", "§ 1 Item", "§ 13 Item", "§ 3 Item", "§ 2 Item"};
var orderedList = (from a in list orderby int.Parse(a.Split(' ')[1]) ascending select a).ToList();
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to order a list of paragraphs

Body:
A have a list:

§ 21 Item

§ 1 Item

§ 13 Item

§ 3 Item

§ 2 Item

I need to order it like this:

§ 1 Item

§ 2 Item

§ 3 Item

§ 13 Item

§ 21 Item

But after

newList = (from a in list orderby a.Name ascending select a).ToList();

I get this:

§ 1 Item

§ 13 Item

§ 2 Item

§ 21 Item

§ 3 Item

How to fix it?

Body:
This should work:

var list = new List<string> {"§ 21 Item", "§ 1 Item", "§ 13 Item", "§ 3 Item", "§ 2 Item"};
var orderedList = (from a in list orderby int.Parse(a.Split(' ')[1]) ascending select a).ToList();


问:
What is the relationship between steps and epochs in TensorFlow?
I am going through TensorFlow get started tutorial. In the tf.contrib.learn example, these are two lines of code:

```<code>input_fn = tf.contrib.learn.io.numpy_input_fn({"x":x}, y, batch_size=4, num_epochs=1000)
estimator.fit(input_fn=input_fn, steps=1000)
</code>```

I am wondering what is the difference between argument steps in the call to fit function and num_epochs in the numpy_input_fn call. Shouldn't there be just one argument? How are they connected?

I have found that code is somehow taking the min of these two as the number of steps in the toy example of the tutorial.

At least, one of the two parameters either num_epochs or steps has to be redundant. We can calculate one from the other. Is there a way I can know how many steps (number of times parameters get updated) my algorithm actually took?

I am curious about which one takes precedence. And does it depend on some other parameters?

答:
Epoch: One pass through the entire data.

Batch size: The no of examples seen in one batch.

If there are 1000 examples and the batch size is 100, then there will be 10 steps per epoch.

The Epochs and batch size completely define the number of steps.

steps_cal = (no of ex / batch_size) * no_of_epochs

```<code>estimator.fit(input_fn=input_fn)
</code>```

If you just write the above code, then the value of 'steps' is as given by 'steps_cal' in the above formula.

```<code>estimator.fit(input_fn=input_fn, steps  = steps_less)
</code>```

If you give a value(say 'steps_less') less than 'steps_cal', then only 'steps_less' no of steps will be executed.In this case, the training will not cover the entire no of epochs that were mentioned.

```<code>estimator.fit(input_fn=input_fn, steps  = steps_more)
</code>```

If you give a value(say steps_more) more than steps_cal, then also 'steps_cal' no of steps will be executed.

ContentLicense: CC BY-SA 4.0

Body:
I am going through TensorFlow get started tutorial. In the tf.contrib.learn example, these are two lines of code:

input_fn = tf.contrib.learn.io.numpy_input_fn({"x":x}, y, batch_size=4, num_epochs=1000)
estimator.fit(input_fn=input_fn, steps=1000)

I am wondering what is the difference between argument steps in the call to fit function and num_epochs in the numpy_input_fn call. Shouldn't there be just one argument? How are they connected?

I have found that code is somehow taking the min of these two as the number of steps in the toy example of the tutorial.

At least, one of the two parameters either num_epochs or steps has to be redundant. We can calculate one from the other. Is there a way I can know how many steps (number of times parameters get updated) my algorithm actually took?

I am curious about which one takes precedence. And does it depend on some other parameters?

Body:
Epoch: One pass through the entire data.

Batch size: The no of examples seen in one batch.

If there are 1000 examples and the batch size is 100, then there will be 10 steps per epoch.

The Epochs and batch size completely define the number of steps.

steps_cal = (no of ex / batch_size) * no_of_epochs

estimator.fit(input_fn=input_fn)

If you just write the above code, then the value of 'steps' is as given by 'steps_cal' in the above formula.

estimator.fit(input_fn=input_fn, steps  = steps_less)

If you give a value(say 'steps_less') less than 'steps_cal', then only 'steps_less' no of steps will be executed.In this case, the training will not cover the entire no of epochs that were mentioned.

estimator.fit(input_fn=input_fn, steps  = steps_more)

If you give a value(say steps_more) more than steps_cal, then also 'steps_cal' no of steps will be executed.


问:
Uploading file using $_FILES and PHP
Today I tried for the first time to upload files to my website, but it seems that it doesn't work. I hope someone can help me, and I hope my code is readable :)

The problem is when I choose file and SUBMIT form it is not accepted because $_FILES is NULL

```<code>if (move_uploaded_file($_FILES['obrazok']['tmp_name'], $uploadfile))
</code>```

UPDATED Error

```<code>Warning: move_uploaded_file(www_nekonomagic/res/img/anime/uploads/793392545Untitled.jpg): failed to open stream: No such file or directory in /home/gj020900/www_nekonomagic/admin/admin-nove-anime.php on line 107

Warning: move_uploaded_file(): Unable to move '/home/gj020900/tmp/php9izgwb' to 'www_nekonomagic/res/img/anime/uploads/793392545Untitled.jpg' in /home/gj020900/www_nekonomagic/admin/admin-nove-anime.php on line 107
</code>```

Shorted form:

```<code><form enctype="multipart/form-data" action="../admin/admin-nove-anime.php" method="post" role="form">
    <div class="form-group col-md-6">
        <!-- MAX_FILE_SIZE must precede the file input field -->
        <input type="hidden" name="MAX_FILE_SIZE" value="3145728" />
        <label for="obrazok" class=""> Obrázok anime (Max. 3MB):</label>
        <input type="file" name="obrazok" id="obrazok" class="form-control" required>
    </div>
    <div class="form-group col-md-12">
        <input type="submit" class="btn btn-success" name="pridaj_anime_submit" value="Pridať anime" style="width: 100%;">
    </div>
</form>
</code>```

PHP part:

```<code>if (isset($_POST['pridaj_anime_submit'])) {
    // skontroluje sa ci sa subor ulozil ak ano pokracuje ak nie napise chybu
    $uploaddir = '/www_nekonomagic/res/img/anime/uploads/';
    $uploadfile = $uploaddir . basename($_FILES['obrazok']['name']);
    if (move_uploaded_file($_FILES['obrazok']['tmp_name'], $uploadfile)) {
        // prva cast formy
        $nazov = mysqli_real_escape_string($connect_to_db, $_POST['nazov']);
        $rok = mysqli_real_escape_string($connect_to_db, $_POST['rok']);
        $pocet = mysqli_real_escape_string($connect_to_db, $_POST['pocet']);
        $preklad = mysqli_real_escape_string($connect_to_db, $_POST['preklad']);
        $stav = mysqli_real_escape_string($connect_to_db, $_POST['stav']);

        $sql_vloz_anime = "INSERT INTO anime (a_name, a_year, a_translated_min, a_translated_max, a_rate_min, a_rate_max, a_edit, a_condition)
                                  VALUES ('$nazov', '$rok', '0', '$pocet', '8', '10', '$preklad', '$stav')";
        mysqli_query($connect_to_db, $sql_vloz_anime);
        $sql_ziskaj_a_id_pridaneho_anime = "SELECT * FROM anime WHERE a_name = '$nazov'";
        $run_sql_ziskaj_a_id_pridaneho_anime = mysqli_query($connect_to_db, $sql_ziskaj_a_id_pridaneho_anime);
        $a_id_ziskane = "";

        while ($db_data = mysqli_fetch_assoc($run_sql_ziskaj_a_id_pridaneho_anime)) {
            $a_id_ziskane = $db_data['a_id'];
        }

        // druha cast formy
        $obrazok = mysqli_real_escape_string($connect_to_db, $uploaddir.$_FILES['obrazok']['name']);
        $zaciatok = mysqli_real_escape_string($connect_to_db, $_POST['zaciatok']);
        $koniec = mysqli_real_escape_string($connect_to_db, $_POST['koniec']);
        $cas = mysqli_real_escape_string($connect_to_db, $_POST['cas']);
        $akihabara = mysqli_real_escape_string($connect_to_db, $_POST['akihabara']);

        $sql_vloz_anime_info = "INSERT INTO anime_info (a_id, a_img, a_start, a_stop, a_time_ep, a_akihabara)
                                            VALUES ('$a_id_ziskane', '$obrazok', '$zaciatok', '$koniec', '$cas', '$akihabara')";
        mysqli_query($connect_to_db, $sql_vloz_anime_info);
    }
    else {
        echo "
            <div class=\"alert alert-success alert-info\" style=\"margin: 10px 0\">
                <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>
                <strong>POZOR!</strong> Súbor sa nepodarilo nahrať.
            </div>
        ";
    }
}
</code>```

答:
MAX_FILE_SIZE is in bytes to limit your upload file size to 3M, convert your size to bytes.

```<code>1024 * (1024 * 3) // 3145728
</code>```

Then change your hidden input to the following

```<code><!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="3145728" />
</code>```

Title: Uploading file using $_FILES and PHP

Body:
Today I tried for the first time to upload files to my website, but it seems that it doesn't work. I hope someone can help me, and I hope my code is readable :)

The problem is when I choose file and SUBMIT form it is not accepted because $_FILES is NULL

if (move_uploaded_file($_FILES['obrazok']['tmp_name'], $uploadfile))

UPDATED Error

Warning: move_uploaded_file(www_nekonomagic/res/img/anime/uploads/793392545Untitled.jpg): failed to open stream: No such file or directory in /home/gj020900/www_nekonomagic/admin/admin-nove-anime.php on line 107

Warning: move_uploaded_file(): Unable to move '/home/gj020900/tmp/php9izgwb' to 'www_nekonomagic/res/img/anime/uploads/793392545Untitled.jpg' in /home/gj020900/www_nekonomagic/admin/admin-nove-anime.php on line 107

Shorted form:

<form enctype="multipart/form-data" action="../admin/admin-nove-anime.php" method="post" role="form">

        <input type="hidden" name="MAX_FILE_SIZE" value="3145728" />
         Obrázok anime (Max. 3MB):
        <input type="file" name="obrazok" id="obrazok" class="form-control" required>

        <input type="submit" class="btn btn-success" name="pridaj_anime_submit" value="Pridať anime" style="width: 100%;">

</form>

PHP part:

if (isset($_POST['pridaj_anime_submit'])) {
    // skontroluje sa ci sa subor ulozil ak ano pokracuje ak nie napise chybu
    $uploaddir = '/www_nekonomagic/res/img/anime/uploads/';
    $uploadfile = $uploaddir . basename($_FILES['obrazok']['name']);
    if (move_uploaded_file($_FILES['obrazok']['tmp_name'], $uploadfile)) {
        // prva cast formy
        $nazov = mysqli_real_escape_string($connect_to_db, $_POST['nazov']);
        $rok = mysqli_real_escape_string($connect_to_db, $_POST['rok']);
        $pocet = mysqli_real_escape_string($connect_to_db, $_POST['pocet']);
        $preklad = mysqli_real_escape_string($connect_to_db, $_POST['preklad']);
        $stav = mysqli_real_escape_string($connect_to_db, $_POST['stav']);

        $sql_vloz_anime = "INSERT INTO anime (a_name, a_year, a_translated_min, a_translated_max, a_rate_min, a_rate_max, a_edit, a_condition)
                                  VALUES ('$nazov', '$rok', '0', '$pocet', '8', '10', '$preklad', '$stav')";
        mysqli_query($connect_to_db, $sql_vloz_anime);
        $sql_ziskaj_a_id_pridaneho_anime = "SELECT * FROM anime WHERE a_name = '$nazov'";
        $run_sql_ziskaj_a_id_pridaneho_anime = mysqli_query($connect_to_db, $sql_ziskaj_a_id_pridaneho_anime);
        $a_id_ziskane = "";

        while ($db_data = mysqli_fetch_assoc($run_sql_ziskaj_a_id_pridaneho_anime)) {
            $a_id_ziskane = $db_data['a_id'];
        }

        // druha cast formy
        $obrazok = mysqli_real_escape_string($connect_to_db, $uploaddir.$_FILES['obrazok']['name']);
        $zaciatok = mysqli_real_escape_string($connect_to_db, $_POST['zaciatok']);
        $koniec = mysqli_real_escape_string($connect_to_db, $_POST['koniec']);
        $cas = mysqli_real_escape_string($connect_to_db, $_POST['cas']);
        $akihabara = mysqli_real_escape_string($connect_to_db, $_POST['akihabara']);

        $sql_vloz_anime_info = "INSERT INTO anime_info (a_id, a_img, a_start, a_stop, a_time_ep, a_akihabara)
                                            VALUES ('$a_id_ziskane', '$obrazok', '$zaciatok', '$koniec', '$cas', '$akihabara')";
        mysqli_query($connect_to_db, $sql_vloz_anime_info);
    }
    else {
        echo "

                ×
                POZOR! Súbor sa nepodarilo nahrať.

        ";
    }
}

Body:
MAX_FILE_SIZE is in bytes to limit your upload file size to 3M, convert your size to bytes.

1024 * (1024 * 3) // 3145728

Then change your hidden input to the following

<!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="3145728" />


问:
hls.js CORS using AWS Cloudfront issues with Cookies
I'm trying to set up a video streaming using Cloudfront HLS capabilities but I'm having trouble getting Hls.js to send my credential cookies in the request.

I already have Cloudfront configured to forward cookies and to forward Access-control headers. I also have set my S3 CORS policies to include GET, HEAD.

The problem I'm having is that even though I'm setting the xhr.withCredentials=true and the cookies are defined in the session, when I look at the request using chrome console, I can see that the HLS request has no cookies. As a result I get an error response from cloudfront saying I need to include the credential cookies.

Code:
First I do an ajax request to my server to generate the cookies. The server returns three Set-Cookies headers stored as session cookies in the browser:

```<code>$.ajax(
{
type: 'GET',
url: 'http://subdomain.mydomain.com:8080/service-
webapp/rest/resourceurl/cookies/98400738-a415-4e32-898c-9592d48d1ad7',
success: function (data) {
        playMyVideo();
},
headers: { "Authorization": 'Bearer XXXXXX' }
});
</code>```

Once the cookies are stored the test function is called to play my video using HLS.js:

```<code>function test(){
  if (Hls.isSupported()) {
  var video = document.getElementById('video');
  var config = {
    debug: true,
    xhrSetup: function (xhr,url) {
        xhr.withCredentials = true; // do send cookie
    xhr.setRequestHeader("Access-Control-Allow-Headers","Content-Type, Accept, X-Requested-With");
        xhr.setRequestHeader("Access-Control-Allow-Origin","http://sybdomain.domain.com:8080");
    xhr.setRequestHeader("Access-Control-Allow-Credentials","true");
    }
  };
  var hls = new Hls(config);
  // bind them together
  hls.attachMedia(video);
  hls.on(Hls.Events.MEDIA_ATTACHED, function () {
    console.log("video and hls.js are now bound together !");
    hls.loadSource("http://cloudfrontDomain.net/small.m3u8");
    hls.on(Hls.Events.MANIFEST_PARSED, function (event, data) {
      console.log("manifest loaded, found " + data.levels.length + " quality level");
    });
  });
}
video.play();
}
</code>```

As you can see below HLS OPTIONS and GET request do not set the session cookies:

HLS OPTIONS request:

```<code>OPTIONS /hls/98400738-a415-4e32-898c-9592d48d1ad7/small.m3u8 HTTP/1.1
Host: cloudfrontDomain.net
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: subdomain.mydomain.com:8080
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36
Access-Control-Request-Headers: access-control-allow-credentials,access-control-allow-headers,access-control-allow-origin
Accept: */*
Referer: http://subdomain.mydomain.com:8080/play.html
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,es;q=0.6
</code>```

CloudFront response:

```<code>HTTP/1.1 200 OK
Content-Length: 0
Connection: keep-alive
Date: Fri, 07 Jul 2017 00:16:31 GMT
Access-Control-Allow-Origin: http://subdomain.mydomain.com:8080
Access-Control-Allow-Methods: GET, HEAD
Access-Control-Allow-Headers: access-control-allow-credentials, access-control-allow-headers, access-control-allow-origin
Access-Control-Max-Age: 3000
Access-Control-Allow-Credentials: true
Server: AmazonS3
Vary: Origin,Access-Control-Request-Headers,Access-Control-Request-Method
Age: 845
X-Cache: Hit from cloudfront
Via: 1.1 cloudfrontDomain.net (CloudFront)
X-Amz-Cf-Id: XXXXXX
</code>```

HLS subsequent GET request missing the cookies:

```<code>GET /hls/98400738-a415-4e32-898c-9592d48d1ad7/small.m3u8 HTTP/1.1
Host: cloudfrontDomain.net
Connection: keep-alive
Origin: http://subdomain.mydomain.com:8080
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36
Access-Control-Allow-Origin: http://subdomain.mydomain.com:8080
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Content-Type, Accept, X-Requested-With
Accept: */*
Referer: http://subdomain.mydomain.com:8080/play.html
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,es;q=0.6
</code>```

I've spent 4 days trying to figure this out. I've done plenty of research but I just can't figure out the solution. I'm new to CORS so maybe I'm not understanding some principle. I thought if the cookies are stored in the session they would get set if you enabled xhr with credentials but it doesn't seem to be the case.

Another thing I noted is that the GET request generated by HLS.js is not setting any xmlhttprequest header.

Thanks for your help :)

答:
I was finally able to make it work. Thanks Michael for helping! Turns out it was a mix of not understanding how CORS principles work and properly configuring aws services. The main issue is to avoid cross domain requests by using cloudfront to serve both your webservice and s3 bucket. One important note I want to add is that any change you make in aws you have to wait for it to propagate. As a new aws dev I didn't know that and got very frustrated making changes that had no effect. Here is the solution:

1) Create your S3 bucket.

2) Create a Cloudfront distribution.

3) In the distribution set as the default origin your web-service domain.

4) Add a second origin and add a behavior in the distribution to forward all .m3u8 and .ts files to your S3 bucket.

5) When you add your bucket origin make sure you mark restrict access and also update bucket policy checkboxes.

6) In your bucket distribution behavior make sure you forward all white list headers and cookies. This can all be set in aws console.

7) If you are using different ports in your service make sure you set those too in the distribution.

8) Go to your S3 bucket settings and update the CORS config to the following:

```<code><?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
</code>```

It is important that if your are using HLS.js to set the following config:

```<code>var config = {
debug: true,
xhrSetup: function (xhr,url) {
xhr.withCredentials = true; // do send cookie
xhr.setRequestHeader("Access-Control-Allow-Headers","Content-Type, Accept, X-Requested-With");
    xhr.setRequestHeader("Access-Control-Allow-Origin","http://sybdomain.domain.com:8080");
xhr.setRequestHeader("Access-Control-Allow-Credentials","true");
}
};
var hls = new Hls(config);
</code>```

Other important notes:

When you serve a cookie with your web service you can set the Path to be "/" and it will apply to all request in your domain.

Body:
I'm trying to set up a video streaming using Cloudfront HLS capabilities but I'm having trouble getting Hls.js to send my credential cookies in the request.

I already have Cloudfront configured to forward cookies and to forward Access-control headers. I also have set my S3 CORS policies to include GET, HEAD.

The problem I'm having is that even though I'm setting the xhr.withCredentials=true and the cookies are defined in the session, when I look at the request using chrome console, I can see that the HLS request has no cookies. As a result I get an error response from cloudfront saying I need to include the credential cookies.

Code:
First I do an ajax request to my server to generate the cookies. The server returns three Set-Cookies headers stored as session cookies in the browser:

$.ajax(
{
type: 'GET',
url: 'http://subdomain.mydomain.com:8080/service-
webapp/rest/resourceurl/cookies/98400738-a415-4e32-898c-9592d48d1ad7',
success: function (data) {
        playMyVideo();
},
headers: { "Authorization": 'Bearer XXXXXX' }
});

Once the cookies are stored the test function is called to play my video using HLS.js:

function test(){
  if (Hls.isSupported()) {
  var video = document.getElementById('video');
  var config = {
    debug: true,
    xhrSetup: function (xhr,url) {
        xhr.withCredentials = true; // do send cookie
    xhr.setRequestHeader("Access-Control-Allow-Headers","Content-Type, Accept, X-Requested-With");
        xhr.setRequestHeader("Access-Control-Allow-Origin","http://sybdomain.domain.com:8080");
    xhr.setRequestHeader("Access-Control-Allow-Credentials","true");
    }
  };
  var hls = new Hls(config);
  // bind them together
  hls.attachMedia(video);
  hls.on(Hls.Events.MEDIA_ATTACHED, function () {
    console.log("video and hls.js are now bound together !");
    hls.loadSource("http://cloudfrontDomain.net/small.m3u8");
    hls.on(Hls.Events.MANIFEST_PARSED, function (event, data) {
      console.log("manifest loaded, found " + data.levels.length + " quality level");
    });
  });
}
video.play();
}

As you can see below HLS OPTIONS and GET request do not set the session cookies:

HLS OPTIONS request:

OPTIONS /hls/98400738-a415-4e32-898c-9592d48d1ad7/small.m3u8 HTTP/1.1
Host: cloudfrontDomain.net
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: subdomain.mydomain.com:8080
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36
Access-Control-Request-Headers: access-control-allow-credentials,access-control-allow-headers,access-control-allow-origin
Accept: */*
Referer: http://subdomain.mydomain.com:8080/play.html
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,es;q=0.6

CloudFront response:

HTTP/1.1 200 OK
Content-Length: 0
Connection: keep-alive
Date: Fri, 07 Jul 2017 00:16:31 GMT
Access-Control-Allow-Origin: http://subdomain.mydomain.com:8080
Access-Control-Allow-Methods: GET, HEAD
Access-Control-Allow-Headers: access-control-allow-credentials, access-control-allow-headers, access-control-allow-origin
Access-Control-Max-Age: 3000
Access-Control-Allow-Credentials: true
Server: AmazonS3
Vary: Origin,Access-Control-Request-Headers,Access-Control-Request-Method
Age: 845
X-Cache: Hit from cloudfront
Via: 1.1 cloudfrontDomain.net (CloudFront)
X-Amz-Cf-Id: XXXXXX

HLS subsequent GET request missing the cookies:

GET /hls/98400738-a415-4e32-898c-9592d48d1ad7/small.m3u8 HTTP/1.1
Host: cloudfrontDomain.net
Connection: keep-alive
Origin: http://subdomain.mydomain.com:8080
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36
Access-Control-Allow-Origin: http://subdomain.mydomain.com:8080
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Content-Type, Accept, X-Requested-With
Accept: */*
Referer: http://subdomain.mydomain.com:8080/play.html
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,es;q=0.6

I've spent 4 days trying to figure this out. I've done plenty of research but I just can't figure out the solution. I'm new to CORS so maybe I'm not understanding some principle. I thought if the cookies are stored in the session they would get set if you enabled xhr with credentials but it doesn't seem to be the case.

Another thing I noted is that the GET request generated by HLS.js is not setting any xmlhttprequest header.

Thanks for your help :)

Body:
I was finally able to make it work. Thanks Michael for helping! Turns out it was a mix of not understanding how CORS principles work and properly configuring aws services. The main issue is to avoid cross domain requests by using cloudfront to serve both your webservice and s3 bucket. One important note I want to add is that any change you make in aws you have to wait for it to propagate. As a new aws dev I didn't know that and got very frustrated making changes that had no effect. Here is the solution:

1) Create your S3 bucket.

2) Create a Cloudfront distribution.

3) In the distribution set as the default origin your web-service domain.

4) Add a second origin and add a behavior in the distribution to forward all .m3u8 and .ts files to your S3 bucket.

5) When you add your bucket origin make sure you mark restrict access and also update bucket policy checkboxes.

6) In your bucket distribution behavior make sure you forward all white list headers and cookies. This can all be set in aws console.

7) If you are using different ports in your service make sure you set those too in the distribution.

8) Go to your S3 bucket settings and update the CORS config to the following:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

It is important that if your are using HLS.js to set the following config:

var config = {
debug: true,
xhrSetup: function (xhr,url) {
xhr.withCredentials = true; // do send cookie
xhr.setRequestHeader("Access-Control-Allow-Headers","Content-Type, Accept, X-Requested-With");
    xhr.setRequestHeader("Access-Control-Allow-Origin","http://sybdomain.domain.com:8080");
xhr.setRequestHeader("Access-Control-Allow-Credentials","true");
}
};
var hls = new Hls(config);

Other important notes:

When you serve a cookie with your web service you can set the Path to be "/" and it will apply to all request in your domain.


问:
Pythonic way to find maximum value and its index in a list?
If I want the maximum value in a list, I can just write max(List), but what if I also need the index of the maximum value?

I can write something like this:

```<code>maximum=0
for i,value in enumerate(List):
    if value>maximum:
        maximum=value
        index=i
</code>```

But it looks tedious to me.

And if I write:

```<code>List.index(max(List))
</code>```

Then it will iterate the list twice.

Is there a better way?

答:
```<code>max([(value,index) for index,value in enumerate(your_list)]) #if maximum value is present more than once in your list then this will return index of the last occurrence
</code>```

If maximum value in present more than once and you want to get all indices,

```<code>max_value = max(your_list)
maxIndexList = [index for index,value in enumerate(your_list) if value==max(your_list)]
</code>```

Body:
If I want the maximum value in a list, I can just write max(List), but what if I also need the index of the maximum value?

I can write something like this:

maximum=0
for i,value in enumerate(List):
    if value>maximum:
        maximum=value
        index=i

But it looks tedious to me.

And if I write:

List.index(max(List))

Then it will iterate the list twice.

Is there a better way?

Body:
max([(value,index) for index,value in enumerate(your_list)]) #if maximum value is present more than once in your list then this will return index of the last occurrence

If maximum value in present more than once and you want to get all indices,

max_value = max(your_list)
maxIndexList = [index for index,value in enumerate(your_list) if value==max(your_list)]


问:
can't start MySql in Mac OS 10.6 Snow Leopard
I've googled this and could'nt find anything new and useful for Apple's new OS SnowLeopard.
I wonder if this is my mistake or I do need to do something?

this is what I did:

Downloaded from mysql site:
http://dev.mysql.com/downloads/mysql/5.1.html#macosx-dmg
I choose : Mac OS X 10.5 (x86_64)

I run all the packages and installed all of them.
So now I certainly have mysql in

```<code>/usr/local/mysql/
</code>```

But when trying to start it from preferences panel, it is always STOPPED.
When I try to do (in the terminal):

```<code>/usr/local/mysql/bin/mysql
</code>```

I got :

-bash: /usr/local/mysql/bin/mysql: Bad CPU type in executable

What is wrong here?
Any help would be very appreciated. Thanks

答:
Maybe this answer helps:

mysql5.58 unstart server in mac os 10.6.5

I just installed MySQL 5.5.8 (mysql-5.5.8-osx10.6-x86_64.dmg) on Mac os X 10.6.5 and also had the problem that MySQL was not starting.

After reading this post: http://forums.mysql.com/read.php?11,399397,399606#msg-399606
and editing the file as suggested everything started working.

I also did

```<code>sudo chown -R root:wheel /Library/StartupItems/MySQLCOM
</code>```

after reading
https://discussions.apple.com/message/12820394
since when restarting my Mac OSx 10.6.6 it kept on asking something about not enough privileges. The line above solved that issue.

Now everything is working.

Body:
I've googled this and could'nt find anything new and useful for Apple's new OS SnowLeopard.
I wonder if this is my mistake or I do need to do something?

this is what I did:

Downloaded from mysql site:
http://dev.mysql.com/downloads/mysql/5.1.html#macosx-dmg
I choose : Mac OS X 10.5 (x86_64)

I run all the packages and installed all of them.
So now I certainly have mysql in

/usr/local/mysql/

But when trying to start it from preferences panel, it is always STOPPED.
When I try to do (in the terminal):

/usr/local/mysql/bin/mysql

I got :

-bash: /usr/local/mysql/bin/mysql: Bad CPU type in executable

What is wrong here?
Any help would be very appreciated. Thanks

Body:
Maybe this answer helps:

mysql5.58 unstart server in mac os 10.6.5

I just installed MySQL 5.5.8 (mysql-5.5.8-osx10.6-x86_64.dmg) on Mac os X 10.6.5 and also had the problem that MySQL was not starting.

After reading this post: http://forums.mysql.com/read.php?11,399397,399606#msg-399606
and editing the file as suggested everything started working.

I also did

sudo chown -R root:wheel /Library/StartupItems/MySQLCOM

after reading
https://discussions.apple.com/message/12820394
since when restarting my Mac OSx 10.6.6 it kept on asking something about not enough privileges. The line above solved that issue.

Now everything is working.


问:
Thrown exception of java.lang.NullPointerException after importing image to my Main Activity XML file
So i tried to copy an image downloaded from the internet to my android studio mainactivity xml file via copying the image and pasting it onto the drawable resource folder, But for some reason, I got an error of "Failed to instantiate one or more classes" This is the first time I'm getting this error as my previous images copied the exact same way had no errors except for other images such as this one. Does it have something to do with PNG or JPG format?I tried to resync the project with Gradle files but its still the same. What should I do to solve this exception? Thank You.

1) the process of copying and pasting image to drawable

2) The error itself after pasting the image

```<code>java.lang.NullPointerException
at android.content.res.Resources_Delegate.getValue(Resources_Delegate.java:788)
at android.content.res.Resources.getValue(Resources.java:1286)
at android.support.v7.widget.AppCompatDrawableManager.createDrawableIfNeeded(AppCompatDrawableManager.java:236)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:199)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:190)
at android.support.v7.content.res.AppCompatResources.getDrawable(AppCompatResources.java:100)
at android.support.v7.widget.AppCompatImageHelper.loadFromAttributes(AppCompatImageHelper.java:54)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:66)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:56)
at sun.reflect.GeneratedConstructorAccessor1111.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.jetbrains.android.uipreview.ViewLoader.createNewInstance(ViewLoader.java:475)
at org.jetbrains.android.uipreview.ViewLoader.loadClass(ViewLoader.java:250)
at org.jetbrains.android.uipreview.ViewLoader.loadClass(ViewLoader.java:213)
at com.android.tools.idea.rendering.LayoutlibCallbackImpl.loadClass(LayoutlibCallbackImpl.java:193)
at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:333)
at android.view.BridgeInflater.onCreateView(BridgeInflater.java:152)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:717)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:785)
at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:222)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:858)
at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:70)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:834)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:324)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:429)
at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:368)
at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:567)
at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:549)
at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:863)
at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:549)
at com.android.tools.idea.rendering.RenderTask.lambda$inflate$1(RenderTask.java:680)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code>```

Edit: Also, When i try to compile the code, my project would'nt start unless i delete the image file in my drawable folder due to this error : `Error:Execution failed for task ':app:mergeDebugResources'.

C:\Users\TP_baseline\AndroidStudioProjects\COMTProject(MeloWide)\app\src\main\res\drawable\icons8-Medal-80.png: Error: '-' is not a valid file-based resource name character: File-based resource names must contain only lowercase a-z, 0-9, or underscore`

答:
Your image has dashes in the name. icons8-Medal-80.png

Replace it with an underscore or remove it.

Only lowercase alphanumeric (plus underscores) resource names are allowed, as indicated in the error.

Body:
So i tried to copy an image downloaded from the internet to my android studio mainactivity xml file via copying the image and pasting it onto the drawable resource folder, But for some reason, I got an error of "Failed to instantiate one or more classes" This is the first time I'm getting this error as my previous images copied the exact same way had no errors except for other images such as this one. Does it have something to do with PNG or JPG format?I tried to resync the project with Gradle files but its still the same. What should I do to solve this exception? Thank You.

1) the process of copying and pasting image to drawable

2) The error itself after pasting the image

java.lang.NullPointerException
at android.content.res.Resources_Delegate.getValue(Resources_Delegate.java:788)
at android.content.res.Resources.getValue(Resources.java:1286)
at android.support.v7.widget.AppCompatDrawableManager.createDrawableIfNeeded(AppCompatDrawableManager.java:236)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:199)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:190)
at android.support.v7.content.res.AppCompatResources.getDrawable(AppCompatResources.java:100)
at android.support.v7.widget.AppCompatImageHelper.loadFromAttributes(AppCompatImageHelper.java:54)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:66)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:56)
at sun.reflect.GeneratedConstructorAccessor1111.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.jetbrains.android.uipreview.ViewLoader.createNewInstance(ViewLoader.java:475)
at org.jetbrains.android.uipreview.ViewLoader.loadClass(ViewLoader.java:250)
at org.jetbrains.android.uipreview.ViewLoader.loadClass(ViewLoader.java:213)
at com.android.tools.idea.rendering.LayoutlibCallbackImpl.loadClass(LayoutlibCallbackImpl.java:193)
at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:333)
at android.view.BridgeInflater.onCreateView(BridgeInflater.java:152)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:717)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:785)
at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:222)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:858)
at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:70)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:834)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:324)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:429)
at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:368)
at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:567)
at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:549)
at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:863)
at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:549)
at com.android.tools.idea.rendering.RenderTask.lambda$inflate$1(RenderTask.java:680)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

Edit: Also, When i try to compile the code, my project would'nt start unless i delete the image file in my drawable folder due to this error : `Error:Execution failed for task ':app:mergeDebugResources'.

C:\Users\TP_baseline\AndroidStudioProjects\COMTProject(MeloWide)\app\src\main\res\drawable\icons8-Medal-80.png: Error: '-' is not a valid file-based resource name character: File-based resource names must contain only lowercase a-z, 0-9, or underscore`


问:
JSONObject parsing in android?
The JSONObject looks like

```<code>{"result":
     {
        "id":"1",
        "name":"ankur",
        "email":"ankur@gmail.com",
        "address":"bblock",
        "designation":"devloper",
        "department":"development",
        "balanceleave":"5"
     }
}
</code>```

and my parse code looks like

```<code>Intent intent = new Intent(Login.this, Profile.class);
intent.putExtra("id", response.getString("id"));
intent.putExtra("name", response.getString("name"));
intent.putExtra("email", response.getString("email"));
intent.putExtra("address", response.getString("address"));
intent.putExtra("designation", response.getString("designation"));
intent.putExtra("department", response.getString("department"));
intent.putExtra("balanceleave", response.getString("balanceleave"));

startActivity(intent);
</code>```

Can you help me out, actually I am parsing the JSON and sending it to the profile activity to display and if you can comeup with something that I can send the JSONObject to profile that would be great!!

答:
yes you have to convert JsonObject to String and then send via Bundle to Profile Screen. Like below

```<code>Intent intent = new Intent(Login.this, Profile.class);
intent.putExtra("JSON_OBJECT", response.toString());

                                startActivity(intent);
</code>```

To Get that

```<code>Intent i = getIntent();
String json = i.getStringExtra("JSON_OBJECT");
try{
JsonObject json = new JsonObject(json);
}catch(Exception e){
}
</code>```

Title: JSONObject parsing in android?

Body:
The JSONObject looks like

{"result":
     {
        "id":"1",
        "name":"ankur",
        "email":"ankur@gmail.com",
        "address":"bblock",
        "designation":"devloper",
        "department":"development",
        "balanceleave":"5"
     }
}

and my parse code looks like

Intent intent = new Intent(Login.this, Profile.class);
intent.putExtra("id", response.getString("id"));
intent.putExtra("name", response.getString("name"));
intent.putExtra("email", response.getString("email"));
intent.putExtra("address", response.getString("address"));
intent.putExtra("designation", response.getString("designation"));
intent.putExtra("department", response.getString("department"));
intent.putExtra("balanceleave", response.getString("balanceleave"));

startActivity(intent);

Can you help me out, actually I am parsing the JSON and sending it to the profile activity to display and if you can comeup with something that I can send the JSONObject to profile that would be great!!

Body:
yes you have to convert JsonObject to String and then send via Bundle to Profile Screen. Like below

Intent intent = new Intent(Login.this, Profile.class);
intent.putExtra("JSON_OBJECT", response.toString());

                                startActivity(intent);

To Get that

Intent i = getIntent();
String json = i.getStringExtra("JSON_OBJECT");
try{
JsonObject json = new JsonObject(json);
}catch(Exception e){
}


问:
Tensorflow: analogue for numpy.take?
Is there analogue for numpy.take?
I want to form N+1-dimensional array from N-dimensional array, more precisely from array with shape (B, H, W, C)  I want to make (B, H, W, X, C) array.

I suppose that for my case there is solution even without such general operation. But I'm really unsure that if I will write code with multiple intermediate operations and tensors (shifting, repeating and so on) TF will be able to optimize it and remove unnecessary operations. Moreover I suppose that such code will be unclean and just awful.

I want to add dimension with shifted values. I.e. for (H,W)->(H,W,3) dimensions case indices must be

```<code>[
[[0,0], #[0,-1], may be padding with zeros but for now pad with edge value
[0,0],
[0,1]],

[[0,0],
[0,1]
[0,2]]
...
[[1,0],
 [1,0],
 [1,1]],

 [[1,0],
 [1,1],
 [1,2]],
...
]
</code>```

I thought about tf.scatter_nd (https://www.tensorflow.org/api_docs/python/tf/scatter_nd) but for now I don't understand how to use it. If I understand correctly, I can't use indices with shapes larger than shapes of update array (i.e. I can't use indices with shape (3,4,5,3) and update with shape (3,4,3) or even (3,4,1,3). If it's so then this operation seems useless until I make intermediate array with shape that I need to form in result.

UPD: may be I'm wrong and tensors operations (shifting, tiling and so on) is more appropriate and efficient solution.
But in any case I think that analogue for np.take will be useful.

答:
The closest function in tensorflow to np.take are tf.gather and tf.gather_nd.

tf.gather_nd is more general than tf.gather (and np.take) as it can slices through several dimensions at once.

A noticeable restriction of tf.gather[_nd] compared to np.take is that they slice through the first dimensions of the tensor only -- you can't slice through inner dimensions. When you want to slice through an arbitrary dimension (as in your case), you need to transpose the array to put the slice dimensions first, gather, then transpose back.

Title: Tensorflow: analogue for numpy.take?

Body:
Is there analogue for numpy.take?
I want to form N+1-dimensional array from N-dimensional array, more precisely from array with shape (B, H, W, C)  I want to make (B, H, W, X, C) array.

I suppose that for my case there is solution even without such general operation. But I'm really unsure that if I will write code with multiple intermediate operations and tensors (shifting, repeating and so on) TF will be able to optimize it and remove unnecessary operations. Moreover I suppose that such code will be unclean and just awful.

I want to add dimension with shifted values. I.e. for (H,W)->(H,W,3) dimensions case indices must be

[
[[0,0], #[0,-1], may be padding with zeros but for now pad with edge value
[0,0],
[0,1]],

[[0,0],
[0,1]
[0,2]]
...
[[1,0],
 [1,0],
 [1,1]],

 [[1,0],
 [1,1],
 [1,2]],
...
]

I thought about tf.scatter_nd (https://www.tensorflow.org/api_docs/python/tf/scatter_nd) but for now I don't understand how to use it. If I understand correctly, I can't use indices with shapes larger than shapes of update array (i.e. I can't use indices with shape (3,4,5,3) and update with shape (3,4,3) or even (3,4,1,3). If it's so then this operation seems useless until I make intermediate array with shape that I need to form in result.

UPD: may be I'm wrong and tensors operations (shifting, tiling and so on) is more appropriate and efficient solution.
But in any case I think that analogue for np.take will be useful.


问:
Issue with a trigger before delete
I need to insert in a table a "log" of the deleted rows of another table using triggers.

```<code>DROP TRIGGER IF EXISTS bajas_pil;
CREATE TRIGGER bajas_pil BEFORE DELETE ON pilotos
  FOR EACH ROW
  BEGIN
    INSERT INTO pilotos_baja (usuario, fecha, hora, dorsal) VALUES (user(), CURRENT_DATE, CURRENT_TIME, OLD.pil_numero);
  END;
</code>```

I can add the trigger, but, when I delete a row in table 'pilotos' it doesn't add any row in table 'pilotos_abaja'. Does somebody know why it happends? Thanks in advance!

答:
I can't reproduce the problem:

mysql> DROP TRIGGER IF EXISTS `bajas_pil`;
Query OK, 0 rows affected (0.00 sec)

mysql> DROP TABLE IF EXISTS `pilotos_baja`, `pilotos`;
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TABLE IF NOT EXISTS `pilotos` (
    ->   `pil_numero` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql> CREATE TABLE IF NOT EXISTS `pilotos_baja` (
    ->   `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    ->   `usuario` VARCHAR(93) NOT NULL,
    ->   `fecha` DATE NOT NULL,
    ->   `hora` TIME NOT NULL,
    ->   `dorsal` BIGINT UNSIGNED NOT NULL
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TRIGGER `bajas_pil` BEFORE DELETE ON `pilotos`
    -> FOR EACH ROW
    ->   INSERT INTO `pilotos_baja` (
    ->     `usuario`,
    ->     `fecha`,
    ->     `hora`,
    ->     `dorsal`)
    ->   VALUES (
    ->     USER(),
    ->     CURRENT_DATE,
    ->     CURRENT_TIME,
    ->     OLD.`pil_numero`);
Query OK, 0 rows affected (0.01 sec)

mysql> INSERT INTO `pilotos`
    -> VALUES (NULL), (NULL), (NULL);
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> SELECT `pil_numero`
    -> FROM `pilotos`;
+------------+
| pil_numero |
+------------+
|          1 |
|          2 |
|          3 |
+------------+
3 rows in set (0.00 sec)

mysql> DELETE FROM `pilotos`;
Query OK, 3 rows affected (0.00 sec)

mysql> SELECT
    ->   `usuario`,
    ->   `fecha`,
    ->   `hora`,
    ->   `dorsal`
    -> FROM
    ->   `pilotos_baja`;
+-----------+------------+----------+--------+
| usuario   | fecha      | hora     | dorsal |
+-----------+------------+----------+--------+
| user@host | 2010-01-01 | 00:00:01 |      1 |
| user@host | 2010-01-01 | 00:00:01 |      2 |
| user@host | 2010-01-01 | 00:00:01 |      3 |
+-----------+------------+----------+--------+
3 rows in set (0.00 sec)
```

See db-fiddle.

Title: Issue with a trigger before delete

Body:
I need to insert in a table a "log" of the deleted rows of another table using triggers.

DROP TRIGGER IF EXISTS bajas_pil;
CREATE TRIGGER bajas_pil BEFORE DELETE ON pilotos
  FOR EACH ROW
  BEGIN
    INSERT INTO pilotos_baja (usuario, fecha, hora, dorsal) VALUES (user(), CURRENT_DATE, CURRENT_TIME, OLD.pil_numero);
  END;

I can add the trigger, but, when I delete a row in table 'pilotos' it doesn't add any row in table 'pilotos_abaja'. Does somebody know why it happends? Thanks in advance!

Body:
I can't reproduce the problem:

mysql> DROP TRIGGER IF EXISTS `bajas_pil`;
Query OK, 0 rows affected (0.00 sec)

mysql> DROP TABLE IF EXISTS `pilotos_baja`, `pilotos`;
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TABLE IF NOT EXISTS `pilotos` (
    ->   `pil_numero` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql> CREATE TABLE IF NOT EXISTS `pilotos_baja` (
    ->   `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    ->   `usuario` VARCHAR(93) NOT NULL,
    ->   `fecha` DATE NOT NULL,
    ->   `hora` TIME NOT NULL,
    ->   `dorsal` BIGINT UNSIGNED NOT NULL
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TRIGGER `bajas_pil` BEFORE DELETE ON `pilotos`
    -> FOR EACH ROW
    ->   INSERT INTO `pilotos_baja` (
    ->     `usuario`,
    ->     `fecha`,
    ->     `hora`,
    ->     `dorsal`)
    ->   VALUES (
    ->     USER(),
    ->     CURRENT_DATE,
    ->     CURRENT_TIME,
    ->     OLD.`pil_numero`);
Query OK, 0 rows affected (0.01 sec)

mysql> INSERT INTO `pilotos`
    -> VALUES (NULL), (NULL), (NULL);
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> SELECT `pil_numero`
    -> FROM `pilotos`;
+------------+
| pil_numero |
+------------+
|          1 |
|          2 |
|          3 |
+------------+
3 rows in set (0.00 sec)

mysql> DELETE FROM `pilotos`;
Query OK, 3 rows affected (0.00 sec)

mysql> SELECT
    ->   `usuario`,
    ->   `fecha`,
    ->   `hora`,
    ->   `dorsal`
    -> FROM
    ->   `pilotos_baja`;
+-----------+------------+----------+--------+
| usuario   | fecha      | hora     | dorsal |
+-----------+------------+----------+--------+
| user@host | 2010-01-01 | 00:00:01 |      1 |
| user@host | 2010-01-01 | 00:00:01 |      2 |
| user@host | 2010-01-01 | 00:00:01 |      3 |
+-----------+------------+----------+--------+
3 rows in set (0.00 sec)

See db-fiddle.