问:
Image upload issue with Codeigniter
I'm stuck with an issue updating images. I've created image upload which works fine but when I try to update an entry with other details which already has an image, it throws an error. Is there a way we can skip the image upload check altogether and the entry updates with or without the image?

View:

        <?php require_once("header.php"); ?>

        <?php require_once("sidebar.php"); ?>

Add Mick Chocolate

                      Chocolate
                      / Home / Add Mick Chocolate

Input

                    <?php

                        echo form_open_multipart('Admin/admin_add_image');

                    ?>

                      <form class="form-horizontal" action = "" method ="post">

                          Name

                            <input type="text" id="text1" name="chocolate_name" pattern="^[A-Za-z -]+$" required >

                          Price

                            <input type="text" id="text2" name="chocolate_price" pattern="^(0|[1-9][0-9]*)$" required >

                          Upload Image

                            <input type="file" id="text3" name="file_to_upload" accept="image/gif, image/jpeg, image/png, image/jpg">

                                <button type="submit" name="btn_add" class="btn btn-info">Add</button>
                      </form>

               <?php require_once("footer.php"); ?>

**Model**

```php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class AdminModel extends CI_Model {

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *      http://example.com/index.php/welcome
     *  - or -
     *      http://example.com/index.php/welcome/index
     *  - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */
    public function admin_register_done()
    {
        $admin_name=$this->input->post('admin_name');
        $admin_email=$this->input->post('admin_email');
        $admin_mobileno=$this->input->post('admin_mobileno');
        $admin_username=$this->input->post('admin_username');
        $admin_password=$this->input->post('admin_password');
        $data=array(
            'admin_name'=>$admin_name,
            'admin_email'=>$admin_email,
            'admin_mobileno'=>$admin_mobileno,
            'admin_username'=>$admin_username,
            'admin_password'=>$admin_password
        );
        $this->db->insert('tbl_admin_registration',$data);
    }
    public function admin_login_done()
    {
        $admin_username=$this->input->post('admin_username');
        $admin_password=$this->input->post('admin_password');
        $this->db->select('admin_username','admin_password');
        $this->db->from('tbl_admin_registration');
        $this->db->where('admin_username',$admin_username);
        $this->db->where("admin_password",$admin_password);
        return $query=$this->db->get();
    }
    public function admin_add_image_done($image)
    {
        $image_info = $this->upload->data();
        $chocolate_name=$this->input->post('chocolate_name');
        $chocolate_price=$this->input->post('chocolate_price');
        $data=array(
            'image_name'=>'http://candymart.co.in/Admin/uploads/'.$image_info['file_name'],
            'chocolate_name'=>$chocolate_name,
            'chocolate_price'=>$chocolate_price
        );
        $this->db->insert('tbl_admin_chocolate',$data);
    }
        public function admin_add_image_done1()
    {

        $chocolate_name=$this->input->post('chocolate_name');
        $chocolate_price=$this->input->post('chocolate_price');
        $data=array(
            'chocolate_name'=>$chocolate_name,
            'chocolate_price'=>$chocolate_price
        );
        $this->db->insert('tbl_admin_chocolate',$data);
    }
    public function admin_add_madhurimage_done()
    {
        $image_info = $this->upload->data();
        $chocolate_name=$this->input->post('chocolate_name');
        $chocolate_price=$this->input->post('chocolate_price');
        $data=array(
            'image_name'=>$image_info['file_name'],
            'chocolate_name'=>$chocolate_name,
            'chocolate_price'=>$chocolate_price
        );
        $this->db->insert('tbl_admin_madhurchocolate',$data);
    }
    public function admin_add_crystalimage_done()
    {
        $image_info = $this->upload->data();
        $chocolate_name=$this->input->post('chocolate_name');
        $chocolate_price=$this->input->post('chocolate_price');
        $data=array(
            'image_name'=>$image_info['file_name'],
            'chocolate_name'=>$chocolate_name,
            'chocolate_price'=>$chocolate_price
        );
        $this->db->insert('tbl_admin_crystalchocolate',$data);
    }
    public function admin_add_candyimage_done()
    {
        $image_info = $this->upload->data();
        $chocolate_name=$this->input->post('chocolate_name');
        $chocolate_price=$this->input->post('chocolate_price');
        $data=array(
            'image_name'=>$image_info['file_name'],
            'chocolate_name'=>$chocolate_name,
            'chocolate_price'=>$chocolate_price
        );
        $this->db->insert('tbl_admin_candychocolate',$data);
    }

        public function admin_display_image_done()
    {

        $this->db->select('*');
        $this->db->from('tbl_admin_chocolate');
        $query=$this->db->get();
        return $query->result();
    }
        public function admin_display_madhurimage_done()
    {

        $this->db->select('*');
        $this->db->from('tbl_admin_madhurchocolate');
        $query=$this->db->get();
        return $query->result();
    }
        public function admin_display_crystalimage_done()
    {

        $this->db->select('*');
        $this->db->from('tbl_admin_crystalchocolate');
        $query=$this->db->get();
        return $query->result();
    }
       public function admin_display_candyimage_done()
    {

        $this->db->select('*');
        $this->db->from('tbl_admin_candychocolate');
        $query=$this->db->get();
        return $query->result();
    }
    public function admin_delete_image_done($id)
    {
        $this->db->where('tbl_admin_chocolate.id',$id);
        return $this->db->delete('tbl_admin_chocolate');

    }
    public function admin_delete_madhurimage_done($id)
    {
        $this->db->where('tbl_admin_madhurchocolate.id',$id);
        return $this->db->delete('tbl_admin_madhurchocolate');

    }
    public function admin_delete_crystalimage_done($id)
    {
        $this->db->where('tbl_admin_crystalchocolate.id',$id);
        return $this->db->delete('tbl_admin_crystalchocolate');

    }
        public function admin_delete_candyimage_done($id)
    {
        $this->db->where('tbl_admin_candychocolate.id',$id);
        return $this->db->delete('tbl_admin_candychocolate');

    }
    public function admin_edit_chocolate_done($id)
    {
       $query = $this->db->get_where('tbl_admin_chocolate',array('id'=>$id));
       return $query->row_array();
    }
    public function admin_edit_madhurchocolate_done($id)
    {
       $query = $this->db->get_where('tbl_admin_madhurchocolate',array('id'=>$id));
       return $query->row_array();
    }
    public function admin_edit_crystalchocolate_done($id)
    {
       $query = $this->db->get_where('tbl_admin_crystalchocolate',array('id'=>$id));
       return $query->row_array();
    }
    public function admin_edit_candychocolate_done($id)
    {
       $query = $this->db->get_where('tbl_admin_candychocolate',array('id'=>$id));
       return $query->row_array();
    }
    public function admin_update_chocolate_done($id)
    {
        $image_info = $this->upload->data();
        $chocolate_name=$this->input->post('chocolate_name');
        $chocolate_price=$this->input->post('chocolate_price');

        $data=array(
            'image_name'=>'http://candymart.co.in/Admin/uploads/'.$image_info['file_name'],
            'chocolate_name'=>$chocolate_name,
            'chocolate_price'=>$chocolate_price
        );
        $this->db->set($data);
        $this->db->where('tbl_admin_chocolate.id',$id);
        return $this->db->update('tbl_admin_chocolate',$data);
    }
        public function admin_update_madhurchocolate_done($id)
    {
        $image_info = $this->upload->data();
        $chocolate_name=$this->input->post('chocolate_name');
        $chocolate_price=$this->input->post('chocolate_price');

        $data=array(
            'image_name'=>$image_info['file_name'],
            'chocolate_name'=>$chocolate_name,
            'chocolate_price'=>$chocolate_price
        );
        $this->db->set($data);
        $this->db->where('tbl_admin_madhurchocolate.id',$id);
        return $this->db->update('tbl_admin_madhurchocolate',$data);
    }
        public function admin_update_crystalchocolate_done($id)
    {
        $image_info = $this->upload->data();
        $chocolate_name=$this->input->post('chocolate_name');
        $chocolate_price=$this->input->post('chocolate_price');

        $data=array(
            'image_name'=>$image_info['file_name'],
            'chocolate_name'=>$chocolate_name,
            'chocolate_price'=>$chocolate_price
        );
        $this->db->set($data);
        $this->db->where('tbl_admin_crystalchocolate.id',$id);
        return $this->db->update('tbl_admin_crystalchocolate',$data);
    }
        public function admin_update_candychocolate_done($id)
    {
        $image_info = $this->upload->data();
        $chocolate_name=$this->input->post('chocolate_name');
        $chocolate_price=$this->input->post('chocolate_price');

        $data=array(
            'image_name'=>$image_info['file_name'],
            'chocolate_name'=>$chocolate_name,
            'chocolate_price'=>$chocolate_price
        );
        $this->db->set($data);
        $this->db->where('tbl_admin_candychocolate.id',$id);
        return $this->db->update('tbl_admin_candychocolate',$data);
    }
}
</code>```

Controller

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Admin extends CI_Controller {

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *      http://example.com/index.php/welcome
     *  - or -
     *      http://example.com/index.php/welcome/index
     *  - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */
    public function index()
    {
        $this->load->view('manisha_admin');
    }
    public function admin_register()
    {
        $this->load->view('admin_register');
    }
    public function admin_register_data()
    {

        $this->load->model('AdminModel');
        $this->AdminModel->admin_register_done();
        $this->load->view('admin_login');
    }
    public function admin_login()
    {
        $this->load->view('admin_login');
    }
    public function admin_login_data()
    {

        $this->load->model('AdminModel');
        $this->AdminModel->admin_login_done();
        $data['sub'] = $this->AdminModel->admin_display_image_done();
        $this->load->view('add_image',$data);
    }
    public function admin_add_image()
    {
         $config['upload_path']   = './uploads/';
         $config['allowed_types'] = 'gif|jpg|png|jpeg';
         //$config['max_size']      = 100;
         //$config['max_width']     = 1024;
         //$config['max_height']    = 768;
         $this->load->library('upload', $config);

         if ( ! $this->upload->do_upload('file_to_upload')) {
            $error = array('error' => $this->upload->display_errors());
            //$image = 'http://candymart.co.in/Admin/uploads/1.JPG';
            $this->load->view('add_image');
         }

         else {
            $data = array('upload_data' => $this->upload->data());
            //$image = $_FILES['file_to_upload']['name'];
            $this->load->view('Upload_success', $data);
            $this->load->model('AdminModel');
            $this->AdminModel->admin_add_image_done();

         }
    }
    public function admin_add_madhurimage()
    {
         $config['upload_path']   = './uploads/';
         $config['allowed_types'] = 'gif|jpg|png|jpeg';
         //$config['max_size']      = 100;
         //$config['max_width']     = 1024;
         //$config['max_height']    = 768;
         $this->load->library('upload', $config);

         if ( ! $this->upload->do_upload('file_to_upload')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('add_madhurimage', $error);
         }

         else {
            $data = array('upload_data' => $this->upload->data());
            $this->load->view('Upload_success', $data);
            $this->load->model('AdminModel');
            $this->AdminModel->admin_add_madhurimage_done();
         }
    }
        public function admin_add_crystalimage()
    {
         $config['upload_path']   = './uploads/';
         $config['allowed_types'] = 'gif|jpg|png|jpeg';
         //$config['max_size']      = 100;
         //$config['max_width']     = 1024;
         //$config['max_height']    = 768;
         $this->load->library('upload', $config);

         if ( ! $this->upload->do_upload('file_to_upload')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('add_crystalimage', $error);
         }

         else {
            $data = array('upload_data' => $this->upload->data());
            $this->load->view('Upload_success', $data);
            $this->load->model('AdminModel');
            $this->AdminModel->admin_add_crystalimage_done();
         }
    }
        public function admin_add_candyimage()
    {
         $config['upload_path']   = './uploads/';
         $config['allowed_types'] = 'gif|jpg|png|jpeg';
         //$config['max_size']      = 100;
         //$config['max_width']     = 1024;
         //$config['max_height']    = 768;
         $this->load->library('upload', $config);

         if ( ! $this->upload->do_upload('file_to_upload')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('add_candyimage', $error);
         }

         else {
            $data = array('upload_data' => $this->upload->data());
            $this->load->view('Upload_success', $data);
            $this->load->model('AdminModel');
            $this->AdminModel->admin_add_candyimage_done();
         }
    }
    public function admin_edit_image()
    {
         $config['upload_path']   = './uploads/';
         $config['allowed_types'] = 'gif|jpg|png';
         //$config['max_size']      = 100;
         //$config['max_width']     = 1024;
         //$config['max_height']    = 768;
         $this->load->library('upload', $config);

         if ( ! $this->upload->do_upload('file_to_upload')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('edit_chocolate', $error);
         }

         else {
            $id = $this->input->post('hidden_id1');
            $data = array('upload_data' => $this->upload->data());
            //$this->load->view('Upload_success',$data);
            $this->load->model('AdminModel');
            $this->AdminModel->admin_update_chocolate_done($id);
            $data['sub'] = $this->AdminModel->admin_display_image_done();
            $this->load->view('display_image',$data);
         }
    }
    public function admin_edit_madhurimage()
    {
         $config['upload_path']   = './uploads/';
         $config['allowed_types'] = 'gif|jpg|png|jpeg';
         //$config['max_size']      = 100;
         //$config['max_width']     = 1024;
         //$config['max_height']    = 768;
         $this->load->library('upload', $config);

         if ( ! $this->upload->do_upload('file_to_upload')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('edit_madhurchocolate', $error);
         }

         else {
            $id = $this->input->post('hidden_id2');
            $data = array('upload_data' => $this->upload->data());
            //$this->load->view('Upload_success',$data);
            $this->load->model('AdminModel');
            $this->AdminModel->admin_update_madhurchocolate_done($id);
            $data['sub'] = $this->AdminModel->admin_display_madhurimage_done();
            $this->load->view('display_madhurimage',$data);
         }
    }
    public function admin_edit_crystalimage()
    {
         $config['upload_path']   = './uploads/';
         $config['allowed_types'] = 'gif|jpg|png|jpeg';
         //$config['max_size']      = 100;
         //$config['max_width']     = 1024;
         //$config['max_height']    = 768;
         $this->load->library('upload', $config);

         if ( ! $this->upload->do_upload('file_to_upload')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('edit_crystalchocolate', $error);
         }

         else {
            $id = $this->input->post('hidden_id3');
            $data = array('upload_data' => $this->upload->data());
            //$this->load->view('Upload_success',$data);
            $this->load->model('AdminModel');
            $this->AdminModel->admin_update_crystalchocolate_done($id);
            $data['sub'] = $this->AdminModel->admin_display_crystalimage_done();
            $this->load->view('display_crystalimage',$data);

         }
    }
    public function admin_edit_candyimage()
    {
         $config['upload_path']   = './uploads/';
         $config['allowed_types'] = 'gif|jpg|png|jpeg';
         //$config['max_size']      = 100;
         //$config['max_width']     = 1024;
         //$config['max_height']    = 768;
         $this->load->library('upload', $config);

         if ( ! $this->upload->do_upload('file_to_upload')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('edit_candychocolate', $error);
         }

         else {
            $id = $this->input->post('hidden_id4');
            $data = array('upload_data' => $this->upload->data());
            //$this->load->view('Upload_success',$data);
            $this->load->model('AdminModel');
            $this->AdminModel->admin_update_candychocolate_done($id);
            $data['sub'] = $this->AdminModel->admin_display_candyimage_done();
            $this->load->view('display_candyimage',$data);
         }
    }
    public function admin_display_image()
    {
        $this->load->model('AdminModel');
        $data['sub'] = $this->AdminModel->admin_display_image_done();
        $this->load->view('display_image',$data);
    }
    public function admin_display_madhurimage()
    {
        $this->load->model('AdminModel');
        $data['sub'] = $this->AdminModel->admin_display_madhurimage_done();
        $this->load->view('display_madhurimage',$data);
    }
    public function admin_display_crystalimage()
    {
        $this->load->model('AdminModel');
        $data['sub'] = $this->AdminModel->admin_display_crystalimage_done();
        $this->load->view('display_crystalimage',$data);
    }
    public function admin_display_candyimage()
    {
        $this->load->model('AdminModel');
        $data['sub'] = $this->AdminModel->admin_display_candyimage_done();
        $this->load->view('display_candyimage',$data);
    }

    public function admin_delete_image()
    {
        $id = $this->uri->segment(3);
        $this->load->model('AdminModel');
        $this->AdminModel->admin_delete_image_done($id);
        $data['sub'] = $this->AdminModel->admin_display_image_done();
        $this->load->view('display_image',$data);
    }
        public function admin_delete_madhurimage()
    {
        $id = $this->uri->segment(3);
        $this->load->model('AdminModel');
        $this->AdminModel->admin_delete_madhurimage_done($id);
        $data['sub'] = $this->AdminModel->admin_display_madhurimage_done();
        $this->load->view('display_madhurimage',$data);

    }
            public function admin_delete_crystalimage()
    {
        $id = $this->uri->segment(3);
        $this->load->model('AdminModel');
        $this->AdminModel->admin_delete_crystalimage_done($id);
        $data['sub'] = $this->AdminModel->admin_display_crystalimage_done();
        $this->load->view('display_crystalimage',$data);

    }
            public function admin_delete_candyimage()
    {
        $id = $this->uri->segment(3);
        $this->load->model('AdminModel');
        $this->AdminModel->admin_delete_candyimage_done($id);
        $data['sub'] = $this->AdminModel->admin_display_candyimage_done();
        $this->load->view('display_candyimage',$data);
    }
    public function admin_edit_chocolate()
    {
        $id = $this->uri->segment(3);

        $this->load->model('AdminModel');
        $data['user1']=$this->AdminModel->admin_edit_chocolate_done($id);
        $this->load->view('edit_chocolate',$data);

    }
        public function admin_edit_madhurchocolate()
    {
        $id = $this->uri->segment(3);

        $this->load->model('AdminModel');
        $data['user2']=$this->AdminModel->admin_edit_madhurchocolate_done($id);
        $this->load->view('edit_madhurchocolate',$data);

    }
        public function admin_edit_crystalchocolate()
    {
        $id = $this->uri->segment(3);

        $this->load->model('AdminModel');
        $data['user3']=$this->AdminModel->admin_edit_crystalchocolate_done($id);
        $this->load->view('edit_crystalchocolate',$data);

    }
        public function admin_edit_candychocolate()
    {
        $id = $this->uri->segment(3);

        $this->load->model('AdminModel');
        $data['user4']=$this->AdminModel->admin_edit_candychocolate_done($id);
        $this->load->view('edit_candychocolate',$data);

    }
        public function admin_update_chocolate()
    {
        $id = $this->input->post('hidden_id1');
        $this->load->model('AdminModel');
        $this->AdminModel->admin_update_chocolate_done($id);
    }
        public function admin_update_madhurchocolate()
    {
        $id = $this->input->post('hidden_id2');
        $this->load->model('AdminModel');
        $this->AdminModel->admin_update_madhurchocolate_done($id);

    }
        public function admin_update_crystalchocolate()
    {
        $id = $this->input->post('hidden_id3');
        $this->load->model('AdminModel');
        $this->AdminModel->admin_update_crystalchocolate_done($id);

    }
        public function admin_update_candychocolate()
    {
        $id = $this->input->post('hidden_id4');
        $this->load->model('AdminModel');
        $this->AdminModel->admin_update_candychocolate_done($id);

    }
        public function admin_logout()
    {
        $user_data = $this->session->all_userdata();
        foreach ($user_data as $key => $value) {
            if ($key != 'session_id' && $key != 'ip_address' && $key != 'user_agent' && $key != 'last_activity') {
                $this->session->unset_userdata($key);
            }
        }
        $this->session->sess_destroy();
        redirect('Admin/index');
     }

}
```

答:
Your view file HTML form should have enctype attribute to upload file.

<form action="" method="post" enctype="multipart/form-data">
 </form>

Title: Image upload issue with Codeigniter

Body:
I'm stuck with an issue updating images. I've created image upload which works fine but when I try to update an entry with other details which already has an image, it throws an error. Is there a way we can skip the image upload check altogether and the entry updates with or without the image?

View:

        <?php require_once("header.php"); ?>

        <?php require_once("sidebar.php"); ?>

Add Mick Chocolate

                      Chocolate
                      / Home / Add Mick Chocolate

Input

                    <?php

                        echo form_open_multipart('Admin/admin_add_image');

                    ?>

                      <form class="form-horizontal" action = "" method ="post">

                          Name

                            <input type="text" id="text1" name="chocolate_name" pattern="^[A-Za-z -]+$" required >

                          Price

                            <input type="text" id="text2" name="chocolate_price" pattern="^(0|[1-9][0-9]*)$" required >

                          Upload Image

                            <input type="file" id="text3" name="file_to_upload" accept="image/gif, image/jpeg, image/png, image/jpg">

                                <button type="submit" name="btn_add" class="btn btn-info">Add</button>
                      </form>

               <?php require_once("footer.php"); ?>

**Model**

```php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class AdminModel extends CI_Model {

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *      http://example.com/index.php/welcome
     *  - or -
     *      http://example.com/index.php/welcome/index
     *  - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */
    public function admin_register_done()
    {
        $admin_name=$this->input->post('admin_name');
        $admin_email=$this->input->post('admin_email');
        $admin_mobileno=$this->input->post('admin_mobileno');
        $admin_username=$this->input->post('admin_username');
        $admin_password=$this->input->post('admin_password');
        $data=array(
            'admin_name'=>$admin_name,
            'admin_email'=>$admin_email,
            'admin_mobileno'=>$admin_mobileno,
            'admin_username'=>$admin_username,
            'admin_password'=>$admin_password
        );
        $this->db->insert('tbl_admin_registration',$data);
    }
    public function admin_login_done()
    {
        $admin_username=$this->input->post('admin_username');
        $admin_password=$this->input->post('admin_password');
        $this->db->select('admin_username','admin_password');
        $this->db->from('tbl_admin_registration');
        $this->db->where('admin_username',$admin_username);
        $this->db->where("admin_password",$admin_password);
        return $query=$this->db->get();
    }
    public function admin_add_image_done($image)
    {
        $image_info = $this->upload->data();
        $chocolate_name=$this->input->post('chocolate_name');
        $chocolate_price=$this->input->post('chocolate_price');
        $data=array(
            'image_name'=>'http://candymart.co.in/Admin/uploads/'.$image_info['file_name'],
            'chocolate_name'=>$chocolate_name,
            'chocolate_price'=>$chocolate_price
        );
        $this->db->insert('tbl_admin_chocolate',$data);
    }
        public function admin_add_image_done1()
    {

        $chocolate_name=$this->input->post('chocolate_name');
        $chocolate_price=$this->input->post('chocolate_price');
        $data=array(
            'chocolate_name'=>$chocolate_name,
            'chocolate_price'=>$chocolate_price
        );
        $this->db->insert('tbl_admin_chocolate',$data);
    }
    public function admin_add_madhurimage_done()
    {
        $image_info = $this->upload->data();
        $chocolate_name=$this->input->post('chocolate_name');
        $chocolate_price=$this->input->post('chocolate_price');
        $data=array(
            'image_name'=>$image_info['file_name'],
            'chocolate_name'=>$chocolate_name,
            'chocolate_price'=>$chocolate_price
        );
        $this->db->insert('tbl_admin_madhurchocolate',$data);
    }
    public function admin_add_crystalimage_done()
    {
        $image_info = $this->upload->data();
        $chocolate_name=$this->input->post('chocolate_name');
        $chocolate_price=$this->input->post('chocolate_price');
        $data=array(
            'image_name'=>$image_info['file_name'],
            'chocolate_name'=>$chocolate_name,
            'chocolate_price'=>$chocolate_price
        );
        $this->db->insert('tbl_admin_crystalchocolate',$data);
    }
    public function admin_add_candyimage_done()
    {
        $image_info = $this->upload->data();
        $chocolate_name=$this->input->post('chocolate_name');
        $chocolate_price=$this->input->post('chocolate_price');
        $data=array(
            'image_name'=>$image_info['file_name'],
            'chocolate_name'=>$chocolate_name,
            'chocolate_price'=>$chocolate_price
        );
        $this->db->insert('tbl_admin_candychocolate',$data);
    }

        public function admin_display_image_done()
    {

        $this->db->select('*');
        $this->db->from('tbl_admin_chocolate');
        $query=$this->db->get();
        return $query->result();
    }
        public function admin_display_madhurimage_done()
    {

        $this->db->select('*');
        $this->db->from('tbl_admin_madhurchocolate');
        $query=$this->db->get();
        return $query->result();
    }
        public function admin_display_crystalimage_done()
    {

        $this->db->select('*');
        $this->db->from('tbl_admin_crystalchocolate');
        $query=$this->db->get();
        return $query->result();
    }
       public function admin_display_candyimage_done()
    {

        $this->db->select('*');
        $this->db->from('tbl_admin_candychocolate');
        $query=$this->db->get();
        return $query->result();
    }
    public function admin_delete_image_done($id)
    {
        $this->db->where('tbl_admin_chocolate.id',$id);
        return $this->db->delete('tbl_admin_chocolate');

    }
    public function admin_delete_madhurimage_done($id)
    {
        $this->db->where('tbl_admin_madhurchocolate.id',$id);
        return $this->db->delete('tbl_admin_madhurchocolate');

    }
    public function admin_delete_crystalimage_done($id)
    {
        $this->db->where('tbl_admin_crystalchocolate.id',$id);
        return $this->db->delete('tbl_admin_crystalchocolate');

    }
        public function admin_delete_candyimage_done($id)
    {
        $this->db->where('tbl_admin_candychocolate.id',$id);
        return $this->db->delete('tbl_admin_candychocolate');

    }
    public function admin_edit_chocolate_done($id)
    {
       $query = $this->db->get_where('tbl_admin_chocolate',array('id'=>$id));
       return $query->row_array();
    }
    public function admin_edit_madhurchocolate_done($id)
    {
       $query = $this->db->get_where('tbl_admin_madhurchocolate',array('id'=>$id));
       return $query->row_array();
    }
    public function admin_edit_crystalchocolate_done($id)
    {
       $query = $this->db->get_where('tbl_admin_crystalchocolate',array('id'=>$id));
       return $query->row_array();
    }
    public function admin_edit_candychocolate_done($id)
    {
       $query = $this->db->get_where('tbl_admin_candychocolate',array('id'=>$id));
       return $query->row_array();
    }
    public function admin_update_chocolate_done($id)
    {
        $image_info = $this->upload->data();
        $chocolate_name=$this->input->post('chocolate_name');
        $chocolate_price=$this->input->post('chocolate_price');

        $data=array(
            'image_name'=>'http://candymart.co.in/Admin/uploads/'.$image_info['file_name'],
            'chocolate_name'=>$chocolate_name,
            'chocolate_price'=>$chocolate_price
        );
        $this->db->set($data);
        $this->db->where('tbl_admin_chocolate.id',$id);
        return $this->db->update('tbl_admin_chocolate',$data);
    }
        public function admin_update_madhurchocolate_done($id)
    {
        $image_info = $this->upload->data();
        $chocolate_name=$this->input->post('chocolate_name');
        $chocolate_price=$this->input->post('chocolate_price');

        $data=array(
            'image_name'=>$image_info['file_name'],
            'chocolate_name'=>$chocolate_name,
            'chocolate_price'=>$chocolate_price
        );
        $this->db->set($data);
        $this->db->where('tbl_admin_madhurchocolate.id',$id);
        return $this->db->update('tbl_admin_madhurchocolate',$data);
    }
        public function admin_update_crystalchocolate_done($id)
    {
        $image_info = $this->upload->data();
        $chocolate_name=$this->input->post('chocolate_name');
        $chocolate_price=$this->input->post('chocolate_price');

        $data=array(
            'image_name'=>$image_info['file_name'],
            'chocolate_name'=>$chocolate_name,
            'chocolate_price'=>$chocolate_price
        );
        $this->db->set($data);
        $this->db->where('tbl_admin_crystalchocolate.id',$id);
        return $this->db->update('tbl_admin_crystalchocolate',$data);
    }
        public function admin_update_candychocolate_done($id)
    {
        $image_info = $this->upload->data();
        $chocolate_name=$this->input->post('chocolate_name');
        $chocolate_price=$this->input->post('chocolate_price');

        $data=array(
            'image_name'=>$image_info['file_name'],
            'chocolate_name'=>$chocolate_name,
            'chocolate_price'=>$chocolate_price
        );
        $this->db->set($data);
        $this->db->where('tbl_admin_candychocolate.id',$id);
        return $this->db->update('tbl_admin_candychocolate',$data);
    }
}

Controller

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Admin extends CI_Controller {

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *      http://example.com/index.php/welcome
     *  - or -
     *      http://example.com/index.php/welcome/index
     *  - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */
    public function index()
    {
        $this->load->view('manisha_admin');
    }
    public function admin_register()
    {
        $this->load->view('admin_register');
    }
    public function admin_register_data()
    {

        $this->load->model('AdminModel');
        $this->AdminModel->admin_register_done();
        $this->load->view('admin_login');
    }
    public function admin_login()
    {
        $this->load->view('admin_login');
    }
    public function admin_login_data()
    {

        $this->load->model('AdminModel');
        $this->AdminModel->admin_login_done();
        $data['sub'] = $this->AdminModel->admin_display_image_done();
        $this->load->view('add_image',$data);
    }
    public function admin_add_image()
    {
         $config['upload_path']   = './uploads/';
         $config['allowed_types'] = 'gif|jpg|png|jpeg';
         //$config['max_size']      = 100;
         //$config['max_width']     = 1024;
         //$config['max_height']    = 768;
         $this->load->library('upload', $config);

         if ( ! $this->upload->do_upload('file_to_upload')) {
            $error = array('error' => $this->upload->display_errors());
            //$image = 'http://candymart.co.in/Admin/uploads/1.JPG';
            $this->load->view('add_image');
         }

         else {
            $data = array('upload_data' => $this->upload->data());
            //$image = $_FILES['file_to_upload']['name'];
            $this->load->view('Upload_success', $data);
            $this->load->model('AdminModel');
            $this->AdminModel->admin_add_image_done();

         }
    }
    public function admin_add_madhurimage()
    {
         $config['upload_path']   = './uploads/';
         $config['allowed_types'] = 'gif|jpg|png|jpeg';
         //$config['max_size']      = 100;
         //$config['max_width']     = 1024;
         //$config['max_height']    = 768;
         $this->load->library('upload', $config);

         if ( ! $this->upload->do_upload('file_to_upload')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('add_madhurimage', $error);
         }

         else {
            $data = array('upload_data' => $this->upload->data());
            $this->load->view('Upload_success', $data);
            $this->load->model('AdminModel');
            $this->AdminModel->admin_add_madhurimage_done();
         }
    }
        public function admin_add_crystalimage()
    {
         $config['upload_path']   = './uploads/';
         $config['allowed_types'] = 'gif|jpg|png|jpeg';
         //$config['max_size']      = 100;
         //$config['max_width']     = 1024;
         //$config['max_height']    = 768;
         $this->load->library('upload', $config);

         if ( ! $this->upload->do_upload('file_to_upload')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('add_crystalimage', $error);
         }

         else {
            $data = array('upload_data' => $this->upload->data());
            $this->load->view('Upload_success', $data);
            $this->load->model('AdminModel');
            $this->AdminModel->admin_add_crystalimage_done();
         }
    }
        public function admin_add_candyimage()
    {
         $config['upload_path']   = './uploads/';
         $config['allowed_types'] = 'gif|jpg|png|jpeg';
         //$config['max_size']      = 100;
         //$config['max_width']     = 1024;
         //$config['max_height']    = 768;
         $this->load->library('upload', $config);

         if ( ! $this->upload->do_upload('file_to_upload')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('add_candyimage', $error);
         }

         else {
            $data = array('upload_data' => $this->upload->data());
            $this->load->view('Upload_success', $data);
            $this->load->model('AdminModel');
            $this->AdminModel->admin_add_candyimage_done();
         }
    }
    public function admin_edit_image()
    {
         $config['upload_path']   = './uploads/';
         $config['allowed_types'] = 'gif|jpg|png';
         //$config['max_size']      = 100;
         //$config['max_width']     = 1024;
         //$config['max_height']    = 768;
         $this->load->library('upload', $config);

         if ( ! $this->upload->do_upload('file_to_upload')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('edit_chocolate', $error);
         }

         else {
            $id = $this->input->post('hidden_id1');
            $data = array('upload_data' => $this->upload->data());
            //$this->load->view('Upload_success',$data);
            $this->load->model('AdminModel');
            $this->AdminModel->admin_update_chocolate_done($id);
            $data['sub'] = $this->AdminModel->admin_display_image_done();
            $this->load->view('display_image',$data);
         }
    }
    public function admin_edit_madhurimage()
    {
         $config['upload_path']   = './uploads/';
         $config['allowed_types'] = 'gif|jpg|png|jpeg';
         //$config['max_size']      = 100;
         //$config['max_width']     = 1024;
         //$config['max_height']    = 768;
         $this->load->library('upload', $config);

         if ( ! $this->upload->do_upload('file_to_upload')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('edit_madhurchocolate', $error);
         }

         else {
            $id = $this->input->post('hidden_id2');
            $data = array('upload_data' => $this->upload->data());
            //$this->load->view('Upload_success',$data);
            $this->load->model('AdminModel');
            $this->AdminModel->admin_update_madhurchocolate_done($id);
            $data['sub'] = $this->AdminModel->admin_display_madhurimage_done();
            $this->load->view('display_madhurimage',$data);
         }
    }
    public function admin_edit_crystalimage()
    {
         $config['upload_path']   = './uploads/';
         $config['allowed_types'] = 'gif|jpg|png|jpeg';
         //$config['max_size']      = 100;
         //$config['max_width']     = 1024;
         //$config['max_height']    = 768;
         $this->load->library('upload', $config);

         if ( ! $this->upload->do_upload('file_to_upload')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('edit_crystalchocolate', $error);
         }

         else {
            $id = $this->input->post('hidden_id3');
            $data = array('upload_data' => $this->upload->data());
            //$this->load->view('Upload_success',$data);
            $this->load->model('AdminModel');
            $this->AdminModel->admin_update_crystalchocolate_done($id);
            $data['sub'] = $this->AdminModel->admin_display_crystalimage_done();
            $this->load->view('display_crystalimage',$data);

         }
    }
    public function admin_edit_candyimage()
    {
         $config['upload_path']   = './uploads/';
         $config['allowed_types'] = 'gif|jpg|png|jpeg';
         //$config['max_size']      = 100;
         //$config['max_width']     = 1024;
         //$config['max_height']    = 768;
         $this->load->library('upload', $config);

         if ( ! $this->upload->do_upload('file_to_upload')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('edit_candychocolate', $error);
         }

         else {
            $id = $this->input->post('hidden_id4');
            $data = array('upload_data' => $this->upload->data());
            //$this->load->view('Upload_success',$data);
            $this->load->model('AdminModel');
            $this->AdminModel->admin_update_candychocolate_done($id);
            $data['sub'] = $this->AdminModel->admin_display_candyimage_done();
            $this->load->view('display_candyimage',$data);
         }
    }
    public function admin_display_image()
    {
        $this->load->model('AdminModel');
        $data['sub'] = $this->AdminModel->admin_display_image_done();
        $this->load->view('display_image',$data);
    }
    public function admin_display_madhurimage()
    {
        $this->load->model('AdminModel');
        $data['sub'] = $this->AdminModel->admin_display_madhurimage_done();
        $this->load->view('display_madhurimage',$data);
    }
    public function admin_display_crystalimage()
    {
        $this->load->model('AdminModel');
        $data['sub'] = $this->AdminModel->admin_display_crystalimage_done();
        $this->load->view('display_crystalimage',$data);
    }
    public function admin_display_candyimage()
    {
        $this->load->model('AdminModel');
        $data['sub'] = $this->AdminModel->admin_display_candyimage_done();
        $this->load->view('display_candyimage',$data);
    }

    public function admin_delete_image()
    {
        $id = $this->uri->segment(3);
        $this->load->model('AdminModel');
        $this->AdminModel->admin_delete_image_done($id);
        $data['sub'] = $this->AdminModel->admin_display_image_done();
        $this->load->view('display_image',$data);
    }
        public function admin_delete_madhurimage()
    {
        $id = $this->uri->segment(3);
        $this->load->model('AdminModel');
        $this->AdminModel->admin_delete_madhurimage_done($id);
        $data['sub'] = $this->AdminModel->admin_display_madhurimage_done();
        $this->load->view('display_madhurimage',$data);

    }
            public function admin_delete_crystalimage()
    {
        $id = $this->uri->segment(3);
        $this->load->model('AdminModel');
        $this->AdminModel->admin_delete_crystalimage_done($id);
        $data['sub'] = $this->AdminModel->admin_display_crystalimage_done();
        $this->load->view('display_crystalimage',$data);

    }
            public function admin_delete_candyimage()
    {
        $id = $this->uri->segment(3);
        $this->load->model('AdminModel');
        $this->AdminModel->admin_delete_candyimage_done($id);
        $data['sub'] = $this->AdminModel->admin_display_candyimage_done();
        $this->load->view('display_candyimage',$data);
    }
    public function admin_edit_chocolate()
    {
        $id = $this->uri->segment(3);

        $this->load->model('AdminModel');
        $data['user1']=$this->AdminModel->admin_edit_chocolate_done($id);
        $this->load->view('edit_chocolate',$data);

    }
        public function admin_edit_madhurchocolate()
    {
        $id = $this->uri->segment(3);

        $this->load->model('AdminModel');
        $data['user2']=$this->AdminModel->admin_edit_madhurchocolate_done($id);
        $this->load->view('edit_madhurchocolate',$data);

    }
        public function admin_edit_crystalchocolate()
    {
        $id = $this->uri->segment(3);

        $this->load->model('AdminModel');
        $data['user3']=$this->AdminModel->admin_edit_crystalchocolate_done($id);
        $this->load->view('edit_crystalchocolate',$data);

    }
        public function admin_edit_candychocolate()
    {
        $id = $this->uri->segment(3);

        $this->load->model('AdminModel');
        $data['user4']=$this->AdminModel->admin_edit_candychocolate_done($id);
        $this->load->view('edit_candychocolate',$data);

    }
        public function admin_update_chocolate()
    {
        $id = $this->input->post('hidden_id1');
        $this->load->model('AdminModel');
        $this->AdminModel->admin_update_chocolate_done($id);
    }
        public function admin_update_madhurchocolate()
    {
        $id = $this->input->post('hidden_id2');
        $this->load->model('AdminModel');
        $this->AdminModel->admin_update_madhurchocolate_done($id);

    }
        public function admin_update_crystalchocolate()
    {
        $id = $this->input->post('hidden_id3');
        $this->load->model('AdminModel');
        $this->AdminModel->admin_update_crystalchocolate_done($id);

    }
        public function admin_update_candychocolate()
    {
        $id = $this->input->post('hidden_id4');
        $this->load->model('AdminModel');
        $this->AdminModel->admin_update_candychocolate_done($id);

    }
        public function admin_logout()
    {
        $user_data = $this->session->all_userdata();
        foreach ($user_data as $key => $value) {
            if ($key != 'session_id' && $key != 'ip_address' && $key != 'user_agent' && $key != 'last_activity') {
                $this->session->unset_userdata($key);
            }
        }
        $this->session->sess_destroy();
        redirect('Admin/index');
     }

}


来源: stackexchange

问:
How to get the direction of <Motion> in tkinter?
I'm trying to get the direction of the tkinter <Motion> (actually <B1-Motion>) event.

I already tried to use event.direction (error), event.keysym (??) and event itself gave me some coordinates.

So here is my code so far:

```<code>def holdanddrag(event):
    print('Direction: '+event.   … ) # here I need some help
Widget.bind('<B1-Motion>', holdanddrag)
</code>```

Does anyone know what to do? Thanks in advance!

答:
In order to determine a direction, you must store a previous position, and use it to calculate the direction of motion (a normalized vector) to the actual position. These variables must be updated as the motion happens.

Here is a small example that draws a vector (arrow) corresponding to the direction of the mouse drag on the canvas:

```<code>import math
import tkinter as tk
from collections import deque

class Vector:
    """small class for vector arithmetic convenience
    """
    def __init__(self, x: float=0, y: float=0) -> None:
        self.x = x
        self.y = y
    def __str__(self) -> str:
        return f'({self.x}, {self.y})'
    def __mul__(self, scalar: float) -> 'Vector':
        return Vector(self.x * scalar, self.y * scalar)
    def magnitude(self) -> float:
        return math.hypot(self.x, self.y)
    def normalize(self) -> 'Vector':
        mag = self.magnitude()
        return Vector(self.x / mag, self.y / mag) if mag != 0 else Vector()
    def __repr__(self) -> str:
        return str(self)
    def __iter__(self) -> float:
        yield self.x
        yield self.y

class Point:
    """small class for point arithmetic convenience
    """
    def __init__(self, x: float, y: float):
        self.x = x
        self.y = y
    def __sub__(self, other: 'Point') -> Vector:
        return Vector(other.x - self.x, other.y - self.y)
    def __add__(self, vec: Vector) -> 'Point':
        return Point(self.x + vec.x, self.y + vec.y)
    def __str__(self) -> str:
        return f'({self.x}, {self.y})'
    def __repr__(self) -> str:
        return str(self)
    def __iter__(self) -> float:
        yield self.x
        yield self.y

def draw_dir(canvas, start_point: Point, _vid=[None]) -> None:
    """draws and updates the scaled normalized direction vector
    on the canvas.
    Keeps track of the id of the canvas item last drawn
    """
    if _vid[0] is not None:
        canvas.delete(_vid[0])
    normed_scaled_v = direct.normalize() * -50
    end_point = start_point + normed_scaled_v
    _vid[0] = canvas.create_line(*start_point, *end_point, arrow=tk.LAST)

_maxlen = 4

def direction(event, _direct=deque([Vector(0, 0) for _ in range(_maxlen)], maxlen=_maxlen)) -> None:
    """stores previous position, and uses it to calculate the direction
    from the current position.
    updates these variables
    """
    global direct
    _direct.append(Point(event.x, event.y))
    p0, p1 = _direct[0], _direct[-1]
    direct = p1 - p0
    draw_dir(canvas, p1)
#     print(_direct, direct)

direct = Vector(0, 0)

root = tk.Tk()
canvas = tk.Canvas(root, bg='cyan')
canvas.pack()
canvas.bind('<B1-Motion>', direction)
root.mainloop()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to get the direction of the tkinter <Motion> (actually <B1-Motion>) event.

I already tried to use event.direction (error), event.keysym (??) and event itself gave me some coordinates.

So here is my code so far:

def holdanddrag(event):
    print('Direction: '+event.   … ) # here I need some help
Widget.bind('<B1-Motion>', holdanddrag)

Does anyone know what to do? Thanks in advance!

Body:
In order to determine a direction, you must store a previous position, and use it to calculate the direction of motion (a normalized vector) to the actual position. These variables must be updated as the motion happens.

Here is a small example that draws a vector (arrow) corresponding to the direction of the mouse drag on the canvas:

import math
import tkinter as tk
from collections import deque

class Vector:
    """small class for vector arithmetic convenience
    """
    def __init__(self, x: float=0, y: float=0) -> None:
        self.x = x
        self.y = y
    def __str__(self) -> str:
        return f'({self.x}, {self.y})'
    def __mul__(self, scalar: float) -> 'Vector':
        return Vector(self.x * scalar, self.y * scalar)
    def magnitude(self) -> float:
        return math.hypot(self.x, self.y)
    def normalize(self) -> 'Vector':
        mag = self.magnitude()
        return Vector(self.x / mag, self.y / mag) if mag != 0 else Vector()
    def __repr__(self) -> str:
        return str(self)
    def __iter__(self) -> float:
        yield self.x
        yield self.y

class Point:
    """small class for point arithmetic convenience
    """
    def __init__(self, x: float, y: float):
        self.x = x
        self.y = y
    def __sub__(self, other: 'Point') -> Vector:
        return Vector(other.x - self.x, other.y - self.y)
    def __add__(self, vec: Vector) -> 'Point':
        return Point(self.x + vec.x, self.y + vec.y)
    def __str__(self) -> str:
        return f'({self.x}, {self.y})'
    def __repr__(self) -> str:
        return str(self)
    def __iter__(self) -> float:
        yield self.x
        yield self.y

def draw_dir(canvas, start_point: Point, _vid=[None]) -> None:
    """draws and updates the scaled normalized direction vector
    on the canvas.
    Keeps track of the id of the canvas item last drawn
    """
    if _vid[0] is not None:
        canvas.delete(_vid[0])
    normed_scaled_v = direct.normalize() * -50
    end_point = start_point + normed_scaled_v
    _vid[0] = canvas.create_line(*start_point, *end_point, arrow=tk.LAST)

_maxlen = 4

def direction(event, _direct=deque([Vector(0, 0) for _ in range(_maxlen)], maxlen=_maxlen)) -> None:
    """stores previous position, and uses it to calculate the direction
    from the current position.
    updates these variables
    """
    global direct
    _direct.append(Point(event.x, event.y))
    p0, p1 = _direct[0], _direct[-1]
    direct = p1 - p0
    draw_dir(canvas, p1)
#     print(_direct, direct)

direct = Vector(0, 0)

root = tk.Tk()
canvas = tk.Canvas(root, bg='cyan')
canvas.pack()
canvas.bind('<B1-Motion>', direction)
root.mainloop()


问:
Need some advanced explanations about BOF
So I was following a tutorial about buffer overflow with the following code:

```<code>#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

int main(int argc, char **argv)
{
  volatile int modified;
  char buffer[64];

 modified = 0;
  gets(buffer);

  if(modified != 0) {
      printf("you have changed the 'modified' variable\n");
  } else {
      printf("Try again?\n");
  }
}
</code>```

I then compile it with gcc and additionnally run beforehand sudo sysctl -w kernel.randomize_va_space=0 to prevent random memory and allow the stack smashing (buffer overflow) exploit

```<code>gcc protostar.c -g -z execstack -fno-stack-protector -o protostar
</code>```

-g is to allow debugging in gdb ('list main')

-z execstack -fno-stack-protector is to remove the stack protection

and then execute it:

```<code>python -c 'print "A"*76' | ./protostar
</code>```

Try again?

```<code>python -c 'print "A"*77' | ./protostar
</code>```

you have changed the 'modified' variable

So I do not understand why the buffer overflow occurs with 77 while it should have been 65, so it makes a 12 bits difference (3 bytes). I wonder the reason why if anyone has a clear explanation ?

Also it remains this way from 77 to 87:

```<code>python -c 'print "A"*87' | ./protostar
you have changed the 'modified' variable
</code>```

And from 88 it adds a segfault:

```<code>python -c 'print "A"*88' | ./protostar
you have changed the 'modified' variable
Segmentation fault (core dumped)
</code>```

Regards

答:
To fully understand what's happening, it's first important to make note of how your program is laying out memory.

From your comment, you have that for this particular run, memory for buffer starts at 0x7fffffffdf10 and then modified starts at 0x7fffffffdf5c  (although randomize_va_space may keep this consistent across runs, but I'm not quite sure).

So you have something like this:

```<code>0x7fffffffdf10            0x7fffffffdf50      0x7fffffffdf5c
↓                         ↓                   ↓
(64 byte buffer)..........(some 12 bytes).....(modified)....
</code>```

Essentially, you have the 64 character buffer, then when that ends, there's 12 bytes that are used for some other stack variable (likely 4 bytes argc and 8 bytes for argv), and then modified comes after, precisely starting 64+12 = 76 bytes after the buffer starts.

Therefore, when you write between 65 and 76 characters into the 64 byte buffer, it goes past and starts writing into those 12 bytes that are in-between the buffer and modified. When you start writing the 77th character, it starts overwriting what's in modified which causes you to see the "you have changed the 'modified' variable" message.

You asked also "why does it work if I go up to 87 and then at 88 there's a segfault? The answer is that because it's undefined behavior, as soon as you start writing into invalid memory and the kernel recognizes it, it'll immediately kill your process because you are trying to read/write memory you don't have access to.

Note that you should almost never use gets in practice and this is a big reason, since you don't know exactly how many bytes you will be reading so there's a chance to overwrite. Also note that the behavior you're seeing is not the same behavior I'm seeing on my machine when I run it. This is normal, and that's because it's undefined behavior. There are no guarantees to what will happen when you run it. On my machine, modified actually comes before buffer in memory, so I don't ever see the modified variable get overwritten. I think this is a good learning example to understand why undefined behavior like this is just so unpredictable.

Body:
So I was following a tutorial about buffer overflow with the following code:

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

int main(int argc, char **argv)
{
  volatile int modified;
  char buffer[64];

 modified = 0;
  gets(buffer);

  if(modified != 0) {
      printf("you have changed the 'modified' variable\n");
  } else {
      printf("Try again?\n");
  }
}

I then compile it with gcc and additionnally run beforehand sudo sysctl -w kernel.randomize_va_space=0 to prevent random memory and allow the stack smashing (buffer overflow) exploit

gcc protostar.c -g -z execstack -fno-stack-protector -o protostar

-g is to allow debugging in gdb ('list main')

-z execstack -fno-stack-protector is to remove the stack protection

and then execute it:

python -c 'print "A"*76' | ./protostar

Try again?

python -c 'print "A"*77' | ./protostar

you have changed the 'modified' variable

So I do not understand why the buffer overflow occurs with 77 while it should have been 65, so it makes a 12 bits difference (3 bytes). I wonder the reason why if anyone has a clear explanation ?

Also it remains this way from 77 to 87:

python -c 'print "A"*87' | ./protostar
you have changed the 'modified' variable

And from 88 it adds a segfault:

python -c 'print "A"*88' | ./protostar
you have changed the 'modified' variable
Segmentation fault (core dumped)

Regards

Body:
To fully understand what's happening, it's first important to make note of how your program is laying out memory.

From your comment, you have that for this particular run, memory for buffer starts at 0x7fffffffdf10 and then modified starts at 0x7fffffffdf5c  (although randomize_va_space may keep this consistent across runs, but I'm not quite sure).

So you have something like this:

0x7fffffffdf10            0x7fffffffdf50      0x7fffffffdf5c
↓                         ↓                   ↓
(64 byte buffer)..........(some 12 bytes).....(modified)....

Essentially, you have the 64 character buffer, then when that ends, there's 12 bytes that are used for some other stack variable (likely 4 bytes argc and 8 bytes for argv), and then modified comes after, precisely starting 64+12 = 76 bytes after the buffer starts.

Therefore, when you write between 65 and 76 characters into the 64 byte buffer, it goes past and starts writing into those 12 bytes that are in-between the buffer and modified. When you start writing the 77th character, it starts overwriting what's in modified which causes you to see the "you have changed the 'modified' variable" message.

You asked also "why does it work if I go up to 87 and then at 88 there's a segfault? The answer is that because it's undefined behavior, as soon as you start writing into invalid memory and the kernel recognizes it, it'll immediately kill your process because you are trying to read/write memory you don't have access to.

Note that you should almost never use gets in practice and this is a big reason, since you don't know exactly how many bytes you will be reading so there's a chance to overwrite. Also note that the behavior you're seeing is not the same behavior I'm seeing on my machine when I run it. This is normal, and that's because it's undefined behavior. There are no guarantees to what will happen when you run it. On my machine, modified actually comes before buffer in memory, so I don't ever see the modified variable get overwritten. I think this is a good learning example to understand why undefined behavior like this is just so unpredictable.


问:
Why committing package-lock.json eliminates npm SignalR installation error?
I upgraded my .Net Core 2.0 project to 2.1. Then I tried to install SignalR (specifically the client library):

Inside Visual Studio 2017 package manager console, I initialized package.json (actually I do not know what does this file do):

```<code>PM> npm init -y
</code>```

Then I tried to install signalR:

```<code>PM> npm install @aspnet/signalr
</code>```

Then I get this error:

```<code>npm : npm notice created a lockfile as package-lock.json. You should commit this file.
At line:1 char:1
+ npm install @aspnet/signalr
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (npm notice crea...mmit this file.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

+ @aspnet/signalr@1.0.0
</code>```

After that, I committed both package.json and package-lock.json files in git, and then tried to reinstall the package. Now the error has gone.

What was that error and why it is gone by committing?

答:
first open package.json file in your project file then
add this <<"private": true>> after version number and try to install signalr again.</p>

Body:
I upgraded my .Net Core 2.0 project to 2.1. Then I tried to install SignalR (specifically the client library):

Inside Visual Studio 2017 package manager console, I initialized package.json (actually I do not know what does this file do):

PM> npm init -y

Then I tried to install signalR:

PM> npm install @aspnet/signalr

Then I get this error:

npm : npm notice created a lockfile as package-lock.json. You should commit this file.
At line:1 char:1
+ npm install @aspnet/signalr
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (npm notice crea...mmit this file.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

+ @aspnet/signalr@1.0.0

After that, I committed both package.json and package-lock.json files in git, and then tried to reinstall the package. Now the error has gone.

What was that error and why it is gone by committing?


问:
Calligraphy library by chrisjenx is not working
I did what his documentation has instructed upon setting up the default font:

```<code> @Override
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupDefaultFont();

        setContentView(R.layout.activity_main);

        setupToolbarAndNavigationDrawer();
  }

  public void setupDefaultFont() {
        CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
                        .setDefaultFontPath("fonts/OpenSans-Regular.ttf")
                        .setFontAttrId(R.attr.fontPath)
                        .build()
        );
  }
</code>```

I also placed the fonts in assets/fonts, but to no avail.
Roboto still shows up as default font and not Open Sans. I tried applying it manually one by one to each TextView, but still it doesn't work.

Any ideas on why this doesn't work?

More info: (In case it is useful)
My miniSdkVersion is 15 and targetSdkVersion is 22.
These are my dependencies:

```<code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.android.support:design:22.2.0'
    compile 'com.android.support:recyclerview-v7:21.0.3'
    compile 'com.android.support:cardview-v7:21.0.3'
    compile 'de.hdodenhof:circleimageview:1.2.1'
    compile 'uk.co.chrisjenx:calligraphy:2.1.0'
}
</code>```

And this is the custom theme that I am using.

```<code><resources>
    <style name="myIIT_theme" parent="Theme.AppCompat">
        <item name="colorPrimaryDark">@color/primary_dark</item>
        <item name="colorPrimary">@color/primary</item>
        <item name="android:textColorPrimary">@color/white</item>
        <item name="android:windowBackground">@color/tertiary_dark</item>
        <item name="android:activatedBackgroundIndicator">@drawable/selected_drawer</item>
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>
</resources>
</code>```

答:
as mentioned in the Readme file in github,
This version of Calligraphy has reached its end-of-life and is no longer maintained. Please migrate to Calligraphy 3!</p>

ContentLicense: CC BY-SA 3.0

Body:
I did what his documentation has instructed upon setting up the default font:

 @Override
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupDefaultFont();

        setContentView(R.layout.activity_main);

        setupToolbarAndNavigationDrawer();
  }

  public void setupDefaultFont() {
        CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
                        .setDefaultFontPath("fonts/OpenSans-Regular.ttf")
                        .setFontAttrId(R.attr.fontPath)
                        .build()
        );
  }

I also placed the fonts in assets/fonts, but to no avail.
Roboto still shows up as default font and not Open Sans. I tried applying it manually one by one to each TextView, but still it doesn't work.

Any ideas on why this doesn't work?

More info: (In case it is useful)
My miniSdkVersion is 15 and targetSdkVersion is 22.
These are my dependencies:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.android.support:design:22.2.0'
    compile 'com.android.support:recyclerview-v7:21.0.3'
    compile 'com.android.support:cardview-v7:21.0.3'
    compile 'de.hdodenhof:circleimageview:1.2.1'
    compile 'uk.co.chrisjenx:calligraphy:2.1.0'
}

And this is the custom theme that I am using.

<resources>

</resources>


答:
I found the solution reading chanpoint-parse code.
I was in the right track.
This is the working code:</p>

```<code>
function isHex(value) {
    var hexRegex = /^[0-9A-Fa-f]{2,}$/
    var result = hexRegex.test(value)
    if (result) result = !(value.length % 2)
    return result
}

var string = Buffer.from(hash, 'hex');
var obj = null;
for ( var i = 0; i < ops.length; i++ ) {
    obj = ops[ i ];
    if ( Object.keys( obj )[0] === 'l' ) {
        let concat_value = isHex(obj['l'])
          ? Buffer.from(obj['l'], 'hex')
          : Buffer.from(obj['l'], 'utf8');
        string = Buffer.concat( [ concat_value, string ] );
    } else if ( Object.keys( obj )[0] === 'r' ) {
        let concat_value = isHex(obj['r'])
          ? Buffer.from(obj['r'], 'hex')
          : Buffer.from(obj['r'], 'utf8');
        string = Buffer.concat( [ string, concat_value ] );
    } else if ( Object.keys( obj )[0] === 'op' ) {
        string = crypto
            .createHash('sha256')
            .update(string)
            .digest()
    }
}

console.log( string.toString('hex') === m_root );
// true
</code>```

Title: Chainpoint proof of existence

Body:
I'm trying to proof the existence of a hash using a chainpoint receipt (version 3).
Using their APIs I submitted an hash and received the receipt, but I can't figure out how to execute the hashing operations to get the merkle root.

This is my receipt:

var hash='5826bb4d3411ec5cf6d5052eebf812063197872891d875d7be406400e2931424';
var proof = {
  "@context": "https://w3id.org/chainpoint/v3",
  "type": "Chainpoint",
  "hash": "5826bb4d3411ec5cf6d5052eebf812063197872891d875d7be406400e2931424",
  "hash_id_node": "0e245ec0-8142-11e9-bed4-017015d9bf71",
  "hash_submitted_node_at": "2019-05-28T12:13:51Z",
  "hash_id_core": "0f048590-8142-11e9-be51-01e14610ae21",
  "hash_submitted_core_at": "2019-05-28T12:13:53Z",
  "branches": [
    {
      "label": "cal_anchor_branch",
      "ops": [
        {
          "l": "node_id:0e245ec0-8142-11e9-bed4-017015d9bf71"
        },
        {
          "op": "sha-256"
        },
        {
          "l": "core_id:0f048590-8142-11e9-be51-01e14610ae21"
        },
        {
          "op": "sha-256"
        },
        {
          "l": "nistv2:1559045520000:d9bdc4ddd1b82ed90274022f00bb01c5378357f4013ce81199257efc96e8f3e5d47a315edc7871b328ce683a2c58c468a406fc9e518bcc27abb75602ce01c9fb"
        },
        {
          "op": "sha-256"
        },
        {
          "r": "4ca74e3ec8fafe24e3369ab4ab14a986a3894a135c0ce73e00fe31db50ecf27f"
        },
        {
          "op": "sha-256"
        },
        {
          "r": "80529beed1232c31e9bb8accdd87d6203d9b98621481da2de1fd7d4f3441b820"
        },
        {
          "op": "sha-256"
        },
        {
          "r": "a3688e37b43b4548543fd39261165812d6cf2e70dd50f54aa7132c9d7990c3f4"
        },
        {
          "op": "sha-256"
        },
        {
          "l": "3277842:1559045636:1:https://b.chainpoint.org:cal:3277842"
        },
        {
          "r": "d0a8b8e6d4cb14d2b23836538382757b34480fb3eb9e3e37cae4d3b4a754a228"
        },
        {
          "op": "sha-256"
        },
        {
          "anchors": [
            {
              "type": "cal",
              "anchor_id": "3277842",
              "uris": [
                "https://b.chainpoint.org/calendar/3277842/hash"
              ]
            }
          ]
        }
      ]
    }
  ]
}

The merkle root of the merkle tree, if I'm doing right, is at the address https://b.chainpoint.org/calendar/3277842/hash

var merkle_root = '2bf7a252fb641a5b67e9563e5e4fc4f9fc11d5a74ffa4ef303db7678a1b521f9';

I have written a simple script to prove the existence of my hash:

var string = hash;
var obj = null;
var ops = proof.branches[0];
for ( var i = 0; i < ops.length; i++ ) {
    obj = ops[ i ];
    if ( Object.keys( obj )[0] === 'l' ) {
        string = `${obj['l']}${string}`;
    } else if ( Object.keys( obj )[0] === 'r' ) {
        string = `${string}${obj['r']}`;
    } else if ( Object.keys( obj )[0] === 'op' ) {
        string = h256(string);
    }
}

console.log( string === merkle_root );

I can't find where is my error, any help would be appreciated.

Body:
I found the solution reading chanpoint-parse code.
I was in the right track.
This is the working code:

function isHex(value) {
    var hexRegex = /^[0-9A-Fa-f]{2,}$/
    var result = hexRegex.test(value)
    if (result) result = !(value.length % 2)
    return result
}

var string = Buffer.from(hash, 'hex');
var obj = null;
for ( var i = 0; i < ops.length; i++ ) {
    obj = ops[ i ];
    if ( Object.keys( obj )[0] === 'l' ) {
        let concat_value = isHex(obj['l'])
          ? Buffer.from(obj['l'], 'hex')
          : Buffer.from(obj['l'], 'utf8');
        string = Buffer.concat( [ concat_value, string ] );
    } else if ( Object.keys( obj )[0] === 'r' ) {
        let concat_value = isHex(obj['r'])
          ? Buffer.from(obj['r'], 'hex')
          : Buffer.from(obj['r'], 'utf8');
        string = Buffer.concat( [ string, concat_value ] );
    } else if ( Object.keys( obj )[0] === 'op' ) {
        string = crypto
            .createHash('sha256')
            .update(string)
            .digest()
    }
}

console.log( string.toString('hex') === m_root );
// true


问:
How to exclude all the test files except two using maven?
I like to do have something like bellow which will exclude all test cases except two of the test files?

```<code><plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>2.12.4</version>
      <configuration>
        <excludes>
            <exclude>**/*Test.java</exclude>
        </excludes>
        <includes>
            <include>path/to/Some1Test.java</include>
            <include>path/to/Some2Test.java</include>
        </includes>
      </configuration>
    </plugin>
</code>```

Critical fact in here, the test files that I do not want to exclude, also has the same naming pattern as the files I want to exclude. Thanks in advance.

答:
Following is the solution with an example:

```<code>package com.example1;
import org.junit.Test;
public class TestClass1 {
    @Test
    public void test1() {
    }
}

package com.example1;
import org.junit.Test;

public class TestClass2 {
    @Test
    public void test2() {
    }
}

package com.example2;
import org.junit.Test;
public class TestClass1 {
    @Test
    public void test1() {
    }
}

package com.example2;
import org.junit.Test;
public class TestClass2 {
    @Test
    public void test2() {
    }
}

</code>```

Now, following is the surefire plugin configuration for inclusion of com.example1.TestClass1 and com.example1.TestClass2. Here, other test classes will not be executed except these two.

```<code>    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.12.4</version>
                <configuration>
                    <includes>
                        <include>com/example1/TestClass1.java</include>
                        <include>com/example1/TestClass2.java</include>
                    </includes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</code>```

Body:
I like to do have something like bellow which will exclude all test cases except two of the test files?

<plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>2.12.4</version>
      <configuration>
        <excludes>
            <exclude>**/*Test.java</exclude>
        </excludes>
        <includes>
            <include>path/to/Some1Test.java</include>
            <include>path/to/Some2Test.java</include>
        </includes>
      </configuration>
    </plugin>

Critical fact in here, the test files that I do not want to exclude, also has the same naming pattern as the files I want to exclude. Thanks in advance.

Body:
Following is the solution with an example:

package com.example1;
import org.junit.Test;
public class TestClass1 {
    @Test
    public void test1() {
    }
}

package com.example1;
import org.junit.Test;

public class TestClass2 {
    @Test
    public void test2() {
    }
}

package com.example2;
import org.junit.Test;
public class TestClass1 {
    @Test
    public void test1() {
    }
}

package com.example2;
import org.junit.Test;
public class TestClass2 {
    @Test
    public void test2() {
    }
}

Now, following is the surefire plugin configuration for inclusion of com.example1.TestClass1 and com.example1.TestClass2. Here, other test classes will not be executed except these two.

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.12.4</version>
                <configuration>
                    <includes>
                        <include>com/example1/TestClass1.java</include>
                        <include>com/example1/TestClass2.java</include>
                    </includes>
                </configuration>
            </plugin>
        </plugins>
    </build>


问:
Icon not showing up in 2.3.3?
In 2.2 there is a generic dialog icon (ic_dialog_generic). I used this in my program by accessing android.R.drawable.ic_dialog_generic. It shows up in 2.2, however when I tested it on 2.3.3, nothing showed up.

So I copied the drawable to my project and accessed it by R.drawable.ic_dialog_generic. Once again, it shows up in 2.2 but it still does not show up in 2.3.3.

It seems there was a change with context menu styles? Any idea?

答:
Duplicate question of Dialog icon missing in 2.3

Looking at the 2.3.3 source, this icon is definitely not there.  This illustrates why they keep warning us to copy the built in images to our own projects.

Title: Icon not showing up in 2.3.3?


问:
pgAdmin 4.7 displays blank popup screen on startup
I've just installed latest pgAdmin (4.7) and whenever I start it up I get this strange blank popup which I can not remove:

I can use the application just fine I just need to move that empty window to the side which is annoying.
I'm using Firefox version 67 (64bit).

答: I've solved the issue by resetting the layout from the pgAdmin menu.


问:
Java and mySQL select from related database index
I need some help understanding this.since I've never done something similar to this.

I have made a small database where 3 tables are related together.
In that database I am selecting from a foreign key called cid and its related to a table where it has as primary key cid.

I made this query:

```<code>SELECT *
FROM sales,continent,product
WHERE sales.cid = continent.cid OR sales.pid = product.pid
</code>```

so I am trying to pull everything from the related databases. I can see it working on my code normally I think for example if  execute the query and then
I do a ResultSet to pull the string for example product.SKU i will get the expected result.

but did I really use my relation or I just pulled it cause my query is allowing me to do so?

答:
You want to join 3 tables, but this is not the way to do it.

Check this:

```<code>SELECT *
FROM sales
INNER JOIN continent ON sales.cid = continent.cid
INNER JOIN product ON sales.pid = product.pid
</code>```

This way you join continent to sales and product to sales by their related columns.

Depending on your needs you may use INNER or LEFT joins, but this is the way to go.
 You can find more here: https://dev.mysql.com/doc/refman/8.0/en/join.html

Body:
I need some help understanding this.since I've never done something similar to this.

I have made a small database where 3 tables are related together.
In that database I am selecting from a foreign key called cid and its related to a table where it has as primary key cid.

I made this query:

SELECT *
FROM sales,continent,product
WHERE sales.cid = continent.cid OR sales.pid = product.pid

so I am trying to pull everything from the related databases. I can see it working on my code normally I think for example if  execute the query and then
I do a ResultSet to pull the string for example product.SKU i will get the expected result.

but did I really use my relation or I just pulled it cause my query is allowing me to do so?

Body:
You want to join 3 tables, but this is not the way to do it.

Check this:

SELECT *
FROM sales
INNER JOIN continent ON sales.cid = continent.cid
INNER JOIN product ON sales.pid = product.pid

This way you join continent to sales and product to sales by their related columns.

Depending on your needs you may use INNER or LEFT joins, but this is the way to go.
 You can find more here: https://dev.mysql.com/doc/refman/8.0/en/join.html


问:
How to send photo in email
For a project I'm trying to take a photo using a camera connected to my raspberry pi after pressing a button and then sending the photo taken using Gmail.

So far, all I've figured out is how to take the photo after pressing the button (see the code), but I still haven't figured out how to send an email with the photo after taking the photo. By the way, I want the photo being taken and the email being sent done in only one button press. Also, I'm using IDLE python 3.

from gpiozero import Button
from picamera import PiCamera
from signal import pause

import time

camera = PiCamera()

def take_picture_with_camera():

    image_path = 'blahblah.jpg'
    camera.capture(image_path)
    print('Took photo')

button = Button(4)
button.when_pressed = take_picture_with_camera

pause()
```

答:
The smtplib provides you with email functionality. You can just add the email sender into the button trigger. The topic of adding attachments has been discussed, f.e. here:

How to send email attachments?

Title: How to send photo in email


问:
What is `uvw` property of QPickTriangleEvent class
QPickTriangleEvent class has a uvw property. What is it? Is uvw the normal vector of the triangle?

I log the QPickTriangleEvent properties:

Qt3DRender::QPickTriangleEvent *eventTri = static_cast<Qt3DRender::QPickTriangleEvent *>(event);
qDebug() << "Triangle Index: " << eventTri->triangleIndex();
qDebug() << "Triangle Vertex 1: " << eventTri->vertex1Index();
qDebug() << "Triangle Vertex 2: " << eventTri->vertex2Index();
qDebug() << "Triangle Vertex 3: " << eventTri->vertex3Index();
qDebug() << "Triangle UVW: " << eventTri->uvw();
```

<p>The output:</p>

```Triangle Index:  79540
Triangle Vertex 1:  238620
Triangle Vertex 2:  238621
Triangle Vertex 3:  238622
Triangle UVW:  QVector3D(0.0390438, 0.151772, 0.809184)
```

Even with examining the output I cannot figure uvw out. Is it the normal vector of the triangle?

I'm examining these source codes to figure out what uvw is:

triangleboundingvolume_p.h

triangleboundingvolume.cpp

答:
In source code triangleboundingvolume.cpp it is commented:

// RealTime Collision Detection page 192
bool intersectsSegmentTriangle(const RayCasting::QRay3D &ray, ...
```

Page 193 of the book comments

... also returns the barycentric coordinates (u,v,w) of the intersection point s, ...

and page 194

... Segment intersects tri at distance t in position s (s = uA + vB + w*C) ...

Body:
QPickTriangleEvent class has a uvw property. What is it? Is uvw the normal vector of the triangle?

I log the QPickTriangleEvent properties:

Qt3DRender::QPickTriangleEvent *eventTri = static_cast<Qt3DRender::QPickTriangleEvent *>(event);
qDebug() << "Triangle Index: " << eventTri->triangleIndex();
qDebug() << "Triangle Vertex 1: " << eventTri->vertex1Index();
qDebug() << "Triangle Vertex 2: " << eventTri->vertex2Index();
qDebug() << "Triangle Vertex 3: " << eventTri->vertex3Index();
qDebug() << "Triangle UVW: " << eventTri->uvw();

The output:

Triangle Index:  79540
Triangle Vertex 1:  238620
Triangle Vertex 2:  238621
Triangle Vertex 3:  238622
Triangle UVW:  QVector3D(0.0390438, 0.151772, 0.809184)

Even with examining the output I cannot figure uvw out. Is it the normal vector of the triangle?

I'm examining these source codes to figure out what uvw is:

triangleboundingvolume_p.h

triangleboundingvolume.cpp

Body:
In source code triangleboundingvolume.cpp it is commented:

// RealTime Collision Detection page 192
bool intersectsSegmentTriangle(const RayCasting::QRay3D &ray, ...

Page 193 of the book comments

... also returns the barycentric coordinates (u,v,w) of the intersection point s, ...

and page 194

... Segment intersects tri at distance t in position s (s = uA + vB + w*C) ...


问:
how can i arrange array like this
I have array like below:

$matrix = array(1, 2, 1,1, 2, 1,1, 1, 1);

how can I get array like below?

```<code>//OUTPUT:
minesweeper(matrix) = [[1, 2, 1],
                       [2, 1, 1],
                       [1, 1, 1]]
</code>```

答:
You can use array_chunk

```<code>$matrix = array(1, 2, 1,1, 2, 1,1, 1, 1);
$res = array_chunk($matrix,3);
print_r($res);
</code>```

Live working example

Title: how can i arrange array like this

Body:
I have array like below:

$matrix = array(1, 2, 1,1, 2, 1,1, 1, 1);

how can I get array like below?

//OUTPUT:
minesweeper(matrix) = [[1, 2, 1],
                       [2, 1, 1],
                       [1, 1, 1]]

Body:
You can use array_chunk

$matrix = array(1, 2, 1,1, 2, 1,1, 1, 1);
$res = array_chunk($matrix,3);
print_r($res);

Live working example


问:
My for-loop won't iterate over a string in python
I have to check what dates are missing for equity options and I want to do this with a for-loop. However

"'(slice(0, 155, None), slice(None, None, None))' is an invalid key"

shows up as error and I can't figure out why.

First it was a datetime64[ns] type and I've already tried to convert it to a string. However, it didn't seem to help. Here is my code :

```<code>def days(data, alldays):
days = np.zeros((len(data),1))
companies = ["AAPL", "AXP", "BA", "CAT", "CSCO", "CVX", "DIS", "DJX", "GS", "HD", "IBM", "INTC", "JNJ", \
    "JPM", "KO", "MCD", "MMM", "MRK", "MSFT", "NKE", "PFE", "PG", "TRV", "UNH", "UTX", "V", "VZ", "WBA", "WMT", "XOM"]
d = {}
for i, firm in enumerate(data):
    firms = data[i]
    days[i] = len(firms.date.unique())
    firmdays = firms.date.unique()
    counter = 0
    if days[i] < 3730:
        print(firms.ticker.unique(), len(firms), days[i])
    elif days[i] < len(alldays) and days[i]>=3730:
        d[companies[i]] = np.zeros((582348,6))
        breakpoint()
        for j in range(3733):
            breakpoint()
            if alldays[j] not in  firmdays:
                breakpoint()
                print(firms.ticker.unique(), alldays[j])
                for k, data in enumerate(np.zeros((582348,6))):
                    d[companies[i]][k:k+155,:] = firms[k-156 - counter*156:k-1- 156*counter,:]
                counter = counter +1
            else:
                for k, data in enumerate(np.zeros((582348,6))):
                    d[companies[i]][k:k+155,:] = firms[k- counter*156:k+155 - 156*counter,:]
    print(firms.ticker.unique(), len(firms), days[i])
return days
</code>```

It gives an error at line "if alldays[j] not in firmdays:", namely

```<code>'(slice(0, 155, None), slice(None, None, None))' is an invalid key
</code>```

答:
Looking at the error, the problem seems more with the use of the slice notation (on part before = sign) on that line:

```<code>d[companies[i]][k:k+155,:] = firms[k- counter*156,:]
</code>```

Not sure what you are trying to achieve but have a look at this post: https://stackoverflow.com/a/509295/6203472

Body:
I have to check what dates are missing for equity options and I want to do this with a for-loop. However

"'(slice(0, 155, None), slice(None, None, None))' is an invalid key"

shows up as error and I can't figure out why.

First it was a datetime64[ns] type and I've already tried to convert it to a string. However, it didn't seem to help. Here is my code :

def days(data, alldays):
days = np.zeros((len(data),1))
companies = ["AAPL", "AXP", "BA", "CAT", "CSCO", "CVX", "DIS", "DJX", "GS", "HD", "IBM", "INTC", "JNJ", \
    "JPM", "KO", "MCD", "MMM", "MRK", "MSFT", "NKE", "PFE", "PG", "TRV", "UNH", "UTX", "V", "VZ", "WBA", "WMT", "XOM"]
d = {}
for i, firm in enumerate(data):
    firms = data[i]
    days[i] = len(firms.date.unique())
    firmdays = firms.date.unique()
    counter = 0
    if days[i] < 3730:
        print(firms.ticker.unique(), len(firms), days[i])
    elif days[i] < len(alldays) and days[i]>=3730:
        d[companies[i]] = np.zeros((582348,6))
        breakpoint()
        for j in range(3733):
            breakpoint()
            if alldays[j] not in  firmdays:
                breakpoint()
                print(firms.ticker.unique(), alldays[j])
                for k, data in enumerate(np.zeros((582348,6))):
                    d[companies[i]][k:k+155,:] = firms[k-156 - counter*156:k-1- 156*counter,:]
                counter = counter +1
            else:
                for k, data in enumerate(np.zeros((582348,6))):
                    d[companies[i]][k:k+155,:] = firms[k- counter*156:k+155 - 156*counter,:]
    print(firms.ticker.unique(), len(firms), days[i])
return days

It gives an error at line "if alldays[j] not in firmdays:", namely

'(slice(0, 155, None), slice(None, None, None))' is an invalid key

Body:
Looking at the error, the problem seems more with the use of the slice notation (on part before = sign) on that line:

d[companies[i]][k:k+155,:] = firms[k- counter*156,:]

Not sure what you are trying to achieve but have a look at this post: https://stackoverflow.com/a/509295/6203472


问:
Finding frequency of maximum digit in a number
```<code>#include <stdio.h>

int main(void)
{
    int i=0,max=0;
    long long int n,p;
    scanf("%lld",&n);
    while(n>0)
    {
        p=n%10;
        if(p==max)
        {
            i++;
        }
        else if(p>max)
        {
            max=p;
            i=1;
        }
        n/=10;
    }
    printf("%d",i);
    return 0;
}
</code>```

The code gives correct results for numbers like 8687557576676885 . But for the input 11111111111111111111111111111111 , it doesn't give the proper result . I've seen similar problem in this site but those were written in different language. I want to know where the problem lies for large number .

Thanks...

N.B. : It would be helpful if anyone could give alternate solutions . I'm still a newbie,so it would help me to understand things more deeply.

答:
There is an overflow in your code.  I printed the value read by scanf and the result is so:

```<code>11111111111111111111111111111111
7 0 922337203685477580
0 7 92233720368547758
8 7 9223372036854775
5 8 922337203685477
7 8 92233720368547
7 8 9223372036854
4 8 922337203685
5 8 92233720368
8 8 9223372036
6 8 922337203
3 8 92233720
0 8 9223372
2 8 922337
7 8 92233
3 8 9223
3 8 922
2 8 92
2 8 9
9 8 0
9 1
</code>```

I used this modified code:

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

int main(void)
{
  int count=0,max=0, digit;
  long long int n;
  scanf("%lld",&n);
  while(n)
  {
    digit=n%10,n/=10;
    printf("%d %d %lld\n",digit, max, n);
    if(digit==max)
      count++;
    else if(digit>max)
      max=digit,
      count=1;
  }
  printf("%d %d",max, count);
  return 0;
}
</code>```

In order to avoid the overflow you need to read the number as a string char*number and treat digits as characters. You should do it so:

```<code>int main(void)
{
  int count=0;
  char max='0', digit;
  char n[1000], *p=n;
  fgets(n, 1000, stdin);
  while(*p)
    {
      digit=*p++;
      if(digit==max)
        count++;
      else if(digit>max)
        max=digit,
        count=1;
    }
  printf("%c %d",max, count);
  return 0;
}
</code>```

Body:
#include <stdio.h>

int main(void)
{
    int i=0,max=0;
    long long int n,p;
    scanf("%lld",&n);
    while(n>0)
    {
        p=n%10;
        if(p==max)
        {
            i++;
        }
        else if(p>max)
        {
            max=p;
            i=1;
        }
        n/=10;
    }
    printf("%d",i);
    return 0;
}

The code gives correct results for numbers like 8687557576676885 . But for the input 11111111111111111111111111111111 , it doesn't give the proper result . I've seen similar problem in this site but those were written in different language. I want to know where the problem lies for large number .

Thanks...

N.B. : It would be helpful if anyone could give alternate solutions . I'm still a newbie,so it would help me to understand things more deeply.

Body:
There is an overflow in your code.  I printed the value read by scanf and the result is so:

11111111111111111111111111111111
7 0 922337203685477580
0 7 92233720368547758
8 7 9223372036854775
5 8 922337203685477
7 8 92233720368547
7 8 9223372036854
4 8 922337203685
5 8 92233720368
8 8 9223372036
6 8 922337203
3 8 92233720
0 8 9223372
2 8 922337
7 8 92233
3 8 9223
3 8 922
2 8 92
2 8 9
9 8 0
9 1

I used this modified code:

#include <stdio.h>

int main(void)
{
  int count=0,max=0, digit;
  long long int n;
  scanf("%lld",&n);
  while(n)
  {
    digit=n%10,n/=10;
    printf("%d %d %lld\n",digit, max, n);
    if(digit==max)
      count++;
    else if(digit>max)
      max=digit,
      count=1;
  }
  printf("%d %d",max, count);
  return 0;
}

In order to avoid the overflow you need to read the number as a string char*number and treat digits as characters. You should do it so:

int main(void)
{
  int count=0;
  char max='0', digit;
  char n[1000], *p=n;
  fgets(n, 1000, stdin);
  while(*p)
    {
      digit=*p++;
      if(digit==max)
        count++;
      else if(digit>max)
        max=digit,
        count=1;
    }
  printf("%c %d",max, count);
  return 0;
}


问:
Is it possible to set coding inside of function instead of first line of code?
It is a little bit complicated but I have to declare utf-8 coding inside a function, not in the first line of code. It is possible? So I have to do e.g. def fun():
    # - * - coding: utf-8 - * - It seems to not work now.

答:
No, it is not possible. PEP 263 is quite specific that it has to be done in the first or second line of the file.

It also doesn't make sense. Python reads the whole file in the same encoding. The encoding therefore has to be specified on the file level, at the beginning of the file. You cannot change the encoding from function to function.


问:
How do I change user presence status in RingCentral programmatically using C#?
I have created as program in C# that is designed to display the users status and availability from RingCentral.

This works brilliantly and I can sort the users by availability, name, etc.

I need to add the functionality to change the status of the user to "Offline".  When the users shift ends they would be set to receive calls when they have gone home, we need to stop that.

The problem I have is that the RingCentral SDK I am using is saying it needs a parameter which should be of type PresenceInfoResource.  here is the path I am using:

```<code>rc.Restapi().Account().Extension().Presence().Put();
</code>```

I have tried various different types but I cannot seem to get, create or cast to a type of PresenceInfoResource.

Does anyone know what it is looking for, how to change the status in c# or where I am going wrong?

I have looked in the RingCentral documentation on line, but can't find anything, only a link to the update presence page which has nothing about PresenceInfoResource:

https://developers.ringcentral.com/api-reference/Presence/updateUserPresenceStatus

答:
I got an answer to this from another site:</p>

```<code>    var parameters = new PresenceInfoResource();
    parameters.userStatus = "Busy";
    parameters.dndStatus = "TakeAllCalls";
    var resp = await rc.Restapi().Account().Extension().Presence().Put(parameters);
    Console.WriteLine("User presence status: " + resp.userStatus);
    Console.WriteLine("User DND status: " + resp.dndStatus);
</code>```

Body:
I have created as program in C# that is designed to display the users status and availability from RingCentral.

This works brilliantly and I can sort the users by availability, name, etc.

I need to add the functionality to change the status of the user to "Offline".  When the users shift ends they would be set to receive calls when they have gone home, we need to stop that.

The problem I have is that the RingCentral SDK I am using is saying it needs a parameter which should be of type PresenceInfoResource.  here is the path I am using:

rc.Restapi().Account().Extension().Presence().Put();

I have tried various different types but I cannot seem to get, create or cast to a type of PresenceInfoResource.

Does anyone know what it is looking for, how to change the status in c# or where I am going wrong?

I have looked in the RingCentral documentation on line, but can't find anything, only a link to the update presence page which has nothing about PresenceInfoResource:

https://developers.ringcentral.com/api-reference/Presence/updateUserPresenceStatus

Body:
I got an answer to this from another site:

    var parameters = new PresenceInfoResource();
    parameters.userStatus = "Busy";
    parameters.dndStatus = "TakeAllCalls";
    var resp = await rc.Restapi().Account().Extension().Presence().Put(parameters);
    Console.WriteLine("User presence status: " + resp.userStatus);
    Console.WriteLine("User DND status: " + resp.dndStatus);


问:
Can a Ruby app call Java code?
This is probably really simple, but all my Google results came back with JRuby, which isn't what I want to know.  I'm curious if a regular Ruby app (e.g. a Rails app or a Sinatra app) could somehow be made to reference and call a Java library that's in the classpath?  Ideally one that works on Heroku.</p>

答: Not directly. Java libraries run within the JVM, Ruby apps in their own VM. If you want those two to communicate, you will need to create some kind of a comms channel between them (there are various solutions, see f.e. http://code.google.com/p/activemessaging/).</p>

Title: Can a Ruby app call Java code?